alepha 0.14.3 → 0.14.4
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/README.md +1 -1
- package/dist/api/audits/index.d.ts +338 -417
- package/dist/api/audits/index.d.ts.map +1 -1
- package/dist/api/files/index.d.ts +1 -80
- package/dist/api/files/index.d.ts.map +1 -1
- package/dist/api/jobs/index.d.ts +156 -235
- package/dist/api/jobs/index.d.ts.map +1 -1
- package/dist/api/notifications/index.d.ts +170 -249
- package/dist/api/notifications/index.d.ts.map +1 -1
- package/dist/api/parameters/index.d.ts +266 -345
- package/dist/api/parameters/index.d.ts.map +1 -1
- package/dist/api/users/index.d.ts +755 -834
- package/dist/api/users/index.d.ts.map +1 -1
- package/dist/api/verifications/index.d.ts +125 -125
- package/dist/api/verifications/index.d.ts.map +1 -1
- package/dist/cli/index.d.ts +116 -20
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +212 -124
- package/dist/cli/index.js.map +1 -1
- package/dist/command/index.d.ts +6 -11
- package/dist/command/index.d.ts.map +1 -1
- package/dist/command/index.js +2 -2
- package/dist/command/index.js.map +1 -1
- package/dist/core/index.browser.js +26 -4
- package/dist/core/index.browser.js.map +1 -1
- package/dist/core/index.d.ts +16 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +26 -4
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.native.js +26 -4
- package/dist/core/index.native.js.map +1 -1
- package/dist/logger/index.d.ts +1 -1
- package/dist/logger/index.d.ts.map +1 -1
- package/dist/logger/index.js +12 -2
- package/dist/logger/index.js.map +1 -1
- package/dist/mcp/index.d.ts.map +1 -1
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/index.js.map +1 -1
- package/dist/orm/index.d.ts +37 -173
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +193 -422
- package/dist/orm/index.js.map +1 -1
- package/dist/server/auth/index.d.ts +167 -167
- package/dist/server/cache/index.d.ts +12 -0
- package/dist/server/cache/index.d.ts.map +1 -1
- package/dist/server/cache/index.js +55 -2
- package/dist/server/cache/index.js.map +1 -1
- package/dist/server/compress/index.d.ts +6 -0
- package/dist/server/compress/index.d.ts.map +1 -1
- package/dist/server/compress/index.js +36 -1
- package/dist/server/compress/index.js.map +1 -1
- package/dist/server/core/index.browser.js +2 -2
- package/dist/server/core/index.browser.js.map +1 -1
- package/dist/server/core/index.d.ts +10 -10
- package/dist/server/core/index.d.ts.map +1 -1
- package/dist/server/core/index.js +6 -3
- package/dist/server/core/index.js.map +1 -1
- package/dist/server/links/index.d.ts +39 -39
- package/dist/server/links/index.d.ts.map +1 -1
- package/dist/server/security/index.d.ts +9 -9
- package/dist/server/static/index.d.ts.map +1 -1
- package/dist/server/static/index.js +4 -0
- package/dist/server/static/index.js.map +1 -1
- package/dist/server/swagger/index.d.ts.map +1 -1
- package/dist/server/swagger/index.js +2 -3
- package/dist/server/swagger/index.js.map +1 -1
- package/dist/vite/index.d.ts +101 -106
- package/dist/vite/index.d.ts.map +1 -1
- package/dist/vite/index.js +571 -508
- package/dist/vite/index.js.map +1 -1
- package/package.json +1 -1
- package/src/cli/apps/AlephaCli.ts +0 -2
- package/src/cli/atoms/buildOptions.ts +88 -0
- package/src/cli/commands/build.ts +32 -69
- package/src/cli/commands/db.ts +0 -4
- package/src/cli/commands/dev.ts +16 -4
- package/src/cli/commands/gen/env.ts +53 -0
- package/src/cli/commands/gen/openapi.ts +1 -1
- package/src/cli/commands/gen/resource.ts +15 -0
- package/src/cli/commands/gen.ts +7 -1
- package/src/cli/commands/init.ts +0 -1
- package/src/cli/commands/test.ts +0 -1
- package/src/cli/commands/verify.ts +1 -1
- package/src/cli/defineConfig.ts +49 -7
- package/src/cli/index.ts +0 -1
- package/src/cli/services/AlephaCliUtils.ts +36 -25
- package/src/command/helpers/Runner.spec.ts +2 -2
- package/src/command/helpers/Runner.ts +1 -1
- package/src/command/primitives/$command.ts +0 -6
- package/src/command/providers/CliProvider.ts +1 -3
- package/src/core/Alepha.ts +42 -0
- package/src/logger/index.ts +15 -3
- package/src/mcp/transports/StdioMcpTransport.ts +1 -1
- package/src/orm/index.ts +2 -8
- package/src/queue/core/providers/WorkerProvider.spec.ts +48 -32
- package/src/server/cache/providers/ServerCacheProvider.spec.ts +183 -0
- package/src/server/cache/providers/ServerCacheProvider.ts +94 -9
- package/src/server/compress/providers/ServerCompressProvider.ts +61 -2
- package/src/server/core/helpers/ServerReply.ts +2 -2
- package/src/server/core/providers/ServerProvider.ts +11 -1
- package/src/server/static/providers/ServerStaticProvider.ts +10 -0
- package/src/server/swagger/providers/ServerSwaggerProvider.ts +5 -8
- package/src/vite/helpers/importViteReact.ts +13 -0
- package/src/vite/index.ts +1 -21
- package/src/vite/plugins/viteAlephaDev.ts +16 -1
- package/src/vite/plugins/viteAlephaSsrPreload.ts +222 -0
- package/src/vite/tasks/buildClient.ts +11 -0
- package/src/vite/tasks/buildServer.ts +47 -3
- package/src/vite/tasks/devServer.ts +69 -0
- package/src/vite/tasks/index.ts +2 -1
- package/src/cli/assets/viteConfigTs.ts +0 -14
- package/src/cli/commands/run.ts +0 -24
- package/src/vite/plugins/viteAlepha.ts +0 -37
- package/src/vite/plugins/viteAlephaBuild.ts +0 -281
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ServerRouteSecure } from "alepha/server/security";
|
|
2
|
-
import * as
|
|
2
|
+
import * as alepha23 from "alepha";
|
|
3
3
|
import { Alepha, Async, KIND, Primitive, Static } from "alepha";
|
|
4
4
|
import * as alepha_server0 from "alepha/server";
|
|
5
5
|
import { ActionPrimitive, ClientRequestEntry, ClientRequestOptions, ClientRequestResponse, FetchResponse, HttpClient, RequestConfigSchema, ServerRequest, ServerRequestConfigEntry, ServerResponseBody, ServerTimingProvider } from "alepha/server";
|
|
@@ -9,30 +9,30 @@ import { ProxyPrimitiveOptions, ServerProxyProvider } from "alepha/server/proxy"
|
|
|
9
9
|
import { ServiceAccountPrimitive, UserAccountToken } from "alepha/security";
|
|
10
10
|
|
|
11
11
|
//#region ../../src/server/links/schemas/apiLinksResponseSchema.d.ts
|
|
12
|
-
declare const apiLinkSchema:
|
|
13
|
-
name:
|
|
14
|
-
group:
|
|
15
|
-
path:
|
|
16
|
-
method:
|
|
17
|
-
requestBodyType:
|
|
18
|
-
service:
|
|
19
|
-
rawSchema:
|
|
20
|
-
body:
|
|
21
|
-
response:
|
|
12
|
+
declare const apiLinkSchema: alepha23.TObject<{
|
|
13
|
+
name: alepha23.TString;
|
|
14
|
+
group: alepha23.TOptional<alepha23.TString>;
|
|
15
|
+
path: alepha23.TString;
|
|
16
|
+
method: alepha23.TOptional<alepha23.TString>;
|
|
17
|
+
requestBodyType: alepha23.TOptional<alepha23.TString>;
|
|
18
|
+
service: alepha23.TOptional<alepha23.TString>;
|
|
19
|
+
rawSchema: alepha23.TOptional<alepha23.TObject<{
|
|
20
|
+
body: alepha23.TOptional<alepha23.TString>;
|
|
21
|
+
response: alepha23.TOptional<alepha23.TString>;
|
|
22
22
|
}>>;
|
|
23
23
|
}>;
|
|
24
|
-
declare const apiLinksResponseSchema:
|
|
25
|
-
prefix:
|
|
26
|
-
links:
|
|
27
|
-
name:
|
|
28
|
-
group:
|
|
29
|
-
path:
|
|
30
|
-
method:
|
|
31
|
-
requestBodyType:
|
|
32
|
-
service:
|
|
33
|
-
rawSchema:
|
|
34
|
-
body:
|
|
35
|
-
response:
|
|
24
|
+
declare const apiLinksResponseSchema: alepha23.TObject<{
|
|
25
|
+
prefix: alepha23.TOptional<alepha23.TString>;
|
|
26
|
+
links: alepha23.TArray<alepha23.TObject<{
|
|
27
|
+
name: alepha23.TString;
|
|
28
|
+
group: alepha23.TOptional<alepha23.TString>;
|
|
29
|
+
path: alepha23.TString;
|
|
30
|
+
method: alepha23.TOptional<alepha23.TString>;
|
|
31
|
+
requestBodyType: alepha23.TOptional<alepha23.TString>;
|
|
32
|
+
service: alepha23.TOptional<alepha23.TString>;
|
|
33
|
+
rawSchema: alepha23.TOptional<alepha23.TObject<{
|
|
34
|
+
body: alepha23.TOptional<alepha23.TString>;
|
|
35
|
+
response: alepha23.TOptional<alepha23.TString>;
|
|
36
36
|
}>>;
|
|
37
37
|
}>>;
|
|
38
38
|
}>;
|
|
@@ -191,8 +191,8 @@ declare class RemotePrimitiveProvider {
|
|
|
191
191
|
protected readonly remotes: Array<ServerRemote>;
|
|
192
192
|
protected readonly log: alepha_logger0.Logger;
|
|
193
193
|
getRemotes(): ServerRemote[];
|
|
194
|
-
readonly configure:
|
|
195
|
-
readonly start:
|
|
194
|
+
readonly configure: alepha23.HookPrimitive<"configure">;
|
|
195
|
+
readonly start: alepha23.HookPrimitive<"start">;
|
|
196
196
|
registerRemote(value: RemotePrimitive): Promise<void>;
|
|
197
197
|
protected readonly fetchLinks: alepha_retry0.RetryPrimitiveFn<(opts: FetchLinksOptions) => Promise<ApiLinksResponse>>;
|
|
198
198
|
}
|
|
@@ -260,25 +260,25 @@ declare class ServerLinksProvider {
|
|
|
260
260
|
protected readonly remoteProvider: RemotePrimitiveProvider;
|
|
261
261
|
protected readonly serverTimingProvider: ServerTimingProvider;
|
|
262
262
|
get prefix(): string;
|
|
263
|
-
readonly onRoute:
|
|
263
|
+
readonly onRoute: alepha23.HookPrimitive<"configure">;
|
|
264
264
|
/**
|
|
265
265
|
* First API - Get all API links for the user.
|
|
266
266
|
*
|
|
267
267
|
* This is based on the user's permissions.
|
|
268
268
|
*/
|
|
269
269
|
readonly links: alepha_server0.RoutePrimitive<{
|
|
270
|
-
response:
|
|
271
|
-
prefix:
|
|
272
|
-
links:
|
|
273
|
-
name:
|
|
274
|
-
group:
|
|
275
|
-
path:
|
|
276
|
-
method:
|
|
277
|
-
requestBodyType:
|
|
278
|
-
service:
|
|
279
|
-
rawSchema:
|
|
280
|
-
body:
|
|
281
|
-
response:
|
|
270
|
+
response: alepha23.TObject<{
|
|
271
|
+
prefix: alepha23.TOptional<alepha23.TString>;
|
|
272
|
+
links: alepha23.TArray<alepha23.TObject<{
|
|
273
|
+
name: alepha23.TString;
|
|
274
|
+
group: alepha23.TOptional<alepha23.TString>;
|
|
275
|
+
path: alepha23.TString;
|
|
276
|
+
method: alepha23.TOptional<alepha23.TString>;
|
|
277
|
+
requestBodyType: alepha23.TOptional<alepha23.TString>;
|
|
278
|
+
service: alepha23.TOptional<alepha23.TString>;
|
|
279
|
+
rawSchema: alepha23.TOptional<alepha23.TObject<{
|
|
280
|
+
body: alepha23.TOptional<alepha23.TString>;
|
|
281
|
+
response: alepha23.TOptional<alepha23.TString>;
|
|
282
282
|
}>>;
|
|
283
283
|
}>>;
|
|
284
284
|
}>;
|
|
@@ -317,7 +317,7 @@ declare module "alepha" {
|
|
|
317
317
|
* @see {@link $client}
|
|
318
318
|
* @module alepha.server.links
|
|
319
319
|
*/
|
|
320
|
-
declare const AlephaServerLinks:
|
|
320
|
+
declare const AlephaServerLinks: alepha23.Service<alepha23.Module>;
|
|
321
321
|
//#endregion
|
|
322
322
|
export { $client, $remote, AlephaServerLinks, ApiLink, ApiLinksResponse, ClientScope, FetchLinksOptions, GetApiLinksOptions, HttpClientLink, HttpVirtualClient, LinkProvider, RemotePrimitive, RemotePrimitiveOptions, RemotePrimitiveProvider, ServerLinksProvider, ServerRemote, VirtualAction, apiLinkSchema, apiLinksResponseSchema };
|
|
323
323
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/server/links/schemas/apiLinksResponseSchema.ts","../../../src/server/links/providers/LinkProvider.ts","../../../src/server/links/primitives/$client.ts","../../../src/server/links/primitives/$remote.ts","../../../src/server/links/providers/RemotePrimitiveProvider.ts","../../../src/server/links/providers/ServerLinksProvider.ts","../../../src/server/links/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;cAGa,
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/server/links/schemas/apiLinksResponseSchema.ts","../../../src/server/links/providers/LinkProvider.ts","../../../src/server/links/primitives/$client.ts","../../../src/server/links/primitives/$remote.ts","../../../src/server/links/providers/RemotePrimitiveProvider.ts","../../../src/server/links/providers/ServerLinksProvider.ts","../../../src/server/links/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;cAGa,wBAAa;QA2CxB,QAAA,CAAA;;;;;;;;;EA3CW,CAAA,CAAA,CAAA;CA2CX,CAAA;cAEW,iCAAsB;6BAGjC,QAAA,CAAA,OAAA;;;;;;;;;;;;;;KAEU,gBAAA,GAAmB,MAlDL,CAAA,OAkDmB,sBAlDnB,CAAA;AAAA,KAmDd,OAAA,GAAU,MAnDI,CAAA,OAmDU,aAnDV,CAAA;;;;;;cC8Bb,YAAA;;;;ED9BA,mBA2CX,GAAA,ECbuB,cAAA,CAKD,MDQtB;EAAA,mBAAA,MAAA,ECPyB,MDOzB;iCCN6B;yBAIN,MAAM;;;;;oBAMJ;;;;qBAcC;eA8BN;;;;YD3FI,CAAA,CAAA,ECsHG,ODtHH,CCsHW,cDtHX,EAAA,CAAA;EAAA;AA6C1B;;;;mCC+FW,cACN,kBAAkB;;;;;;;;;;;gCA2BX,QAAQ,qCACP,uBAAuB,cAC/B;0CAiCqC,2CAE/B,cACN,cAAc;+BA8DT,yBACE,QAAQ,qCACP,uBACR,QAAQ;kDA2CA,cACR,QAAQ;;UAsCI,cAAA,SAAuB;SDpTL,CAAA,EAAA,OAAA,GCqTb,iBDrTa;EAAA,MAAA,CAAA,EAAA,MAAA;EAKvB,IAAA,CAAA,EAAA,MAAA;EACA,OAAA,CAAA,EAAO,MAAA;WCsTR;sBAEE,wBACA,yBACN,MAAM;;AA/UA,UAkVI,WAAA,CAlVQ;EAAA,KAAA,CAAA,EAAA,MAKD;EACG,OAAA,CAAA,EAAA,MAAA;EACI,QAAA,CAAA,EAAA,MAAA;;AAIN,KA6Ub,iBA7Ua,CAAA,CAAA,CAAA,GAAA,QAME,MAwUb,CAxUa,IAwUR,CAxUQ,CAwUN,CAxUM,CAA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,CAUJ;wBAuCc,kBAAkB;iCAsEF,aAAA,CAXtB,wBAWL,sBAAoB,QAAQ;;UA0BrC,iBAAA;;;;;;;;EJ7KS,GAAA,EAAA,MAAA;EA6Cb;;;;;UIiJI,YAAA;;;;;;;;;;;;;;;;UJjJkB,EAAA,OAAA;EAAA;AAKnC;AACA;;;QImK+C,QAAQ;EHxL1C;;;EAOkB,MAAA,EAAA,CAAA,IAAA,EAAA;IAIA,IAAA,EAAA,MAAA;IAAN,aAAA,CAAA,EAAA,MAAA;EAME,CAAA,EAAA,GG4KmC,OH5KnC,CAAA,GAAA,CAAA;EAcC;;;EAyDC,cAAA,CAAA,EG0GV,uBH1GU;EAsBlB;;;EA4BS,MAAA,EAAA,MAAA;;;;cI9IP,mBAAA;;;;6BAEc;EL5Bd,mBA2CX,YAAA,EKd+B,YLc/B;EAAA,mBAAA,cAAA,EKbiC,uBLajC;2CKZuC;;oBAAA,QAAA,CAMhB;;;;;;iCA6BF;;iCA7BE,QAAA,CAAA,OAAA;;;;;QLrCC,MAAA,oBAAA,kBAAA;QAAA,eAAA,oBAAA,kBAAA;QA6Cb,OAAA,oBAGX,kBAAA;QAAA,SAAA,oBAAA,iBAAA,CAAA;;;;;;;;;;;2BKoCW,qBACR,QAAQ;;UAkGI,kBAAA;SACR;;;;;;;;ALxLT;;;;;uCM0BuC;;;;;;;;;;;;;;ANmB1B,cMFA,iBNKX,EML4B,QAAA,CAAA,ONK5B,CMIA,QAAA,CAT4B,MAAA,CNK5B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as alepha5 from "alepha";
|
|
2
2
|
import { Alepha, KIND, Primitive } from "alepha";
|
|
3
3
|
import { JwtProvider, Permission, SecurityProvider, UserAccount, UserAccountToken } from "alepha/security";
|
|
4
4
|
import { FetchOptions, ServerRequest, ServerRouterProvider } from "alepha/server";
|
|
@@ -28,15 +28,15 @@ declare class ServerBasicAuthProvider {
|
|
|
28
28
|
* Register a basic auth configuration (called by primitives)
|
|
29
29
|
*/
|
|
30
30
|
registerAuth(config: BasicAuthPrimitiveConfig): void;
|
|
31
|
-
readonly onStart:
|
|
31
|
+
readonly onStart: alepha5.HookPrimitive<"start">;
|
|
32
32
|
/**
|
|
33
33
|
* Hook into server:onRequest to check basic auth
|
|
34
34
|
*/
|
|
35
|
-
readonly onRequest:
|
|
35
|
+
readonly onRequest: alepha5.HookPrimitive<"server:onRequest">;
|
|
36
36
|
/**
|
|
37
37
|
* Hook into action:onRequest to check basic auth for actions
|
|
38
38
|
*/
|
|
39
|
-
readonly onActionRequest:
|
|
39
|
+
readonly onActionRequest: alepha5.HookPrimitive<"action:onRequest">;
|
|
40
40
|
/**
|
|
41
41
|
* Check basic authentication
|
|
42
42
|
*/
|
|
@@ -66,9 +66,9 @@ declare class ServerSecurityProvider {
|
|
|
66
66
|
protected readonly securityProvider: SecurityProvider;
|
|
67
67
|
protected readonly jwtProvider: JwtProvider;
|
|
68
68
|
protected readonly alepha: Alepha;
|
|
69
|
-
protected readonly onConfigure:
|
|
70
|
-
protected readonly onActionRequest:
|
|
71
|
-
protected readonly onRequest:
|
|
69
|
+
protected readonly onConfigure: alepha5.HookPrimitive<"configure">;
|
|
70
|
+
protected readonly onActionRequest: alepha5.HookPrimitive<"action:onRequest">;
|
|
71
|
+
protected readonly onRequest: alepha5.HookPrimitive<"server:onRequest">;
|
|
72
72
|
protected check(user: UserAccountToken, secure: ServerRouteSecure): void;
|
|
73
73
|
/**
|
|
74
74
|
* Get the user account token for a local action call.
|
|
@@ -85,7 +85,7 @@ declare class ServerSecurityProvider {
|
|
|
85
85
|
user?: UserAccountToken | "system" | "context";
|
|
86
86
|
}, permission?: Permission): UserAccountToken;
|
|
87
87
|
protected createTestUser(): UserAccountToken;
|
|
88
|
-
protected readonly onClientRequest:
|
|
88
|
+
protected readonly onClientRequest: alepha5.HookPrimitive<"client:onRequest">;
|
|
89
89
|
}
|
|
90
90
|
type ServerRouteSecure = {
|
|
91
91
|
realm?: string;
|
|
@@ -167,7 +167,7 @@ declare module "alepha/server" {
|
|
|
167
167
|
* @see {@link ServerSecurityProvider}
|
|
168
168
|
* @module alepha.server.security
|
|
169
169
|
*/
|
|
170
|
-
declare const AlephaServerSecurity:
|
|
170
|
+
declare const AlephaServerSecurity: alepha5.Service<alepha5.Module>;
|
|
171
171
|
//#endregion
|
|
172
172
|
export { $basicAuth, AbstractBasicAuthPrimitive, AlephaServerSecurity, BasicAuthOptions, BasicAuthPrimitive, BasicAuthPrimitiveConfig, ServerBasicAuthProvider, ServerRouteSecure, ServerSecurityProvider, isBasicAuth };
|
|
173
173
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/server/static/primitives/$serve.ts","../../../src/server/static/providers/ServerStaticProvider.ts","../../../src/server/static/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;cAMa;aAAmB,wBAA6B;;AAA7D,CAAA;AAAgC,UAIf,qBAAA,CAJe;EAA6B;;;;AAI7D;EA0DiB,IAAA,CAAA,EAAA,MAAA;EAuBJ;;;;AChFb;EAC2B,IAAA,CAAA,EAAA,MAAA;EACQ;;;;;EAIa,QAElB,CAAA,EAAA,OAAA;EAYjB;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/server/static/primitives/$serve.ts","../../../src/server/static/providers/ServerStaticProvider.ts","../../../src/server/static/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;cAMa;aAAmB,wBAA6B;;AAA7D,CAAA;AAAgC,UAIf,qBAAA,CAJe;EAA6B;;;;AAI7D;EA0DiB,IAAA,CAAA,EAAA,MAAA;EAuBJ;;;;AChFb;EAC2B,IAAA,CAAA,EAAA,MAAA;EACQ;;;;;EAIa,QAElB,CAAA,EAAA,OAAA;EAYjB;;;;;EAoLA,iBAAA,CAAA,EAAA,OAAA;EAwBR;;AAmBL;;;;EC5Oa;;;;;;;;;;;;;;;;;iBF+CI,QAAQ;;UAGR,mBAAA;;;;;;;;;;;;UAaP;;;;;;;;cAUG,cAAA,SAAuB,UAAU;;;cChFjC,oBAAA;6BACc;qCACQ;EDPtB,mBAEZ,gBAAA,ECMoC,gBDNpC;EAF+B,mBAAA,YAAA,ECSC,YDTD;EAA6B,mBAAA,GAAA,ECS5B,cAAA,CACT,MDVqC;kCCW3B;gCAAc,OAAA,CAElB;8BAYjB,wBACR;EDtBY,iBAAA,CAAA,QAAqB,EAAA,MAAA,EAuDb,OAAA,ECmDZ,qBDnDW,CAAA,ECoDnB,ODpDmB,CCoDX,aDpDW,CAAA;EAGP,UAAA,iBAAmB,CAAA,CAAA,EAAA,MAa1B,EAAA;EAUG,UAAA,eAAe,CAAA,QAAkB,EAAA,MAAA,EAAA,OAAV,ECwHvB,qBDxHgC,CAAA,EAAA;;;;EChFhC,WAAA,CAAA,GAAA,EAAA,MAAoB,EAAA,iBAAA,CAAA,EAAA,OAAA,CAAA,EAgO5B,OAhO4B,CAAA,MAAA,EAAA,CAAA;;AAEE,UAiPlB,cAAA,CAjPkB;EACE,OAAA,EAiP1B,qBAjP0B;EACJ,KAAA,EAAA,MAAA,EAAA;;;;;;;;;;ADTpB,cEYA,kBFVZ,EEU8B,OAAA,CAAA,OFV9B,CEcC,OAAA,CAJ6B,MAAA,CFV9B"}
|
|
@@ -97,6 +97,10 @@ var ServerStaticProvider = class {
|
|
|
97
97
|
return async (request) => {
|
|
98
98
|
const { headers, reply } = request;
|
|
99
99
|
let path = filepath;
|
|
100
|
+
if (options.path && options.path === request.url.pathname && !options.path.endsWith("/")) {
|
|
101
|
+
reply.redirect(`${options.path}/`);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
100
104
|
const encoding = headers["accept-encoding"];
|
|
101
105
|
if (encoding) {
|
|
102
106
|
if (hasBr && encoding.includes("br")) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/server/static/primitives/$serve.ts","../../../src/server/static/providers/ServerStaticProvider.ts","../../../src/server/static/index.ts"],"sourcesContent":["import { createPrimitive, KIND, Primitive } from \"alepha\";\nimport type { DurationLike } from \"alepha/datetime\";\n\n/**\n * Create a new static file handler.\n */\nexport const $serve = (options: ServePrimitiveOptions = {}): ServePrimitive => {\n return createPrimitive(ServePrimitive, options);\n};\n\nexport interface ServePrimitiveOptions {\n /**\n * Prefix for the served path.\n *\n * @default \"/\"\n */\n path?: string;\n\n /**\n * Path to the directory to serve.\n *\n * @default process.cwd()\n */\n root?: string;\n\n /**\n * If true, primitive will be ignored.\n *\n * @default false\n */\n disabled?: boolean;\n\n /**\n * Whether to keep dot files (e.g. `.gitignore`, `.env`) in the served directory.\n *\n * @default true\n */\n ignoreDotEnvFiles?: boolean;\n\n /**\n * Whether to use the index.html file when the path is a directory.\n *\n * @default true\n */\n indexFallback?: boolean;\n\n /**\n * Force all requests \"not found\" to be served with the index.html file.\n * This is useful for single-page applications (SPAs) that use client-side only routing.\n */\n historyApiFallback?: boolean;\n\n /**\n * Optional name of the primitive.\n * This is used for logging and debugging purposes.\n *\n * @default Key name.\n */\n name?: string;\n\n /**\n * Whether to use cache control headers.\n *\n * @default {}\n */\n cacheControl?: Partial<CacheControlOptions> | false;\n}\n\nexport interface CacheControlOptions {\n /**\n * Whether to use cache control headers.\n *\n * @default [.js, .css]\n */\n fileTypes: string[];\n\n /**\n * The maximum age of the cache in seconds.\n *\n * @default 60 * 60 * 24 * 2 // 2 days\n */\n maxAge: DurationLike;\n\n /**\n * Whether to use immutable cache control headers.\n *\n * @default true\n */\n immutable: boolean;\n}\n\nexport class ServePrimitive extends Primitive<ServePrimitiveOptions> {}\n\n$serve[KIND] = ServePrimitive;\n","import { createReadStream } from \"node:fs\";\nimport { access, readdir, stat } from \"node:fs/promises\";\nimport { basename, isAbsolute, join } from \"node:path\";\nimport type { Readable as NodeStream } from \"node:stream\";\nimport { $hook, $inject, Alepha } from \"alepha\";\nimport { DateTimeProvider } from \"alepha/datetime\";\nimport { FileDetector } from \"alepha/file\";\nimport { $logger } from \"alepha/logger\";\nimport { type ServerHandler, ServerRouterProvider } from \"alepha/server\";\nimport { $serve, type ServePrimitiveOptions } from \"../primitives/$serve.ts\";\n\nexport class ServerStaticProvider {\n protected readonly alepha = $inject(Alepha);\n protected readonly routerProvider = $inject(ServerRouterProvider);\n protected readonly dateTimeProvider = $inject(DateTimeProvider);\n protected readonly fileDetector = $inject(FileDetector);\n protected readonly log = $logger();\n protected readonly directories: ServeDirectory[] = [];\n\n protected readonly configure = $hook({\n on: \"configure\",\n handler: async () => {\n await Promise.all(\n this.alepha\n .primitives($serve)\n .map((it) => this.createStaticServer(it.options)),\n );\n },\n });\n\n public async createStaticServer(\n options: ServePrimitiveOptions,\n ): Promise<void> {\n const prefix = options.path ?? \"/\";\n\n let root = options.root ?? process.cwd();\n if (!isAbsolute(root)) {\n root = join(process.cwd(), root);\n }\n\n this.log.debug(\"Serve static files\", { prefix, root });\n\n await stat(root);\n\n // 1. get all files in the root directory (recursively)\n const files = await this.getAllFiles(root, options.ignoreDotEnvFiles);\n\n // 2. create a $route for each file (yes, this could be a lot of routes)\n const routes = await Promise.all(\n files.map(async (file) => {\n const path = file.replace(root, \"\").replace(/\\\\/g, \"/\");\n this.log.trace(`Mount ${join(prefix, path)} -> ${join(root, path)}`);\n return {\n path: join(prefix, encodeURI(path)),\n handler: await this.createFileHandler(join(root, path), options),\n };\n }),\n );\n\n for (const route of routes) {\n this.routerProvider.createRoute(route);\n\n // if route is for index.html, also create a route without it\n // e.g. /my/path/index.html -> /my/path/\n if (\n options.indexFallback !== false &&\n route.path.endsWith(\"index.html\")\n ) {\n this.routerProvider.createRoute({\n path: route.path.replace(/index\\.html$/, \"\"),\n handler: route.handler,\n });\n }\n }\n\n // 3. store the directory info for reference\n this.directories.push({\n options,\n files: files.map((file) => file.replace(root, \"\").replace(/\\\\/g, \"/\")),\n });\n\n // bonus! for SPAs, handle history API fallback\n if (options.historyApiFallback) {\n // meaning all unmatched routes should serve index.html\n this.routerProvider.createRoute({\n path: join(prefix, \"*\").replace(/\\\\/g, \"/\"),\n handler: async (request) => {\n const { reply } = request;\n\n if (request.url.pathname.includes(\".\")) {\n // If the request is for a file (e.g., /style.css), do not fall back\n reply.headers[\"content-type\"] = \"text/plain\";\n reply.body = \"Not Found\";\n reply.status = 404;\n return;\n }\n\n reply.headers[\"content-type\"] = \"text/html\";\n reply.status = 200;\n\n return new Promise<any>((resolve, reject) => {\n const stream = createReadStream(join(root, \"index.html\"));\n stream.on(\"open\", () => {\n resolve(stream);\n });\n stream.on(\"error\", (err) => {\n reject(err);\n });\n });\n },\n });\n }\n }\n\n public async createFileHandler(\n filepath: string,\n options: ServePrimitiveOptions,\n ): Promise<ServerHandler> {\n const filename = basename(filepath);\n\n const hasGzip = await access(`${filepath}.gz`)\n .then(() => true)\n .catch(() => false);\n\n const hasBr = await access(`${filepath}.br`)\n .then(() => true)\n .catch(() => false);\n\n const fileStat = await stat(filepath);\n const lastModified = fileStat.mtime.toUTCString();\n const etag = `\"${fileStat.size}-${fileStat.mtime.getTime()}\"`;\n const contentType = this.fileDetector.getContentType(filename);\n const cacheControl = this.getCacheControl(filename, options);\n\n return async (request): Promise<NodeStream | undefined> => {\n const { headers, reply } = request;\n let path = filepath;\n\n const encoding = headers[\"accept-encoding\"];\n if (encoding) {\n if (hasBr && encoding.includes(\"br\")) {\n reply.headers[\"content-encoding\"] = \"br\";\n path += \".br\";\n } else if (hasGzip && encoding.includes(\"gzip\")) {\n reply.headers[\"content-encoding\"] = \"gzip\";\n path += \".gz\";\n }\n }\n\n reply.headers[\"content-type\"] = contentType;\n reply.headers[\"accept-ranges\"] = \"bytes\";\n reply.headers[\"last-modified\"] = lastModified;\n\n if (cacheControl) {\n reply.headers[\"cache-control\"] =\n `public, max-age=${cacheControl.maxAge}`;\n if (cacheControl.immutable) {\n reply.headers[\"cache-control\"] += \", immutable\";\n }\n }\n\n reply.headers.etag = etag;\n if (\n headers[\"if-none-match\"] === etag ||\n headers[\"if-modified-since\"] === lastModified\n ) {\n reply.status = 304;\n return;\n }\n\n return new Promise<any>((resolve, reject) => {\n const stream = createReadStream(path);\n stream.on(\"open\", () => {\n resolve(stream);\n });\n stream.on(\"error\", (err) => {\n reject(err);\n });\n });\n };\n }\n\n protected getCacheFileTypes(): string[] {\n return [\n \".js\",\n \".css\",\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".eot\",\n \".otf\",\n \".jpg\",\n \".jpeg\",\n \".png\",\n \".svg\",\n \".gif\",\n ];\n }\n\n protected getCacheControl(\n filename: string,\n options: ServePrimitiveOptions,\n ): { maxAge: number; immutable: boolean } | undefined {\n if (!options.cacheControl) {\n return;\n }\n\n const fileTypes =\n options.cacheControl.fileTypes ?? this.getCacheFileTypes();\n\n for (const type of fileTypes) {\n if (filename.endsWith(type)) {\n return {\n immutable: options.cacheControl.immutable ?? true,\n maxAge: this.dateTimeProvider\n .duration(options.cacheControl.maxAge ?? [30, \"days\"])\n .as(\"seconds\"),\n };\n }\n }\n }\n\n public async getAllFiles(\n dir: string,\n ignoreDotEnvFiles = true,\n ): Promise<string[]> {\n const entries = await readdir(dir, { withFileTypes: true });\n\n const files = await Promise.all(\n entries.map((dirent) => {\n // skip .env & other dot files\n if (ignoreDotEnvFiles && dirent.name.startsWith(\".\")) {\n return [];\n }\n\n const fullPath = join(dir, dirent.name);\n return dirent.isDirectory() ? this.getAllFiles(fullPath) : fullPath;\n }),\n );\n\n return files.flat();\n }\n}\n\nexport interface ServeDirectory {\n options: ServePrimitiveOptions;\n files: string[];\n}\n","import { $module } from \"alepha\";\nimport { AlephaServer } from \"alepha/server\";\nimport { $serve } from \"./primitives/$serve.ts\";\nimport { ServerStaticProvider } from \"./providers/ServerStaticProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./primitives/$serve.ts\";\nexport * from \"./providers/ServerStaticProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Create static file server with `$static()`.\n *\n * @see {@link ServerStaticProvider}\n * @module alepha.server.static\n */\nexport const AlephaServerStatic = $module({\n name: \"alepha.server.static\",\n primitives: [$serve],\n services: [AlephaServer, ServerStaticProvider],\n});\n"],"mappings":";;;;;;;;;;;;;AAMA,MAAa,UAAU,UAAiC,EAAE,KAAqB;AAC7E,QAAO,gBAAgB,gBAAgB,QAAQ;;AAoFjD,IAAa,iBAAb,cAAoC,UAAiC;AAErE,OAAO,QAAQ;;;;AClFf,IAAa,uBAAb,MAAkC;CAChC,AAAmB,SAAS,QAAQ,OAAO;CAC3C,AAAmB,iBAAiB,QAAQ,qBAAqB;CACjE,AAAmB,mBAAmB,QAAQ,iBAAiB;CAC/D,AAAmB,eAAe,QAAQ,aAAa;CACvD,AAAmB,MAAM,SAAS;CAClC,AAAmB,cAAgC,EAAE;CAErD,AAAmB,YAAY,MAAM;EACnC,IAAI;EACJ,SAAS,YAAY;AACnB,SAAM,QAAQ,IACZ,KAAK,OACF,WAAW,OAAO,CAClB,KAAK,OAAO,KAAK,mBAAmB,GAAG,QAAQ,CAAC,CACpD;;EAEJ,CAAC;CAEF,MAAa,mBACX,SACe;EACf,MAAM,SAAS,QAAQ,QAAQ;EAE/B,IAAI,OAAO,QAAQ,QAAQ,QAAQ,KAAK;AACxC,MAAI,CAAC,WAAW,KAAK,CACnB,QAAO,KAAK,QAAQ,KAAK,EAAE,KAAK;AAGlC,OAAK,IAAI,MAAM,sBAAsB;GAAE;GAAQ;GAAM,CAAC;AAEtD,QAAM,KAAK,KAAK;EAGhB,MAAM,QAAQ,MAAM,KAAK,YAAY,MAAM,QAAQ,kBAAkB;EAGrE,MAAM,SAAS,MAAM,QAAQ,IAC3B,MAAM,IAAI,OAAO,SAAS;GACxB,MAAM,OAAO,KAAK,QAAQ,MAAM,GAAG,CAAC,QAAQ,OAAO,IAAI;AACvD,QAAK,IAAI,MAAM,SAAS,KAAK,QAAQ,KAAK,CAAC,MAAM,KAAK,MAAM,KAAK,GAAG;AACp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S,SAAS,KAAK,CACzB,QAAO;GACL,WAAW,QAAQ,aAAa,aAAa;GAC7C,QAAQ,KAAK,iBACV,SAAS,QAAQ,aAAa,UAAU,CAAC,IAAI,OAAO,CAAC,CACrD,GAAG,UAAU;GACjB;;CAKP,MAAa,YACX,KACA,oBAAoB,MACD;EACnB,MAAM,UAAU,MAAM,QAAQ,KAAK,EAAE,eAAe,MAAM,CAAC;AAc3D,UAZc,MAAM,QAAQ,IAC1B,QAAQ,KAAK,WAAW;AAEtB,OAAI,qBAAqB,OAAO,KAAK,WAAW,IAAI,CAClD,QAAO,EAAE;GAGX,MAAM,WAAW,KAAK,KAAK,OAAO,KAAK;AACvC,UAAO,OAAO,aAAa,GAAG,KAAK,YAAY,SAAS,GAAG;IAC3D,CACH,EAEY,MAAM;;;;;;;;;;;;AC9NvB,MAAa,qBAAqB,QAAQ;CACxC,MAAM;CACN,YAAY,CAAC,OAAO;CACpB,UAAU,CAAC,cAAc,qBAAqB;CAC/C,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/server/static/primitives/$serve.ts","../../../src/server/static/providers/ServerStaticProvider.ts","../../../src/server/static/index.ts"],"sourcesContent":["import { createPrimitive, KIND, Primitive } from \"alepha\";\nimport type { DurationLike } from \"alepha/datetime\";\n\n/**\n * Create a new static file handler.\n */\nexport const $serve = (options: ServePrimitiveOptions = {}): ServePrimitive => {\n return createPrimitive(ServePrimitive, options);\n};\n\nexport interface ServePrimitiveOptions {\n /**\n * Prefix for the served path.\n *\n * @default \"/\"\n */\n path?: string;\n\n /**\n * Path to the directory to serve.\n *\n * @default process.cwd()\n */\n root?: string;\n\n /**\n * If true, primitive will be ignored.\n *\n * @default false\n */\n disabled?: boolean;\n\n /**\n * Whether to keep dot files (e.g. `.gitignore`, `.env`) in the served directory.\n *\n * @default true\n */\n ignoreDotEnvFiles?: boolean;\n\n /**\n * Whether to use the index.html file when the path is a directory.\n *\n * @default true\n */\n indexFallback?: boolean;\n\n /**\n * Force all requests \"not found\" to be served with the index.html file.\n * This is useful for single-page applications (SPAs) that use client-side only routing.\n */\n historyApiFallback?: boolean;\n\n /**\n * Optional name of the primitive.\n * This is used for logging and debugging purposes.\n *\n * @default Key name.\n */\n name?: string;\n\n /**\n * Whether to use cache control headers.\n *\n * @default {}\n */\n cacheControl?: Partial<CacheControlOptions> | false;\n}\n\nexport interface CacheControlOptions {\n /**\n * Whether to use cache control headers.\n *\n * @default [.js, .css]\n */\n fileTypes: string[];\n\n /**\n * The maximum age of the cache in seconds.\n *\n * @default 60 * 60 * 24 * 2 // 2 days\n */\n maxAge: DurationLike;\n\n /**\n * Whether to use immutable cache control headers.\n *\n * @default true\n */\n immutable: boolean;\n}\n\nexport class ServePrimitive extends Primitive<ServePrimitiveOptions> {}\n\n$serve[KIND] = ServePrimitive;\n","import { createReadStream } from \"node:fs\";\nimport { access, readdir, stat } from \"node:fs/promises\";\nimport { basename, isAbsolute, join } from \"node:path\";\nimport type { Readable as NodeStream } from \"node:stream\";\nimport { $hook, $inject, Alepha } from \"alepha\";\nimport { DateTimeProvider } from \"alepha/datetime\";\nimport { FileDetector } from \"alepha/file\";\nimport { $logger } from \"alepha/logger\";\nimport { type ServerHandler, ServerRouterProvider } from \"alepha/server\";\nimport { $serve, type ServePrimitiveOptions } from \"../primitives/$serve.ts\";\n\nexport class ServerStaticProvider {\n protected readonly alepha = $inject(Alepha);\n protected readonly routerProvider = $inject(ServerRouterProvider);\n protected readonly dateTimeProvider = $inject(DateTimeProvider);\n protected readonly fileDetector = $inject(FileDetector);\n protected readonly log = $logger();\n protected readonly directories: ServeDirectory[] = [];\n\n protected readonly configure = $hook({\n on: \"configure\",\n handler: async () => {\n await Promise.all(\n this.alepha\n .primitives($serve)\n .map((it) => this.createStaticServer(it.options)),\n );\n },\n });\n\n public async createStaticServer(\n options: ServePrimitiveOptions,\n ): Promise<void> {\n const prefix = options.path ?? \"/\";\n\n let root = options.root ?? process.cwd();\n if (!isAbsolute(root)) {\n root = join(process.cwd(), root);\n }\n\n this.log.debug(\"Serve static files\", { prefix, root });\n\n await stat(root);\n\n // 1. get all files in the root directory (recursively)\n const files = await this.getAllFiles(root, options.ignoreDotEnvFiles);\n\n // 2. create a $route for each file (yes, this could be a lot of routes)\n const routes = await Promise.all(\n files.map(async (file) => {\n const path = file.replace(root, \"\").replace(/\\\\/g, \"/\");\n this.log.trace(`Mount ${join(prefix, path)} -> ${join(root, path)}`);\n return {\n path: join(prefix, encodeURI(path)),\n handler: await this.createFileHandler(join(root, path), options),\n };\n }),\n );\n\n for (const route of routes) {\n this.routerProvider.createRoute(route);\n\n // if route is for index.html, also create a route without it\n // e.g. /my/path/index.html -> /my/path/\n if (\n options.indexFallback !== false &&\n route.path.endsWith(\"index.html\")\n ) {\n this.routerProvider.createRoute({\n path: route.path.replace(/index\\.html$/, \"\"),\n handler: route.handler,\n });\n }\n }\n\n // 3. store the directory info for reference\n this.directories.push({\n options,\n files: files.map((file) => file.replace(root, \"\").replace(/\\\\/g, \"/\")),\n });\n\n // bonus! for SPAs, handle history API fallback\n if (options.historyApiFallback) {\n // meaning all unmatched routes should serve index.html\n this.routerProvider.createRoute({\n path: join(prefix, \"*\").replace(/\\\\/g, \"/\"),\n handler: async (request) => {\n const { reply } = request;\n\n if (request.url.pathname.includes(\".\")) {\n // If the request is for a file (e.g., /style.css), do not fall back\n reply.headers[\"content-type\"] = \"text/plain\";\n reply.body = \"Not Found\";\n reply.status = 404;\n return;\n }\n\n reply.headers[\"content-type\"] = \"text/html\";\n reply.status = 200;\n\n return new Promise<any>((resolve, reject) => {\n const stream = createReadStream(join(root, \"index.html\"));\n stream.on(\"open\", () => {\n resolve(stream);\n });\n stream.on(\"error\", (err) => {\n reject(err);\n });\n });\n },\n });\n }\n }\n\n public async createFileHandler(\n filepath: string,\n options: ServePrimitiveOptions,\n ): Promise<ServerHandler> {\n const filename = basename(filepath);\n\n const hasGzip = await access(`${filepath}.gz`)\n .then(() => true)\n .catch(() => false);\n\n const hasBr = await access(`${filepath}.br`)\n .then(() => true)\n .catch(() => false);\n\n const fileStat = await stat(filepath);\n const lastModified = fileStat.mtime.toUTCString();\n const etag = `\"${fileStat.size}-${fileStat.mtime.getTime()}\"`;\n const contentType = this.fileDetector.getContentType(filename);\n const cacheControl = this.getCacheControl(filename, options);\n\n return async (request): Promise<NodeStream | undefined> => {\n const { headers, reply } = request;\n let path = filepath;\n\n // 01/26 - when calling \"/directory\", redirect to \"/directory/\"\n if (\n options.path &&\n options.path === request.url.pathname &&\n !options.path.endsWith(\"/\")\n ) {\n reply.redirect(`${options.path}/`);\n return;\n }\n\n const encoding = headers[\"accept-encoding\"];\n if (encoding) {\n if (hasBr && encoding.includes(\"br\")) {\n reply.headers[\"content-encoding\"] = \"br\";\n path += \".br\";\n } else if (hasGzip && encoding.includes(\"gzip\")) {\n reply.headers[\"content-encoding\"] = \"gzip\";\n path += \".gz\";\n }\n }\n\n reply.headers[\"content-type\"] = contentType;\n reply.headers[\"accept-ranges\"] = \"bytes\";\n reply.headers[\"last-modified\"] = lastModified;\n\n if (cacheControl) {\n reply.headers[\"cache-control\"] =\n `public, max-age=${cacheControl.maxAge}`;\n if (cacheControl.immutable) {\n reply.headers[\"cache-control\"] += \", immutable\";\n }\n }\n\n reply.headers.etag = etag;\n if (\n headers[\"if-none-match\"] === etag ||\n headers[\"if-modified-since\"] === lastModified\n ) {\n reply.status = 304;\n return;\n }\n\n return new Promise<any>((resolve, reject) => {\n const stream = createReadStream(path);\n stream.on(\"open\", () => {\n resolve(stream);\n });\n stream.on(\"error\", (err) => {\n reject(err);\n });\n });\n };\n }\n\n protected getCacheFileTypes(): string[] {\n return [\n \".js\",\n \".css\",\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".eot\",\n \".otf\",\n \".jpg\",\n \".jpeg\",\n \".png\",\n \".svg\",\n \".gif\",\n ];\n }\n\n protected getCacheControl(\n filename: string,\n options: ServePrimitiveOptions,\n ): { maxAge: number; immutable: boolean } | undefined {\n if (!options.cacheControl) {\n return;\n }\n\n const fileTypes =\n options.cacheControl.fileTypes ?? this.getCacheFileTypes();\n\n for (const type of fileTypes) {\n if (filename.endsWith(type)) {\n return {\n immutable: options.cacheControl.immutable ?? true,\n maxAge: this.dateTimeProvider\n .duration(options.cacheControl.maxAge ?? [30, \"days\"])\n .as(\"seconds\"),\n };\n }\n }\n }\n\n public async getAllFiles(\n dir: string,\n ignoreDotEnvFiles = true,\n ): Promise<string[]> {\n const entries = await readdir(dir, { withFileTypes: true });\n\n const files = await Promise.all(\n entries.map((dirent) => {\n // skip .env & other dot files\n if (ignoreDotEnvFiles && dirent.name.startsWith(\".\")) {\n return [];\n }\n\n const fullPath = join(dir, dirent.name);\n return dirent.isDirectory() ? this.getAllFiles(fullPath) : fullPath;\n }),\n );\n\n return files.flat();\n }\n}\n\nexport interface ServeDirectory {\n options: ServePrimitiveOptions;\n files: string[];\n}\n","import { $module } from \"alepha\";\nimport { AlephaServer } from \"alepha/server\";\nimport { $serve } from \"./primitives/$serve.ts\";\nimport { ServerStaticProvider } from \"./providers/ServerStaticProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./primitives/$serve.ts\";\nexport * from \"./providers/ServerStaticProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Create static file server with `$static()`.\n *\n * @see {@link ServerStaticProvider}\n * @module alepha.server.static\n */\nexport const AlephaServerStatic = $module({\n name: \"alepha.server.static\",\n primitives: [$serve],\n services: [AlephaServer, ServerStaticProvider],\n});\n"],"mappings":";;;;;;;;;;;;;AAMA,MAAa,UAAU,UAAiC,EAAE,KAAqB;AAC7E,QAAO,gBAAgB,gBAAgB,QAAQ;;AAoFjD,IAAa,iBAAb,cAAoC,UAAiC;AAErE,OAAO,QAAQ;;;;AClFf,IAAa,uBAAb,MAAkC;CAChC,AAAmB,SAAS,QAAQ,OAAO;CAC3C,AAAmB,iBAAiB,QAAQ,qBAAqB;CACjE,AAAmB,mBAAmB,QAAQ,i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,IAC1B,QAAQ,KAAK,WAAW;AAEtB,OAAI,qBAAqB,OAAO,KAAK,WAAW,IAAI,CAClD,QAAO,EAAE;GAGX,MAAM,WAAW,KAAK,KAAK,OAAO,KAAK;AACvC,UAAO,OAAO,aAAa,GAAG,KAAK,YAAY,SAAS,GAAG;IAC3D,CACH,EAEY,MAAM;;;;;;;;;;;;ACxOvB,MAAa,qBAAqB,QAAQ;CACxC,MAAM;CACN,YAAY,CAAC,OAAO;CACpB,UAAU,CAAC,cAAc,qBAAqB;CAC/C,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/server/swagger/primitives/$swagger.ts","../../../src/server/swagger/providers/ServerSwaggerProvider.ts","../../../src/server/swagger/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;AAyBA;;;;;;AAMA;;;;;AA+BA;AA6DA;AAIA;;AASc,cA/GD,QA+GC,EAAA;EACQ,CAAA,OAAA,CAAA,EA/GX,uBA+GW,CAAA,EA9GnB,gBA8GmB;EAAM,MAAA,EAAA,uBAAA;AAI5B,CAAA;AAKe,UAnHE,uBAAA,CAmHF;EASF,IAAA,CAAA,EA3HJ,eA2HI,CAAA,MAAA,CAAA;EAYG;;;EAQH,MAAA,CAAA,EAAA,MAAA;EAAK;;;;EC1IL;;;;EAAc;;;AAc3B;AAAgF;EAAA,EAAA,CAAA,EAAA,OAAA,GDG/D,gBCH+D;;;;EAUnE,OAAA,CAAA,EAAA,CAAA,GAAA,EDFK,eCEgB,EAAA,GAAA,IAAA;;AAEO,UDDxB,gBAAA,CCCwB;EACN,IAAA,CAAA,EAAA,MAAA;EACR,SAAA,CAAA,EAAA;IAAA;;;IAKX,QAAA,CAAA,EAAA,MAAA;IAAe;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/server/swagger/primitives/$swagger.ts","../../../src/server/swagger/providers/ServerSwaggerProvider.ts","../../../src/server/swagger/index.ts"],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AA,EAAA,MAAA,EAAA,CAAA,EA0ZtB,CA1ZsB;;;;;mDCrBwB;;;;IFStC,OAIZ,CAAA,EAAA,MAAA;IAHU;;;;;AAKX;;;;;AA+BA;AA6DA;AAIA;;AASc,cEjGD,mBFiGC,EEjGkB,OAAA,CAAA,OFiGlB,CEtFZ,OAAA,CAX8B,MAAA,CFiGlB"}
|
|
@@ -65,7 +65,6 @@ var ServerSwaggerProvider = class {
|
|
|
65
65
|
const options = alepha.primitives($swagger)?.[0]?.options;
|
|
66
66
|
if (!options) return;
|
|
67
67
|
this.json = await this.setupSwaggerPlugin(options);
|
|
68
|
-
if (this.json) this.log.info("Swagger documentation generated successfully.");
|
|
69
68
|
}
|
|
70
69
|
});
|
|
71
70
|
generateSwaggerDoc(options) {
|
|
@@ -79,6 +78,7 @@ var ServerSwaggerProvider = class {
|
|
|
79
78
|
const prefix = options.prefix ?? "/docs";
|
|
80
79
|
this.configureSwaggerApi(prefix, json);
|
|
81
80
|
if (options.ui !== false) await this.configureSwaggerUi(prefix, options);
|
|
81
|
+
else this.log.info(`Swagger API available at ${prefix}/json`);
|
|
82
82
|
return json;
|
|
83
83
|
}
|
|
84
84
|
configureOpenApi(actions, doc) {
|
|
@@ -212,7 +212,6 @@ var ServerSwaggerProvider = class {
|
|
|
212
212
|
schema: { response: t.json() },
|
|
213
213
|
handler: () => json
|
|
214
214
|
});
|
|
215
|
-
this.log.info(`Swagger API available at ${prefix}/json`);
|
|
216
215
|
}
|
|
217
216
|
async configureSwaggerUi(prefix, options) {
|
|
218
217
|
const ui = typeof options.ui === "object" ? options.ui : {};
|
|
@@ -260,7 +259,7 @@ window.onload = function() {
|
|
|
260
259
|
return initializer;
|
|
261
260
|
}
|
|
262
261
|
});
|
|
263
|
-
this.log.info(
|
|
262
|
+
this.log.info("SwaggerUI OK", { url: `${this.serverProvider.hostname}${prefix}` });
|
|
264
263
|
}
|
|
265
264
|
async getAssetPath(...paths) {
|
|
266
265
|
for (const path of paths) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/server/swagger/primitives/$swagger.ts","../../../src/server/swagger/providers/ServerSwaggerProvider.ts","../../../src/server/swagger/index.ts"],"sourcesContent":["import { createPrimitive, KIND, Primitive } from \"alepha\";\n\n/**\n * Creates an OpenAPI/Swagger documentation primitive with interactive UI.\n *\n * Automatically generates API documentation from your $action primitives and serves\n * an interactive Swagger UI for testing endpoints. Supports customization, tag filtering,\n * and OAuth configuration.\n *\n * @example\n * ```ts\n * class App {\n * docs = $swagger({\n * prefix: \"/api-docs\",\n * info: {\n * title: \"My API\",\n * version: \"1.0.0\",\n * description: \"REST API documentation\"\n * },\n * excludeTags: [\"internal\"],\n * ui: { root: \"/swagger\" }\n * });\n * }\n * ```\n */\nexport const $swagger = (\n options: SwaggerPrimitiveOptions = {},\n): SwaggerPrimitive => {\n return createPrimitive(SwaggerPrimitive, options);\n};\n\nexport interface SwaggerPrimitiveOptions {\n info?: OpenApiDocument[\"info\"];\n\n /**\n * @default: \"/docs\"\n */\n prefix?: string;\n\n /**\n * If true, docs will be disabled.\n */\n disabled?: boolean;\n\n /**\n * Tags to exclude from the documentation.\n */\n excludeTags?: string[];\n\n /**\n * Enable Swagger UI.\n *\n * @default true\n */\n ui?: boolean | SwaggerUiOptions;\n\n /**\n * Function to rewrite the OpenAPI document before serving it.\n */\n rewrite?: (doc: OpenApiDocument) => void;\n}\n\nexport interface SwaggerUiOptions {\n root?: string;\n\n initOAuth?: {\n /**\n * Default clientId.\n */\n clientId?: string;\n\n /**\n * realm query parameter (for oauth1) added to authorizationUrl and tokenUrl.\n */\n realm?: string;\n\n /**\n * application name, displayed in authorization popup.\n */\n appName?: string;\n\n /**\n * scope separator for passing scopes, encoded before calling, default\n * value is a space (encoded value %20).\n *\n * @default ' '\n */\n scopeSeparator?: string;\n\n /**\n * string array or scope separator (i.e. space) separated string of\n * initially selected oauth scopes\n *\n * @default []\n */\n scopes?: string | string[];\n\n /**\n * Additional query parameters added to authorizationUrl and tokenUrl.\n * MUST be an object\n */\n additionalQueryStringParams?: { [key: string]: any };\n\n /**\n * Only activated for the accessCode flow. During the authorization_code\n * request to the tokenUrl, pass the Client Password using the HTTP Basic\n * Authentication scheme (Authorization header with Basic\n * base64encode(client_id + client_secret)).\n *\n * @default false\n */\n useBasicAuthenticationWithAccessCodeGrant?: boolean;\n\n /**\n * Only applies to Authorization Code flows. Proof Key for Code Exchange\n * brings enhanced security for OAuth public clients.\n *\n * @default false\n */\n usePkceWithAuthorizationCodeGrant?: boolean;\n };\n}\n\nexport class SwaggerPrimitive extends Primitive<SwaggerPrimitiveOptions> {}\n\n$swagger[KIND] = SwaggerPrimitive;\n\nexport interface OpenApiDocument {\n openapi: string;\n info: {\n title: string;\n version: string;\n description?: string;\n };\n paths: Record<string, any>;\n components?: {\n schemas?: Record<string, any>;\n securitySchemes?: Record<string, any>;\n };\n}\n\nexport interface OpenApiOperation {\n tags?: string[];\n summary?: string;\n description?: string;\n operationId?: string;\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n description?: string;\n required?: boolean;\n schema: any;\n }>;\n requestBody?: {\n description?: string;\n content: Record<\n string,\n {\n schema: any;\n }\n >;\n required?: boolean;\n };\n responses: Record<\n string,\n {\n description: string;\n content?: Record<\n string,\n {\n schema: any;\n }\n >;\n }\n >;\n security?: Array<Record<string, any[]>>;\n}\n","import { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n $atom,\n $hook,\n $inject,\n $use,\n Alepha,\n isTypeFile,\n type Static,\n type TObject,\n type TSchema,\n t,\n} from \"alepha\";\nimport { FileSystemProvider } from \"alepha/file\";\nimport { $logger } from \"alepha/logger\";\nimport { AlephaSecurity } from \"alepha/security\";\nimport {\n $action,\n type ActionPrimitive,\n type RequestConfigSchema,\n ServerProvider,\n ServerRouterProvider,\n} from \"alepha/server\";\nimport { ServerStaticProvider } from \"alepha/server/static\";\nimport {\n $swagger,\n type OpenApiDocument,\n type OpenApiOperation,\n type SwaggerPrimitiveOptions,\n} from \"../primitives/$swagger.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Swagger provider configuration atom\n */\nexport const swaggerOptions = $atom({\n name: \"alepha.server.swagger.options\",\n schema: t.object({\n excludeKeys: t.optional(\n t.array(t.string(), {\n description: \"Keys to exclude from swagger schema\",\n }),\n ),\n }),\n default: {\n excludeKeys: [],\n },\n});\n\nexport type ServerSwaggerProviderOptions = Static<typeof swaggerOptions.schema>;\n\ndeclare module \"alepha\" {\n interface State {\n [swaggerOptions.key]: ServerSwaggerProviderOptions;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ServerSwaggerProvider {\n protected readonly serverStaticProvider = $inject(ServerStaticProvider);\n protected readonly serverRouterProvider = $inject(ServerRouterProvider);\n protected readonly serverProvider = $inject(ServerProvider);\n protected readonly alepha = $inject(Alepha);\n protected readonly log = $logger();\n protected readonly options = $use(swaggerOptions);\n protected readonly fs = $inject(FileSystemProvider);\n\n public json?: OpenApiDocument;\n\n protected readonly configure = $hook({\n on: \"configure\",\n priority: \"last\", // wait for all configurations, sometimes some actions are registered late!\n handler: async (alepha) => {\n const options = alepha.primitives($swagger)?.[0]?.options;\n if (!options) {\n return;\n }\n\n this.json = await this.setupSwaggerPlugin(options);\n\n if (this.json) {\n this.log.info(\"Swagger documentation generated successfully.\");\n }\n },\n });\n\n public generateSwaggerDoc(options: SwaggerPrimitiveOptions): OpenApiDocument {\n const json = this.configureOpenApi(\n this.alepha.primitives($action),\n options,\n );\n\n if (options.rewrite) {\n options.rewrite(json);\n }\n\n return json;\n }\n\n protected async setupSwaggerPlugin(\n options: SwaggerPrimitiveOptions,\n ): Promise<OpenApiDocument | undefined> {\n if (options.disabled) {\n return;\n }\n\n const json = this.generateSwaggerDoc(options);\n\n const prefix = options.prefix ?? \"/docs\";\n\n this.configureSwaggerApi(prefix, json);\n\n if (options.ui !== false) {\n await this.configureSwaggerUi(prefix, options);\n }\n\n return json;\n }\n\n protected configureOpenApi(\n actions: ActionPrimitive<RequestConfigSchema>[],\n doc: SwaggerPrimitiveOptions,\n ): OpenApiDocument {\n const openApi: OpenApiDocument = {\n openapi: \"3.0.0\",\n info: doc.info ?? {\n title: \"API Documentation\",\n version: \"1.0.0\",\n },\n paths: {},\n components: {},\n };\n\n const hasSecurity = this.alepha.has(AlephaSecurity);\n if (hasSecurity && openApi.components) {\n openApi.components.securitySchemes = {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n },\n };\n }\n\n const excludeTags = doc.excludeTags ?? [];\n const schemas: Record<string, any> = {};\n\n const schema = (source: TSchema) => {\n if (\"title\" in source && typeof source.title === \"string\") {\n schemas[source.title] = copy(source);\n return { $ref: `#/components/schemas/${source.title}` };\n }\n return copy(source);\n };\n\n const copy = (obj: any) => {\n const newValue = JSON.parse(JSON.stringify(obj));\n this.removePrivateFields(newValue, [\n ...(this.options.excludeKeys || []),\n \"~options\",\n ]);\n return newValue;\n };\n\n for (const route of actions) {\n if (!route.options.schema) {\n continue;\n }\n\n const response = this.getResponseSchema(route);\n if (!response) {\n continue;\n }\n\n if (excludeTags.includes(route.group)) {\n continue;\n }\n\n if (route.options.hide) {\n continue;\n }\n\n const operation: OpenApiOperation = {\n operationId: route.name,\n summary: route.options.summary,\n description: route.options.description,\n tags: [route.group.replaceAll(\":\", \" / \")],\n responses: {\n [response.status]: {\n description: \"\",\n content: response.type\n ? {\n [response.type]: {\n schema: schema(response.schema),\n },\n }\n : undefined,\n },\n },\n };\n\n if (route.options.secure !== false && hasSecurity) {\n operation.security = [{ bearerAuth: [] }];\n }\n\n const g = t.raw;\n\n if (\n g.IsObject(route.options.schema.body) ||\n g.IsArray(route.options.schema.body)\n ) {\n if (\n g.IsObject(route.options.schema.body) &&\n this.isBodyMultipart(route.options.schema.body)\n ) {\n operation.requestBody = {\n required: true,\n content: {\n \"multipart/form-data\": {\n schema: schema(route.options.schema.body),\n },\n },\n };\n } else {\n operation.requestBody = {\n required: true,\n content: {\n \"application/json\": {\n schema: schema(route.options.schema.body),\n },\n },\n };\n }\n }\n\n if (g.IsObject(route.options.schema.query)) {\n operation.parameters ??= [];\n for (const [key, value] of Object.entries(\n route.options.schema.query.properties,\n )) {\n operation.parameters.push({\n name: key,\n in: \"query\",\n required: false,\n schema: schema(value),\n });\n }\n }\n\n if (g.IsObject(route.options.schema.params)) {\n operation.parameters ??= [];\n for (const [key, value] of Object.entries(\n route.options.schema.params.properties,\n )) {\n const description =\n \"description\" in value && typeof value.description === \"string\"\n ? value.description\n : undefined;\n const ref = schema(value);\n delete ref.description;\n operation.parameters.push({\n name: key,\n in: \"path\",\n required: true,\n description,\n schema: ref,\n });\n }\n }\n\n const url = route.prefix + this.replacePathParams(route.path);\n\n openApi.paths[url] = {\n ...openApi.paths[url],\n [route.method.toLowerCase()]: operation,\n };\n }\n\n if (openApi.components) openApi.components.schemas = schemas;\n\n return JSON.parse(JSON.stringify(openApi));\n }\n\n public isBodyMultipart(schema: TObject): boolean {\n for (const key in schema.properties) {\n if (isTypeFile(schema.properties[key])) {\n return true;\n }\n }\n return false;\n }\n\n public replacePathParams(url: string): string {\n return url.replace(/:\\w+/g, (match) => {\n const paramName = match.slice(1);\n return `{${paramName}}`;\n });\n }\n\n public getResponseSchema(route: ActionPrimitive<RequestConfigSchema>):\n | {\n type?: string;\n schema?: any;\n status: number;\n }\n | undefined {\n const schema: any = route.options.schema?.response;\n if (!schema) {\n return {\n status: 204,\n };\n }\n\n if (t.schema.isObject(schema) || t.schema.isArray(schema)) {\n return {\n schema,\n status: 200,\n type: \"application/json\",\n };\n }\n\n if (t.schema.isString(schema)) {\n return {\n schema,\n status: 200,\n type: \"text/plain\",\n };\n }\n\n if (isTypeFile(schema)) {\n return {\n schema,\n status: 200,\n type: \"application/octet-stream\",\n };\n }\n\n const status = Object.keys(schema)[0];\n if (t.schema.isObject(schema[status]) || isTypeFile(schema[status])) {\n return {\n schema,\n type: t.schema.isObject(schema[status])\n ? \"application/json\"\n : \"application/octet-stream\",\n status: Number(status),\n };\n }\n }\n\n protected configureSwaggerApi(prefix: string, json: OpenApiDocument): void {\n this.serverRouterProvider.createRoute({\n method: \"GET\",\n path: `${prefix}/json`,\n cache: {\n etag: true,\n },\n schema: {\n response: t.json(),\n },\n handler: () => json,\n });\n this.log.info(`Swagger API available at ${prefix}/json`);\n }\n\n protected async configureSwaggerUi(\n prefix: string,\n options: SwaggerPrimitiveOptions,\n ): Promise<void> {\n const ui = typeof options.ui === \"object\" ? options.ui : {};\n const initializer = `\nwindow.onload = function() {\n\twindow.ui = SwaggerUIBundle({\n\t\turl: \"/docs/json\",\n\t\tdom_id: '#swagger-ui',\n\t\tdeepLinking: true,\n\t\tpresets: [\n\t\t\tSwaggerUIBundle.presets.apis,\n\t\t\tSwaggerUIStandalonePreset\n\t\t],\n\t\tplugins: [\n\t\t\tSwaggerUIBundle.plugins.DownloadUrl\n\t\t],\n\t\tlayout: \"BaseLayout\"\n\t});\n\n document.body.style.backgroundColor = \"#f2f2f2\";\n\n\tconst options = ${JSON.stringify(ui)};\n\n\tif (options.initOAuth) {\n\t\tui.initOAuth(options.initOAuth);\n\t}\n};\n\t\t`.trim();\n\n const dirname = fileURLToPath(import.meta.url);\n\n const root = await this.getAssetPath(\n ui.root,\n join(dirname, \"../../assets/swagger-ui\"),\n join(dirname, \"../../../assets/swagger-ui\"),\n join(dirname, \"../../../../assets/swagger-ui\"),\n join(dirname, \"../../../../../assets/swagger-ui\"),\n );\n\n if (!root) {\n this.log.warn(`Failed to locate Swagger UI assets for path ${prefix}`);\n return;\n }\n\n await this.serverStaticProvider.createStaticServer({\n path: prefix,\n root,\n });\n\n this.serverRouterProvider.createRoute({\n method: \"GET\",\n path: `${prefix}/swagger-initializer.js`,\n cache: {\n etag: true,\n },\n handler: ({ reply }) => {\n reply.headers[\"content-type\"] = \"application/javascript; charset=utf-8\";\n return initializer;\n },\n });\n\n this.log.info(\n `Swagger UI available at ${this.serverProvider.hostname}${prefix}/`,\n );\n }\n\n protected async getAssetPath(\n ...paths: (string | undefined)[]\n ): Promise<string | undefined> {\n for (const path of paths) {\n if (!path) continue;\n const exists = await this.fs.exists(path);\n if (exists) {\n return path;\n }\n }\n }\n\n public removePrivateFields<T extends Record<string, any>>(\n obj: T,\n excludeList: string[],\n ): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n\n const visited = new WeakSet();\n\n const traverse = (o: any): void => {\n if (visited.has(o)) return;\n visited.add(o);\n\n if (Array.isArray(o)) {\n for (let i = 0; i < o.length; i++) {\n const item = o[i];\n if (item !== null && typeof item === \"object\") {\n traverse(item);\n }\n }\n } else {\n for (const excludeKey of excludeList) {\n if (excludeKey in o) {\n delete o[excludeKey];\n }\n }\n for (const key in o) {\n const item = o[key];\n if (item !== null && typeof item === \"object\") {\n traverse(item);\n }\n }\n }\n };\n\n traverse(obj);\n return obj;\n }\n}\n","import \"alepha/server/security\";\nimport { $module } from \"alepha\";\nimport { AlephaServer, type RequestConfigSchema } from \"alepha/server\";\nimport { AlephaServerCache } from \"alepha/server/cache\";\nimport { AlephaServerStatic } from \"alepha/server/static\";\nimport { $swagger } from \"./primitives/$swagger.ts\";\nimport { ServerSwaggerProvider } from \"./providers/ServerSwaggerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./primitives/$swagger.ts\";\nexport * from \"./providers/ServerSwaggerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha/server\" {\n interface ActionPrimitiveOptions<TConfig extends RequestConfigSchema> {\n /**\n * Short description of the route.\n */\n summary?: string;\n\n /**\n * Don't include this action in the Swagger documentation.\n */\n hide?: boolean;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Plugin for Alepha Server that provides Swagger documentation capabilities.\n * It generates OpenAPI v3 documentation for the server's endpoints ($action).\n * It also provides a Swagger UI for interactive API documentation.\n *\n * @see {@link ServerSwaggerProvider}\n * @module alepha.server.swagger\n */\nexport const AlephaServerSwagger = $module({\n name: \"alepha.server.swagger\",\n primitives: [$swagger],\n services: [ServerSwaggerProvider],\n register: (alepha) => {\n alepha.with(AlephaServer);\n alepha.with(AlephaServerCache);\n alepha.with(AlephaServerStatic);\n alepha.with(ServerSwaggerProvider);\n alepha.store.push(\"alepha.build.assets\", \"alepha\");\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,YACX,UAAmC,EAAE,KAChB;AACrB,QAAO,gBAAgB,kBAAkB,QAAQ;;AA+FnD,IAAa,mBAAb,cAAsC,UAAmC;AAEzE,SAAS,QAAQ;;;;;;;ACxFjB,MAAa,iBAAiB,MAAM;CAClC,MAAM;CACN,QAAQ,EAAE,OAAO,EACf,aAAa,EAAE,SACb,EAAE,MAAM,EAAE,QAAQ,EAAE,EAClB,aAAa,uCACd,CAAC,CACH,EACF,CAAC;CACF,SAAS,EACP,aAAa,EAAE,EAChB;CACF,CAAC;AAYF,IAAa,wBAAb,MAAmC;CACjC,AAAmB,uBAAuB,QAAQ,qBAAqB;CACvE,AAAmB,uBAAuB,QAAQ,qBAAqB;CACvE,AAAmB,iBAAiB,QAAQ,eAAe;CAC3D,AAAmB,SAAS,QAAQ,OAAO;CAC3C,AAAmB,MAAM,SAAS;CAClC,AAAmB,UAAU,KAAK,eAAe;CACjD,AAAmB,KAAK,QAAQ,mBAAmB;CAEnD,AAAO;CAEP,AAAmB,YAAY,MAAM;EACnC,IAAI;EACJ,UAAU;EACV,SAAS,OAAO,WAAW;GACzB,MAAM,UAAU,OAAO,WAAW,SAAS,GAAG,IAAI;AAClD,OAAI,CAAC,QACH;AAGF,QAAK,OAAO,MAAM,KAAK,mBAAmB,QAAQ;AAElD,OAAI,KAAK,KACP,MAAK,IAAI,KAAK,gDAAgD;;EAGnE,CAAC;CAEF,AAAO,mBAAmB,SAAmD;EAC3E,MAAM,OAAO,KAAK,iBAChB,KA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AQ,QAAQ,OAAO,QAAQ,SAAU,QAAO;EAEpD,MAAM,0BAAU,IAAI,SAAS;EAE7B,MAAM,YAAY,MAAiB;AACjC,OAAI,QAAQ,IAAI,EAAE,CAAE;AACpB,WAAQ,IAAI,EAAE;AAEd,OAAI,MAAM,QAAQ,EAAE,CAClB,MAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;IACjC,MAAM,OAAO,EAAE;AACf,QAAI,SAAS,QAAQ,OAAO,SAAS,SACnC,UAAS,KAAK;;QAGb;AACL,SAAK,MAAM,cAAc,YACvB,KAAI,cAAc,EAChB,QAAO,EAAE;AAGb,SAAK,MAAM,OAAO,GAAG;KACnB,MAAM,OAAO,EAAE;AACf,SAAI,SAAS,QAAQ,OAAO,SAAS,SACnC,UAAS,KAAK;;;;AAMtB,WAAS,IAAI;AACb,SAAO;;;;;;;;;;;;;;AC3bX,MAAa,sBAAsB,QAAQ;CACzC,MAAM;CACN,YAAY,CAAC,SAAS;CACtB,UAAU,CAAC,sBAAsB;CACjC,WAAW,WAAW;AACpB,SAAO,KAAK,aAAa;AACzB,SAAO,KAAK,kBAAkB;AAC9B,SAAO,KAAK,mBAAmB;AAC/B,SAAO,KAAK,sBAAsB;AAClC,SAAO,MAAM,KAAK,uBAAuB,SAAS;;CAErD,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/server/swagger/primitives/$swagger.ts","../../../src/server/swagger/providers/ServerSwaggerProvider.ts","../../../src/server/swagger/index.ts"],"sourcesContent":["import { createPrimitive, KIND, Primitive } from \"alepha\";\n\n/**\n * Creates an OpenAPI/Swagger documentation primitive with interactive UI.\n *\n * Automatically generates API documentation from your $action primitives and serves\n * an interactive Swagger UI for testing endpoints. Supports customization, tag filtering,\n * and OAuth configuration.\n *\n * @example\n * ```ts\n * class App {\n * docs = $swagger({\n * prefix: \"/api-docs\",\n * info: {\n * title: \"My API\",\n * version: \"1.0.0\",\n * description: \"REST API documentation\"\n * },\n * excludeTags: [\"internal\"],\n * ui: { root: \"/swagger\" }\n * });\n * }\n * ```\n */\nexport const $swagger = (\n options: SwaggerPrimitiveOptions = {},\n): SwaggerPrimitive => {\n return createPrimitive(SwaggerPrimitive, options);\n};\n\nexport interface SwaggerPrimitiveOptions {\n info?: OpenApiDocument[\"info\"];\n\n /**\n * @default: \"/docs\"\n */\n prefix?: string;\n\n /**\n * If true, docs will be disabled.\n */\n disabled?: boolean;\n\n /**\n * Tags to exclude from the documentation.\n */\n excludeTags?: string[];\n\n /**\n * Enable Swagger UI.\n *\n * @default true\n */\n ui?: boolean | SwaggerUiOptions;\n\n /**\n * Function to rewrite the OpenAPI document before serving it.\n */\n rewrite?: (doc: OpenApiDocument) => void;\n}\n\nexport interface SwaggerUiOptions {\n root?: string;\n\n initOAuth?: {\n /**\n * Default clientId.\n */\n clientId?: string;\n\n /**\n * realm query parameter (for oauth1) added to authorizationUrl and tokenUrl.\n */\n realm?: string;\n\n /**\n * application name, displayed in authorization popup.\n */\n appName?: string;\n\n /**\n * scope separator for passing scopes, encoded before calling, default\n * value is a space (encoded value %20).\n *\n * @default ' '\n */\n scopeSeparator?: string;\n\n /**\n * string array or scope separator (i.e. space) separated string of\n * initially selected oauth scopes\n *\n * @default []\n */\n scopes?: string | string[];\n\n /**\n * Additional query parameters added to authorizationUrl and tokenUrl.\n * MUST be an object\n */\n additionalQueryStringParams?: { [key: string]: any };\n\n /**\n * Only activated for the accessCode flow. During the authorization_code\n * request to the tokenUrl, pass the Client Password using the HTTP Basic\n * Authentication scheme (Authorization header with Basic\n * base64encode(client_id + client_secret)).\n *\n * @default false\n */\n useBasicAuthenticationWithAccessCodeGrant?: boolean;\n\n /**\n * Only applies to Authorization Code flows. Proof Key for Code Exchange\n * brings enhanced security for OAuth public clients.\n *\n * @default false\n */\n usePkceWithAuthorizationCodeGrant?: boolean;\n };\n}\n\nexport class SwaggerPrimitive extends Primitive<SwaggerPrimitiveOptions> {}\n\n$swagger[KIND] = SwaggerPrimitive;\n\nexport interface OpenApiDocument {\n openapi: string;\n info: {\n title: string;\n version: string;\n description?: string;\n };\n paths: Record<string, any>;\n components?: {\n schemas?: Record<string, any>;\n securitySchemes?: Record<string, any>;\n };\n}\n\nexport interface OpenApiOperation {\n tags?: string[];\n summary?: string;\n description?: string;\n operationId?: string;\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n description?: string;\n required?: boolean;\n schema: any;\n }>;\n requestBody?: {\n description?: string;\n content: Record<\n string,\n {\n schema: any;\n }\n >;\n required?: boolean;\n };\n responses: Record<\n string,\n {\n description: string;\n content?: Record<\n string,\n {\n schema: any;\n }\n >;\n }\n >;\n security?: Array<Record<string, any[]>>;\n}\n","import { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n $atom,\n $hook,\n $inject,\n $use,\n Alepha,\n isTypeFile,\n type Static,\n type TObject,\n type TSchema,\n t,\n} from \"alepha\";\nimport { FileSystemProvider } from \"alepha/file\";\nimport { $logger } from \"alepha/logger\";\nimport { AlephaSecurity } from \"alepha/security\";\nimport {\n $action,\n type ActionPrimitive,\n type RequestConfigSchema,\n ServerProvider,\n ServerRouterProvider,\n} from \"alepha/server\";\nimport { ServerStaticProvider } from \"alepha/server/static\";\nimport {\n $swagger,\n type OpenApiDocument,\n type OpenApiOperation,\n type SwaggerPrimitiveOptions,\n} from \"../primitives/$swagger.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Swagger provider configuration atom\n */\nexport const swaggerOptions = $atom({\n name: \"alepha.server.swagger.options\",\n schema: t.object({\n excludeKeys: t.optional(\n t.array(t.string(), {\n description: \"Keys to exclude from swagger schema\",\n }),\n ),\n }),\n default: {\n excludeKeys: [],\n },\n});\n\nexport type ServerSwaggerProviderOptions = Static<typeof swaggerOptions.schema>;\n\ndeclare module \"alepha\" {\n interface State {\n [swaggerOptions.key]: ServerSwaggerProviderOptions;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ServerSwaggerProvider {\n protected readonly serverStaticProvider = $inject(ServerStaticProvider);\n protected readonly serverRouterProvider = $inject(ServerRouterProvider);\n protected readonly serverProvider = $inject(ServerProvider);\n protected readonly alepha = $inject(Alepha);\n protected readonly log = $logger();\n protected readonly options = $use(swaggerOptions);\n protected readonly fs = $inject(FileSystemProvider);\n\n public json?: OpenApiDocument;\n\n protected readonly configure = $hook({\n on: \"configure\",\n priority: \"last\", // wait for all configurations, sometimes some actions are registered late!\n handler: async (alepha) => {\n const options = alepha.primitives($swagger)?.[0]?.options;\n if (!options) {\n return;\n }\n\n this.json = await this.setupSwaggerPlugin(options);\n },\n });\n\n public generateSwaggerDoc(options: SwaggerPrimitiveOptions): OpenApiDocument {\n const json = this.configureOpenApi(\n this.alepha.primitives($action),\n options,\n );\n\n if (options.rewrite) {\n options.rewrite(json);\n }\n\n return json;\n }\n\n protected async setupSwaggerPlugin(\n options: SwaggerPrimitiveOptions,\n ): Promise<OpenApiDocument | undefined> {\n if (options.disabled) {\n return;\n }\n\n const json = this.generateSwaggerDoc(options);\n\n const prefix = options.prefix ?? \"/docs\";\n\n this.configureSwaggerApi(prefix, json);\n\n if (options.ui !== false) {\n await this.configureSwaggerUi(prefix, options);\n } else {\n this.log.info(`Swagger API available at ${prefix}/json`);\n }\n\n return json;\n }\n\n protected configureOpenApi(\n actions: ActionPrimitive<RequestConfigSchema>[],\n doc: SwaggerPrimitiveOptions,\n ): OpenApiDocument {\n const openApi: OpenApiDocument = {\n openapi: \"3.0.0\",\n info: doc.info ?? {\n title: \"API Documentation\",\n version: \"1.0.0\",\n },\n paths: {},\n components: {},\n };\n\n const hasSecurity = this.alepha.has(AlephaSecurity);\n if (hasSecurity && openApi.components) {\n openApi.components.securitySchemes = {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: \"JWT\",\n },\n };\n }\n\n const excludeTags = doc.excludeTags ?? [];\n const schemas: Record<string, any> = {};\n\n const schema = (source: TSchema) => {\n if (\"title\" in source && typeof source.title === \"string\") {\n schemas[source.title] = copy(source);\n return { $ref: `#/components/schemas/${source.title}` };\n }\n return copy(source);\n };\n\n const copy = (obj: any) => {\n const newValue = JSON.parse(JSON.stringify(obj));\n this.removePrivateFields(newValue, [\n ...(this.options.excludeKeys || []),\n \"~options\",\n ]);\n return newValue;\n };\n\n for (const route of actions) {\n if (!route.options.schema) {\n continue;\n }\n\n const response = this.getResponseSchema(route);\n if (!response) {\n continue;\n }\n\n if (excludeTags.includes(route.group)) {\n continue;\n }\n\n if (route.options.hide) {\n continue;\n }\n\n const operation: OpenApiOperation = {\n operationId: route.name,\n summary: route.options.summary,\n description: route.options.description,\n tags: [route.group.replaceAll(\":\", \" / \")],\n responses: {\n [response.status]: {\n description: \"\",\n content: response.type\n ? {\n [response.type]: {\n schema: schema(response.schema),\n },\n }\n : undefined,\n },\n },\n };\n\n if (route.options.secure !== false && hasSecurity) {\n operation.security = [{ bearerAuth: [] }];\n }\n\n const g = t.raw;\n\n if (\n g.IsObject(route.options.schema.body) ||\n g.IsArray(route.options.schema.body)\n ) {\n if (\n g.IsObject(route.options.schema.body) &&\n this.isBodyMultipart(route.options.schema.body)\n ) {\n operation.requestBody = {\n required: true,\n content: {\n \"multipart/form-data\": {\n schema: schema(route.options.schema.body),\n },\n },\n };\n } else {\n operation.requestBody = {\n required: true,\n content: {\n \"application/json\": {\n schema: schema(route.options.schema.body),\n },\n },\n };\n }\n }\n\n if (g.IsObject(route.options.schema.query)) {\n operation.parameters ??= [];\n for (const [key, value] of Object.entries(\n route.options.schema.query.properties,\n )) {\n operation.parameters.push({\n name: key,\n in: \"query\",\n required: false,\n schema: schema(value),\n });\n }\n }\n\n if (g.IsObject(route.options.schema.params)) {\n operation.parameters ??= [];\n for (const [key, value] of Object.entries(\n route.options.schema.params.properties,\n )) {\n const description =\n \"description\" in value && typeof value.description === \"string\"\n ? value.description\n : undefined;\n const ref = schema(value);\n delete ref.description;\n operation.parameters.push({\n name: key,\n in: \"path\",\n required: true,\n description,\n schema: ref,\n });\n }\n }\n\n const url = route.prefix + this.replacePathParams(route.path);\n\n openApi.paths[url] = {\n ...openApi.paths[url],\n [route.method.toLowerCase()]: operation,\n };\n }\n\n if (openApi.components) openApi.components.schemas = schemas;\n\n return JSON.parse(JSON.stringify(openApi));\n }\n\n public isBodyMultipart(schema: TObject): boolean {\n for (const key in schema.properties) {\n if (isTypeFile(schema.properties[key])) {\n return true;\n }\n }\n return false;\n }\n\n public replacePathParams(url: string): string {\n return url.replace(/:\\w+/g, (match) => {\n const paramName = match.slice(1);\n return `{${paramName}}`;\n });\n }\n\n public getResponseSchema(route: ActionPrimitive<RequestConfigSchema>):\n | {\n type?: string;\n schema?: any;\n status: number;\n }\n | undefined {\n const schema: any = route.options.schema?.response;\n if (!schema) {\n return {\n status: 204,\n };\n }\n\n if (t.schema.isObject(schema) || t.schema.isArray(schema)) {\n return {\n schema,\n status: 200,\n type: \"application/json\",\n };\n }\n\n if (t.schema.isString(schema)) {\n return {\n schema,\n status: 200,\n type: \"text/plain\",\n };\n }\n\n if (isTypeFile(schema)) {\n return {\n schema,\n status: 200,\n type: \"application/octet-stream\",\n };\n }\n\n const status = Object.keys(schema)[0];\n if (t.schema.isObject(schema[status]) || isTypeFile(schema[status])) {\n return {\n schema,\n type: t.schema.isObject(schema[status])\n ? \"application/json\"\n : \"application/octet-stream\",\n status: Number(status),\n };\n }\n }\n\n protected configureSwaggerApi(prefix: string, json: OpenApiDocument): void {\n this.serverRouterProvider.createRoute({\n method: \"GET\",\n path: `${prefix}/json`,\n cache: {\n etag: true,\n },\n schema: {\n response: t.json(),\n },\n handler: () => json,\n });\n }\n\n protected async configureSwaggerUi(\n prefix: string,\n options: SwaggerPrimitiveOptions,\n ): Promise<void> {\n const ui = typeof options.ui === \"object\" ? options.ui : {};\n const initializer = `\nwindow.onload = function() {\n\twindow.ui = SwaggerUIBundle({\n\t\turl: \"/docs/json\",\n\t\tdom_id: '#swagger-ui',\n\t\tdeepLinking: true,\n\t\tpresets: [\n\t\t\tSwaggerUIBundle.presets.apis,\n\t\t\tSwaggerUIStandalonePreset\n\t\t],\n\t\tplugins: [\n\t\t\tSwaggerUIBundle.plugins.DownloadUrl\n\t\t],\n\t\tlayout: \"BaseLayout\"\n\t});\n\n document.body.style.backgroundColor = \"#f2f2f2\";\n\n\tconst options = ${JSON.stringify(ui)};\n\n\tif (options.initOAuth) {\n\t\tui.initOAuth(options.initOAuth);\n\t}\n};\n\t\t`.trim();\n\n const dirname = fileURLToPath(import.meta.url);\n\n const root = await this.getAssetPath(\n ui.root,\n join(dirname, \"../../assets/swagger-ui\"),\n join(dirname, \"../../../assets/swagger-ui\"),\n join(dirname, \"../../../../assets/swagger-ui\"),\n join(dirname, \"../../../../../assets/swagger-ui\"),\n );\n\n if (!root) {\n this.log.warn(`Failed to locate Swagger UI assets for path ${prefix}`);\n return;\n }\n\n await this.serverStaticProvider.createStaticServer({\n path: prefix,\n root,\n });\n\n this.serverRouterProvider.createRoute({\n method: \"GET\",\n path: `${prefix}/swagger-initializer.js`,\n cache: {\n etag: true,\n },\n handler: ({ reply }) => {\n reply.headers[\"content-type\"] = \"application/javascript; charset=utf-8\";\n return initializer;\n },\n });\n\n this.log.info(\"SwaggerUI OK\", {\n url: `${this.serverProvider.hostname}${prefix}`,\n });\n }\n\n protected async getAssetPath(\n ...paths: (string | undefined)[]\n ): Promise<string | undefined> {\n for (const path of paths) {\n if (!path) continue;\n const exists = await this.fs.exists(path);\n if (exists) {\n return path;\n }\n }\n }\n\n public removePrivateFields<T extends Record<string, any>>(\n obj: T,\n excludeList: string[],\n ): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n\n const visited = new WeakSet();\n\n const traverse = (o: any): void => {\n if (visited.has(o)) return;\n visited.add(o);\n\n if (Array.isArray(o)) {\n for (let i = 0; i < o.length; i++) {\n const item = o[i];\n if (item !== null && typeof item === \"object\") {\n traverse(item);\n }\n }\n } else {\n for (const excludeKey of excludeList) {\n if (excludeKey in o) {\n delete o[excludeKey];\n }\n }\n for (const key in o) {\n const item = o[key];\n if (item !== null && typeof item === \"object\") {\n traverse(item);\n }\n }\n }\n };\n\n traverse(obj);\n return obj;\n }\n}\n","import \"alepha/server/security\";\nimport { $module } from \"alepha\";\nimport { AlephaServer, type RequestConfigSchema } from \"alepha/server\";\nimport { AlephaServerCache } from \"alepha/server/cache\";\nimport { AlephaServerStatic } from \"alepha/server/static\";\nimport { $swagger } from \"./primitives/$swagger.ts\";\nimport { ServerSwaggerProvider } from \"./providers/ServerSwaggerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./primitives/$swagger.ts\";\nexport * from \"./providers/ServerSwaggerProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha/server\" {\n interface ActionPrimitiveOptions<TConfig extends RequestConfigSchema> {\n /**\n * Short description of the route.\n */\n summary?: string;\n\n /**\n * Don't include this action in the Swagger documentation.\n */\n hide?: boolean;\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Plugin for Alepha Server that provides Swagger documentation capabilities.\n * It generates OpenAPI v3 documentation for the server's endpoints ($action).\n * It also provides a Swagger UI for interactive API documentation.\n *\n * @see {@link ServerSwaggerProvider}\n * @module alepha.server.swagger\n */\nexport const AlephaServerSwagger = $module({\n name: \"alepha.server.swagger\",\n primitives: [$swagger],\n services: [ServerSwaggerProvider],\n register: (alepha) => {\n alepha.with(AlephaServer);\n alepha.with(AlephaServerCache);\n alepha.with(AlephaServerStatic);\n alepha.with(ServerSwaggerProvider);\n alepha.store.push(\"alepha.build.assets\", \"alepha\");\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,YACX,UAAmC,EAAE,KAChB;AACrB,QAAO,gBAAgB,kBAAkB,QAAQ;;AA+FnD,IAAa,mBAAb,cAAsC,UAAmC;AAEzE,SAAS,QAAQ;;;;;;;ACxFjB,MAAa,iBAAiB,M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