@ng-desktop/server 0.5.0 → 0.7.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.
@@ -1,14 +1,19 @@
1
+ /** HTTP methods matched by [`createNativeServerRouter`], including `' * '` wildcard routes. */
1
2
  export type NativeServerMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | '*';
3
+ /** Logical XDG directory root exposed to local server route handlers. */
2
4
  export type NativeServerXdgKind = 'config' | 'data' | 'cache';
5
+ /** Match entry returned by [`NativeServerComputeContext.fuzzyFilter`]. */
3
6
  export interface NativeServerComputeMatch {
4
7
  index: number;
5
8
  score: number;
6
9
  value: string;
7
10
  }
11
+ /** Optional headers and call classification for outbound server-side HTTP requests. */
8
12
  export interface NativeServerHttpRequestOptions {
9
13
  headers?: Record<string, string>;
10
14
  callKind?: string;
11
15
  }
16
+ /** Response returned from `event.context.http` inside a native server handler. */
12
17
  export interface NativeServerHttpResponse {
13
18
  status: number;
14
19
  statusText: string;
@@ -16,12 +21,15 @@ export interface NativeServerHttpResponse {
16
21
  headers: Record<string, string>;
17
22
  cached?: boolean;
18
23
  }
24
+ /** Positional bind parameter accepted by `event.context.db.execute` and `query`. */
19
25
  export type NativeServerSqlParam = string | number | boolean | null;
26
+ /** Host-backed SQLite context available to native server route handlers. */
20
27
  export interface NativeServerDbContext {
21
28
  open(path: string): string;
22
29
  execute(sql: string, params?: readonly NativeServerSqlParam[]): boolean;
23
30
  query<T extends Record<string, unknown> = Record<string, unknown>>(sql: string, params?: readonly NativeServerSqlParam[]): T[];
24
31
  }
32
+ /** Sandboxed XDG filesystem context available to native server route handlers. */
25
33
  export interface NativeServerFsContext {
26
34
  resolvePath(kind: NativeServerXdgKind, relPath: string): string;
27
35
  readText(path: string): string | null;
@@ -29,15 +37,18 @@ export interface NativeServerFsContext {
29
37
  watchFile(path: string): boolean;
30
38
  pollChangedFiles(): string[];
31
39
  }
40
+ /** Multithreaded Rust compute helper exposed on `event.context.compute`. */
32
41
  export interface NativeServerComputeContext {
33
42
  fuzzyFilter(items: readonly string[], query: string, limit?: number): NativeServerComputeMatch[];
34
43
  hash(input: string): string;
35
44
  }
45
+ /** Outbound OS-native HTTP client exposed on `event.context.http`. */
36
46
  export interface NativeServerHttpContext {
37
47
  request(method: string, url: string, body?: unknown, options?: NativeServerHttpRequestOptions): Promise<NativeServerHttpResponse>;
38
48
  get(url: string, options?: NativeServerHttpRequestOptions): Promise<NativeServerHttpResponse>;
39
49
  post(url: string, body?: unknown, options?: NativeServerHttpRequestOptions): Promise<NativeServerHttpResponse>;
40
50
  }
51
+ /** Execution context injected into every handled `NativeServerEvent`. */
41
52
  export interface NativeServerContext {
42
53
  params: Record<string, string>;
43
54
  query: Record<string, string>;
@@ -46,18 +57,21 @@ export interface NativeServerContext {
46
57
  compute: NativeServerComputeContext;
47
58
  http: NativeServerHttpContext;
48
59
  }
60
+ /** Incoming request payload routed to [`NativeServerRouter.handle`]. */
49
61
  export interface NativeServerRequest {
50
62
  method: string;
51
63
  url: string;
52
64
  headers?: Record<string, string>;
53
65
  body?: string | null;
54
66
  }
67
+ /** Serialized HTTP-like response returned by [`NativeServerRouter.handle`]. */
55
68
  export interface NativeServerResponse {
56
69
  status: number;
57
70
  statusText: string;
58
71
  headers: Record<string, string>;
59
72
  body: string;
60
73
  }
74
+ /** Event object passed to native file-based API route handlers (`Analog`/`h3` ergonomics). */
61
75
  export interface NativeServerEvent {
62
76
  readonly method: string;
63
77
  readonly url: string;
@@ -71,7 +85,9 @@ export interface NativeServerEvent {
71
85
  headers: Record<string, string>;
72
86
  };
73
87
  }
88
+ /** Handler function signature exported by `src/server/routes/**` files. */
74
89
  export type NativeEventHandler<T = unknown> = (event: NativeServerEvent) => T | Promise<T>;
90
+ /** Structured HTTP error converted into JSON responses by [`createNativeServerRouter`]. */
75
91
  export declare class NativeServerHttpError extends Error {
76
92
  readonly statusCode: number;
77
93
  readonly statusMessage: string;
@@ -83,13 +99,21 @@ export declare class NativeServerHttpError extends Error {
83
99
  data?: unknown;
84
100
  });
85
101
  }
102
+ /** Returns the standard HTTP reason phrase for common status codes. */
86
103
  export declare function defaultStatusText(status: number): string;
104
+ /** Identity helper providing type inference for local server route handlers. */
87
105
  export declare function defineNativeEventHandler<T = unknown>(handler: NativeEventHandler<T>): NativeEventHandler<T>;
106
+ /** Reads a named dynamic segment (e.g. `[id]`) from the matched route parameters. */
88
107
  export declare function getRouterParam(event: NativeServerEvent, name: string): string | undefined;
108
+ /** Returns a shallow copy of the parsed URL query parameters for the current request. */
89
109
  export declare function getQuery(event: NativeServerEvent): Record<string, string>;
110
+ /** Parses JSON payloads or returns raw request body strings for non-JSON requests. */
90
111
  export declare function readBody<T = unknown>(event: NativeServerEvent): T;
112
+ /** Sets the HTTP status code (and optional reason phrase) on `event.response`. */
91
113
  export declare function setResponseStatus(event: NativeServerEvent, code: number, statusText?: string): void;
114
+ /** Sets a lowercase response header on `event.response`. */
92
115
  export declare function setResponseHeader(event: NativeServerEvent, name: string, value: string): void;
116
+ /** Constructs a [`NativeServerHttpError`] for clean early-return error responses inside handlers. */
93
117
  export declare function createError(input: {
94
118
  statusCode?: number;
95
119
  statusMessage?: string;
package/fesm2022/event.js CHANGED
@@ -1,3 +1,4 @@
1
+ /** Structured HTTP error converted into JSON responses by [`createNativeServerRouter`]. */
1
2
  export class NativeServerHttpError extends Error {
2
3
  statusCode;
3
4
  statusMessage;
@@ -11,6 +12,7 @@ export class NativeServerHttpError extends Error {
11
12
  this.data = options.data;
12
13
  }
13
14
  }
15
+ /** Returns the standard HTTP reason phrase for common status codes. */
14
16
  export function defaultStatusText(status) {
15
17
  switch (status) {
16
18
  case 200:
@@ -37,15 +39,19 @@ export function defaultStatusText(status) {
37
39
  return status >= 400 ? 'Error' : 'OK';
38
40
  }
39
41
  }
42
+ /** Identity helper providing type inference for local server route handlers. */
40
43
  export function defineNativeEventHandler(handler) {
41
44
  return handler;
42
45
  }
46
+ /** Reads a named dynamic segment (e.g. `[id]`) from the matched route parameters. */
43
47
  export function getRouterParam(event, name) {
44
48
  return event.context.params[name];
45
49
  }
50
+ /** Returns a shallow copy of the parsed URL query parameters for the current request. */
46
51
  export function getQuery(event) {
47
52
  return { ...event.context.query };
48
53
  }
54
+ /** Parses JSON payloads or returns raw request body strings for non-JSON requests. */
49
55
  export function readBody(event) {
50
56
  const raw = event.body;
51
57
  if (raw === null || raw === undefined || raw.length === 0) {
@@ -68,15 +74,18 @@ export function readBody(event) {
68
74
  }
69
75
  return raw;
70
76
  }
77
+ /** Sets the HTTP status code (and optional reason phrase) on `event.response`. */
71
78
  export function setResponseStatus(event, code, statusText) {
72
79
  event.response.status = code;
73
80
  if (statusText !== undefined) {
74
81
  event.response.statusText = statusText;
75
82
  }
76
83
  }
84
+ /** Sets a lowercase response header on `event.response`. */
77
85
  export function setResponseHeader(event, name, value) {
78
86
  event.response.headers[name.toLowerCase()] = value;
79
87
  }
88
+ /** Constructs a [`NativeServerHttpError`] for clean early-return error responses inside handlers. */
80
89
  export function createError(input) {
81
90
  return new NativeServerHttpError({
82
91
  statusCode: input.statusCode ?? 500,
@@ -1,13 +1,16 @@
1
1
  import { NativeEventHandler, NativeServerComputeMatch, NativeServerContext, NativeServerHttpRequestOptions, NativeServerHttpResponse, NativeServerMethod, NativeServerRequest, NativeServerResponse, NativeServerSqlParam, NativeServerXdgKind } from './event';
2
+ /** Route entry pairing an HTTP method, URL pattern (static, `:param`, or `*slug`), and handler. */
2
3
  export interface NativeServerRouteDefinition {
3
4
  method: NativeServerMethod;
4
5
  pattern: string;
5
6
  handler: NativeEventHandler;
6
7
  }
8
+ /** In-process router dispatching local `HttpClient` requests inside the Rust server worker. */
7
9
  export interface NativeServerRouter {
8
10
  handle(request: NativeServerRequest): Promise<NativeServerResponse>;
9
11
  getRoutes(): readonly NativeServerRouteDefinition[];
10
12
  }
13
+ /** Low-level host bridge contract exposed to `server.bundle.js` via `globalThis.__NG_NATIVE_SERVER_HOST__`. */
11
14
  export interface NativeServerHostBridge {
12
15
  sqliteOpen?(path: string): string;
13
16
  sqliteExecute(sql: string, params?: readonly NativeServerSqlParam[]): boolean;
@@ -26,5 +29,7 @@ declare global {
26
29
  var __NG_NATIVE_SERVER_ROUTER__: NativeServerRouter | undefined;
27
30
  }
28
31
  export declare function createHostServerContext(): Omit<NativeServerContext, 'params' | 'query'>;
32
+ /** Creates an in-process router sorting routes by specificity (`static > :param > *wildcard`). */
29
33
  export declare function createNativeServerRouter(routes: readonly NativeServerRouteDefinition[], contextFactory?: () => Omit<NativeServerContext, 'params' | 'query'>): NativeServerRouter;
34
+ /** Registers the compiled server router globally on `__NG_NATIVE_SERVER_ROUTER__` for Rust IPC dispatch. */
30
35
  export declare function registerNativeServerApp(routes: readonly NativeServerRouteDefinition[]): NativeServerRouter;
@@ -1,6 +1,20 @@
1
- import { defaultStatusText, NativeServerHttpError, } from './event.js';
1
+ import { createError, defaultStatusText, NativeServerHttpError, } from './event.js';
2
+ function safeDecodeUriComponent(raw) {
3
+ try {
4
+ return decodeURIComponent(raw);
5
+ }
6
+ catch {
7
+ throw createError({
8
+ statusCode: 400,
9
+ statusMessage: 'Bad Request',
10
+ message: `Malformed URI component '${raw}'`,
11
+ });
12
+ }
13
+ }
2
14
  function parseUrlParts(rawUrl) {
3
- const withoutOrigin = rawUrl.trim().replace(/^(?:https?:\/\/localhost|local:\/?)/i, '');
15
+ const withoutOrigin = rawUrl
16
+ .trim()
17
+ .replace(/^(?:https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?|local:\/?)/i, '');
4
18
  const hashIdx = withoutOrigin.indexOf('#');
5
19
  const cleanUrl = hashIdx === -1 ? withoutOrigin : withoutOrigin.slice(0, hashIdx);
6
20
  const qIdx = cleanUrl.indexOf('?');
@@ -18,8 +32,8 @@ function parseUrlParts(rawUrl) {
18
32
  const eq = pair.indexOf('=');
19
33
  const rawKey = eq === -1 ? pair : pair.slice(0, eq);
20
34
  const rawVal = eq === -1 ? '' : pair.slice(eq + 1);
21
- const key = decodeURIComponent(rawKey.replaceAll('+', ' '));
22
- const val = decodeURIComponent(rawVal.replaceAll('+', ' '));
35
+ const key = safeDecodeUriComponent(rawKey.replaceAll('+', ' '));
36
+ const val = safeDecodeUriComponent(rawVal.replaceAll('+', ' '));
23
37
  query[key] = val;
24
38
  }
25
39
  }
@@ -38,7 +52,7 @@ function matchPattern(pattern, path) {
38
52
  const seg = patSegs[i];
39
53
  if (seg.startsWith('*')) {
40
54
  const paramName = seg.slice(1).trim() || 'slug';
41
- params[paramName] = pathSegs.slice(i).map(decodeURIComponent).join('/');
55
+ params[paramName] = pathSegs.slice(i).map(safeDecodeUriComponent).join('/');
42
56
  weights.push(1);
43
57
  return { params, weights };
44
58
  }
@@ -47,7 +61,7 @@ function matchPattern(pattern, path) {
47
61
  }
48
62
  if (seg.startsWith(':')) {
49
63
  const paramName = seg.slice(1).trim();
50
- params[paramName] = decodeURIComponent(pathSegs[i]);
64
+ params[paramName] = safeDecodeUriComponent(pathSegs[i]);
51
65
  weights.push(2);
52
66
  continue;
53
67
  }
@@ -223,6 +237,7 @@ function serializeResult(result, event) {
223
237
  headers['content-type'] ??= 'application/json; charset=utf-8';
224
238
  return { status, statusText, headers, body: JSON.stringify(result) };
225
239
  }
240
+ /** Creates an in-process router sorting routes by specificity (`static > :param > *wildcard`). */
226
241
  export function createNativeServerRouter(routes, contextFactory = createHostServerContext) {
227
242
  const routeList = [...routes];
228
243
  return {
@@ -231,59 +246,61 @@ export function createNativeServerRouter(routes, contextFactory = createHostServ
231
246
  const method = String(request.method || 'GET')
232
247
  .trim()
233
248
  .toUpperCase();
234
- const { path, query } = parseUrlParts(request.url);
235
- const pathMatches = [];
236
- for (const route of routeList) {
237
- const matched = matchPattern(route.pattern, path);
238
- if (!matched)
239
- continue;
240
- pathMatches.push({
241
- route,
242
- params: matched.params,
243
- weights: matched.weights,
244
- isExactMethod: route.method.toUpperCase() === method,
245
- });
246
- }
247
- if (pathMatches.length === 0) {
248
- return {
249
- status: 404,
250
- statusText: 'Not Found',
251
- headers: { 'content-type': 'application/json; charset=utf-8' },
252
- body: JSON.stringify({ error: `Route not found: ${path}`, statusCode: 404 }),
253
- };
254
- }
255
- const methodMatches = pathMatches.filter((m) => m.isExactMethod || m.route.method === '*');
256
- if (methodMatches.length === 0) {
257
- return {
258
- status: 405,
259
- statusText: 'Method Not Allowed',
260
- headers: { 'content-type': 'application/json; charset=utf-8' },
261
- body: JSON.stringify({
262
- error: `Method ${method} not allowed for ${path}`,
263
- statusCode: 405,
264
- }),
265
- };
266
- }
267
- methodMatches.sort(compareMatchPrecedence);
268
- const selected = methodMatches[0];
269
- const baseCtx = contextFactory();
270
- const event = {
271
- method,
272
- url: request.url,
273
- path,
274
- headers: normalizeHeaders(request.headers),
275
- body: request.body ?? null,
276
- context: {
277
- ...baseCtx,
278
- params: selected.params,
279
- query,
280
- },
281
- response: {
282
- status: 200,
283
- headers: {},
284
- },
285
- };
249
+ let responseHeaders = {};
286
250
  try {
251
+ const { path, query } = parseUrlParts(request.url);
252
+ const pathMatches = [];
253
+ for (const route of routeList) {
254
+ const matched = matchPattern(route.pattern, path);
255
+ if (!matched)
256
+ continue;
257
+ pathMatches.push({
258
+ route,
259
+ params: matched.params,
260
+ weights: matched.weights,
261
+ isExactMethod: route.method.toUpperCase() === method,
262
+ });
263
+ }
264
+ if (pathMatches.length === 0) {
265
+ return {
266
+ status: 404,
267
+ statusText: 'Not Found',
268
+ headers: { 'content-type': 'application/json; charset=utf-8' },
269
+ body: JSON.stringify({ error: `Route not found: ${path}`, statusCode: 404 }),
270
+ };
271
+ }
272
+ const methodMatches = pathMatches.filter((m) => m.isExactMethod || m.route.method === '*');
273
+ if (methodMatches.length === 0) {
274
+ return {
275
+ status: 405,
276
+ statusText: 'Method Not Allowed',
277
+ headers: { 'content-type': 'application/json; charset=utf-8' },
278
+ body: JSON.stringify({
279
+ error: `Method ${method} not allowed for ${path}`,
280
+ statusCode: 405,
281
+ }),
282
+ };
283
+ }
284
+ methodMatches.sort(compareMatchPrecedence);
285
+ const selected = methodMatches[0];
286
+ const baseCtx = contextFactory();
287
+ const event = {
288
+ method,
289
+ url: request.url,
290
+ path,
291
+ headers: normalizeHeaders(request.headers),
292
+ body: request.body ?? null,
293
+ context: {
294
+ ...baseCtx,
295
+ params: selected.params,
296
+ query,
297
+ },
298
+ response: {
299
+ status: 200,
300
+ headers: {},
301
+ },
302
+ };
303
+ responseHeaders = event.response.headers;
287
304
  const result = await selected.route.handler(event);
288
305
  return serializeResult(result, event);
289
306
  }
@@ -293,7 +310,7 @@ export function createNativeServerRouter(routes, contextFactory = createHostServ
293
310
  status: err.statusCode,
294
311
  statusText: err.statusMessage,
295
312
  headers: {
296
- ...event.response.headers,
313
+ ...responseHeaders,
297
314
  'content-type': 'application/json; charset=utf-8',
298
315
  },
299
316
  body: JSON.stringify({
@@ -314,6 +331,7 @@ export function createNativeServerRouter(routes, contextFactory = createHostServ
314
331
  },
315
332
  };
316
333
  }
334
+ /** Registers the compiled server router globally on `__NG_NATIVE_SERVER_ROUTER__` for Rust IPC dispatch. */
317
335
  export function registerNativeServerApp(routes) {
318
336
  const router = createNativeServerRouter(routes, createHostServerContext);
319
337
  globalThis.__NG_NATIVE_SERVER_ROUTER__ = router;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ng-desktop/server",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Isolated local AnalogJS-style backend router and host context (SQLite, XDG FS, Compute, HTTP) for NgDesktop",
5
5
  "license": "MIT",
6
6
  "keywords": [