cooper-stack 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/dist/ai.d.ts +60 -0
- package/dist/ai.d.ts.map +1 -0
- package/dist/ai.js +66 -0
- package/dist/ai.js.map +1 -0
- package/dist/api.d.ts +31 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +40 -0
- package/dist/api.js.map +1 -0
- package/dist/auth.d.ts +13 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +16 -0
- package/dist/auth.js.map +1 -0
- package/dist/bridge.d.ts +15 -0
- package/dist/bridge.d.ts.map +1 -0
- package/dist/bridge.js +217 -0
- package/dist/bridge.js.map +1 -0
- package/dist/cache.d.ts +27 -0
- package/dist/cache.d.ts.map +1 -0
- package/dist/cache.js +69 -0
- package/dist/cache.js.map +1 -0
- package/dist/cron.d.ts +22 -0
- package/dist/cron.d.ts.map +1 -0
- package/dist/cron.js +26 -0
- package/dist/cron.js.map +1 -0
- package/dist/db.d.ts +46 -0
- package/dist/db.d.ts.map +1 -0
- package/dist/db.js +158 -0
- package/dist/db.js.map +1 -0
- package/dist/error.d.ts +18 -0
- package/dist/error.d.ts.map +1 -0
- package/dist/error.js +30 -0
- package/dist/error.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -0
- package/dist/islands.d.ts +16 -0
- package/dist/islands.d.ts.map +1 -0
- package/dist/islands.js +23 -0
- package/dist/islands.js.map +1 -0
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +26 -0
- package/dist/middleware.js.map +1 -0
- package/dist/nats.d.ts +46 -0
- package/dist/nats.d.ts.map +1 -0
- package/dist/nats.js +157 -0
- package/dist/nats.js.map +1 -0
- package/dist/pubsub.d.ts +27 -0
- package/dist/pubsub.d.ts.map +1 -0
- package/dist/pubsub.js +152 -0
- package/dist/pubsub.js.map +1 -0
- package/dist/queue.d.ts +39 -0
- package/dist/queue.d.ts.map +1 -0
- package/dist/queue.js +298 -0
- package/dist/queue.js.map +1 -0
- package/dist/rateLimit.d.ts +29 -0
- package/dist/rateLimit.d.ts.map +1 -0
- package/dist/rateLimit.js +70 -0
- package/dist/rateLimit.js.map +1 -0
- package/dist/registry.d.ts +75 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +41 -0
- package/dist/registry.js.map +1 -0
- package/dist/secrets.d.ts +10 -0
- package/dist/secrets.d.ts.map +1 -0
- package/dist/secrets.js +35 -0
- package/dist/secrets.js.map +1 -0
- package/dist/ssr.d.ts +53 -0
- package/dist/ssr.d.ts.map +1 -0
- package/dist/ssr.js +39 -0
- package/dist/ssr.js.map +1 -0
- package/dist/storage.d.ts +28 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +61 -0
- package/dist/storage.js.map +1 -0
- package/package.json +40 -0
- package/src/ai.ts +99 -0
- package/src/api.ts +56 -0
- package/src/auth.ts +16 -0
- package/src/bridge.ts +267 -0
- package/src/cache.ts +86 -0
- package/src/cron.ts +32 -0
- package/src/db.ts +211 -0
- package/src/error.ts +44 -0
- package/src/index.ts +17 -0
- package/src/islands.ts +28 -0
- package/src/middleware.ts +27 -0
- package/src/nats.ts +186 -0
- package/src/pubsub.ts +208 -0
- package/src/queue.ts +414 -0
- package/src/rateLimit.ts +89 -0
- package/src/registry.ts +98 -0
- package/src/secrets.ts +40 -0
- package/src/ssr.ts +58 -0
- package/src/storage.ts +79 -0
- package/tsconfig.json +17 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ssr.d.ts","sourceRoot":"","sources":["../src/ssr.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,GAAG,CAAC,EAAE,GAAG,CAAC;IACV,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ;AAED;;;;;;;;;GASG;AACH,wBAAgB,IAAI,CAAC,CAAC,GAAG,GAAG,EAC1B,MAAM,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,GACvC;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,MAAM,CAAA;CAAE,CAEjD;AAED;;;;;;;;GAQG;AACH,wBAAgB,MAAM,CAAC,CAAC,GAAG,GAAG,EAC5B,MAAM,EAAE,CAAC,KAAK,EAAE;IAAE,QAAQ,EAAE,GAAG,CAAA;CAAE,KAAK,CAAC,GACtC;IAAE,YAAY,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,OAAO,MAAM,CAAA;CAAE,CAEnD;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAC1B,MAAM,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC,CAAC,CAAC,GACvC;IAAE,YAAY,EAAE,QAAQ,CAAC;IAAC,MAAM,EAAE,OAAO,MAAM,CAAA;CAAE,CAEnD;AAED;;GAEG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE;IAAE,QAAQ,EAAE,GAAG,CAAC;IAAC,QAAQ,EAAE,GAAG,CAAA;CAAE,QAGhE"}
|
package/dist/ssr.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Define a server-rendered page.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* export default page(async ({ params }) => {
|
|
6
|
+
* const { user } = await UsersService.getUser({ id: params.id });
|
|
7
|
+
* return <div><h1>{user.name}</h1></div>;
|
|
8
|
+
* });
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export function page(render) {
|
|
12
|
+
return { _cooper_type: "page", render };
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Define a layout that wraps pages.
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* export default layout(({ children }) => (
|
|
19
|
+
* <div><Nav /><main>{children}</main><Footer /></div>
|
|
20
|
+
* ));
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export function layout(render) {
|
|
24
|
+
return { _cooper_type: "layout", render };
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Define a page data loader — runs on the server, data passed to the page.
|
|
28
|
+
*/
|
|
29
|
+
export function pageLoader(loader) {
|
|
30
|
+
return { _cooper_type: "loader", loader };
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Suspense boundary for streaming SSR.
|
|
34
|
+
*/
|
|
35
|
+
export function Suspense(_props) {
|
|
36
|
+
// Handled by the SSR renderer — this is a marker component
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=ssr.js.map
|
package/dist/ssr.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ssr.js","sourceRoot":"","sources":["../src/ssr.ts"],"names":[],"mappings":"AAWA;;;;;;;;;GASG;AACH,MAAM,UAAU,IAAI,CAClB,MAAwC;IAExC,OAAO,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC1C,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,MAAM,CACpB,MAAuC;IAEvC,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;AAC5C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CACxB,MAAwC;IAExC,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;AAC5C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAwC;IAC/D,2DAA2D;IAC3D,OAAO,IAAI,CAAC;AACd,CAAC"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface BucketConfig {
|
|
2
|
+
public?: boolean;
|
|
3
|
+
}
|
|
4
|
+
export interface BucketClient {
|
|
5
|
+
upload(key: string, data: Buffer | Uint8Array, opts?: {
|
|
6
|
+
contentType?: string;
|
|
7
|
+
}): Promise<void>;
|
|
8
|
+
download(key: string): Promise<Buffer>;
|
|
9
|
+
signedUrl(key: string, opts?: {
|
|
10
|
+
ttl?: string;
|
|
11
|
+
}): Promise<string>;
|
|
12
|
+
delete(key: string): Promise<void>;
|
|
13
|
+
list(prefix?: string): Promise<{
|
|
14
|
+
key: string;
|
|
15
|
+
size: number;
|
|
16
|
+
lastModified: Date;
|
|
17
|
+
}[]>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Declare an object storage bucket.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* export const avatars = bucket("avatars", { public: true });
|
|
24
|
+
* await avatars.upload("user-123/avatar.png", buffer, { contentType: "image/png" });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function bucket(name: string, config?: BucketConfig): BucketClient;
|
|
28
|
+
//# sourceMappingURL=storage.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.d.ts","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,EAAE,IAAI,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/F,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACvC,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACjE,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,IAAI,CAAA;KAAE,EAAE,CAAC,CAAC;CACrF;AAED;;;;;;;GAOG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,GAAG,YAAY,CA0DxE"}
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Declare an object storage bucket.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* export const avatars = bucket("avatars", { public: true });
|
|
6
|
+
* await avatars.upload("user-123/avatar.png", buffer, { contentType: "image/png" });
|
|
7
|
+
* ```
|
|
8
|
+
*/
|
|
9
|
+
export function bucket(name, config) {
|
|
10
|
+
const fs = require("node:fs");
|
|
11
|
+
const path = require("node:path");
|
|
12
|
+
// Local storage directory — in production this maps to S3/GCS/Azure Blob
|
|
13
|
+
const localDir = path.join(process.env.COOPER_STORAGE_DIR ?? ".cooper/storage", name);
|
|
14
|
+
return {
|
|
15
|
+
async upload(key, data, opts) {
|
|
16
|
+
const fullPath = path.join(localDir, key);
|
|
17
|
+
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
|
18
|
+
fs.writeFileSync(fullPath, data);
|
|
19
|
+
},
|
|
20
|
+
async download(key) {
|
|
21
|
+
const fullPath = path.join(localDir, key);
|
|
22
|
+
return fs.readFileSync(fullPath);
|
|
23
|
+
},
|
|
24
|
+
async signedUrl(key, opts) {
|
|
25
|
+
// In local dev, return a direct file path
|
|
26
|
+
// In production, generate a presigned S3/GCS URL
|
|
27
|
+
return `http://localhost:9400/storage/${name}/${key}`;
|
|
28
|
+
},
|
|
29
|
+
async delete(key) {
|
|
30
|
+
const fullPath = path.join(localDir, key);
|
|
31
|
+
if (fs.existsSync(fullPath))
|
|
32
|
+
fs.unlinkSync(fullPath);
|
|
33
|
+
},
|
|
34
|
+
async list(prefix) {
|
|
35
|
+
const dir = prefix ? path.join(localDir, prefix) : localDir;
|
|
36
|
+
if (!fs.existsSync(dir))
|
|
37
|
+
return [];
|
|
38
|
+
const entries = [];
|
|
39
|
+
const walk = (d, rel) => {
|
|
40
|
+
for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
|
|
41
|
+
const fullPath = path.join(d, entry.name);
|
|
42
|
+
const relPath = rel ? `${rel}/${entry.name}` : entry.name;
|
|
43
|
+
if (entry.isDirectory()) {
|
|
44
|
+
walk(fullPath, relPath);
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
const stat = fs.statSync(fullPath);
|
|
48
|
+
entries.push({
|
|
49
|
+
key: relPath,
|
|
50
|
+
size: stat.size,
|
|
51
|
+
lastModified: stat.mtime,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
walk(dir, "");
|
|
57
|
+
return entries;
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=storage.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage.js","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAYA;;;;;;;GAOG;AACH,MAAM,UAAU,MAAM,CAAC,IAAY,EAAE,MAAqB;IACxD,MAAM,EAAE,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAElC,yEAAyE;IACzE,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CACxB,OAAO,CAAC,GAAG,CAAC,kBAAkB,IAAI,iBAAiB,EACnD,IAAI,CACL,CAAC;IAEF,OAAO;QACL,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,IAAyB,EAAE,IAA+B;YAClF,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC1C,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAC1D,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACnC,CAAC;QAED,KAAK,CAAC,QAAQ,CAAC,GAAW;YACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC1C,OAAO,EAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QACnC,CAAC;QAED,KAAK,CAAC,SAAS,CAAC,GAAW,EAAE,IAAuB;YAClD,0CAA0C;YAC1C,iDAAiD;YACjD,OAAO,iCAAiC,IAAI,IAAI,GAAG,EAAE,CAAC;QACxD,CAAC;QAED,KAAK,CAAC,MAAM,CAAC,GAAW;YACtB,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC1C,IAAI,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;QACvD,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,MAAe;YACxB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;YAC5D,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC;gBAAE,OAAO,EAAE,CAAC;YAEnC,MAAM,OAAO,GAAwD,EAAE,CAAC;YACxE,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,GAAW,EAAE,EAAE;gBACtC,KAAK,MAAM,KAAK,IAAI,EAAE,CAAC,WAAW,CAAC,CAAC,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;oBAC/D,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;oBAC1C,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;oBAC1D,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;wBACxB,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;oBAC1B,CAAC;yBAAM,CAAC;wBACN,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;wBACnC,OAAO,CAAC,IAAI,CAAC;4BACX,GAAG,EAAE,OAAO;4BACZ,IAAI,EAAE,IAAI,CAAC,IAAI;4BACf,YAAY,EAAE,IAAI,CAAC,KAAK;yBACzB,CAAC,CAAC;oBACL,CAAC;gBACH,CAAC;YACH,CAAC,CAAC;YACF,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YACd,OAAO,OAAO,CAAC;QACjB,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "cooper-stack",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The backend framework for TypeScript",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./dist/index.js",
|
|
10
|
+
"./api": "./dist/api.js",
|
|
11
|
+
"./db": "./dist/db.js",
|
|
12
|
+
"./middleware": "./dist/middleware.js",
|
|
13
|
+
"./auth": "./dist/auth.js",
|
|
14
|
+
"./pubsub": "./dist/pubsub.js",
|
|
15
|
+
"./cron": "./dist/cron.js",
|
|
16
|
+
"./cache": "./dist/cache.js",
|
|
17
|
+
"./storage": "./dist/storage.js",
|
|
18
|
+
"./secrets": "./dist/secrets.js",
|
|
19
|
+
"./queue": "./dist/queue.js",
|
|
20
|
+
"./ssr": "./dist/ssr.js",
|
|
21
|
+
"./islands": "./dist/islands.js",
|
|
22
|
+
"./ai": "./dist/ai.js",
|
|
23
|
+
"./rateLimit": "./dist/rateLimit.js"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsc",
|
|
27
|
+
"dev": "tsc --watch"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"pg": "^8.13.0",
|
|
31
|
+
"mysql2": "^3.11.0",
|
|
32
|
+
"ioredis": "^5.4.0",
|
|
33
|
+
"nats": "^2.29.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"typescript": "^5.7.0",
|
|
37
|
+
"@types/node": "^22.0.0",
|
|
38
|
+
"@types/pg": "^8.11.0"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/ai.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
export interface VectorStoreConfig {
|
|
2
|
+
dimensions: number;
|
|
3
|
+
similarity?: "cosine" | "euclidean" | "dot";
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface VectorStoreClient {
|
|
7
|
+
upsert(id: string, vector: number[], metadata?: Record<string, any>): Promise<void>;
|
|
8
|
+
search(vector: number[], opts?: { topK?: number; filter?: Record<string, any> }): Promise<{ id: string; score: number; metadata?: any }[]>;
|
|
9
|
+
delete(id: string): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface LLMGatewayConfig {
|
|
13
|
+
primary: { provider: string; model: string };
|
|
14
|
+
fallback?: { provider: string; model: string };
|
|
15
|
+
budget?: { dailyLimit: string };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface LLMGatewayClient {
|
|
19
|
+
chat(messages: { role: string; content: string }[]): Promise<string>;
|
|
20
|
+
embed(text: string): Promise<number[]>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Declare a vector store.
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* export const embeddings = vectorStore("product-embeddings", {
|
|
28
|
+
* dimensions: 1536,
|
|
29
|
+
* similarity: "cosine",
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export function vectorStore(name: string, config: VectorStoreConfig): VectorStoreClient {
|
|
34
|
+
// Local dev: pgvector extension on embedded Postgres
|
|
35
|
+
// Production: Pinecone, Weaviate, or pgvector on managed Postgres
|
|
36
|
+
const store = new Map<string, { vector: number[]; metadata?: any }>();
|
|
37
|
+
|
|
38
|
+
const cosineSimilarity = (a: number[], b: number[]): number => {
|
|
39
|
+
let dot = 0, magA = 0, magB = 0;
|
|
40
|
+
for (let i = 0; i < a.length; i++) {
|
|
41
|
+
dot += a[i] * b[i];
|
|
42
|
+
magA += a[i] * a[i];
|
|
43
|
+
magB += b[i] * b[i];
|
|
44
|
+
}
|
|
45
|
+
return dot / (Math.sqrt(magA) * Math.sqrt(magB));
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
return {
|
|
49
|
+
async upsert(id, vector, metadata) {
|
|
50
|
+
store.set(id, { vector, metadata });
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
async search(vector, opts) {
|
|
54
|
+
const topK = opts?.topK ?? 10;
|
|
55
|
+
const results: { id: string; score: number; metadata?: any }[] = [];
|
|
56
|
+
|
|
57
|
+
for (const [id, entry] of store) {
|
|
58
|
+
const score = cosineSimilarity(vector, entry.vector);
|
|
59
|
+
results.push({ id, score, metadata: entry.metadata });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
results.sort((a, b) => b.score - a.score);
|
|
63
|
+
return results.slice(0, topK);
|
|
64
|
+
},
|
|
65
|
+
|
|
66
|
+
async delete(id) {
|
|
67
|
+
store.delete(id);
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Declare an LLM gateway with cost tracking and fallbacks.
|
|
74
|
+
*
|
|
75
|
+
* ```ts
|
|
76
|
+
* export const llm = llmGateway({
|
|
77
|
+
* primary: { provider: "openai", model: "gpt-4o" },
|
|
78
|
+
* fallback: { provider: "anthropic", model: "claude-sonnet-4-20250514" },
|
|
79
|
+
* budget: { dailyLimit: "$50" },
|
|
80
|
+
* });
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export function llmGateway(config: LLMGatewayConfig): LLMGatewayClient {
|
|
84
|
+
return {
|
|
85
|
+
async chat(messages) {
|
|
86
|
+
// Route to the configured provider
|
|
87
|
+
// Track cost, apply rate limits, handle fallback
|
|
88
|
+
throw new Error(
|
|
89
|
+
`LLM gateway not yet connected. Configure API keys via: cooper secrets set ${config.primary.provider}-api-key --env local`
|
|
90
|
+
);
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
async embed(text) {
|
|
94
|
+
throw new Error(
|
|
95
|
+
`LLM gateway not yet connected. Configure API keys via: cooper secrets set ${config.primary.provider}-api-key --env local`
|
|
96
|
+
);
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { registry, type MiddlewareFn } from "./registry.js";
|
|
2
|
+
import { CooperError } from "./error.js";
|
|
3
|
+
|
|
4
|
+
export interface ApiConfig {
|
|
5
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
6
|
+
path: string;
|
|
7
|
+
auth?: boolean;
|
|
8
|
+
stream?: "sse" | "websocket";
|
|
9
|
+
validate?: any; // Zod schema
|
|
10
|
+
middleware?: MiddlewareFn[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Define an API endpoint.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* export const getUser = api(
|
|
18
|
+
* { method: "GET", path: "/users/:id", auth: true },
|
|
19
|
+
* async ({ id }, principal) => {
|
|
20
|
+
* const user = await db.queryRow("SELECT * FROM users WHERE id = $1", [id]);
|
|
21
|
+
* if (!user) throw new CooperError("NOT_FOUND", "User not found");
|
|
22
|
+
* return { user };
|
|
23
|
+
* }
|
|
24
|
+
* );
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export function api<TInput = any, TOutput = any>(
|
|
28
|
+
config: ApiConfig,
|
|
29
|
+
handler: (input: TInput, principal?: any) => Promise<TOutput>
|
|
30
|
+
): { _cooper_type: "api"; config: ApiConfig; handler: typeof handler } {
|
|
31
|
+
const method = config.method ?? "GET";
|
|
32
|
+
const key = `${method}:${config.path}`;
|
|
33
|
+
|
|
34
|
+
const descriptor = {
|
|
35
|
+
_cooper_type: "api" as const,
|
|
36
|
+
config,
|
|
37
|
+
handler,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// Register for the bridge to find at runtime
|
|
41
|
+
registry.registerRoute(key, {
|
|
42
|
+
method,
|
|
43
|
+
path: config.path,
|
|
44
|
+
auth: config.auth ?? false,
|
|
45
|
+
stream: config.stream,
|
|
46
|
+
validate: config.validate,
|
|
47
|
+
middleware: config.middleware ?? [],
|
|
48
|
+
handler,
|
|
49
|
+
exportName: "", // filled in by bridge during module scan
|
|
50
|
+
sourceFile: "",
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
return descriptor;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export { CooperError };
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { registry, type AuthHandlerFn } from "./registry.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Register an auth handler that verifies tokens and returns a principal.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* export const auth = authHandler(async (token) => {
|
|
8
|
+
* const payload = await verifyJWT(token);
|
|
9
|
+
* return { userId: payload.sub, role: payload.role };
|
|
10
|
+
* });
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export function authHandler(handler: AuthHandlerFn) {
|
|
14
|
+
registry.setAuthHandler(handler);
|
|
15
|
+
return handler;
|
|
16
|
+
}
|
package/src/bridge.ts
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Cooper JS Worker Bridge
|
|
4
|
+
*
|
|
5
|
+
* Spawned by the Rust runtime as a subprocess. Communicates via
|
|
6
|
+
* JSON-RPC over stdin/stdout. Loads user TypeScript modules and
|
|
7
|
+
* executes handler functions on demand.
|
|
8
|
+
*
|
|
9
|
+
* Protocol:
|
|
10
|
+
* → { "id": 1, "method": "call", "params": { "source": "services/users/api.ts", "export": "getUser", "input": {...}, "auth": {...} } }
|
|
11
|
+
* ← { "id": 1, "result": {...} }
|
|
12
|
+
* ← { "id": 1, "error": { "code": "NOT_FOUND", "message": "User not found" } }
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { registry } from "./registry.js";
|
|
16
|
+
import { CooperError } from "./error.js";
|
|
17
|
+
import { createRequire } from "node:module";
|
|
18
|
+
import { createInterface } from "node:readline";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import { pathToFileURL } from "node:url";
|
|
21
|
+
|
|
22
|
+
const projectRoot = process.env.COOPER_PROJECT_ROOT ?? process.cwd();
|
|
23
|
+
|
|
24
|
+
// Module cache — avoid re-importing on every request
|
|
25
|
+
const moduleCache = new Map<string, any>();
|
|
26
|
+
|
|
27
|
+
async function loadModule(sourcePath: string): Promise<any> {
|
|
28
|
+
if (moduleCache.has(sourcePath)) return moduleCache.get(sourcePath)!;
|
|
29
|
+
|
|
30
|
+
const fullPath = path.resolve(projectRoot, sourcePath);
|
|
31
|
+
const fileUrl = pathToFileURL(fullPath).href;
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
const mod = await import(fileUrl);
|
|
35
|
+
moduleCache.set(sourcePath, mod);
|
|
36
|
+
return mod;
|
|
37
|
+
} catch (err: any) {
|
|
38
|
+
throw new Error(`Failed to load module "${sourcePath}": ${err.message}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface RPCRequest {
|
|
43
|
+
id: number;
|
|
44
|
+
method: string;
|
|
45
|
+
params: any;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface RPCResponse {
|
|
49
|
+
id: number;
|
|
50
|
+
result?: any;
|
|
51
|
+
error?: { code: string; message: string; statusCode?: number };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function handleCall(params: {
|
|
55
|
+
source: string;
|
|
56
|
+
export: string;
|
|
57
|
+
input: any;
|
|
58
|
+
auth?: any;
|
|
59
|
+
headers?: Record<string, string>;
|
|
60
|
+
}): Promise<any> {
|
|
61
|
+
const mod = await loadModule(params.source);
|
|
62
|
+
const exported = mod[params.export];
|
|
63
|
+
|
|
64
|
+
if (!exported) {
|
|
65
|
+
throw new CooperError("NOT_FOUND", `Export "${params.export}" not found in ${params.source}`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Get the handler function
|
|
69
|
+
let handler: Function;
|
|
70
|
+
let routeConfig: any = null;
|
|
71
|
+
|
|
72
|
+
if (exported._cooper_type === "api") {
|
|
73
|
+
handler = exported.handler;
|
|
74
|
+
routeConfig = exported.config;
|
|
75
|
+
} else if (typeof exported === "function") {
|
|
76
|
+
handler = exported;
|
|
77
|
+
} else {
|
|
78
|
+
throw new CooperError("INTERNAL", `Export "${params.export}" is not callable`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Validation — run Zod schema if present.
|
|
82
|
+
// Use passthrough() to preserve path params that aren't in the schema.
|
|
83
|
+
let validatedInput = params.input;
|
|
84
|
+
if (routeConfig?.validate) {
|
|
85
|
+
const schema = routeConfig.validate;
|
|
86
|
+
const lenient = typeof schema.passthrough === "function" ? schema.passthrough() : schema;
|
|
87
|
+
const result = lenient.safeParse(params.input);
|
|
88
|
+
if (!result.success) {
|
|
89
|
+
throw new CooperError(
|
|
90
|
+
"VALIDATION_FAILED",
|
|
91
|
+
result.error.issues.map((i: any) => `${i.path.join(".")}: ${i.message}`).join("; ")
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
validatedInput = result.data;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Auth — verify token and inject principal
|
|
98
|
+
let principal: any = undefined;
|
|
99
|
+
if (routeConfig?.auth) {
|
|
100
|
+
if (!params.auth?.token) {
|
|
101
|
+
throw new CooperError("UNAUTHORIZED", "Authentication required");
|
|
102
|
+
}
|
|
103
|
+
if (registry.authHandler) {
|
|
104
|
+
principal = await registry.authHandler(params.auth.token);
|
|
105
|
+
} else {
|
|
106
|
+
throw new CooperError("INTERNAL", "No auth handler registered");
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Middleware chain
|
|
111
|
+
const middlewares = [
|
|
112
|
+
...registry.globalMiddleware,
|
|
113
|
+
...(routeConfig?.middleware ?? []),
|
|
114
|
+
];
|
|
115
|
+
|
|
116
|
+
const req = {
|
|
117
|
+
...validatedInput,
|
|
118
|
+
headers: params.headers ?? {},
|
|
119
|
+
ip: params.headers?.["x-forwarded-for"] ?? "127.0.0.1",
|
|
120
|
+
method: routeConfig?.method ?? "GET",
|
|
121
|
+
path: routeConfig?.path ?? "/",
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// Build the middleware chain
|
|
125
|
+
let idx = 0;
|
|
126
|
+
const runMiddleware = async (currentReq: any): Promise<any> => {
|
|
127
|
+
if (idx < middlewares.length) {
|
|
128
|
+
const mw = middlewares[idx++];
|
|
129
|
+
return mw(currentReq, runMiddleware);
|
|
130
|
+
}
|
|
131
|
+
// End of chain — call the actual handler
|
|
132
|
+
if (routeConfig?.auth) {
|
|
133
|
+
return handler(validatedInput, principal);
|
|
134
|
+
}
|
|
135
|
+
return handler(validatedInput);
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
return runMiddleware(req);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function handleCron(params: { source: string; export: string }): Promise<any> {
|
|
142
|
+
const mod = await loadModule(params.source);
|
|
143
|
+
const exported = mod[params.export];
|
|
144
|
+
|
|
145
|
+
if (!exported) {
|
|
146
|
+
throw new CooperError("NOT_FOUND", `Cron "${params.export}" not found in ${params.source}`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (exported._cooper_type === "cron") {
|
|
150
|
+
// The cron was registered via the SDK, find it in the registry
|
|
151
|
+
const cronEntry = registry.crons.get(exported.name);
|
|
152
|
+
if (cronEntry) {
|
|
153
|
+
await cronEntry.handler();
|
|
154
|
+
return { ok: true };
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
throw new CooperError("INTERNAL", `Cannot execute cron "${params.export}"`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function handlePubSub(params: {
|
|
162
|
+
topic: string;
|
|
163
|
+
subscriber: string;
|
|
164
|
+
data: any;
|
|
165
|
+
}): Promise<any> {
|
|
166
|
+
const topicEntry = registry.topics.get(params.topic);
|
|
167
|
+
if (!topicEntry) {
|
|
168
|
+
throw new CooperError("NOT_FOUND", `Topic "${params.topic}" not registered`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const sub = topicEntry.subscribers.get(params.subscriber);
|
|
172
|
+
if (!sub) {
|
|
173
|
+
throw new CooperError("NOT_FOUND", `Subscriber "${params.subscriber}" not found on topic "${params.topic}"`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
await sub.handler(params.data);
|
|
177
|
+
return { ok: true };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function handleRequest(req: RPCRequest): Promise<RPCResponse> {
|
|
181
|
+
try {
|
|
182
|
+
let result: any;
|
|
183
|
+
|
|
184
|
+
switch (req.method) {
|
|
185
|
+
case "call":
|
|
186
|
+
result = await handleCall(req.params);
|
|
187
|
+
break;
|
|
188
|
+
case "cron":
|
|
189
|
+
result = await handleCron(req.params);
|
|
190
|
+
break;
|
|
191
|
+
case "pubsub":
|
|
192
|
+
result = await handlePubSub(req.params);
|
|
193
|
+
break;
|
|
194
|
+
case "ping":
|
|
195
|
+
result = { pong: true, pid: process.pid };
|
|
196
|
+
break;
|
|
197
|
+
case "invalidate":
|
|
198
|
+
// Clear module cache for hot reload
|
|
199
|
+
moduleCache.clear();
|
|
200
|
+
result = { ok: true };
|
|
201
|
+
break;
|
|
202
|
+
default:
|
|
203
|
+
throw new CooperError("INVALID_ARGUMENT", `Unknown method: ${req.method}`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return { id: req.id, result };
|
|
207
|
+
} catch (err: any) {
|
|
208
|
+
if (err instanceof CooperError) {
|
|
209
|
+
return {
|
|
210
|
+
id: req.id,
|
|
211
|
+
error: { code: err.code, message: err.message, statusCode: err.statusCode },
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
id: req.id,
|
|
216
|
+
error: { code: "INTERNAL", message: err.message ?? "Unknown error", statusCode: 500 },
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Main loop — read JSON lines from stdin, write responses to stdout
|
|
222
|
+
const rl = createInterface({ input: process.stdin });
|
|
223
|
+
|
|
224
|
+
rl.on("line", async (line) => {
|
|
225
|
+
if (!line.trim()) return;
|
|
226
|
+
|
|
227
|
+
try {
|
|
228
|
+
const req: RPCRequest = JSON.parse(line);
|
|
229
|
+
const res = await handleRequest(req);
|
|
230
|
+
process.stdout.write(JSON.stringify(res) + "\n");
|
|
231
|
+
} catch (err: any) {
|
|
232
|
+
process.stdout.write(
|
|
233
|
+
JSON.stringify({ id: 0, error: { code: "INTERNAL", message: `Bridge parse error: ${err.message}` } }) + "\n"
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
// Preload auth handlers and middleware — these register via side effects
|
|
239
|
+
async function preloadSideEffects() {
|
|
240
|
+
const fs = await import("node:fs");
|
|
241
|
+
const servicesDir = path.join(projectRoot, "services");
|
|
242
|
+
if (!fs.existsSync(servicesDir)) return;
|
|
243
|
+
|
|
244
|
+
const scanDir = (dir: string) => {
|
|
245
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
246
|
+
const fullPath = path.join(dir, entry.name);
|
|
247
|
+
if (entry.isDirectory()) {
|
|
248
|
+
scanDir(fullPath);
|
|
249
|
+
} else if (entry.name.endsWith(".ts") || entry.name.endsWith(".js")) {
|
|
250
|
+
try {
|
|
251
|
+
const content = fs.readFileSync(fullPath, "utf-8");
|
|
252
|
+
if (content.includes("authHandler") || content.includes("middleware(")) {
|
|
253
|
+
const relative = path.relative(projectRoot, fullPath);
|
|
254
|
+
loadModule(relative).catch(() => {});
|
|
255
|
+
}
|
|
256
|
+
} catch {}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
scanDir(servicesDir);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
await preloadSideEffects();
|
|
265
|
+
|
|
266
|
+
// Signal ready
|
|
267
|
+
process.stdout.write(JSON.stringify({ id: 0, result: { ready: true, pid: process.pid } }) + "\n");
|