@fonderie/core 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 +21 -0
- package/README.md +65 -0
- package/dist/config.cjs +33 -0
- package/dist/config.cjs.map +1 -0
- package/dist/config.d.cts +35 -0
- package/dist/config.d.ts +35 -0
- package/dist/config.js +8 -0
- package/dist/config.js.map +1 -0
- package/dist/index.cjs +371 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +30 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +335 -0
- package/dist/index.js.map +1 -0
- package/dist/middlewares/index.cjs +201 -0
- package/dist/middlewares/index.cjs.map +1 -0
- package/dist/middlewares/index.d.cts +23 -0
- package/dist/middlewares/index.d.ts +23 -0
- package/dist/middlewares/index.js +167 -0
- package/dist/middlewares/index.js.map +1 -0
- package/dist/parser.cjs +58 -0
- package/dist/parser.cjs.map +1 -0
- package/dist/parser.d.cts +7 -0
- package/dist/parser.d.ts +7 -0
- package/dist/parser.js +29 -0
- package/dist/parser.js.map +1 -0
- package/dist/response.cjs +58 -0
- package/dist/response.cjs.map +1 -0
- package/dist/response.d.cts +33 -0
- package/dist/response.d.ts +33 -0
- package/dist/response.js +32 -0
- package/dist/response.js.map +1 -0
- package/dist/types.cjs +19 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +75 -0
- package/dist/types.d.ts +75 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +1 -0
- package/package.json +85 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fonderie, Inc.
|
|
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 all
|
|
13
|
+
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 THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# @fonderie/core
|
|
2
|
+
|
|
3
|
+
The framework core every other `@fonderie-js` package builds on: a web-standard
|
|
4
|
+
request router, a composable middleware pipeline, a module system, and the
|
|
5
|
+
shared `IFonderieContext` that flows through all of it.
|
|
6
|
+
|
|
7
|
+
You can run it standalone — `FonderieApp` includes a Node HTTP server — or
|
|
8
|
+
mount it inside an existing Express, Hono, or Koa app via the adapter packages.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @fonderie/core
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Use
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { FonderieApp, defineConfig } from '@fonderie/core';
|
|
20
|
+
|
|
21
|
+
const app = new FonderieApp(defineConfig({ basePath: '/v1' }));
|
|
22
|
+
app.listen(3000, { name: 'my-api' });
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Built-in middlewares (CORS, request logging, auth guards, body parsing) live
|
|
26
|
+
under their own entry point so the root barrel stays lean:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { cors, requireAuth } from '@fonderie/core/middlewares';
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Also exported: `compose` for middleware composition, `HTTP`/`setApiResponse`
|
|
33
|
+
response helpers, and defensive parsers (`stringOrEmpty`, `numberOrZero`, …)
|
|
34
|
+
for untrusted input.
|
|
35
|
+
|
|
36
|
+
## The module system
|
|
37
|
+
|
|
38
|
+
Feature packages — [auth](https://github.com/fonderie-js/sdk/tree/main/packages/auth),
|
|
39
|
+
[workspaces](https://github.com/fonderie-js/sdk/tree/main/packages/workspaces),
|
|
40
|
+
[billing](https://github.com/fonderie-js/sdk/tree/main/packages/billing),
|
|
41
|
+
[courier](https://github.com/fonderie-js/sdk/tree/main/packages/courier), and
|
|
42
|
+
friends — implement `IFonderieModule` and register their routes, migrations,
|
|
43
|
+
and event handlers against this core. Pick the modules your product needs;
|
|
44
|
+
skip the rest.
|
|
45
|
+
|
|
46
|
+
## Why this exists
|
|
47
|
+
|
|
48
|
+
You've shipped this plumbing before — auth, teams, billing, messaging —
|
|
49
|
+
and the next project will ask for it again. Fonderie packages it once:
|
|
50
|
+
plain TypeScript modules for
|
|
51
|
+
[`@fonderie/core`](https://github.com/fonderie-js/sdk/tree/main/packages/core),
|
|
52
|
+
PostgreSQL-backed, self-hosted, MIT. No external control plane, no
|
|
53
|
+
per-seat anything. Register the modules you need; skip the ones you don't.
|
|
54
|
+
|
|
55
|
+
**This package owns** the contract. The router, middleware pipeline, request context, and
|
|
56
|
+
module lifecycle every other brick builds against. It depends on nothing;
|
|
57
|
+
everything depends on it.
|
|
58
|
+
|
|
59
|
+
Browse the whole set at
|
|
60
|
+
[fonderie-js/sdk](https://github.com/fonderie-js/sdk) · follow
|
|
61
|
+
[@fonderiejs](https://x.com/fonderiejs)
|
|
62
|
+
|
|
63
|
+
## License
|
|
64
|
+
|
|
65
|
+
MIT © Fonderie, Inc.
|
package/dist/config.cjs
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/config.ts
|
|
21
|
+
var config_exports = {};
|
|
22
|
+
__export(config_exports, {
|
|
23
|
+
defineConfig: () => defineConfig
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(config_exports);
|
|
26
|
+
function defineConfig(config) {
|
|
27
|
+
return config;
|
|
28
|
+
}
|
|
29
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
30
|
+
0 && (module.exports = {
|
|
31
|
+
defineConfig
|
|
32
|
+
});
|
|
33
|
+
//# sourceMappingURL=config.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["export interface IBillingPlan {\n\tname: string;\n\tprice: number | null; // null = custom/enterprise pricing\n\tseats: number | 'unlimited';\n\tinterval?: 'month' | 'year';\n\ttrialDays?: number;\n}\n\nexport interface ISMTPConfig {\n\thost: string;\n\tport: number;\n\tsecure: boolean; // true = TLS, false = STARTTLS\n\tuser: string;\n\tpass: string;\n}\n\nexport interface FonderieConfig {\n\tbasePath?: string; // e.g. '/v1' — prefixes all routes; defaults to ''\n\n\tdb: {\n\t\turl: string; // Standard postgres:// connection string\n\t\t// Future: adapter pattern for other vendors\n\t\t// adapter?: 'pg' | 'mysql2' | 'oracledb' ← v2 concern\n\t};\n\n\tbilling?: {\n\t\tprovider: 'stripe';\n\t\tplans: IBillingPlan[];\n\t\tstripeSecretKey: string;\n\t};\n\n\temail?: {\n\t\tfrom: string;\n\t\t// Credentials from their .env — Fonderie never stores these\n\t\tapiKey?: string;\n\t\tsmtp?: ISMTPConfig;\n\t\tprovider: 'resend' | 'ses' | 'smtp';\n\t};\n\n\tonError?: (err: unknown) => Response;\n}\n\nexport function defineConfig(config: FonderieConfig): FonderieConfig {\n\treturn config; // typed identity — same pattern as defineConfig in Vite/Nuxt\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA0CO,SAAS,aAAa,QAAwC;AACpE,SAAO;AACR;","names":[]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
interface IBillingPlan {
|
|
2
|
+
name: string;
|
|
3
|
+
price: number | null;
|
|
4
|
+
seats: number | 'unlimited';
|
|
5
|
+
interval?: 'month' | 'year';
|
|
6
|
+
trialDays?: number;
|
|
7
|
+
}
|
|
8
|
+
interface ISMTPConfig {
|
|
9
|
+
host: string;
|
|
10
|
+
port: number;
|
|
11
|
+
secure: boolean;
|
|
12
|
+
user: string;
|
|
13
|
+
pass: string;
|
|
14
|
+
}
|
|
15
|
+
interface FonderieConfig {
|
|
16
|
+
basePath?: string;
|
|
17
|
+
db: {
|
|
18
|
+
url: string;
|
|
19
|
+
};
|
|
20
|
+
billing?: {
|
|
21
|
+
provider: 'stripe';
|
|
22
|
+
plans: IBillingPlan[];
|
|
23
|
+
stripeSecretKey: string;
|
|
24
|
+
};
|
|
25
|
+
email?: {
|
|
26
|
+
from: string;
|
|
27
|
+
apiKey?: string;
|
|
28
|
+
smtp?: ISMTPConfig;
|
|
29
|
+
provider: 'resend' | 'ses' | 'smtp';
|
|
30
|
+
};
|
|
31
|
+
onError?: (err: unknown) => Response;
|
|
32
|
+
}
|
|
33
|
+
declare function defineConfig(config: FonderieConfig): FonderieConfig;
|
|
34
|
+
|
|
35
|
+
export { type FonderieConfig, type IBillingPlan, type ISMTPConfig, defineConfig };
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
interface IBillingPlan {
|
|
2
|
+
name: string;
|
|
3
|
+
price: number | null;
|
|
4
|
+
seats: number | 'unlimited';
|
|
5
|
+
interval?: 'month' | 'year';
|
|
6
|
+
trialDays?: number;
|
|
7
|
+
}
|
|
8
|
+
interface ISMTPConfig {
|
|
9
|
+
host: string;
|
|
10
|
+
port: number;
|
|
11
|
+
secure: boolean;
|
|
12
|
+
user: string;
|
|
13
|
+
pass: string;
|
|
14
|
+
}
|
|
15
|
+
interface FonderieConfig {
|
|
16
|
+
basePath?: string;
|
|
17
|
+
db: {
|
|
18
|
+
url: string;
|
|
19
|
+
};
|
|
20
|
+
billing?: {
|
|
21
|
+
provider: 'stripe';
|
|
22
|
+
plans: IBillingPlan[];
|
|
23
|
+
stripeSecretKey: string;
|
|
24
|
+
};
|
|
25
|
+
email?: {
|
|
26
|
+
from: string;
|
|
27
|
+
apiKey?: string;
|
|
28
|
+
smtp?: ISMTPConfig;
|
|
29
|
+
provider: 'resend' | 'ses' | 'smtp';
|
|
30
|
+
};
|
|
31
|
+
onError?: (err: unknown) => Response;
|
|
32
|
+
}
|
|
33
|
+
declare function defineConfig(config: FonderieConfig): FonderieConfig;
|
|
34
|
+
|
|
35
|
+
export { type FonderieConfig, type IBillingPlan, type ISMTPConfig, defineConfig };
|
package/dist/config.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config.ts"],"sourcesContent":["export interface IBillingPlan {\n\tname: string;\n\tprice: number | null; // null = custom/enterprise pricing\n\tseats: number | 'unlimited';\n\tinterval?: 'month' | 'year';\n\ttrialDays?: number;\n}\n\nexport interface ISMTPConfig {\n\thost: string;\n\tport: number;\n\tsecure: boolean; // true = TLS, false = STARTTLS\n\tuser: string;\n\tpass: string;\n}\n\nexport interface FonderieConfig {\n\tbasePath?: string; // e.g. '/v1' — prefixes all routes; defaults to ''\n\n\tdb: {\n\t\turl: string; // Standard postgres:// connection string\n\t\t// Future: adapter pattern for other vendors\n\t\t// adapter?: 'pg' | 'mysql2' | 'oracledb' ← v2 concern\n\t};\n\n\tbilling?: {\n\t\tprovider: 'stripe';\n\t\tplans: IBillingPlan[];\n\t\tstripeSecretKey: string;\n\t};\n\n\temail?: {\n\t\tfrom: string;\n\t\t// Credentials from their .env — Fonderie never stores these\n\t\tapiKey?: string;\n\t\tsmtp?: ISMTPConfig;\n\t\tprovider: 'resend' | 'ses' | 'smtp';\n\t};\n\n\tonError?: (err: unknown) => Response;\n}\n\nexport function defineConfig(config: FonderieConfig): FonderieConfig {\n\treturn config; // typed identity — same pattern as defineConfig in Vite/Nuxt\n}\n"],"mappings":";AA0CO,SAAS,aAAa,QAAwC;AACpE,SAAO;AACR;","names":[]}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
FonderieApp: () => FonderieApp,
|
|
24
|
+
HTTP: () => HTTP,
|
|
25
|
+
arrayOrEmpty: () => arrayOrEmpty,
|
|
26
|
+
booleanOrFalse: () => booleanOrFalse,
|
|
27
|
+
compose: () => compose,
|
|
28
|
+
dateOrEmpty: () => dateOrEmpty,
|
|
29
|
+
defineConfig: () => defineConfig,
|
|
30
|
+
numberOrZero: () => numberOrZero,
|
|
31
|
+
setApiResponse: () => setApiResponse,
|
|
32
|
+
stringOrEmpty: () => stringOrEmpty
|
|
33
|
+
});
|
|
34
|
+
module.exports = __toCommonJS(index_exports);
|
|
35
|
+
|
|
36
|
+
// src/app.ts
|
|
37
|
+
var import_node_os = require("os");
|
|
38
|
+
var import_node_http = require("http");
|
|
39
|
+
|
|
40
|
+
// src/router.ts
|
|
41
|
+
var Router = class {
|
|
42
|
+
routes = [];
|
|
43
|
+
add(method, path, handler) {
|
|
44
|
+
this.routes.push({ method: method.toUpperCase(), path, handler });
|
|
45
|
+
}
|
|
46
|
+
match(method, path) {
|
|
47
|
+
for (const route of this.routes) {
|
|
48
|
+
if (route.method !== method.toUpperCase()) {
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const params = matchPath(route.path, path);
|
|
52
|
+
if (params !== null) {
|
|
53
|
+
return { handler: route.handler, params };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
function matchPath(pattern, path) {
|
|
60
|
+
const clean = (path.split("?")[0] ?? path).replace(/\/$/, "") || "/";
|
|
61
|
+
const pp = pattern.split("/");
|
|
62
|
+
const vp = clean.split("/");
|
|
63
|
+
if (pp.length !== vp.length) {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
const params = {};
|
|
67
|
+
for (let i = 0; i < pp.length; i++) {
|
|
68
|
+
const ps = pp[i] ?? "";
|
|
69
|
+
const vs = vp[i] ?? "";
|
|
70
|
+
if (ps.startsWith(":")) {
|
|
71
|
+
params[ps.slice(1)] = decodeURIComponent(vs);
|
|
72
|
+
} else if (ps !== vs) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return params;
|
|
77
|
+
}
|
|
78
|
+
function routerMiddleware(router) {
|
|
79
|
+
return async (ctx, next) => {
|
|
80
|
+
const url = new URL(ctx.request.url);
|
|
81
|
+
const match = router.match(ctx.request.method, url.pathname);
|
|
82
|
+
if (!match) {
|
|
83
|
+
return next();
|
|
84
|
+
}
|
|
85
|
+
ctx.meta.params = match.params;
|
|
86
|
+
return match.handler(ctx, next);
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/compose.ts
|
|
91
|
+
function compose(middlewares) {
|
|
92
|
+
return function(ctx, fallback) {
|
|
93
|
+
let index = -1;
|
|
94
|
+
function dispatch(i) {
|
|
95
|
+
if (i <= index) {
|
|
96
|
+
throw new Error("next() called multiple times");
|
|
97
|
+
}
|
|
98
|
+
index = i;
|
|
99
|
+
const fn = middlewares[i] ?? fallback;
|
|
100
|
+
return fn(ctx, () => dispatch(i + 1));
|
|
101
|
+
}
|
|
102
|
+
return dispatch(0);
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// src/response.ts
|
|
107
|
+
var HTTP = {
|
|
108
|
+
OK: 200,
|
|
109
|
+
CREATED: 201,
|
|
110
|
+
ACCEPTED: 202,
|
|
111
|
+
NO_CONTENT: 204,
|
|
112
|
+
BAD_REQUEST: 400,
|
|
113
|
+
UNAUTHORIZED: 401,
|
|
114
|
+
PAYMENT_REQUIRED: 402,
|
|
115
|
+
FORBIDDEN: 403,
|
|
116
|
+
NOT_FOUND: 404,
|
|
117
|
+
CONFLICT: 409,
|
|
118
|
+
GONE: 410,
|
|
119
|
+
UNPROCESSABLE: 422,
|
|
120
|
+
TOO_MANY_REQUESTS: 429,
|
|
121
|
+
SERVER_ERROR: 500,
|
|
122
|
+
NOT_IMPLEMENTED: 501,
|
|
123
|
+
BAD_GATEWAY: 502,
|
|
124
|
+
SERVICE_UNAVAILABLE: 503
|
|
125
|
+
};
|
|
126
|
+
function setApiResponse(status, reason, explanation, payload) {
|
|
127
|
+
const body = { reason, explanation };
|
|
128
|
+
if (payload !== void 0) {
|
|
129
|
+
body[status < 400 ? "result" : "details"] = payload;
|
|
130
|
+
}
|
|
131
|
+
return Response.json(body, { status });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/middlewares/not-found.ts
|
|
135
|
+
function notFoundMiddleware() {
|
|
136
|
+
return async (_ctx, _next) => setApiResponse(HTTP.NOT_FOUND, "NOT_FOUND", "Not found");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// src/middlewares/body-parser.ts
|
|
140
|
+
var withBody = async (ctx, next) => {
|
|
141
|
+
const method = ctx.request.method.toUpperCase();
|
|
142
|
+
if (method === "GET" || method === "HEAD") {
|
|
143
|
+
return next();
|
|
144
|
+
}
|
|
145
|
+
const ct = ctx.request.headers.get("content-type") ?? "";
|
|
146
|
+
try {
|
|
147
|
+
if (ct.includes("application/json")) {
|
|
148
|
+
const text = (await ctx.request.clone().text()).trim();
|
|
149
|
+
ctx.meta.body = text ? JSON.parse(text) : {};
|
|
150
|
+
} else if (ct.includes("application/x-www-form-urlencoded")) {
|
|
151
|
+
const text = await ctx.request.clone().text();
|
|
152
|
+
ctx.meta.body = Object.fromEntries(new URLSearchParams(text));
|
|
153
|
+
}
|
|
154
|
+
} catch {
|
|
155
|
+
return setApiResponse(HTTP.BAD_REQUEST, "INVALID_REQUEST", "Invalid request body");
|
|
156
|
+
}
|
|
157
|
+
return next();
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// src/middlewares/error-handler.ts
|
|
161
|
+
function defaultErrorHandler(err) {
|
|
162
|
+
const dev = process.env["NODE_ENV"] !== "production";
|
|
163
|
+
if (err instanceof Error) {
|
|
164
|
+
console.error("[fonderie]", err.message, err.stack);
|
|
165
|
+
return setApiResponse(
|
|
166
|
+
HTTP.SERVER_ERROR,
|
|
167
|
+
"SERVER_ERROR",
|
|
168
|
+
dev ? err.message : "Internal server error"
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
console.error("[fonderie] unknown error", err);
|
|
172
|
+
return setApiResponse(HTTP.SERVER_ERROR, "SERVER_ERROR", "Internal server error");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/app.ts
|
|
176
|
+
var FonderieApp = class {
|
|
177
|
+
config;
|
|
178
|
+
prefix;
|
|
179
|
+
router = new Router();
|
|
180
|
+
middlewares = [];
|
|
181
|
+
modules = /* @__PURE__ */ new Map();
|
|
182
|
+
constructor(config) {
|
|
183
|
+
this.config = config;
|
|
184
|
+
this.prefix = (config.basePath ?? "").replace(/\/$/, "");
|
|
185
|
+
this.middlewares = [withBody];
|
|
186
|
+
}
|
|
187
|
+
listen(port, options = {}) {
|
|
188
|
+
const {
|
|
189
|
+
name = "Fonderie",
|
|
190
|
+
version = "0.0.1",
|
|
191
|
+
env = process.env["NODE_ENV"] ?? "development"
|
|
192
|
+
} = options;
|
|
193
|
+
(0, import_node_http.createServer)(async (req, res) => {
|
|
194
|
+
const host = req.headers.host ?? "localhost";
|
|
195
|
+
const url = `http://${host}${req.url ?? "/"}`;
|
|
196
|
+
const headers = new Headers();
|
|
197
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
198
|
+
if (!value) {
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
Array.isArray(value) ? value.forEach((v) => headers.append(key, v)) : headers.set(key, value);
|
|
202
|
+
}
|
|
203
|
+
const body = await new Promise((resolve, reject) => {
|
|
204
|
+
const chunks = [];
|
|
205
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
206
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
207
|
+
req.on("error", reject);
|
|
208
|
+
});
|
|
209
|
+
const method = req.method ?? "GET";
|
|
210
|
+
const hasBody = !["GET", "HEAD"].includes(method.toUpperCase());
|
|
211
|
+
const request = new Request(url, {
|
|
212
|
+
method,
|
|
213
|
+
headers,
|
|
214
|
+
body: hasBody && body.length > 0 ? new Uint8Array(body) : null
|
|
215
|
+
});
|
|
216
|
+
const response = await this.handle(request);
|
|
217
|
+
res.statusCode = response.status;
|
|
218
|
+
response.headers.forEach((v, k) => res.setHeader(k, v));
|
|
219
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
220
|
+
}).listen(port, () => {
|
|
221
|
+
const ip = getLocalIPv4();
|
|
222
|
+
const mode = env.includes("dev") ? "development" : "production";
|
|
223
|
+
console.log(
|
|
224
|
+
`
|
|
225
|
+
\u0192 ${name} v${version} ${mode}
|
|
226
|
+
|
|
227
|
+
Local http://localhost:${port}
|
|
228
|
+
Network http://${ip}:${port}
|
|
229
|
+
`
|
|
230
|
+
);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
// ─── Module registration ───────────────────────────────
|
|
234
|
+
register(module2) {
|
|
235
|
+
this.modules.set(module2.name, module2);
|
|
236
|
+
return this;
|
|
237
|
+
}
|
|
238
|
+
async boot() {
|
|
239
|
+
for (const module2 of topoSort([...this.modules.values()])) {
|
|
240
|
+
await module2.install(this);
|
|
241
|
+
}
|
|
242
|
+
return this;
|
|
243
|
+
}
|
|
244
|
+
// Runs global middleware only (no routing, no 404).
|
|
245
|
+
// Adapter packages call this to populate user/workspace/meta into their
|
|
246
|
+
// native context before handing off to user-defined route handlers.
|
|
247
|
+
async buildContext(request) {
|
|
248
|
+
const ctx = {
|
|
249
|
+
request,
|
|
250
|
+
tenant: null,
|
|
251
|
+
user: null,
|
|
252
|
+
workspace: null,
|
|
253
|
+
meta: { _buildContext: true },
|
|
254
|
+
_router: this.router
|
|
255
|
+
};
|
|
256
|
+
await compose(this.middlewares)(ctx, async () => new Response());
|
|
257
|
+
delete ctx.meta["_buildContext"];
|
|
258
|
+
return ctx;
|
|
259
|
+
}
|
|
260
|
+
// ─── Middleware ────────────────────────────────────────
|
|
261
|
+
use(middleware) {
|
|
262
|
+
this.middlewares.push(middleware);
|
|
263
|
+
return this;
|
|
264
|
+
}
|
|
265
|
+
// Modules call this to register their routes
|
|
266
|
+
addRoute(method, path, ...handlers) {
|
|
267
|
+
this.router.add(method, this.prefix + path, compose(handlers));
|
|
268
|
+
}
|
|
269
|
+
// ─── The core handler ──────────────────────────────────
|
|
270
|
+
// This is the ONE thing every adapter calls.
|
|
271
|
+
// Takes a Web Standard Request, returns a Web Standard Response.
|
|
272
|
+
async handle(request) {
|
|
273
|
+
const ctx = {
|
|
274
|
+
request,
|
|
275
|
+
tenant: null,
|
|
276
|
+
user: null,
|
|
277
|
+
workspace: null,
|
|
278
|
+
meta: {},
|
|
279
|
+
_router: this.router
|
|
280
|
+
};
|
|
281
|
+
const pipeline = compose([
|
|
282
|
+
...this.middlewares,
|
|
283
|
+
routerMiddleware(this.router),
|
|
284
|
+
notFoundMiddleware()
|
|
285
|
+
]);
|
|
286
|
+
try {
|
|
287
|
+
return await pipeline(ctx, async () => new Response("Not Found", { status: 404 }));
|
|
288
|
+
} catch (err) {
|
|
289
|
+
return this.config.onError?.(err) ?? defaultErrorHandler(err);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
function topoSort(modules) {
|
|
294
|
+
const byName = new Map(modules.map((m) => [m.name, m]));
|
|
295
|
+
const result = [];
|
|
296
|
+
const visited = /* @__PURE__ */ new Set();
|
|
297
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
298
|
+
function visit(m, path) {
|
|
299
|
+
if (visited.has(m.name)) return;
|
|
300
|
+
if (visiting.has(m.name)) {
|
|
301
|
+
throw new Error(`[fonderie] circular dependency: ${[...path, m.name].join(" \u2192 ")}`);
|
|
302
|
+
}
|
|
303
|
+
visiting.add(m.name);
|
|
304
|
+
for (const dep of m.deps ?? []) {
|
|
305
|
+
const found = byName.get(dep);
|
|
306
|
+
if (!found)
|
|
307
|
+
throw new Error(`[fonderie] "${m.name}" requires "${dep}" but it is not registered`);
|
|
308
|
+
visit(found, [...path, m.name]);
|
|
309
|
+
}
|
|
310
|
+
visiting.delete(m.name);
|
|
311
|
+
visited.add(m.name);
|
|
312
|
+
result.push(m);
|
|
313
|
+
}
|
|
314
|
+
for (const m of modules) visit(m, []);
|
|
315
|
+
return result;
|
|
316
|
+
}
|
|
317
|
+
function getLocalIPv4() {
|
|
318
|
+
const nets = (0, import_node_os.networkInterfaces)();
|
|
319
|
+
for (const interfaces of Object.values(nets)) {
|
|
320
|
+
if (!interfaces) {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
for (const iface of interfaces) {
|
|
324
|
+
if (iface.family === "IPv4" && !iface.internal) {
|
|
325
|
+
return iface.address;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return "127.0.0.1";
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// src/config.ts
|
|
333
|
+
function defineConfig(config) {
|
|
334
|
+
return config;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// src/parser.ts
|
|
338
|
+
function stringOrEmpty(value) {
|
|
339
|
+
return typeof value === "string" ? value : "";
|
|
340
|
+
}
|
|
341
|
+
function booleanOrFalse(value) {
|
|
342
|
+
if (typeof value === "boolean") return value;
|
|
343
|
+
if (value === "true" || value === "1") return true;
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
function arrayOrEmpty(value) {
|
|
347
|
+
return Array.isArray(value) ? value : [];
|
|
348
|
+
}
|
|
349
|
+
function numberOrZero(value) {
|
|
350
|
+
const n = Number(value);
|
|
351
|
+
return Number.isFinite(n) ? n : 0;
|
|
352
|
+
}
|
|
353
|
+
function dateOrEmpty(value) {
|
|
354
|
+
if (typeof value === "string") return value;
|
|
355
|
+
if (value instanceof Date) return value.toISOString();
|
|
356
|
+
return "";
|
|
357
|
+
}
|
|
358
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
359
|
+
0 && (module.exports = {
|
|
360
|
+
FonderieApp,
|
|
361
|
+
HTTP,
|
|
362
|
+
arrayOrEmpty,
|
|
363
|
+
booleanOrFalse,
|
|
364
|
+
compose,
|
|
365
|
+
dateOrEmpty,
|
|
366
|
+
defineConfig,
|
|
367
|
+
numberOrZero,
|
|
368
|
+
setApiResponse,
|
|
369
|
+
stringOrEmpty
|
|
370
|
+
});
|
|
371
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/app.ts","../src/router.ts","../src/compose.ts","../src/response.ts","../src/middlewares/not-found.ts","../src/middlewares/body-parser.ts","../src/middlewares/error-handler.ts","../src/config.ts","../src/parser.ts"],"sourcesContent":["// ── Public API ───────────────────────────────────────────────────\nexport type {\n\tITenant,\n\tIRouter,\n\tIAuthUser,\n\tMiddleware,\n\tIWorkspace,\n\tIRouteMatch,\n\tIFonderieApp,\n\tIFonderieModule,\n\tIFonderieContext,\n\tICourierMessage,\n\tIFonderieContextMeta,\n} from './types';\n\nexport { FonderieApp } from './app';\nexport { defineConfig } from './config';\nexport { compose } from './compose';\nexport type { FonderieConfig } from './config';\n\n// Built-in middleware — import from '@fonderie/core/middlewares', not the root barrel\n\n// Parser utilities\nexport { stringOrEmpty, booleanOrFalse, arrayOrEmpty, numberOrZero, dateOrEmpty } from './parser';\n\n// Response helpers\nexport type { IApiError, HttpStatus } from './response';\nexport { HTTP, setApiResponse } from './response';\n\n// NOT exported: adapters/, router internals, error-handler, not-found\n// Those are consumed by FonderieApp, never by users directly\n","import { networkInterfaces } from 'node:os';\nimport { createServer } from 'node:http';\n\nimport type { Middleware, IFonderieApp, IFonderieContext, IFonderieModule } from './types';\nimport type { FonderieConfig } from './config';\nimport { Router, routerMiddleware } from './router';\nimport { compose } from './compose';\nimport { notFoundMiddleware, defaultErrorHandler } from './middlewares';\nimport { withBody } from './middlewares/body-parser';\n\nexport class FonderieApp {\n\tprivate config: FonderieConfig;\n\tprivate prefix: string;\n\tprivate router: Router = new Router();\n\tprivate middlewares: Middleware[] = [];\n\tprivate modules: Map<string, IFonderieModule> = new Map();\n\n\tconstructor(config: FonderieConfig) {\n\t\tthis.config = config;\n\t\tthis.prefix = (config.basePath ?? '').replace(/\\/$/, '');\n\t\tthis.middlewares = [withBody];\n\t}\n\n\tlisten(\n\t\tport: number,\n\t\toptions: {\n\t\t\tname?: string;\n\t\t\tversion?: string;\n\t\t\tenv?: string;\n\t\t} = {},\n\t): void {\n\t\tconst {\n\t\t\tname = 'Fonderie',\n\t\t\tversion = '0.0.1',\n\t\t\tenv = process.env['NODE_ENV'] ?? 'development',\n\t\t} = options;\n\n\t\tcreateServer(async (req, res) => {\n\t\t\tconst host = req.headers.host ?? 'localhost';\n\t\t\tconst url = `http://${host}${req.url ?? '/'}`;\n\t\t\tconst headers = new Headers();\n\n\t\t\tfor (const [key, value] of Object.entries(req.headers)) {\n\t\t\t\tif (!value) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tArray.isArray(value)\n\t\t\t\t\t? value.forEach((v) => headers.append(key, v))\n\t\t\t\t\t: headers.set(key, value);\n\t\t\t}\n\n\t\t\t// Read the body stream — this was missing\n\t\t\tconst body = await new Promise<Buffer>((resolve, reject) => {\n\t\t\t\tconst chunks: Buffer[] = [];\n\t\t\t\treq.on('data', (chunk: Buffer) => chunks.push(chunk));\n\t\t\t\treq.on('end', () => resolve(Buffer.concat(chunks)));\n\t\t\t\treq.on('error', reject);\n\t\t\t});\n\n\t\t\tconst method = req.method ?? 'GET';\n\t\t\tconst hasBody = !['GET', 'HEAD'].includes(method.toUpperCase());\n\n\t\t\tconst request = new Request(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders,\n\t\t\t\tbody: hasBody && body.length > 0 ? new Uint8Array(body) : null,\n\t\t\t});\n\n\t\t\tconst response = await this.handle(request);\n\n\t\t\tres.statusCode = response.status;\n\t\t\tresponse.headers.forEach((v, k) => res.setHeader(k, v));\n\t\t\tres.end(Buffer.from(await response.arrayBuffer()));\n\t\t}).listen(port, () => {\n\t\t\tconst ip = getLocalIPv4();\n\t\t\tconst mode = env.includes('dev') ? 'development' : 'production';\n\n\t\t\tconsole.log(\n\t\t\t\t`\\n ƒ ${name} v${version} ${mode}\\n` +\n\t\t\t\t\t`\\n Local http://localhost:${port}` +\n\t\t\t\t\t`\\n Network http://${ip}:${port}\\n`,\n\t\t\t);\n\t\t});\n\t}\n\n\t// ─── Module registration ───────────────────────────────\n\n\tregister(module: IFonderieModule): this {\n\t\tthis.modules.set(module.name, module);\n\t\treturn this;\n\t}\n\n\tasync boot(): Promise<this> {\n\t\tfor (const module of topoSort([...this.modules.values()])) {\n\t\t\tawait module.install(this);\n\t\t}\n\t\treturn this;\n\t}\n\n\t// Runs global middleware only (no routing, no 404).\n\t// Adapter packages call this to populate user/workspace/meta into their\n\t// native context before handing off to user-defined route handlers.\n\tasync buildContext(request: Request): Promise<IFonderieContext> {\n\t\tconst ctx: IFonderieContext = {\n\t\t\trequest,\n\t\t\ttenant: null,\n\t\t\tuser: null,\n\t\t\tworkspace: null,\n\t\t\tmeta: { _buildContext: true },\n\t\t\t_router: this.router,\n\t\t};\n\t\tawait compose(this.middlewares)(ctx, async () => new Response());\n\t\tdelete ctx.meta['_buildContext'];\n\t\treturn ctx;\n\t}\n\n\t// ─── Middleware ────────────────────────────────────────\n\n\tuse(middleware: Middleware): this {\n\t\tthis.middlewares.push(middleware);\n\t\treturn this;\n\t}\n\n\t// Modules call this to register their routes\n\taddRoute(method: string, path: string, ...handlers: Middleware[]): void {\n\t\tthis.router.add(method, this.prefix + path, compose(handlers));\n\t}\n\n\t// ─── The core handler ──────────────────────────────────\n\t// This is the ONE thing every adapter calls.\n\t// Takes a Web Standard Request, returns a Web Standard Response.\n\n\tasync handle(request: Request): Promise<Response> {\n\t\tconst ctx: IFonderieContext = {\n\t\t\trequest,\n\t\t\ttenant: null,\n\t\t\tuser: null,\n\t\t\tworkspace: null,\n\t\t\tmeta: {},\n\t\t\t_router: this.router,\n\t\t};\n\n\t\t// Build the pipeline: global middleware → router → 404\n\t\tconst pipeline = compose([\n\t\t\t...this.middlewares,\n\t\t\trouterMiddleware(this.router),\n\t\t\tnotFoundMiddleware(),\n\t\t]);\n\n\t\ttry {\n\t\t\treturn await pipeline(ctx, async () => new Response('Not Found', { status: 404 }));\n\t\t} catch (err) {\n\t\t\treturn this.config.onError?.(err) ?? defaultErrorHandler(err);\n\t\t}\n\t}\n}\n// Framework adapters live in their own packages — no framework deps in core:\n// @fonderie/adapter-hono\n// @fonderie/adapter-express\n// @fonderie/adapter-koa\n\nfunction topoSort(modules: IFonderieModule[]): IFonderieModule[] {\n\tconst byName = new Map(modules.map((m) => [m.name, m]));\n\tconst result: IFonderieModule[] = [];\n\tconst visited = new Set<string>();\n\tconst visiting = new Set<string>();\n\n\tfunction visit(m: IFonderieModule, path: string[]): void {\n\t\tif (visited.has(m.name)) return;\n\t\tif (visiting.has(m.name)) {\n\t\t\tthrow new Error(`[fonderie] circular dependency: ${[...path, m.name].join(' → ')}`);\n\t\t}\n\t\tvisiting.add(m.name);\n\t\tfor (const dep of m.deps ?? []) {\n\t\t\tconst found = byName.get(dep);\n\t\t\tif (!found)\n\t\t\t\tthrow new Error(`[fonderie] \"${m.name}\" requires \"${dep}\" but it is not registered`);\n\t\t\tvisit(found, [...path, m.name]);\n\t\t}\n\t\tvisiting.delete(m.name);\n\t\tvisited.add(m.name);\n\t\tresult.push(m);\n\t}\n\n\tfor (const m of modules) visit(m, []);\n\treturn result;\n}\n\nfunction getLocalIPv4(): string {\n\tconst nets = networkInterfaces();\n\n\tfor (const interfaces of Object.values(nets)) {\n\t\tif (!interfaces) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (const iface of interfaces) {\n\t\t\tif (iface.family === 'IPv4' && !iface.internal) {\n\t\t\t\treturn iface.address;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn '127.0.0.1'; // fallback if no external interface found\n}\n","import type { IRouter, Middleware, IRouteMatch, IFonderieContext } from './types';\n\nexport class Router implements IRouter {\n\tprivate routes: Array<{ method: string; path: string; handler: Middleware }> = [];\n\n\tadd(method: string, path: string, handler: Middleware): void {\n\t\tthis.routes.push({ method: method.toUpperCase(), path, handler });\n\t}\n\n\tmatch(method: string, path: string): IRouteMatch | null {\n\t\tfor (const route of this.routes) {\n\t\t\tif (route.method !== method.toUpperCase()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst params = matchPath(route.path, path);\n\t\t\tif (params !== null) {\n\t\t\t\treturn { handler: route.handler, params };\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}\n\n// Segment-by-segment match with :param extraction\n// /users/:id matches /users/42 → { id: '42' }\nfunction matchPath(pattern: string, path: string): Record<string, string> | null {\n\tconst clean = (path.split('?')[0] ?? path).replace(/\\/$/, '') || '/'; // strip query string and trailing slash\n\tconst pp = pattern.split('/');\n\tconst vp = clean.split('/');\n\n\tif (pp.length !== vp.length) {\n\t\treturn null;\n\t}\n\n\tconst params: Record<string, string> = {};\n\n\tfor (let i = 0; i < pp.length; i++) {\n\t\tconst ps = pp[i] ?? '';\n\t\tconst vs = vp[i] ?? '';\n\t\tif (ps.startsWith(':')) {\n\t\t\tparams[ps.slice(1)] = decodeURIComponent(vs);\n\t\t} else if (ps !== vs) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\treturn params;\n}\n\n// Middleware that runs the router inside the pipeline\nexport function routerMiddleware(router: Router): Middleware {\n\treturn async (ctx: IFonderieContext, next) => {\n\t\tconst url = new URL(ctx.request.url);\n\t\tconst match = router.match(ctx.request.method, url.pathname);\n\n\t\tif (!match) {\n\t\t\treturn next();\n\t\t}\n\n\t\t// Route params available to handlers via ctx.meta.params\n\t\tctx.meta.params = match.params;\n\t\treturn match.handler(ctx, next);\n\t};\n}\n","import type { IFonderieContext, Middleware } from './types';\n\n// Classic onion middleware compose — same pattern as Koa's\nexport function compose(middlewares: Middleware[]) {\n\treturn function (ctx: IFonderieContext, fallback: () => Promise<Response>): Promise<Response> {\n\t\tlet index = -1;\n\n\t\tfunction dispatch(i: number): Promise<Response> {\n\t\t\tif (i <= index) {\n\t\t\t\tthrow new Error('next() called multiple times');\n\t\t\t}\n\t\t\tindex = i;\n\t\t\tconst fn = middlewares[i] ?? fallback;\n\t\t\treturn fn(ctx, () => dispatch(i + 1));\n\t\t}\n\n\t\treturn dispatch(0);\n\t};\n}\n","export const HTTP = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tUNPROCESSABLE: 422,\n\tTOO_MANY_REQUESTS: 429,\n\tSERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n} as const;\n\nexport type HttpStatus = (typeof HTTP)[keyof typeof HTTP];\n\nexport interface IApiEnvelope {\n\treason: string;\n\texplanation: string;\n\tresult?: unknown;\n}\n\nexport interface IApiError {\n\treason: string;\n\texplanation: string;\n\tdetails?: unknown;\n}\n\nexport function setApiResponse<T>(\n\tstatus: number,\n\treason: string,\n\texplanation: string,\n\tpayload?: T,\n): Response {\n\tconst body: Record<string, unknown> = { reason, explanation };\n\tif (payload !== undefined) {\n\t\tbody[status < 400 ? 'result' : 'details'] = payload;\n\t}\n\treturn Response.json(body, { status });\n}\n","import { setApiResponse, HTTP } from '../response';\nimport type { Middleware } from '../types';\n\nexport function notFoundMiddleware(): Middleware {\n\treturn async (_ctx, _next) => setApiResponse(HTTP.NOT_FOUND, 'NOT_FOUND', 'Not found');\n}\n","import type { Middleware } from '../types';\nimport { setApiResponse, HTTP } from '../response';\n\nexport const withBody: Middleware = async (ctx, next) => {\n\tconst method = ctx.request.method.toUpperCase();\n\n\tif (method === 'GET' || method === 'HEAD') {\n\t\treturn next();\n\t}\n\n\tconst ct = ctx.request.headers.get('content-type') ?? '';\n\n\ttry {\n\t\tif (ct.includes('application/json')) {\n\t\t\tconst text = (await ctx.request.clone().text()).trim();\n\t\t\tctx.meta.body = text ? JSON.parse(text) : {};\n\t\t} else if (ct.includes('application/x-www-form-urlencoded')) {\n\t\t\tconst text = await ctx.request.clone().text();\n\t\t\tctx.meta.body = Object.fromEntries(new URLSearchParams(text));\n\t\t}\n\t\t// multipart/form-data left to the handler — no dep-free way to parse it\n\t} catch {\n\t\treturn setApiResponse(HTTP.BAD_REQUEST, 'INVALID_REQUEST', 'Invalid request body');\n\t}\n\n\treturn next();\n};\n","import { setApiResponse, HTTP } from '../response';\n\nexport function defaultErrorHandler(err: unknown): Response {\n\tconst dev = process.env['NODE_ENV'] !== 'production';\n\n\tif (err instanceof Error) {\n\t\tconsole.error('[fonderie]', err.message, err.stack);\n\t\treturn setApiResponse(\n\t\t\tHTTP.SERVER_ERROR,\n\t\t\t'SERVER_ERROR',\n\t\t\tdev ? err.message : 'Internal server error',\n\t\t);\n\t}\n\n\tconsole.error('[fonderie] unknown error', err);\n\treturn setApiResponse(HTTP.SERVER_ERROR, 'SERVER_ERROR', 'Internal server error');\n}\n","export interface IBillingPlan {\n\tname: string;\n\tprice: number | null; // null = custom/enterprise pricing\n\tseats: number | 'unlimited';\n\tinterval?: 'month' | 'year';\n\ttrialDays?: number;\n}\n\nexport interface ISMTPConfig {\n\thost: string;\n\tport: number;\n\tsecure: boolean; // true = TLS, false = STARTTLS\n\tuser: string;\n\tpass: string;\n}\n\nexport interface FonderieConfig {\n\tbasePath?: string; // e.g. '/v1' — prefixes all routes; defaults to ''\n\n\tdb: {\n\t\turl: string; // Standard postgres:// connection string\n\t\t// Future: adapter pattern for other vendors\n\t\t// adapter?: 'pg' | 'mysql2' | 'oracledb' ← v2 concern\n\t};\n\n\tbilling?: {\n\t\tprovider: 'stripe';\n\t\tplans: IBillingPlan[];\n\t\tstripeSecretKey: string;\n\t};\n\n\temail?: {\n\t\tfrom: string;\n\t\t// Credentials from their .env — Fonderie never stores these\n\t\tapiKey?: string;\n\t\tsmtp?: ISMTPConfig;\n\t\tprovider: 'resend' | 'ses' | 'smtp';\n\t};\n\n\tonError?: (err: unknown) => Response;\n}\n\nexport function defineConfig(config: FonderieConfig): FonderieConfig {\n\treturn config; // typed identity — same pattern as defineConfig in Vite/Nuxt\n}\n","export function stringOrEmpty(value: unknown): string {\n\treturn typeof value === 'string' ? value : '';\n}\n\nexport function booleanOrFalse(value: unknown): boolean {\n\tif (typeof value === 'boolean') return value;\n\tif (value === 'true' || value === '1') return true;\n\treturn false;\n}\n\nexport function arrayOrEmpty<T>(value: unknown): T[] {\n\treturn Array.isArray(value) ? (value as T[]) : [];\n}\n\nexport function numberOrZero(value: unknown): number {\n\tconst n = Number(value);\n\treturn Number.isFinite(n) ? n : 0;\n}\n\nexport function dateOrEmpty(value: unknown): string {\n\tif (typeof value === 'string') return value;\n\tif (value instanceof Date) return value.toISOString();\n\treturn '';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAAkC;AAClC,uBAA6B;;;ACCtB,IAAM,SAAN,MAAgC;AAAA,EAC9B,SAAuE,CAAC;AAAA,EAEhF,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AAC/B,UAAI,MAAM,WAAW,UAAU,CAAC,MAAM,UAAU;AAC/C,eAAO,MAAM;AAAA,MACd;AAAA,IACD;AAAA,EACD;AAEA,SAAO;AACR;;;AOnKO,SAAS,aAAa,QAAwC;AACpE,SAAO;AACR;;;AC5CO,SAAS,cAAc,OAAwB;AACrD,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC5C;AAEO,SAAS,eAAe,OAAyB;AACvD,MAAI,OAAO,UAAU,UAAW,QAAO;AACvC,MAAI,UAAU,UAAU,UAAU,IAAK,QAAO;AAC9C,SAAO;AACR;AAEO,SAAS,aAAgB,OAAqB;AACpD,SAAO,MAAM,QAAQ,KAAK,IAAK,QAAgB,CAAC;AACjD;AAEO,SAAS,aAAa,OAAwB;AACpD,QAAM,IAAI,OAAO,KAAK;AACtB,SAAO,OAAO,SAAS,CAAC,IAAI,IAAI;AACjC;AAEO,SAAS,YAAY,OAAwB;AACnD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,iBAAiB,KAAM,QAAO,MAAM,YAAY;AACpD,SAAO;AACR;","names":["module"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { IFonderieModule, IFonderieContext, Middleware } from './types.cjs';
|
|
2
|
+
export { IAuthUser, ICourierMessage, IFonderieApp, IFonderieContextMeta, IRouteMatch, IRouter, ITenant, IWorkspace } from './types.cjs';
|
|
3
|
+
import { FonderieConfig } from './config.cjs';
|
|
4
|
+
export { defineConfig } from './config.cjs';
|
|
5
|
+
export { arrayOrEmpty, booleanOrFalse, dateOrEmpty, numberOrZero, stringOrEmpty } from './parser.cjs';
|
|
6
|
+
export { HTTP, HttpStatus, IApiError, setApiResponse } from './response.cjs';
|
|
7
|
+
|
|
8
|
+
declare class FonderieApp {
|
|
9
|
+
private config;
|
|
10
|
+
private prefix;
|
|
11
|
+
private router;
|
|
12
|
+
private middlewares;
|
|
13
|
+
private modules;
|
|
14
|
+
constructor(config: FonderieConfig);
|
|
15
|
+
listen(port: number, options?: {
|
|
16
|
+
name?: string;
|
|
17
|
+
version?: string;
|
|
18
|
+
env?: string;
|
|
19
|
+
}): void;
|
|
20
|
+
register(module: IFonderieModule): this;
|
|
21
|
+
boot(): Promise<this>;
|
|
22
|
+
buildContext(request: Request): Promise<IFonderieContext>;
|
|
23
|
+
use(middleware: Middleware): this;
|
|
24
|
+
addRoute(method: string, path: string, ...handlers: Middleware[]): void;
|
|
25
|
+
handle(request: Request): Promise<Response>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
declare function compose(middlewares: Middleware[]): (ctx: IFonderieContext, fallback: () => Promise<Response>) => Promise<Response>;
|
|
29
|
+
|
|
30
|
+
export { FonderieApp, FonderieConfig, IFonderieContext, IFonderieModule, Middleware, compose };
|