@spfn/core 0.3.0-beta.2 → 0.3.0-beta.20

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.
Files changed (93) hide show
  1. package/README.md +331 -16
  2. package/dist/app-config/index.d.ts +134 -0
  3. package/dist/app-config/index.js +58 -0
  4. package/dist/app-config/index.js.map +1 -0
  5. package/dist/authz/index.js +1 -381
  6. package/dist/authz/index.js.map +1 -1
  7. package/dist/{boss-D16fO2oG.d.ts → boss-BiDCbbAQ.d.ts} +60 -7
  8. package/dist/codegen/index.d.ts +93 -15
  9. package/dist/codegen/index.js +626 -165
  10. package/dist/codegen/index.js.map +1 -1
  11. package/dist/config/index.d.ts +0 -63
  12. package/dist/config/index.js +15 -15
  13. package/dist/config/index.js.map +1 -1
  14. package/dist/contract/index.d.ts +40 -17
  15. package/dist/contract/index.js +147 -23
  16. package/dist/contract/index.js.map +1 -1
  17. package/dist/db/index.d.ts +201 -34
  18. package/dist/db/index.js +294 -158
  19. package/dist/db/index.js.map +1 -1
  20. package/dist/{define-middleware-DfDP39Nq.d.ts → define-middleware-CVKgqo8S.d.ts} +1 -1
  21. package/dist/env/index.d.ts +6 -442
  22. package/dist/env/index.js +13 -16
  23. package/dist/env/index.js.map +1 -1
  24. package/dist/env/loader.js +24 -1
  25. package/dist/env/loader.js.map +1 -1
  26. package/dist/error-BcdBVfRA.d.ts +150 -0
  27. package/dist/errors/index.js +1 -381
  28. package/dist/errors/index.js.map +1 -1
  29. package/dist/event/index.d.ts +5 -5
  30. package/dist/event/index.js +32 -1
  31. package/dist/event/index.js.map +1 -1
  32. package/dist/event/sse/client.d.ts +18 -4
  33. package/dist/event/sse/client.js +38 -2
  34. package/dist/event/sse/client.js.map +1 -1
  35. package/dist/event/sse/index.d.ts +5 -4
  36. package/dist/event/ws/client.d.ts +3 -2
  37. package/dist/event/ws/index.d.ts +4 -3
  38. package/dist/job/index.d.ts +48 -3
  39. package/dist/job/index.js +131 -52
  40. package/dist/job/index.js.map +1 -1
  41. package/dist/logger/index.js +0 -12
  42. package/dist/logger/index.js.map +1 -1
  43. package/dist/middleware/index.d.ts +6 -2
  44. package/dist/middleware/index.js +7 -388
  45. package/dist/middleware/index.js.map +1 -1
  46. package/dist/nextjs/index.d.ts +88 -8
  47. package/dist/nextjs/index.js +138 -62
  48. package/dist/nextjs/index.js.map +1 -1
  49. package/dist/nextjs/server.d.ts +45 -7
  50. package/dist/nextjs/server.js +14 -0
  51. package/dist/nextjs/server.js.map +1 -1
  52. package/dist/ops/index.d.ts +59 -43
  53. package/dist/ops/index.js +543 -97
  54. package/dist/ops/index.js.map +1 -1
  55. package/dist/registry-C2KQCh0m.d.ts +473 -0
  56. package/dist/route/index.d.ts +5 -3
  57. package/dist/route/index.js +48 -28
  58. package/dist/route/index.js.map +1 -1
  59. package/dist/{router-Qbssr11H.d.ts → route-builder-BHKgGkwI.d.ts} +3 -126
  60. package/dist/{token-manager-BT5EnUAR.d.ts → router-CysBmgv3.d.ts} +81 -127
  61. package/dist/router-DaDrprJd.d.ts +172 -0
  62. package/dist/server/index.d.ts +185 -14
  63. package/dist/server/index.js +834 -78
  64. package/dist/server/index.js.map +1 -1
  65. package/dist/surface/index.d.ts +109 -0
  66. package/dist/surface/index.js +908 -0
  67. package/dist/surface/index.js.map +1 -0
  68. package/dist/token-manager-Ckjt2-qq.d.ts +122 -0
  69. package/dist/{types-ZQODsBft.d.ts → types-B8zAxFsE.d.ts} +2 -1
  70. package/dist/types-CxhPH4s_.d.ts +375 -0
  71. package/dist/{types-D1c57Ko-.d.ts → types-D52SokSM.d.ts} +43 -4
  72. package/dist/{types-2AbaW4Ie.d.ts → types-W4u_S0lF.d.ts} +4 -3
  73. package/docs/file-upload.md +195 -333
  74. package/package.json +20 -9
  75. package/src/cache/README.md +330 -0
  76. package/src/codegen/README.md +634 -0
  77. package/src/config/README.md +333 -0
  78. package/src/contract/README.md +440 -0
  79. package/src/db/README.md +589 -0
  80. package/src/db/manager/README.md +500 -0
  81. package/src/db/schema/README.md +354 -0
  82. package/src/db/transaction/README.md +822 -0
  83. package/src/env/README.md +787 -0
  84. package/src/errors/README.md +429 -0
  85. package/src/event/README.md +789 -0
  86. package/src/job/README.md +613 -0
  87. package/src/logger/README.md +321 -0
  88. package/src/middleware/README.md +634 -0
  89. package/src/nextjs/README.md +688 -0
  90. package/src/route/README.md +763 -0
  91. package/src/security/README.md +100 -0
  92. package/src/server/README.md +704 -0
  93. package/dist/types-9oszaJqp.d.ts +0 -250
@@ -0,0 +1,908 @@
1
+ // src/route/route-builder.ts
2
+ var RouteBuilder = class _RouteBuilder {
3
+ _method;
4
+ _path;
5
+ _input;
6
+ _interceptor;
7
+ _middlewares;
8
+ _skipMiddlewares;
9
+ _contract;
10
+ /**
11
+ * Create a new RouteBuilder with copied properties and optional overrides
12
+ */
13
+ clone(overrides) {
14
+ const builder = new _RouteBuilder();
15
+ builder._method = this._method;
16
+ builder._path = this._path;
17
+ builder._input = overrides?.input ?? this._input;
18
+ builder._interceptor = overrides?.interceptor ?? this._interceptor;
19
+ builder._middlewares = overrides?.middlewares ?? this._middlewares;
20
+ builder._skipMiddlewares = overrides?.skipMiddlewares ?? this._skipMiddlewares;
21
+ builder._contract = overrides?.contract ?? this._contract;
22
+ return builder;
23
+ }
24
+ /**
25
+ * Define input schemas
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * route.get('/users/:id')
30
+ * .input({
31
+ * params: Type.Object({ id: Type.String() }),
32
+ * query: Type.Object({ page: Type.Number() }),
33
+ * headers: Type.Object({ authorization: Type.String() })
34
+ * })
35
+ * .handler(async (c) => {
36
+ * const { params, query, headers } = await c.data();
37
+ * // params = { id: string }
38
+ * // query = { page: number }
39
+ * // headers = { authorization: string }
40
+ * })
41
+ * ```
42
+ */
43
+ input(input) {
44
+ return this.clone({ input });
45
+ }
46
+ /**
47
+ * Define fields injected by interceptors
48
+ *
49
+ * These fields are:
50
+ * - Available in the handler (merged with input)
51
+ * - Excluded from client types (codegen uses only input)
52
+ * - Not validated by route input schema (injected by middleware)
53
+ *
54
+ * Use this when middleware/interceptors add fields to the request
55
+ * before it reaches the handler.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * // Auth interceptor injects crypto key fields
60
+ * route.post('/_auth/login')
61
+ * .input({
62
+ * body: Type.Object({
63
+ * email: Type.String(),
64
+ * password: Type.String()
65
+ * })
66
+ * })
67
+ * .interceptor({
68
+ * body: Type.Object({
69
+ * publicKey: Type.String(),
70
+ * keyId: Type.String(),
71
+ * fingerprint: Type.String()
72
+ * })
73
+ * })
74
+ * .handler(async (c) => {
75
+ * const { body } = await c.data();
76
+ * // body type: { email, password, publicKey, keyId, fingerprint }
77
+ * // Client only sees: { email, password }
78
+ * return loginService(body);
79
+ * });
80
+ * ```
81
+ */
82
+ interceptor(interceptor) {
83
+ return this.clone({ interceptor });
84
+ }
85
+ /**
86
+ * Add middlewares to the route
87
+ *
88
+ * Accepts both regular middleware handlers and named middlewares (NamedMiddleware).
89
+ * Named middlewares that are already registered globally will be automatically
90
+ * deduplicated to prevent double execution.
91
+ *
92
+ * @example
93
+ * ```ts
94
+ * import { authenticate } from '@spfn/auth/server/middleware';
95
+ *
96
+ * // With NamedMiddleware (auto-deduped if registered globally)
97
+ * route.get('/users')
98
+ * .use([authenticate, RateLimitMiddleware()])
99
+ *
100
+ * // With regular middleware handlers
101
+ * route.get('/users')
102
+ * .use([AuthMiddleware(), RateLimitMiddleware()])
103
+ * ```
104
+ */
105
+ middleware(middlewares) {
106
+ return this.clone({ middlewares });
107
+ }
108
+ /**
109
+ * Add middlewares to the route (alias for `.middleware()`)
110
+ *
111
+ * Accepts both regular middleware handlers and named middlewares (NamedMiddleware).
112
+ * Named middlewares that are already registered globally will be automatically
113
+ * deduplicated to prevent double execution.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * import { authenticate } from '@spfn/auth/server/middleware';
118
+ *
119
+ * // With NamedMiddleware (auto-deduped if registered globally)
120
+ * route.get('/users')
121
+ * .use([authenticate, RateLimitMiddleware()])
122
+ *
123
+ * // With regular middleware handlers
124
+ * route.get('/users')
125
+ * .use([AuthMiddleware(), RateLimitMiddleware()])
126
+ * ```
127
+ */
128
+ use(middlewares) {
129
+ return this.middleware(middlewares);
130
+ }
131
+ /**
132
+ * Skip server-level named middlewares
133
+ *
134
+ * Useful for public endpoints that should bypass auth or rate limiting
135
+ *
136
+ * @param middlewareNames - Array of middleware names to skip, or '*' to skip all
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * // Skip specific middlewares
141
+ * route.get('/status')
142
+ * .skip(['auth', 'rateLimit'])
143
+ * .handler(async (c) => c.json({ status: 'ok' }));
144
+ *
145
+ * // Skip only auth (still apply rate limiting)
146
+ * route.get('/public-data')
147
+ * .skip(['auth'])
148
+ * .handler(async (c) => { ... });
149
+ *
150
+ * // Skip all middlewares
151
+ * route.get('/public-health')
152
+ * .skip('*')
153
+ * .handler(async (c) => c.json({ status: 'ok' }));
154
+ * ```
155
+ */
156
+ skip(middlewareNames) {
157
+ return this.clone({ skipMiddlewares: middlewareNames });
158
+ }
159
+ /**
160
+ * Publish this route as a versioned contract operation
161
+ *
162
+ * Marks the route as a promise to clients that are compiled and deployed
163
+ * separately from the server — a mobile app, an external API consumer.
164
+ * The `@spfn/core:contract` generator writes every contracted route into
165
+ * `contracts/current.json`, and the build refuses a change that would break
166
+ * an already-released client.
167
+ *
168
+ * Routes without `.contract()` are unaffected: they simply do not appear in
169
+ * the contract. A web client needs nothing here — it derives its types from
170
+ * the router in the same build.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * export const getUser = route.get('/users/:id')
175
+ * .input({ params: Type.Object({ id: Type.String() }) })
176
+ * .contract({
177
+ * since: '1.2.0',
178
+ * auth: 'clientProofV1',
179
+ * requiresSession: true,
180
+ * response: Type.Object({
181
+ * id: Type.String(),
182
+ * name: Type.String(),
183
+ * email: Type.Optional(Type.String()),
184
+ * }),
185
+ * })
186
+ * .handler(async (c) => { ... });
187
+ * ```
188
+ */
189
+ contract(contract) {
190
+ return this.clone({ contract });
191
+ }
192
+ /**
193
+ * Define handler function
194
+ *
195
+ * Response type is automatically inferred from the return value.
196
+ * Use helper methods like `c.created()`, `c.paginated()` for proper type inference.
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * // Direct return - type inferred from data
201
+ * route.get('/users/:id')
202
+ * .input({ params: Type.Object({ id: Type.String() }) })
203
+ * .handler(async (c) => {
204
+ * const { params } = await c.data();
205
+ * return await getUser(params.id); // Type: User
206
+ * })
207
+ *
208
+ * // Using c.created() - returns data with 201 status, type preserved
209
+ * route.post('/users')
210
+ * .input({ body: Type.Object({ name: Type.String() }) })
211
+ * .handler(async (c) => {
212
+ * const { body } = await c.data();
213
+ * return c.created(await createUser(body)); // Type: User
214
+ * })
215
+ *
216
+ * // Using c.paginated() - returns PaginatedResult<T>
217
+ * route.get('/users')
218
+ * .handler(async (c) => {
219
+ * const users = await getUsers();
220
+ * return c.paginated(users, 1, 20, 100); // Type: PaginatedResult<User>
221
+ * })
222
+ *
223
+ * // Using c.noContent() - returns void
224
+ * route.delete('/users/:id')
225
+ * .handler(async (c) => {
226
+ * await deleteUser(params.id);
227
+ * return c.noContent(); // Type: void
228
+ * })
229
+ *
230
+ * // Using c.json() - returns Response (type inference lost)
231
+ * // Use only when you need custom status codes not covered by helpers
232
+ * route.get('/custom')
233
+ * .handler(async (c) => {
234
+ * return c.json({ data }, 418); // Type: Response
235
+ * })
236
+ * ```
237
+ */
238
+ handler(fn) {
239
+ return {
240
+ method: this._method,
241
+ path: this._path,
242
+ input: this._input,
243
+ interceptor: this._interceptor,
244
+ middlewares: this._middlewares,
245
+ skipMiddlewares: this._skipMiddlewares,
246
+ contract: this._contract,
247
+ handler: fn,
248
+ _input: {},
249
+ _interceptor: {},
250
+ _response: {}
251
+ };
252
+ }
253
+ };
254
+ function createMethodRoute(method) {
255
+ return (path) => {
256
+ const builder = new RouteBuilder();
257
+ builder._method = method;
258
+ builder._path = path;
259
+ return builder;
260
+ };
261
+ }
262
+ var route = {
263
+ get: createMethodRoute("GET"),
264
+ post: createMethodRoute("POST"),
265
+ put: createMethodRoute("PUT"),
266
+ patch: createMethodRoute("PATCH"),
267
+ delete: createMethodRoute("DELETE")
268
+ };
269
+
270
+ // src/route/router.ts
271
+ function createRouterInstance(state) {
272
+ return {
273
+ routes: state.routes,
274
+ _routes: state.routes,
275
+ _packageRouters: state.packageRouters,
276
+ _globalMiddlewares: state.globalMiddlewares,
277
+ _contractVersion: state.contractVersion,
278
+ _publishesRouteMap: state.publishesRouteMap,
279
+ packages(routers) {
280
+ const newPackageRouters = [...state.packageRouters, ...routers];
281
+ for (const pkgRouter of routers) {
282
+ if (pkgRouter._packageRouters?.length > 0) {
283
+ newPackageRouters.push(...pkgRouter._packageRouters);
284
+ }
285
+ }
286
+ assertDistinctSurfaces(newPackageRouters);
287
+ return createRouterInstance({ ...state, packageRouters: newPackageRouters });
288
+ },
289
+ use(middlewares) {
290
+ return createRouterInstance({
291
+ ...state,
292
+ globalMiddlewares: [...state.globalMiddlewares, ...middlewares]
293
+ });
294
+ },
295
+ contractVersion(version) {
296
+ assertContractVersion(version);
297
+ return createRouterInstance({ ...state, contractVersion: version });
298
+ }
299
+ };
300
+ }
301
+ function assertContractVersion(version) {
302
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)*$/.test(version)) {
303
+ throw new Error(
304
+ `contractVersion("${version}") is not a version of the form major.minor.patch. The released snapshot is named from this value and releases are compared by it.`
305
+ );
306
+ }
307
+ }
308
+ function assertDistinctSurfaces(packageRouters) {
309
+ const namespaces = /* @__PURE__ */ new Set();
310
+ for (const router of packageRouters) {
311
+ const namespace = router._surfaceNamespace;
312
+ if (namespace === void 0) {
313
+ continue;
314
+ }
315
+ if (namespaces.has(namespace)) {
316
+ throw new Error(
317
+ `.packages() mounts two command surfaces on "${namespace}". Both serve ${namespace}/_manifest, so the second one's commands would answer while no manifest lists them. Mount one router per namespace.`
318
+ );
319
+ }
320
+ namespaces.add(namespace);
321
+ }
322
+ }
323
+ function defineUnmappedRouter(routes) {
324
+ return createRouterInstance({
325
+ routes,
326
+ packageRouters: [],
327
+ globalMiddlewares: [],
328
+ contractVersion: null,
329
+ publishesRouteMap: false
330
+ });
331
+ }
332
+
333
+ // src/surface/error.ts
334
+ var SurfaceError = class extends Error {
335
+ constructor(message) {
336
+ super(message);
337
+ this.name = "SurfaceError";
338
+ }
339
+ };
340
+
341
+ // src/surface/wording.ts
342
+ var SURFACE_WORDING = {
343
+ noun: "surface",
344
+ builder: "`<surface>.route`",
345
+ factory: "defineSurface"
346
+ };
347
+ function capitalized(noun) {
348
+ return noun.charAt(0).toUpperCase() + noun.slice(1);
349
+ }
350
+
351
+ // src/surface/manifest.ts
352
+ function isRouter(value) {
353
+ return value !== null && typeof value === "object" && "routes" in value && "_routes" in value;
354
+ }
355
+ function isRouteDef(value) {
356
+ return value !== null && typeof value === "object" && "handler" in value;
357
+ }
358
+ function toJsonSchema(schema) {
359
+ return JSON.parse(JSON.stringify(schema));
360
+ }
361
+ var INPUT_SECTIONS = ["params", "query", "body"];
362
+ function toCommandInput(input) {
363
+ const sections = {};
364
+ if (!input) {
365
+ return sections;
366
+ }
367
+ for (const section of INPUT_SECTIONS) {
368
+ const schema = input[section];
369
+ if (schema) {
370
+ sections[section] = toJsonSchema(schema);
371
+ }
372
+ }
373
+ return sections;
374
+ }
375
+ function collectSurfaceCommands(routes, wording = SURFACE_WORDING) {
376
+ const commands = [];
377
+ visit(routes, commands, /* @__PURE__ */ new Map(), wording);
378
+ commands.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
379
+ return commands;
380
+ }
381
+ function visit(routes, commands, claimed, wording) {
382
+ for (const [name, entry] of Object.entries(routes)) {
383
+ if (isRouter(entry)) {
384
+ visit(entry.routes, commands, claimed, wording);
385
+ continue;
386
+ }
387
+ if (!isRouteDef(entry) || !entry.method || !entry.path) {
388
+ continue;
389
+ }
390
+ assertUnclaimedName(name, entry.path, claimed, wording);
391
+ commands.push({
392
+ name,
393
+ method: entry.method,
394
+ path: entry.path,
395
+ input: toCommandInput(entry.input)
396
+ });
397
+ }
398
+ }
399
+ function assertUnclaimedName(name, path, claimed, wording) {
400
+ const existing = claimed.get(name);
401
+ if (existing !== void 0) {
402
+ throw new SurfaceError(
403
+ `Two ${wording.noun} routes are named "${name}" ("${existing}" and "${path}"). Command names are flattened across nested routers, so each must be unique for a client to resolve the one its caller asked for.`
404
+ );
405
+ }
406
+ claimed.set(name, path);
407
+ }
408
+
409
+ // src/surface/route-overlap.ts
410
+ function routeSegments(path) {
411
+ return path.split("/").slice(1).map((raw) => {
412
+ if (raw === "*" || raw.endsWith("*")) {
413
+ return { kind: "wildcard", value: raw, optional: true };
414
+ }
415
+ if (raw.startsWith(":")) {
416
+ return {
417
+ kind: "parameter",
418
+ value: raw.slice(1).replace(/\?$/, ""),
419
+ optional: raw.endsWith("?")
420
+ };
421
+ }
422
+ return { kind: "static", value: raw, optional: false };
423
+ });
424
+ }
425
+ function customPattern(parameter) {
426
+ const openingBrace = parameter.indexOf("{");
427
+ return openingBrace >= 0 && parameter.endsWith("}") ? parameter.slice(openingBrace + 1, -1) : null;
428
+ }
429
+ function parameterAccepts(parameter, value) {
430
+ const pattern = customPattern(parameter);
431
+ if (pattern === null) {
432
+ return value.length > 0 && !value.includes("/");
433
+ }
434
+ try {
435
+ return new RegExp(`^(?:${pattern})$`).test(value);
436
+ } catch {
437
+ return true;
438
+ }
439
+ }
440
+ function remainingStaticPath(segments, from) {
441
+ const remaining = segments.slice(from);
442
+ return remaining.every((segment) => segment.kind === "static") ? remaining.map((segment) => segment.value).join("/") : null;
443
+ }
444
+ function routePatternsOverlap(firstPath, secondPath) {
445
+ const first = routeSegments(firstPath);
446
+ const second = routeSegments(secondPath);
447
+ const length = Math.max(first.length, second.length);
448
+ for (let index = 0; index < length; index++) {
449
+ const left = first[index];
450
+ const right = second[index];
451
+ if (!left || !right) {
452
+ const remaining = left ? first.slice(index) : second.slice(index);
453
+ return remaining.every((segment) => segment.optional || segment.kind === "wildcard");
454
+ }
455
+ if (left.kind === "wildcard" || right.kind === "wildcard") {
456
+ return true;
457
+ }
458
+ if (left.kind === "static" && right.kind === "static") {
459
+ if (left.value !== right.value) {
460
+ return false;
461
+ }
462
+ continue;
463
+ }
464
+ if (left.kind === "parameter" && right.kind === "static") {
465
+ const remaining = remainingStaticPath(second, index);
466
+ if (customPattern(left.value) !== null && remaining !== null && parameterAccepts(left.value, remaining)) {
467
+ return true;
468
+ }
469
+ if (!parameterAccepts(left.value, right.value)) {
470
+ return customPattern(left.value) !== null && remaining === null;
471
+ }
472
+ if (customPattern(left.value) !== null && first.length !== second.length) {
473
+ return true;
474
+ }
475
+ continue;
476
+ }
477
+ if (left.kind === "static" && right.kind === "parameter") {
478
+ const remaining = remainingStaticPath(first, index);
479
+ if (customPattern(right.value) !== null && remaining !== null && parameterAccepts(right.value, remaining)) {
480
+ return true;
481
+ }
482
+ if (!parameterAccepts(right.value, left.value)) {
483
+ return customPattern(right.value) !== null && remaining === null;
484
+ }
485
+ if (customPattern(right.value) !== null && first.length !== second.length) {
486
+ return true;
487
+ }
488
+ continue;
489
+ }
490
+ return true;
491
+ }
492
+ return true;
493
+ }
494
+
495
+ // src/surface/module.ts
496
+ var MODULE_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
497
+ var COMMAND_NAME = /^[A-Za-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)*$/;
498
+ var CONTRACT_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)*$/;
499
+ var EFFECTS = /* @__PURE__ */ new Set(["read", "write", "destructive"]);
500
+ var PATH_BASE = "https://spfn.invalid";
501
+ function assertText(label, value) {
502
+ if (typeof value !== "string" || value.trim().length === 0) {
503
+ throw new SurfaceError(`${label} must be a non-empty string.`);
504
+ }
505
+ }
506
+ function assertStableModulePath(at, moduleId, commandName, path) {
507
+ const label = `${at.label} command "${moduleId}.${commandName}" path "${path}"`;
508
+ const transportPath = path.replace(/[{}?#]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
509
+ let url;
510
+ try {
511
+ url = new URL(transportPath, PATH_BASE);
512
+ } catch {
513
+ throw new SurfaceError(`${label} is not a valid URL path.`);
514
+ }
515
+ if (url.origin !== PATH_BASE || url.search !== "" || url.hash !== "" || url.pathname !== transportPath) {
516
+ throw new SurfaceError(`${label} is not a stable plain absolute path.`);
517
+ }
518
+ const slashCount = (path.match(/\//g) ?? []).length;
519
+ let decoded = path;
520
+ for (let depth = 0; depth < 8; depth++) {
521
+ let next;
522
+ try {
523
+ next = decodeURIComponent(decoded);
524
+ } catch {
525
+ throw new SurfaceError(`${label} contains malformed percent encoding.`);
526
+ }
527
+ if (next.includes("\\") || (next.match(/\//g) ?? []).length !== slashCount || next.split("/").some((segment) => segment === "." || segment === "..")) {
528
+ throw new SurfaceError(`${label} contains encoded path separators or dot segments.`);
529
+ }
530
+ if (next === decoded) {
531
+ return;
532
+ }
533
+ decoded = next;
534
+ }
535
+ throw new SurfaceError(`${label} uses too many percent-encoding layers.`);
536
+ }
537
+ function assertCliCallableModulePath(at, moduleId, commandName, path) {
538
+ const unsupported = path.split("/").slice(1).find((segment) => segment === "*" || segment.includes("*") || (segment.startsWith(":") ? !/^:[A-Za-z0-9_]+$/.test(segment) : !/^[A-Za-z0-9._~-]+$/.test(segment)));
539
+ if (unsupported !== void 0) {
540
+ throw new SurfaceError(
541
+ `${at.label} command "${moduleId}.${commandName}" path segment "${unsupported}" is not CLI-callable. Module routes support URL-safe static segments and simple :name parameters only; optional, wildcard, and custom-regex parameters are not supported.`
542
+ );
543
+ }
544
+ }
545
+ function assertCommand(at, moduleId, name, command) {
546
+ if (!COMMAND_NAME.test(name)) {
547
+ throw new SurfaceError(
548
+ `${at.label} module "${moduleId}" has invalid command name "${name}". Use dot-separated alphanumeric names.`
549
+ );
550
+ }
551
+ assertText(`${at.label} command "${moduleId}.${name}" summary`, command?.summary);
552
+ if (!EFFECTS.has(command?.effect)) {
553
+ throw new SurfaceError(
554
+ `${at.label} command "${moduleId}.${name}" has invalid effect ${JSON.stringify(command?.effect)}.`
555
+ );
556
+ }
557
+ if (!Array.isArray(command?.scopes) || command.scopes.length === 0 || command.scopes.some((scope) => typeof scope !== "string" || scope.trim().length === 0)) {
558
+ throw new SurfaceError(`${at.label} command "${moduleId}.${name}" must declare at least one non-empty scope.`);
559
+ }
560
+ const route2 = command?.route;
561
+ if (!route2 || typeof route2.handler !== "function" || !route2.method || !route2.path) {
562
+ throw new SurfaceError(`${at.label} command "${moduleId}.${name}" must carry a complete route.`);
563
+ }
564
+ assertStableModulePath(at, moduleId, name, route2.path);
565
+ assertCliCallableModulePath(at, moduleId, name, route2.path);
566
+ const modulePath = `${at.namespace}/${moduleId}/`;
567
+ if (!route2.path.startsWith(modulePath)) {
568
+ throw new SurfaceError(
569
+ `${at.label} command "${moduleId}.${name}" is at "${route2.path}", outside "${modulePath}". A module mounted on "${at.namespace}" keeps every command under "${modulePath}".`
570
+ );
571
+ }
572
+ if (route2.path.split("/").includes("..")) {
573
+ throw new SurfaceError(`${at.label} command "${moduleId}.${name}" path climbs out of its module namespace.`);
574
+ }
575
+ }
576
+ function validateSurfaceModule(module, namespace, wording = SURFACE_WORDING) {
577
+ const at = { namespace, label: capitalized(wording.noun) };
578
+ if (!MODULE_ID.test(module?.id ?? "")) {
579
+ throw new SurfaceError(
580
+ `${at.label} module id ${JSON.stringify(module?.id)} is invalid. Use lower-kebab-case.`
581
+ );
582
+ }
583
+ assertText(`${at.label} module "${module.id}" source`, module.source);
584
+ assertText(`${at.label} module "${module.id}" summary`, module.summary);
585
+ if (!CONTRACT_VERSION.test(module.contractVersion)) {
586
+ throw new SurfaceError(
587
+ `${at.label} module "${module.id}" contractVersion must be a semantic version.`
588
+ );
589
+ }
590
+ if (!module.commands || typeof module.commands !== "object" || Array.isArray(module.commands)) {
591
+ throw new SurfaceError(`${at.label} module "${module.id}" commands must be an object.`);
592
+ }
593
+ const signatures = /* @__PURE__ */ new Map();
594
+ const claimedRoutes = [];
595
+ for (const [name, command] of Object.entries(module.commands)) {
596
+ assertCommand(at, module.id, name, command);
597
+ const signature = `${command.route.method} ${command.route.path}`;
598
+ const existing = signatures.get(signature);
599
+ if (existing) {
600
+ throw new SurfaceError(
601
+ `${at.label} module "${module.id}" commands "${existing}" and "${name}" both use ${signature}.`
602
+ );
603
+ }
604
+ signatures.set(signature, name);
605
+ const overlapping = claimedRoutes.find((claim) => claim.method === command.route.method && routePatternsOverlap(claim.path, command.route.path));
606
+ if (overlapping) {
607
+ throw new SurfaceError(
608
+ `${at.label} module "${module.id}" commands "${overlapping.name}" and "${name}" have overlapping ${command.route.method} routes ("${overlapping.path}" and "${command.route.path}").`
609
+ );
610
+ }
611
+ claimedRoutes.push({
612
+ name,
613
+ method: command.route.method,
614
+ path: command.route.path
615
+ });
616
+ }
617
+ return module;
618
+ }
619
+ function defineSurfaceModule(module, namespace) {
620
+ return validateSurfaceModule(module, namespace);
621
+ }
622
+
623
+ // src/surface/namespace.ts
624
+ var NAMESPACE = /^(?:\/[A-Za-z0-9_-]+)+$/;
625
+ function assertNamespace(namespace) {
626
+ if (typeof namespace !== "string" || !NAMESPACE.test(namespace)) {
627
+ throw new SurfaceError(
628
+ `Surface namespace ${JSON.stringify(namespace)} is invalid. Use an absolute path of [A-Za-z0-9_-] segments without a trailing slash, such as "/_app".`
629
+ );
630
+ }
631
+ }
632
+ function manifestPathOf(namespace) {
633
+ return `${namespace}/_manifest`;
634
+ }
635
+ function manifestNameOf(namespace) {
636
+ return `get${namespace.slice(1).replace(/_[a-z]|[A-Z_/-]/g, encodedCharacter)}Manifest`;
637
+ }
638
+ var ESCAPES = { "_": "_", "-": "d", "/": "s" };
639
+ function encodedCharacter(match) {
640
+ if (match.length === 2) {
641
+ return match.charAt(1).toUpperCase();
642
+ }
643
+ return `_${ESCAPES[match] ?? match}`;
644
+ }
645
+ function toSurfacePath(namespace, path, wording) {
646
+ const label = capitalized(wording.noun);
647
+ if (!path.startsWith("/")) {
648
+ throw new SurfaceError(
649
+ `${label} route path "${path}" must start with "/". It is appended to "${namespace}", so "${path}" would read as "${namespace}${path}".`
650
+ );
651
+ }
652
+ if (path === "/") {
653
+ throw new SurfaceError(
654
+ `${label} route path "/" names no command \u2014 "${namespace}" itself is not a command.`
655
+ );
656
+ }
657
+ return namespace + path;
658
+ }
659
+ function surfaceRouteBuilder(namespace, wording) {
660
+ const method = (name) => (path) => route[name](toSurfacePath(namespace, path, wording));
661
+ return {
662
+ get: method("get"),
663
+ post: method("post"),
664
+ put: method("put"),
665
+ patch: method("patch"),
666
+ delete: method("delete")
667
+ };
668
+ }
669
+
670
+ // src/surface/define-surface.ts
671
+ function isRouter2(value) {
672
+ return value !== null && typeof value === "object" && "routes" in value && "_routes" in value;
673
+ }
674
+ function isRouteDef2(value) {
675
+ return value !== null && typeof value === "object" && "handler" in value;
676
+ }
677
+ function assertSurfaceRoute(plan, name, def) {
678
+ const label = capitalized(plan.wording.noun);
679
+ if (!def.method || !def.path) {
680
+ throw new SurfaceError(
681
+ `${label} route "${name}" has no method or path. A command is invoked on the wire, so both are required.`
682
+ );
683
+ }
684
+ if (!def.path.startsWith(plan.prefix)) {
685
+ throw new SurfaceError(
686
+ `${label} route "${name}" is at "${def.path}", outside "${plan.prefix}". Build ${plan.wording.noun} routes with ${plan.wording.builder} rather than \`route\` \u2014 it applies the namespace, so the path a definition carries is only the part the app owns.`
687
+ );
688
+ }
689
+ if (def.path === plan.manifestPath) {
690
+ throw new SurfaceError(
691
+ `${label} route "${name}" claims "${plan.manifestPath}", which is reserved for the manifest. The manifest is registered first, so this route would never answer.`
692
+ );
693
+ }
694
+ }
695
+ function assertSurfaceName(plan, name) {
696
+ if (name === plan.manifestName) {
697
+ throw new SurfaceError(
698
+ `${capitalized(plan.wording.noun)} route name "${plan.manifestName}" is reserved for the manifest route.`
699
+ );
700
+ }
701
+ }
702
+ function rebuildNestedRouter(plan, name, router, guards, inherited) {
703
+ if (router._packageRouters?.length > 0) {
704
+ throw new SurfaceError(
705
+ `${capitalized(plan.wording.noun)} router "${name}" mounts package routers with .packages(). Their routes bypass the prefix check and the auth injection, so a surface cannot carry them.`
706
+ );
707
+ }
708
+ const handedDown = [...inherited, ...router._globalMiddlewares ?? []];
709
+ let rebuilt = defineUnmappedRouter(
710
+ secureRoutes(plan, router.routes, guards, handedDown)
711
+ );
712
+ if (router._contractVersion) {
713
+ rebuilt = rebuilt.contractVersion(router._contractVersion);
714
+ }
715
+ return rebuilt;
716
+ }
717
+ function secureRoutes(plan, routes, guards, inherited = []) {
718
+ const secured = {};
719
+ for (const [name, entry] of Object.entries(routes)) {
720
+ assertSurfaceName(plan, name);
721
+ if (isRouter2(entry)) {
722
+ secured[name] = rebuildNestedRouter(plan, name, entry, guards, inherited);
723
+ continue;
724
+ }
725
+ if (!isRouteDef2(entry)) {
726
+ throw new SurfaceError(
727
+ `${capitalized(plan.wording.noun)} router entry "${name}" is neither a route nor a router.`
728
+ );
729
+ }
730
+ assertSurfaceRoute(plan, name, entry);
731
+ secured[name] = {
732
+ ...entry,
733
+ middlewares: commandChain(plan, name, guards.get(name), [...inherited, ...entry.middlewares ?? []])
734
+ };
735
+ }
736
+ return secured;
737
+ }
738
+ function commandChain(plan, name, guard, declared) {
739
+ if (guard === void 0) {
740
+ return [plan.auth, ...declared];
741
+ }
742
+ const guardName = middlewareNameOf(guard);
743
+ if (guardName !== void 0) {
744
+ refuseGuardCollision(plan, name, guardName, declared);
745
+ }
746
+ return [plan.auth, guard, ...declared];
747
+ }
748
+ function refuseGuardCollision(plan, name, guardName, declared) {
749
+ const noun = capitalized(plan.wording.noun);
750
+ if (middlewareNameOf(plan.auth) === guardName) {
751
+ throw new SurfaceError(
752
+ `${noun} command "${name}"'s guard shares the name "${guardName}" with the surface's auth middleware. Route registration keeps one middleware per name, so the command's guard would never run. Give one of the two a distinct name.`
753
+ );
754
+ }
755
+ if (declared.some((middleware) => middlewareNameOf(middleware) === guardName)) {
756
+ throw new SurfaceError(
757
+ `${noun} command "${name}" declares a middleware named "${guardName}", the name of the guard authorize gave it. Route registration keeps one middleware per name, so the command's own guard would never run. Give one of the two a distinct name.`
758
+ );
759
+ }
760
+ }
761
+ function middlewareNameOf(middleware) {
762
+ return typeof middleware === "function" ? void 0 : middleware.name;
763
+ }
764
+ function guardsFor(plan, commands) {
765
+ return new Map(commands.map((command) => [command.name, plan.authorize?.(command)]));
766
+ }
767
+ function assertModuleCommandFree(plan, command, appCommands, claimed) {
768
+ const noun = plan.wording.noun;
769
+ if (claimed.names.has(command.name)) {
770
+ throw new SurfaceError(`Two ${noun} commands are named "${command.name}".`);
771
+ }
772
+ const signature = `${command.method} ${command.path}`;
773
+ const existing = claimed.signatures.get(signature);
774
+ if (existing) {
775
+ throw new SurfaceError(
776
+ `${capitalized(noun)} commands "${existing}" and "${command.name}" both use ${signature}.`
777
+ );
778
+ }
779
+ const overlapping = appCommands.find((app) => app.method === command.method && routePatternsOverlap(app.path, command.path));
780
+ if (overlapping) {
781
+ throw new SurfaceError(
782
+ `App ${noun} command "${overlapping.name}" at ${command.method} ${overlapping.path} overlaps module command "${command.name}" at ${command.method} ${command.path}. Which one answers cannot depend on route registration order.`
783
+ );
784
+ }
785
+ claimed.names.add(command.name);
786
+ claimed.signatures.set(signature, command.name);
787
+ }
788
+ function compileModules(plan, appCommands) {
789
+ const compiled = { descriptors: [], commands: [], routes: {} };
790
+ const moduleIds = /* @__PURE__ */ new Set();
791
+ const claimed = {
792
+ names: new Set(appCommands.map((command) => command.name)),
793
+ signatures: new Map(appCommands.map((command) => [`${command.method} ${command.path}`, command.name]))
794
+ };
795
+ for (const rawModule of plan.modules) {
796
+ const module = validateSurfaceModule(rawModule, plan.namespace, plan.wording);
797
+ if (moduleIds.has(module.id)) {
798
+ throw new SurfaceError(`Two ${plan.wording.noun} modules use id "${module.id}".`);
799
+ }
800
+ moduleIds.add(module.id);
801
+ compiled.descriptors.push({
802
+ id: module.id,
803
+ source: module.source,
804
+ contractVersion: module.contractVersion,
805
+ summary: module.summary
806
+ });
807
+ for (const [localName, definition] of Object.entries(module.commands)) {
808
+ const command = {
809
+ name: `${module.id}.${localName}`,
810
+ module: module.id,
811
+ summary: definition.summary,
812
+ effect: definition.effect,
813
+ scopes: [...definition.scopes],
814
+ method: definition.route.method,
815
+ path: definition.route.path,
816
+ input: collectSurfaceCommands({ [localName]: definition.route }, plan.wording)[0].input
817
+ };
818
+ assertModuleCommandFree(plan, command, appCommands, claimed);
819
+ compiled.commands.push(command);
820
+ compiled.routes[command.name] = { route: definition.route, command };
821
+ }
822
+ }
823
+ compiled.descriptors.sort((a, b) => a.id.localeCompare(b.id));
824
+ compiled.commands.sort((a, b) => a.name.localeCompare(b.name));
825
+ return compiled;
826
+ }
827
+ function secureModuleRoutes(plan, routes) {
828
+ const secured = {};
829
+ for (const [name, definition] of Object.entries(routes)) {
830
+ assertSurfaceName(plan, name);
831
+ assertSurfaceRoute(plan, name, definition.route);
832
+ secured[name] = {
833
+ ...definition.route,
834
+ middlewares: commandChain(
835
+ plan,
836
+ name,
837
+ plan.authorize?.(definition.command),
838
+ definition.route.middlewares ?? []
839
+ )
840
+ };
841
+ }
842
+ return secured;
843
+ }
844
+ function manifestRoute(plan, manifest) {
845
+ const builder = route.get(plan.manifestPath);
846
+ return (plan.manifest === "public" ? builder.skip(["auth"]) : builder.use([plan.auth])).handler(async () => manifest);
847
+ }
848
+ function buildRouter(plan, routes) {
849
+ const appCommands = collectSurfaceCommands(routes, plan.wording);
850
+ const moduleSurface = compileModules(plan, appCommands);
851
+ const commands = [...appCommands, ...moduleSurface.commands].sort((a, b) => a.name.localeCompare(b.name));
852
+ const manifest = {
853
+ manifestVersion: 1,
854
+ ...moduleSurface.descriptors.length > 0 ? { modules: moduleSurface.descriptors } : {},
855
+ commands
856
+ };
857
+ const secured = secureRoutes(plan, routes, guardsFor(plan, appCommands));
858
+ const securedModules = secureModuleRoutes(plan, moduleSurface.routes);
859
+ return Object.defineProperty(defineUnmappedRouter({
860
+ [plan.manifestName]: manifestRoute(plan, manifest),
861
+ ...secured,
862
+ ...securedModules
863
+ }), "_surfaceNamespace", { value: plan.namespace, enumerable: false });
864
+ }
865
+ function planOf(options, wording) {
866
+ assertNamespace(options?.namespace);
867
+ if (!options.auth) {
868
+ throw new SurfaceError(
869
+ `${wording.factory} requires an auth middleware ({ auth: ... }). A surface reachable without authentication cannot be created.`
870
+ );
871
+ }
872
+ const modules = options.modules ?? [];
873
+ if (modules.length > 0 && !options.authorize) {
874
+ throw new SurfaceError(`${wording.factory} requires an authorize function when modules are mounted.`);
875
+ }
876
+ const manifest = options.manifest ?? "authenticated";
877
+ if (manifest !== "authenticated" && manifest !== "public") {
878
+ throw new SurfaceError(
879
+ `${wording.factory} manifest must be 'authenticated' or 'public', got ${JSON.stringify(manifest)}.`
880
+ );
881
+ }
882
+ return {
883
+ namespace: options.namespace,
884
+ prefix: `${options.namespace}/`,
885
+ manifestPath: manifestPathOf(options.namespace),
886
+ manifestName: manifestNameOf(options.namespace),
887
+ auth: options.auth,
888
+ authorize: options.authorize,
889
+ manifest,
890
+ modules,
891
+ wording
892
+ };
893
+ }
894
+ function createSurface(options, wording) {
895
+ const plan = planOf(options, wording);
896
+ return {
897
+ namespace: plan.namespace,
898
+ route: surfaceRouteBuilder(plan.namespace, wording),
899
+ router: (routes) => buildRouter(plan, routes)
900
+ };
901
+ }
902
+ function defineSurface(options) {
903
+ return createSurface(options, SURFACE_WORDING);
904
+ }
905
+
906
+ export { SurfaceError, collectSurfaceCommands, defineSurface, defineSurfaceModule };
907
+ //# sourceMappingURL=index.js.map
908
+ //# sourceMappingURL=index.js.map