local-lite 0.0.28 → 0.0.29
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/server/index.d.ts +33 -0
- package/dist/server/index.js +133 -0
- package/package.json +6 -1
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
|
|
2
|
+
export interface ApiRequestContext<TConfig = unknown> {
|
|
3
|
+
request: Request;
|
|
4
|
+
config: TConfig;
|
|
5
|
+
path: string;
|
|
6
|
+
params: Record<string, string>;
|
|
7
|
+
}
|
|
8
|
+
export type ApiHandler<TConfig = unknown> = (context: ApiRequestContext<TConfig>) => Response | Promise<Response>;
|
|
9
|
+
export type ApiMiddleware<TConfig = unknown> = (context: ApiRequestContext<TConfig>, next: () => Promise<Response>) => Response | Promise<Response>;
|
|
10
|
+
export type ApiEndpoint<TConfig = unknown> = Partial<Record<ApiMethod, ApiHandler<TConfig>>>;
|
|
11
|
+
export interface ServerConfig<TConfig = unknown> {
|
|
12
|
+
/** Server-only services and provider configuration passed to endpoint handlers. */
|
|
13
|
+
config: TConfig;
|
|
14
|
+
/** Explicit endpoint map. Keys are URL patterns such as `/api/bookings/:bookingId`. */
|
|
15
|
+
endpoints: Record<string, ApiEndpoint<TConfig>>;
|
|
16
|
+
/** Middleware applied to every generated endpoint, in declaration order. */
|
|
17
|
+
middleware?: ApiMiddleware<TConfig>[];
|
|
18
|
+
/** Safe error hook for server-side reporting. Response details are not exposed to clients. */
|
|
19
|
+
onError?: (error: unknown, context: ApiRequestContext<TConfig>) => void;
|
|
20
|
+
}
|
|
21
|
+
export type GeneratedApiHandlers = Record<string, Partial<Record<ApiMethod, (request: Request) => Promise<Response>>>>;
|
|
22
|
+
/** Define and validate an app's server/API configuration. */
|
|
23
|
+
export declare function defineServerConfig<TConfig>(config: ServerConfig<TConfig>): ServerConfig<TConfig>;
|
|
24
|
+
/**
|
|
25
|
+
* Build framework-neutral Request/Response handlers from one server config.
|
|
26
|
+
* App route files can re-export a generated method handler, while tests and
|
|
27
|
+
* custom servers can use `fetch()` as a single dispatcher.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createServer<TConfig>(config: ServerConfig<TConfig>): {
|
|
30
|
+
handlers: GeneratedApiHandlers;
|
|
31
|
+
handler(path: string, method: ApiMethod): (request: Request) => Promise<Response>;
|
|
32
|
+
fetch(request: Request): Promise<Response>;
|
|
33
|
+
};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.defineServerConfig = defineServerConfig;
|
|
4
|
+
exports.createServer = createServer;
|
|
5
|
+
function normalizePath(path) {
|
|
6
|
+
const normalized = `/${path.split('/').filter(Boolean).join('/')}`;
|
|
7
|
+
return normalized === '/' ? normalized : normalized.replace(/\/$/, '');
|
|
8
|
+
}
|
|
9
|
+
function matchPath(pattern, pathname) {
|
|
10
|
+
const patternSegments = normalizePath(pattern).split('/').filter(Boolean);
|
|
11
|
+
const pathSegments = normalizePath(pathname).split('/').filter(Boolean);
|
|
12
|
+
if (patternSegments.length !== pathSegments.length)
|
|
13
|
+
return null;
|
|
14
|
+
const params = {};
|
|
15
|
+
for (let index = 0; index < patternSegments.length; index += 1) {
|
|
16
|
+
const expected = patternSegments[index];
|
|
17
|
+
const actual = pathSegments[index];
|
|
18
|
+
if (expected.startsWith(':')) {
|
|
19
|
+
try {
|
|
20
|
+
params[expected.slice(1)] = decodeURIComponent(actual);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
else if (expected !== actual) {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return params;
|
|
31
|
+
}
|
|
32
|
+
function methodNotAllowed(methods) {
|
|
33
|
+
return Response.json({ error: 'Method Not Allowed' }, { status: 405, headers: { Allow: methods.join(', ') } });
|
|
34
|
+
}
|
|
35
|
+
/** Define and validate an app's server/API configuration. */
|
|
36
|
+
function defineServerConfig(config) {
|
|
37
|
+
for (const [path, endpoint] of Object.entries(config.endpoints)) {
|
|
38
|
+
if (!path.startsWith('/'))
|
|
39
|
+
throw new TypeError(`API endpoint path must start with '/': ${path}`);
|
|
40
|
+
if (!Object.values(endpoint).some(handler => typeof handler === 'function')) {
|
|
41
|
+
throw new TypeError(`API endpoint '${path}' must define at least one method handler.`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return config;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Build framework-neutral Request/Response handlers from one server config.
|
|
48
|
+
* App route files can re-export a generated method handler, while tests and
|
|
49
|
+
* custom servers can use `fetch()` as a single dispatcher.
|
|
50
|
+
*/
|
|
51
|
+
function createServer(config) {
|
|
52
|
+
const definitions = Object.entries(config.endpoints).map(([path, endpoint]) => ({
|
|
53
|
+
path: normalizePath(path),
|
|
54
|
+
endpoint,
|
|
55
|
+
}));
|
|
56
|
+
const run = async (request, pathPattern, endpoint) => {
|
|
57
|
+
const method = request.method.toUpperCase();
|
|
58
|
+
const url = new URL(request.url);
|
|
59
|
+
const params = matchPath(pathPattern, url.pathname);
|
|
60
|
+
const handler = endpoint[method];
|
|
61
|
+
const context = {
|
|
62
|
+
request,
|
|
63
|
+
config: config.config,
|
|
64
|
+
path: pathPattern,
|
|
65
|
+
params: params ?? {},
|
|
66
|
+
};
|
|
67
|
+
if (!params)
|
|
68
|
+
return Response.json({ error: 'Not Found' }, { status: 404 });
|
|
69
|
+
if (!handler)
|
|
70
|
+
return methodNotAllowed(Object.keys(endpoint));
|
|
71
|
+
const stack = config.middleware ?? [];
|
|
72
|
+
let index = -1;
|
|
73
|
+
const dispatch = async (position) => {
|
|
74
|
+
if (position <= index)
|
|
75
|
+
throw new Error('API middleware called next() more than once.');
|
|
76
|
+
index = position;
|
|
77
|
+
const middleware = stack[position];
|
|
78
|
+
if (!middleware)
|
|
79
|
+
return await handler(context);
|
|
80
|
+
return await middleware(context, () => dispatch(position + 1));
|
|
81
|
+
};
|
|
82
|
+
try {
|
|
83
|
+
return await dispatch(0);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
try {
|
|
87
|
+
config.onError?.(error, context);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
// Reporting failures must not replace the original generic API response.
|
|
91
|
+
}
|
|
92
|
+
return Response.json({ error: 'Internal Server Error' }, { status: 500 });
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const handlers = {};
|
|
96
|
+
for (const { path, endpoint } of definitions) {
|
|
97
|
+
handlers[path] = {};
|
|
98
|
+
for (const method of Object.keys(endpoint)) {
|
|
99
|
+
handlers[path][method] = (request) => run(request, path, endpoint);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
handlers,
|
|
104
|
+
handler(path, method) {
|
|
105
|
+
const normalized = normalizePath(path);
|
|
106
|
+
const definition = definitions.find(item => item.path === normalized);
|
|
107
|
+
if (!definition || !definition.endpoint[method]) {
|
|
108
|
+
throw new Error(`No ${method} API handler is configured for '${normalized}'.`);
|
|
109
|
+
}
|
|
110
|
+
return (request) => run(request, definition.path, definition.endpoint);
|
|
111
|
+
},
|
|
112
|
+
async fetch(request) {
|
|
113
|
+
const url = new URL(request.url);
|
|
114
|
+
const method = request.method.toUpperCase();
|
|
115
|
+
let pathMatched = false;
|
|
116
|
+
for (const definition of definitions) {
|
|
117
|
+
if (!matchPath(definition.path, url.pathname))
|
|
118
|
+
continue;
|
|
119
|
+
pathMatched = true;
|
|
120
|
+
if (!definition.endpoint[method])
|
|
121
|
+
continue;
|
|
122
|
+
return await run(request, definition.path, definition.endpoint);
|
|
123
|
+
}
|
|
124
|
+
if (pathMatched) {
|
|
125
|
+
const allowed = definitions
|
|
126
|
+
.filter(definition => matchPath(definition.path, url.pathname))
|
|
127
|
+
.flatMap(definition => Object.keys(definition.endpoint));
|
|
128
|
+
return methodNotAllowed([...new Set(allowed)]);
|
|
129
|
+
}
|
|
130
|
+
return Response.json({ error: 'Not Found' }, { status: 404 });
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-lite",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.29",
|
|
4
4
|
"description": "Never let a lost connection break a promise. Local-first sync that faithfully keeps data safe until you're back online.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -31,6 +31,11 @@
|
|
|
31
31
|
"import": "./dist/config/index.js",
|
|
32
32
|
"default": "./dist/config/index.js"
|
|
33
33
|
},
|
|
34
|
+
"./server": {
|
|
35
|
+
"types": "./dist/server/index.d.ts",
|
|
36
|
+
"import": "./dist/server/index.js",
|
|
37
|
+
"default": "./dist/server/index.js"
|
|
38
|
+
},
|
|
34
39
|
"./schema": {
|
|
35
40
|
"types": "./dist/schema/index.d.ts",
|
|
36
41
|
"import": "./dist/schema/index.js",
|