deepspace 0.2.3 → 0.2.5
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/cli.js +734 -17
- package/dist/cli.js.map +1 -1
- package/dist/testing.d.ts +115 -0
- package/dist/testing.js +175 -0
- package/dist/testing.js.map +1 -0
- package/dist/worker.d.ts +43 -4
- package/dist/worker.js +22 -2
- package/dist/worker.js.map +1 -1
- package/package.json +13 -4
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import * as _playwright_test from '@playwright/test';
|
|
2
|
+
import { BrowserContext, Page, Browser } from '@playwright/test';
|
|
3
|
+
export { expect } from '@playwright/test';
|
|
4
|
+
|
|
5
|
+
interface MultiplayerUser {
|
|
6
|
+
context: BrowserContext;
|
|
7
|
+
page: Page;
|
|
8
|
+
email: string;
|
|
9
|
+
name: string;
|
|
10
|
+
/** Test account user ID, if known from the accounts registry. */
|
|
11
|
+
userId?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Fixture function signature. Pass either a count (`users(2)`) or an
|
|
15
|
+
* array of account names (`users(['Alice', 'Bob'])`). Returns one entry
|
|
16
|
+
* per requested user.
|
|
17
|
+
*/
|
|
18
|
+
type UsersFixture = (selector: number | string[], options?: {
|
|
19
|
+
label?: string;
|
|
20
|
+
}) => Promise<MultiplayerUser[]>;
|
|
21
|
+
interface MultiplayerFixtures {
|
|
22
|
+
users: UsersFixture;
|
|
23
|
+
}
|
|
24
|
+
declare const test: _playwright_test.TestType<_playwright_test.PlaywrightTestArgs & _playwright_test.PlaywrightTestOptions & MultiplayerFixtures, _playwright_test.PlaywrightWorkerArgs & _playwright_test.PlaywrightWorkerOptions>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Account-credential plumbing for the testing module.
|
|
28
|
+
*
|
|
29
|
+
* Reads test accounts from `~/.deepspace/test-accounts.json` (the same
|
|
30
|
+
* file `deepspace test-accounts create` writes). Each account has at
|
|
31
|
+
* minimum `{email, password}`; `name` and `label` are optional.
|
|
32
|
+
*
|
|
33
|
+
* Used by the multi-user Playwright fixture in `./fixtures.ts` and is
|
|
34
|
+
* also exported standalone in case suites want to do their own
|
|
35
|
+
* orchestration.
|
|
36
|
+
*/
|
|
37
|
+
interface TestAccount {
|
|
38
|
+
email: string;
|
|
39
|
+
password: string;
|
|
40
|
+
name?: string;
|
|
41
|
+
label?: string | null;
|
|
42
|
+
id?: string;
|
|
43
|
+
userId?: string;
|
|
44
|
+
createdAt?: number;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Load all test accounts the developer has created. Returns an empty
|
|
48
|
+
* array if the file doesn't exist yet.
|
|
49
|
+
*/
|
|
50
|
+
declare function loadAllTestAccounts(): TestAccount[];
|
|
51
|
+
/**
|
|
52
|
+
* Pick `count` test accounts from the local registry, optionally
|
|
53
|
+
* filtered by `label`. Order-stable: sorted by `createdAt` ascending so
|
|
54
|
+
* the first test account you created is always the first one returned.
|
|
55
|
+
*
|
|
56
|
+
* Throws with a helpful message if not enough accounts exist.
|
|
57
|
+
*/
|
|
58
|
+
declare function pickTestAccounts(count: number, options?: {
|
|
59
|
+
label?: string;
|
|
60
|
+
}): TestAccount[];
|
|
61
|
+
/**
|
|
62
|
+
* Find a single account by name. Used by `users(['Alice', 'Bob'])`.
|
|
63
|
+
* Throws if not found.
|
|
64
|
+
*/
|
|
65
|
+
declare function findTestAccountByName(name: string): TestAccount;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Per-account `storageState` cache for Playwright.
|
|
69
|
+
*
|
|
70
|
+
* Better Auth applies a per-IP rate limit on `/api/auth/sign-in/email`
|
|
71
|
+
* (~5 sign-ins / 60s / endpoint). A multiplayer suite that spins up
|
|
72
|
+
* 5+ users per spec would hit the limit and start failing in non-obvious
|
|
73
|
+
* ways. This module signs each account in *once*, persists the
|
|
74
|
+
* resulting browser cookies + storage to disk, and reuses the file on
|
|
75
|
+
* subsequent runs.
|
|
76
|
+
*
|
|
77
|
+
* Cache layout:
|
|
78
|
+
* ~/.deepspace/playwright-states/<sha256(email)>.json
|
|
79
|
+
*
|
|
80
|
+
* Validity: a cached file is reused if Playwright successfully loads it
|
|
81
|
+
* AND the resulting context produces a non-anonymous session on the
|
|
82
|
+
* target app. If validation fails, we fall back to a fresh sign-in and
|
|
83
|
+
* overwrite the cache.
|
|
84
|
+
*/
|
|
85
|
+
|
|
86
|
+
interface EnsureStorageStateOptions {
|
|
87
|
+
/** Max age of a cached state file before we re-sign-in. Default 7 days. */
|
|
88
|
+
maxAgeMs?: number;
|
|
89
|
+
/** Force a fresh sign-in even if the cache is fresh. */
|
|
90
|
+
force?: boolean;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Ensure a Playwright `storageState` file exists for `account` and
|
|
94
|
+
* return its path. Signs in once if the cache is missing, stale, or
|
|
95
|
+
* `force: true`.
|
|
96
|
+
*/
|
|
97
|
+
declare function ensureStorageState(browser: Browser, account: {
|
|
98
|
+
email: string;
|
|
99
|
+
password: string;
|
|
100
|
+
}, baseURL: string, options?: EnsureStorageStateOptions): Promise<string>;
|
|
101
|
+
/**
|
|
102
|
+
* Convenience: open a fresh `BrowserContext` for `account` using the
|
|
103
|
+
* cached storage state (signing in if needed). The caller is responsible
|
|
104
|
+
* for closing the context.
|
|
105
|
+
*/
|
|
106
|
+
declare function newSignedInContext(browser: Browser, account: {
|
|
107
|
+
email: string;
|
|
108
|
+
password: string;
|
|
109
|
+
}, baseURL: string, options?: EnsureStorageStateOptions): Promise<BrowserContext>;
|
|
110
|
+
/** Read a cached storageState file (mostly for debugging). */
|
|
111
|
+
declare function readCachedState(email: string): unknown | null;
|
|
112
|
+
/** Where the cache for `email` lives. Useful for diagnostics. */
|
|
113
|
+
declare function getStatePathForEmail(email: string): string;
|
|
114
|
+
|
|
115
|
+
export { type EnsureStorageStateOptions, type MultiplayerUser, type TestAccount, type UsersFixture, ensureStorageState, findTestAccountByName, getStatePathForEmail, loadAllTestAccounts, newSignedInContext, pickTestAccounts, readCachedState, test };
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// src/testing/fixtures.ts
|
|
2
|
+
import { test as baseTest } from "@playwright/test";
|
|
3
|
+
|
|
4
|
+
// src/testing/accounts.ts
|
|
5
|
+
import { existsSync, readFileSync } from "fs";
|
|
6
|
+
import { homedir } from "os";
|
|
7
|
+
import { join } from "path";
|
|
8
|
+
var ACCOUNTS_PATH = join(homedir(), ".deepspace", "test-accounts.json");
|
|
9
|
+
function loadAllTestAccounts() {
|
|
10
|
+
if (!existsSync(ACCOUNTS_PATH)) return [];
|
|
11
|
+
try {
|
|
12
|
+
const raw = JSON.parse(readFileSync(ACCOUNTS_PATH, "utf-8"));
|
|
13
|
+
if (!Array.isArray(raw)) return [];
|
|
14
|
+
return raw.filter(
|
|
15
|
+
(r) => r && typeof r.email === "string" && typeof r.password === "string"
|
|
16
|
+
);
|
|
17
|
+
} catch {
|
|
18
|
+
return [];
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function pickTestAccounts(count, options) {
|
|
22
|
+
const all = loadAllTestAccounts();
|
|
23
|
+
const filtered = options?.label ? all.filter((a) => a.label === options.label) : all;
|
|
24
|
+
const sorted = filtered.slice().sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
|
|
25
|
+
if (sorted.length < count) {
|
|
26
|
+
const labelHint = options?.label ? ` (label="${options.label}")` : "";
|
|
27
|
+
throw new Error(
|
|
28
|
+
`Multiplayer test needs ${count} test accounts${labelHint}, but only ${sorted.length} are present in ${ACCOUNTS_PATH}. Create more with:
|
|
29
|
+
deepspace test-accounts create --email <name>@deepspace.test --password <pw> --name "<name>"${options?.label ? ` --label ${options.label}` : ""}`
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
return sorted.slice(0, count);
|
|
33
|
+
}
|
|
34
|
+
function findTestAccountByName(name) {
|
|
35
|
+
const all = loadAllTestAccounts();
|
|
36
|
+
const match = all.find((a) => a.name === name);
|
|
37
|
+
if (!match) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
`No test account named "${name}" in ${ACCOUNTS_PATH}. Create with:
|
|
40
|
+
deepspace test-accounts create --email ${name.toLowerCase()}@deepspace.test --password <pw> --name "${name}"`
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
return match;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/testing/storage-state.ts
|
|
47
|
+
import { createHash } from "crypto";
|
|
48
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, statSync } from "fs";
|
|
49
|
+
import { homedir as homedir2 } from "os";
|
|
50
|
+
import { join as join2 } from "path";
|
|
51
|
+
var STATES_DIR = join2(homedir2(), ".deepspace", "playwright-states");
|
|
52
|
+
var DEFAULT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
53
|
+
function statePathForEmail(email) {
|
|
54
|
+
const hash = createHash("sha256").update(email.trim().toLowerCase()).digest("hex").slice(0, 24);
|
|
55
|
+
return join2(STATES_DIR, `${hash}.json`);
|
|
56
|
+
}
|
|
57
|
+
function ensureStatesDir() {
|
|
58
|
+
if (!existsSync2(STATES_DIR)) mkdirSync(STATES_DIR, { recursive: true });
|
|
59
|
+
}
|
|
60
|
+
function isCacheFresh(path, maxAgeMs) {
|
|
61
|
+
if (!existsSync2(path)) return false;
|
|
62
|
+
try {
|
|
63
|
+
const age = Date.now() - statSync(path).mtimeMs;
|
|
64
|
+
return age < maxAgeMs;
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function signInAndSaveState(browser, account, baseURL, outPath) {
|
|
70
|
+
ensureStatesDir();
|
|
71
|
+
const ctx = await browser.newContext({ baseURL });
|
|
72
|
+
try {
|
|
73
|
+
const page = await ctx.newPage();
|
|
74
|
+
await page.goto("/");
|
|
75
|
+
const ok = await page.evaluate(
|
|
76
|
+
async ({ email, password }) => {
|
|
77
|
+
const res = await fetch("/api/auth/sign-in/email", {
|
|
78
|
+
method: "POST",
|
|
79
|
+
headers: { "Content-Type": "application/json" },
|
|
80
|
+
body: JSON.stringify({ email, password })
|
|
81
|
+
});
|
|
82
|
+
return res.ok;
|
|
83
|
+
},
|
|
84
|
+
account
|
|
85
|
+
);
|
|
86
|
+
if (!ok) {
|
|
87
|
+
throw new Error(
|
|
88
|
+
`Sign-in failed for ${account.email}. Check the password is current; if the account was deleted on the server, re-create with \`deepspace test-accounts create\`.`
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
await ctx.storageState({ path: outPath });
|
|
92
|
+
return outPath;
|
|
93
|
+
} finally {
|
|
94
|
+
await ctx.close();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
async function ensureStorageState(browser, account, baseURL, options = {}) {
|
|
98
|
+
const path = statePathForEmail(account.email);
|
|
99
|
+
const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
|
|
100
|
+
if (!options.force && isCacheFresh(path, maxAgeMs)) {
|
|
101
|
+
return path;
|
|
102
|
+
}
|
|
103
|
+
return signInAndSaveState(browser, account, baseURL, path);
|
|
104
|
+
}
|
|
105
|
+
async function newSignedInContext(browser, account, baseURL, options = {}) {
|
|
106
|
+
const statePath = await ensureStorageState(browser, account, baseURL, options);
|
|
107
|
+
return browser.newContext({ storageState: statePath, baseURL });
|
|
108
|
+
}
|
|
109
|
+
function readCachedState(email) {
|
|
110
|
+
const path = statePathForEmail(email);
|
|
111
|
+
if (!existsSync2(path)) return null;
|
|
112
|
+
try {
|
|
113
|
+
return JSON.parse(readFileSync2(path, "utf-8"));
|
|
114
|
+
} catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function getStatePathForEmail(email) {
|
|
119
|
+
return statePathForEmail(email);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/testing/fixtures.ts
|
|
123
|
+
import { expect } from "@playwright/test";
|
|
124
|
+
async function buildUser(browser, account, baseURL) {
|
|
125
|
+
const statePath = await ensureStorageState(browser, account, baseURL);
|
|
126
|
+
const context = await browser.newContext({ storageState: statePath, baseURL });
|
|
127
|
+
const page = await context.newPage();
|
|
128
|
+
return {
|
|
129
|
+
user: {
|
|
130
|
+
context,
|
|
131
|
+
page,
|
|
132
|
+
email: account.email,
|
|
133
|
+
name: account.name ?? account.email.split("@")[0],
|
|
134
|
+
userId: account.userId
|
|
135
|
+
},
|
|
136
|
+
cleanup: async () => {
|
|
137
|
+
await context.close();
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
var test = baseTest.extend({
|
|
142
|
+
users: async ({ browser, baseURL }, use) => {
|
|
143
|
+
if (!baseURL) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
'`users` fixture requires a baseURL. Set it on your Playwright config (e.g. `use: { baseURL: "http://localhost:5173" }`) or via the webServer.url shortcut.'
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
const cleanups = [];
|
|
149
|
+
const usersFn = async (selector, options) => {
|
|
150
|
+
const accounts = Array.isArray(selector) ? selector.map((name) => findTestAccountByName(name)) : pickTestAccounts(selector, options);
|
|
151
|
+
const built = await Promise.all(
|
|
152
|
+
accounts.map((acct) => buildUser(browser, acct, baseURL))
|
|
153
|
+
);
|
|
154
|
+
for (const b of built) cleanups.push(b.cleanup);
|
|
155
|
+
return built.map((b) => b.user);
|
|
156
|
+
};
|
|
157
|
+
await use(usersFn);
|
|
158
|
+
for (const cleanup of cleanups) {
|
|
159
|
+
await cleanup().catch(() => {
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
export {
|
|
165
|
+
ensureStorageState,
|
|
166
|
+
expect,
|
|
167
|
+
findTestAccountByName,
|
|
168
|
+
getStatePathForEmail,
|
|
169
|
+
loadAllTestAccounts,
|
|
170
|
+
newSignedInContext,
|
|
171
|
+
pickTestAccounts,
|
|
172
|
+
readCachedState,
|
|
173
|
+
test
|
|
174
|
+
};
|
|
175
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testing/fixtures.ts","../src/testing/accounts.ts","../src/testing/storage-state.ts"],"sourcesContent":["/**\n * Multi-user Playwright fixture for DeepSpace apps.\n *\n * Usage:\n *\n * import { test, expect } from 'deepspace/testing'\n *\n * test('A sends, B sees', async ({ users }) => {\n * const [a, b] = await users(2)\n * await a.page.goto('/chat')\n * await b.page.goto('/chat')\n * await a.page.getByTestId('message-input').fill('hi')\n * await a.page.getByTestId('send-message-btn').click()\n * await expect(b.page.getByText('hi')).toBeVisible()\n * })\n *\n * `users(N)` picks the first N test accounts from\n * `~/.deepspace/test-accounts.json` (created via\n * `deepspace test-accounts create`). `users(['Alice', 'Bob'])` picks\n * specific accounts by name.\n *\n * Each user gets a separate browser context with cached storageState\n * (per-account JSON in `~/.deepspace/playwright-states/`). Sign-in\n * happens once per account, not once per test, sidestepping Better\n * Auth's per-IP rate limit on `/api/auth/sign-in/email`.\n *\n * Contexts are auto-closed when the test finishes.\n */\n\nimport { test as baseTest, type Browser, type BrowserContext, type Page } from '@playwright/test'\nimport {\n type TestAccount,\n pickTestAccounts,\n findTestAccountByName,\n} from './accounts'\nimport { ensureStorageState } from './storage-state'\n\nexport interface MultiplayerUser {\n context: BrowserContext\n page: Page\n email: string\n name: string\n /** Test account user ID, if known from the accounts registry. */\n userId?: string\n}\n\n/**\n * Fixture function signature. Pass either a count (`users(2)`) or an\n * array of account names (`users(['Alice', 'Bob'])`). Returns one entry\n * per requested user.\n */\nexport type UsersFixture = (\n selector: number | string[],\n options?: { label?: string },\n) => Promise<MultiplayerUser[]>\n\ninterface MultiplayerFixtures {\n users: UsersFixture\n}\n\nasync function buildUser(\n browser: Browser,\n account: TestAccount,\n baseURL: string,\n): Promise<{ user: MultiplayerUser; cleanup: () => Promise<void> }> {\n const statePath = await ensureStorageState(browser, account, baseURL)\n const context = await browser.newContext({ storageState: statePath, baseURL })\n const page = await context.newPage()\n return {\n user: {\n context,\n page,\n email: account.email,\n name: account.name ?? account.email.split('@')[0],\n userId: account.userId,\n },\n cleanup: async () => {\n await context.close()\n },\n }\n}\n\nexport const test = baseTest.extend<MultiplayerFixtures>({\n users: async ({ browser, baseURL }, use) => {\n if (!baseURL) {\n throw new Error(\n '`users` fixture requires a baseURL. Set it on your Playwright config ' +\n '(e.g. `use: { baseURL: \"http://localhost:5173\" }`) or via the ' +\n 'webServer.url shortcut.',\n )\n }\n\n const cleanups: Array<() => Promise<void>> = []\n\n const usersFn: UsersFixture = async (selector, options) => {\n const accounts: TestAccount[] = Array.isArray(selector)\n ? selector.map((name) => findTestAccountByName(name))\n : pickTestAccounts(selector, options)\n\n const built = await Promise.all(\n accounts.map((acct) => buildUser(browser, acct, baseURL)),\n )\n for (const b of built) cleanups.push(b.cleanup)\n return built.map((b) => b.user)\n }\n\n await use(usersFn)\n\n // Tear down any contexts we created. Errors are swallowed — a test\n // failure shouldn't be masked by a cleanup error.\n for (const cleanup of cleanups) {\n await cleanup().catch(() => {})\n }\n },\n})\n\nexport { expect } from '@playwright/test'\n","/**\n * Account-credential plumbing for the testing module.\n *\n * Reads test accounts from `~/.deepspace/test-accounts.json` (the same\n * file `deepspace test-accounts create` writes). Each account has at\n * minimum `{email, password}`; `name` and `label` are optional.\n *\n * Used by the multi-user Playwright fixture in `./fixtures.ts` and is\n * also exported standalone in case suites want to do their own\n * orchestration.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface TestAccount {\n email: string\n password: string\n name?: string\n label?: string | null\n id?: string\n userId?: string\n createdAt?: number\n}\n\nconst ACCOUNTS_PATH = join(homedir(), '.deepspace', 'test-accounts.json')\n\n/**\n * Load all test accounts the developer has created. Returns an empty\n * array if the file doesn't exist yet.\n */\nexport function loadAllTestAccounts(): TestAccount[] {\n if (!existsSync(ACCOUNTS_PATH)) return []\n try {\n const raw = JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))\n if (!Array.isArray(raw)) return []\n // Filter out any malformed entries (missing email or password). Keep\n // bare {email, password} rows so the file format stays forgiving.\n return raw.filter(\n (r) => r && typeof r.email === 'string' && typeof r.password === 'string',\n )\n } catch {\n return []\n }\n}\n\n/**\n * Pick `count` test accounts from the local registry, optionally\n * filtered by `label`. Order-stable: sorted by `createdAt` ascending so\n * the first test account you created is always the first one returned.\n *\n * Throws with a helpful message if not enough accounts exist.\n */\nexport function pickTestAccounts(\n count: number,\n options?: { label?: string },\n): TestAccount[] {\n const all = loadAllTestAccounts()\n const filtered = options?.label\n ? all.filter((a) => a.label === options.label)\n : all\n const sorted = filtered.slice().sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0))\n\n if (sorted.length < count) {\n const labelHint = options?.label ? ` (label=\"${options.label}\")` : ''\n throw new Error(\n `Multiplayer test needs ${count} test accounts${labelHint}, but only ${sorted.length} ` +\n `are present in ${ACCOUNTS_PATH}. Create more with:\\n` +\n ` deepspace test-accounts create --email <name>@deepspace.test --password <pw> --name \"<name>\"${\n options?.label ? ` --label ${options.label}` : ''\n }`,\n )\n }\n\n return sorted.slice(0, count)\n}\n\n/**\n * Find a single account by name. Used by `users(['Alice', 'Bob'])`.\n * Throws if not found.\n */\nexport function findTestAccountByName(name: string): TestAccount {\n const all = loadAllTestAccounts()\n const match = all.find((a) => a.name === name)\n if (!match) {\n throw new Error(\n `No test account named \"${name}\" in ${ACCOUNTS_PATH}. Create with:\\n` +\n ` deepspace test-accounts create --email ${name.toLowerCase()}@deepspace.test --password <pw> --name \"${name}\"`,\n )\n }\n return match\n}\n","/**\n * Per-account `storageState` cache for Playwright.\n *\n * Better Auth applies a per-IP rate limit on `/api/auth/sign-in/email`\n * (~5 sign-ins / 60s / endpoint). A multiplayer suite that spins up\n * 5+ users per spec would hit the limit and start failing in non-obvious\n * ways. This module signs each account in *once*, persists the\n * resulting browser cookies + storage to disk, and reuses the file on\n * subsequent runs.\n *\n * Cache layout:\n * ~/.deepspace/playwright-states/<sha256(email)>.json\n *\n * Validity: a cached file is reused if Playwright successfully loads it\n * AND the resulting context produces a non-anonymous session on the\n * target app. If validation fails, we fall back to a fresh sign-in and\n * overwrite the cache.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, writeFileSync, readFileSync, statSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { Browser, BrowserContext } from '@playwright/test'\n\nconst STATES_DIR = join(homedir(), '.deepspace', 'playwright-states')\n\n/** Default freshness window — re-sign-in if the cache is older than this. */\nconst DEFAULT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 // 7 days\n\nfunction statePathForEmail(email: string): string {\n const hash = createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 24)\n return join(STATES_DIR, `${hash}.json`)\n}\n\nfunction ensureStatesDir() {\n if (!existsSync(STATES_DIR)) mkdirSync(STATES_DIR, { recursive: true })\n}\n\n/** Returns true if a cache file exists and is younger than `maxAgeMs`. */\nfunction isCacheFresh(path: string, maxAgeMs: number): boolean {\n if (!existsSync(path)) return false\n try {\n const age = Date.now() - statSync(path).mtimeMs\n return age < maxAgeMs\n } catch {\n return false\n }\n}\n\n/**\n * Sign `account` in by POSTing `/api/auth/sign-in/email` against\n * `baseURL` and capturing the resulting cookies. Returns the path to the\n * Playwright `storageState` JSON file.\n *\n * The browser-driven approach is intentional: we want the cookies set\n * on the same origin Playwright contexts will load from, otherwise the\n * Set-Cookie domain attribute won't match.\n */\nasync function signInAndSaveState(\n browser: Browser,\n account: { email: string; password: string },\n baseURL: string,\n outPath: string,\n): Promise<string> {\n ensureStatesDir()\n const ctx = await browser.newContext({ baseURL })\n try {\n const page = await ctx.newPage()\n // Hit the app first so the origin is established (some auth plugins\n // require a same-origin Origin header on sign-in).\n await page.goto('/')\n const ok = await page.evaluate(\n async ({ email, password }: { email: string; password: string }) => {\n const res = await fetch('/api/auth/sign-in/email', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email, password }),\n })\n return res.ok\n },\n account,\n )\n if (!ok) {\n throw new Error(\n `Sign-in failed for ${account.email}. Check the password is current; ` +\n `if the account was deleted on the server, re-create with ` +\n `\\`deepspace test-accounts create\\`.`,\n )\n }\n await ctx.storageState({ path: outPath })\n return outPath\n } finally {\n await ctx.close()\n }\n}\n\nexport interface EnsureStorageStateOptions {\n /** Max age of a cached state file before we re-sign-in. Default 7 days. */\n maxAgeMs?: number\n /** Force a fresh sign-in even if the cache is fresh. */\n force?: boolean\n}\n\n/**\n * Ensure a Playwright `storageState` file exists for `account` and\n * return its path. Signs in once if the cache is missing, stale, or\n * `force: true`.\n */\nexport async function ensureStorageState(\n browser: Browser,\n account: { email: string; password: string },\n baseURL: string,\n options: EnsureStorageStateOptions = {},\n): Promise<string> {\n const path = statePathForEmail(account.email)\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS\n\n if (!options.force && isCacheFresh(path, maxAgeMs)) {\n return path\n }\n\n return signInAndSaveState(browser, account, baseURL, path)\n}\n\n/**\n * Convenience: open a fresh `BrowserContext` for `account` using the\n * cached storage state (signing in if needed). The caller is responsible\n * for closing the context.\n */\nexport async function newSignedInContext(\n browser: Browser,\n account: { email: string; password: string },\n baseURL: string,\n options: EnsureStorageStateOptions = {},\n): Promise<BrowserContext> {\n const statePath = await ensureStorageState(browser, account, baseURL, options)\n return browser.newContext({ storageState: statePath, baseURL })\n}\n\n/** Read a cached storageState file (mostly for debugging). */\nexport function readCachedState(email: string): unknown | null {\n const path = statePathForEmail(email)\n if (!existsSync(path)) return null\n try {\n return JSON.parse(readFileSync(path, 'utf-8'))\n } catch {\n return null\n }\n}\n\n/** Where the cache for `email` lives. Useful for diagnostics. */\nexport function getStatePathForEmail(email: string): string {\n return statePathForEmail(email)\n}\n"],"mappings":";AA6BA,SAAS,QAAQ,gBAA8D;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AO,QAAQ;AAAA,MACf,MAAM,QAAQ,QAAQ,QAAQ,MAAM,MAAM,GAAG,EAAE,CAAC;AAAA,MAChD,QAAQ,QAAQ;AAAA,IAClB;AAAA,IACA,SAAS,YAAY;AACnB,YAAM,QAAQ,MAAM;AAAA,IACtB;AAAA,EACF;AACF;AAEO,IAAM,OAAO,SAAS,OAA4B;AAAA,EACvD,OAAO,OAAO,EAAE,SAAS,QAAQ,GAAG,QAAQ;AAC1C,QAAI,CAAC,SAAS;AACZ,YAAM,IAAI;AAAA,QACR;AAAA,MAGF;AAAA,IACF;AAEA,UAAM,WAAuC,CAAC;AAE9C,UAAM,UAAwB,OAAO,UAAU,YAAY;AACzD,YAAM,WAA0B,MAAM,QAAQ,QAAQ,IAClD,SAAS,IAAI,CAAC,SAAS,sBAAsB,IAAI,CAAC,IAClD,iBAAiB,UAAU,OAAO;AAEtC,YAAM,QAAQ,MAAM,QAAQ;AAAA,QAC1B,SAAS,IAAI,CAAC,SAAS,UAAU,SAAS,MAAM,OAAO,CAAC;AAAA,MAC1D;AACA,iBAAW,KAAK,MAAO,UAAS,KAAK,EAAE,OAAO;AAC9C,aAAO,MAAM,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,IAChC;AAEA,UAAM,IAAI,OAAO;AAIjB,eAAW,WAAW,UAAU;AAC9B,YAAM,QAAQ,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAChC;AAAA,EACF;AACF,CAAC;","names":["existsSync","readFileSync","homedir","join"]}
|
package/dist/worker.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as Y from 'yjs';
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
2
|
+
import { AnthropicProvider } from '@ai-sdk/anthropic';
|
|
3
|
+
import { OpenAIProvider } from '@ai-sdk/openai';
|
|
4
|
+
import { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';
|
|
5
5
|
import * as better_auth from 'better-auth';
|
|
6
6
|
import * as better_auth_plugins from 'better-auth/plugins';
|
|
7
7
|
|
|
@@ -2187,7 +2187,46 @@ declare function platformWorkerFetch(env: PlatformWorkerEnv, pathOrRequest: stri
|
|
|
2187
2187
|
*/
|
|
2188
2188
|
declare function authWorkerFetch(env: AuthWorkerEnv, path: string, init?: RequestInit): Promise<Response>;
|
|
2189
2189
|
|
|
2190
|
+
/**
|
|
2191
|
+
* AI provider helpers — create Vercel AI SDK providers that route through
|
|
2192
|
+
* the DeepSpace API worker proxy for per-user billing.
|
|
2193
|
+
*
|
|
2194
|
+
* Supported providers: anthropic, openai, cerebras.
|
|
2195
|
+
*
|
|
2196
|
+
* The API worker can be reached in two ways:
|
|
2197
|
+
* - Service binding `env.API_WORKER` (Cloudflare Fetcher) — preferred in
|
|
2198
|
+
* production if the app has declared the binding in wrangler.toml.
|
|
2199
|
+
* - HTTPS URL `env.API_WORKER_URL` — used in local dev and in production
|
|
2200
|
+
* for apps that don't declare the binding. `deepspace dev` writes this
|
|
2201
|
+
* into `.dev.vars` automatically.
|
|
2202
|
+
*
|
|
2203
|
+
* Auth is automatic by default:
|
|
2204
|
+
* - For server-side autonomous calls (cron, DO alarms, background agents),
|
|
2205
|
+
* the helper reads the long-lived `env.APP_OWNER_JWT` minted at deploy
|
|
2206
|
+
* time (or by `deepspace dev` in local development) and uses it for the
|
|
2207
|
+
* proxy auth header. The owner is billed automatically via the JWT sub.
|
|
2208
|
+
* - For user-initiated calls (e.g. an `/api/ai/chat` route handling a
|
|
2209
|
+
* browser request), pass `options.authToken` explicitly with the user's
|
|
2210
|
+
* own JWT so the call is billed to the user.
|
|
2211
|
+
*
|
|
2212
|
+
* Usage:
|
|
2213
|
+
*
|
|
2214
|
+
* // Server-side autonomous — no auth config needed
|
|
2215
|
+
* import { createDeepSpaceAI } from 'deepspace/worker'
|
|
2216
|
+
* const cerebras = createDeepSpaceAI(env, 'cerebras')
|
|
2217
|
+
* const result = await generateText({ model: cerebras('llama-3.3-70b'), ... })
|
|
2218
|
+
*
|
|
2219
|
+
* // User-initiated (inside a request handler)
|
|
2220
|
+
* const jwt = c.req.header('Authorization')!.slice(7)
|
|
2221
|
+
* const anthropic = createDeepSpaceAI(c.env, 'anthropic', { authToken: jwt })
|
|
2222
|
+
*/
|
|
2223
|
+
|
|
2190
2224
|
type Provider = 'anthropic' | 'openai' | 'cerebras';
|
|
2225
|
+
type ProviderReturn = {
|
|
2226
|
+
anthropic: AnthropicProvider;
|
|
2227
|
+
openai: OpenAIProvider;
|
|
2228
|
+
cerebras: OpenAICompatibleProvider;
|
|
2229
|
+
};
|
|
2191
2230
|
interface DeepSpaceAIEnv extends ApiWorkerEnv {
|
|
2192
2231
|
/**
|
|
2193
2232
|
* Long-lived owner-scoped JWT minted at deploy time (or by `deepspace dev`).
|
|
@@ -2215,7 +2254,7 @@ interface DeepSpaceAIOptions {
|
|
|
2215
2254
|
* (explicit or `env.APP_OWNER_JWT`) automatically. Throws a clear error if
|
|
2216
2255
|
* either is unconfigured.
|
|
2217
2256
|
*/
|
|
2218
|
-
declare function createDeepSpaceAI(env: DeepSpaceAIEnv, provider:
|
|
2257
|
+
declare function createDeepSpaceAI<P extends Provider>(env: DeepSpaceAIEnv, provider: P, options?: DeepSpaceAIOptions): ProviderReturn[P];
|
|
2219
2258
|
|
|
2220
2259
|
/**
|
|
2221
2260
|
* Auth types for the DeepSpace SDK.
|
package/dist/worker.js
CHANGED
|
@@ -5221,6 +5221,21 @@ function authWorkerFetch(env, path, init) {
|
|
|
5221
5221
|
}
|
|
5222
5222
|
|
|
5223
5223
|
// src/server/utils/ai.ts
|
|
5224
|
+
var ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS = 4096;
|
|
5225
|
+
function withDefaultAnthropicMaxTokens(body) {
|
|
5226
|
+
if (typeof body !== "string") return body;
|
|
5227
|
+
try {
|
|
5228
|
+
const parsed = JSON.parse(body);
|
|
5229
|
+
const hasExplicitLimit = typeof parsed.max_tokens === "number" || typeof parsed.max_completion_tokens === "number" || typeof parsed.max_output_tokens === "number";
|
|
5230
|
+
if (hasExplicitLimit) return body;
|
|
5231
|
+
return JSON.stringify({
|
|
5232
|
+
...parsed,
|
|
5233
|
+
max_tokens: ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
|
|
5234
|
+
});
|
|
5235
|
+
} catch {
|
|
5236
|
+
return body;
|
|
5237
|
+
}
|
|
5238
|
+
}
|
|
5224
5239
|
function createDeepSpaceAI(env, provider, options = {}) {
|
|
5225
5240
|
const transport = resolveApiTransport(env);
|
|
5226
5241
|
const authToken = options.authToken ?? env.APP_OWNER_JWT;
|
|
@@ -5235,12 +5250,17 @@ function createDeepSpaceAI(env, provider, options = {}) {
|
|
|
5235
5250
|
headers.delete("authorization");
|
|
5236
5251
|
headers.delete("x-api-key");
|
|
5237
5252
|
headers.set("X-Auth-Token", authToken);
|
|
5253
|
+
const body = provider === "anthropic" ? withDefaultAnthropicMaxTokens(init?.body) : init?.body;
|
|
5254
|
+
if (body !== init?.body) {
|
|
5255
|
+
headers.delete("content-length");
|
|
5256
|
+
}
|
|
5257
|
+
const nextInit = { ...init, headers, body };
|
|
5238
5258
|
if (transport.kind === "binding") {
|
|
5239
|
-
return transport.fetcher.fetch(url,
|
|
5259
|
+
return transport.fetcher.fetch(url, nextInit);
|
|
5240
5260
|
}
|
|
5241
5261
|
const original = new URL(url);
|
|
5242
5262
|
const rewritten = `${transport.baseUrl}${original.pathname}${original.search}`;
|
|
5243
|
-
return fetch(rewritten,
|
|
5263
|
+
return fetch(rewritten, nextInit);
|
|
5244
5264
|
};
|
|
5245
5265
|
const baseURL = `https://api-worker.internal/api/proxy/${provider}/v1`;
|
|
5246
5266
|
switch (provider) {
|