balda-js 0.0.54 → 0.0.56

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.
@@ -0,0 +1 @@
1
+ (function(){"use strict";AdminJS.UserComponents={}})();
@@ -0,0 +1 @@
1
+ AdminJS.UserComponents = {}
package/lib/index.cjs CHANGED
@@ -2395,12 +2395,40 @@ var Request2 = class _Request extends NativeRequest {
2395
2395
  }
2396
2396
  };
2397
2397
 
2398
+ // src/runtime/native_env.ts
2399
+ var NativeEnv = class {
2400
+ get(key) {
2401
+ switch (runtime.type) {
2402
+ case "node":
2403
+ case "bun":
2404
+ case "deno":
2405
+ return process.env[key] ?? "";
2406
+ default:
2407
+ throw new Error(`Unsupported runtime: ${runtime.type}`);
2408
+ }
2409
+ }
2410
+ getEnvironment() {
2411
+ switch (runtime.type) {
2412
+ case "node":
2413
+ case "deno":
2414
+ case "bun":
2415
+ return Object.fromEntries(
2416
+ Object.entries(process.env).filter(
2417
+ ([_, value]) => value !== void 0
2418
+ )
2419
+ );
2420
+ }
2421
+ }
2422
+ };
2423
+
2398
2424
  // src/errors/error_factory.ts
2425
+ var nativeEnv = new NativeEnv();
2399
2426
  var errorFactory = (error) => {
2427
+ const isDevelopment = nativeEnv.get("NODE_ENV") !== "production";
2400
2428
  return {
2401
- cause: error.cause,
2429
+ code: error.name || "INTERNAL_ERROR",
2402
2430
  message: error.message,
2403
- stack: error.stack
2431
+ ...isDevelopment && { stack: error.stack, cause: error.cause }
2404
2432
  };
2405
2433
  };
2406
2434
 
@@ -3440,6 +3468,330 @@ async function verifySignedCookie(value, secret) {
3440
3468
  return signature === expectedSignature ? cookieValue : false;
3441
3469
  }
3442
3470
 
3471
+ // src/plugins/express/express.ts
3472
+ function toBaldaToExpressRequest(baldaReq, basePath = "") {
3473
+ const url = new URL(baldaReq.url);
3474
+ const headersObj = Object.fromEntries(baldaReq.headers.entries());
3475
+ const expressReq = {
3476
+ body: baldaReq.body,
3477
+ query: baldaReq.query,
3478
+ params: baldaReq.params,
3479
+ cookies: baldaReq.cookies,
3480
+ session: baldaReq.session,
3481
+ originalUrl: url.pathname + url.search,
3482
+ baseUrl: basePath,
3483
+ path: url.pathname.replace(basePath, "") || "/",
3484
+ method: baldaReq.method,
3485
+ ip: baldaReq.ip,
3486
+ headers: headersObj,
3487
+ url: url.pathname,
3488
+ get(name) {
3489
+ return baldaReq.headers.get(name.toLowerCase()) ?? void 0;
3490
+ },
3491
+ header(name) {
3492
+ return baldaReq.headers.get(name.toLowerCase()) ?? void 0;
3493
+ },
3494
+ app: {},
3495
+ res: null,
3496
+ route: null,
3497
+ protocol: url.protocol.replace(":", ""),
3498
+ secure: url.protocol === "https:",
3499
+ hostname: url.hostname,
3500
+ host: url.host,
3501
+ fresh: false,
3502
+ stale: true,
3503
+ xhr: headersObj["x-requested-with"]?.toLowerCase() === "xmlhttprequest",
3504
+ accepts: () => void 0,
3505
+ acceptsCharsets: () => void 0,
3506
+ acceptsEncodings: () => void 0,
3507
+ acceptsLanguages: () => void 0,
3508
+ is: () => null,
3509
+ range: () => void 0,
3510
+ param: (name) => baldaReq.params[name] ?? baldaReq.query[name],
3511
+ files: baldaReq.files,
3512
+ file: baldaReq.file,
3513
+ rawBody: baldaReq.rawBody
3514
+ };
3515
+ return expressReq;
3516
+ }
3517
+ function createExpressResponse(baldaRes) {
3518
+ const expressRes = {
3519
+ locals: {},
3520
+ headersSent: false,
3521
+ statusCode: baldaRes.responseStatus,
3522
+ status(code) {
3523
+ baldaRes.status(code);
3524
+ this.statusCode = code;
3525
+ return this;
3526
+ },
3527
+ sendStatus(code) {
3528
+ this.status(code).send(String(code));
3529
+ return this;
3530
+ },
3531
+ send(body) {
3532
+ this.headersSent = true;
3533
+ const hasContentType = !!baldaRes.headers["Content-Type"];
3534
+ if (!hasContentType && typeof body === "string") {
3535
+ const trimmed = body.trim();
3536
+ if (trimmed.startsWith("<!DOCTYPE") || trimmed.startsWith("<html") || trimmed.startsWith("<HTML")) {
3537
+ baldaRes.html(body);
3538
+ return this;
3539
+ }
3540
+ }
3541
+ baldaRes.send(body);
3542
+ return this;
3543
+ },
3544
+ json(body) {
3545
+ this.headersSent = true;
3546
+ baldaRes.json(body);
3547
+ return this;
3548
+ },
3549
+ redirect(statusOrUrl, url) {
3550
+ this.headersSent = true;
3551
+ const redirectUrl = typeof statusOrUrl === "string" ? statusOrUrl : url;
3552
+ const status = typeof statusOrUrl === "number" ? statusOrUrl : 302;
3553
+ baldaRes.status(status).setHeader("Location", redirectUrl);
3554
+ baldaRes.send("");
3555
+ return this;
3556
+ },
3557
+ setHeader(name, value) {
3558
+ const stringValue = Array.isArray(value) ? value.join(", ") : String(value);
3559
+ baldaRes.setHeader(name, stringValue);
3560
+ return this;
3561
+ },
3562
+ set(field, value) {
3563
+ if (typeof field === "object") {
3564
+ for (const [key, val] of Object.entries(field)) {
3565
+ baldaRes.setHeader(key, val);
3566
+ }
3567
+ } else if (value !== void 0) {
3568
+ baldaRes.setHeader(field, value);
3569
+ }
3570
+ return this;
3571
+ },
3572
+ header(field, value) {
3573
+ return this.set(field, value);
3574
+ },
3575
+ type(contentType) {
3576
+ baldaRes.setHeader("Content-Type", contentType);
3577
+ return this;
3578
+ },
3579
+ contentType(type) {
3580
+ return this.type(type);
3581
+ },
3582
+ end(data) {
3583
+ this.headersSent = true;
3584
+ baldaRes.send(data ?? "");
3585
+ return this;
3586
+ },
3587
+ write(chunk) {
3588
+ return true;
3589
+ },
3590
+ get(name) {
3591
+ return baldaRes.headers[name];
3592
+ },
3593
+ getHeader(name) {
3594
+ return baldaRes.headers[name];
3595
+ },
3596
+ removeHeader(name) {
3597
+ delete baldaRes.headers[name];
3598
+ return this;
3599
+ },
3600
+ append(field, value) {
3601
+ const prev = baldaRes.headers[field];
3602
+ const newValue = Array.isArray(value) ? value.join(", ") : value;
3603
+ baldaRes.setHeader(field, prev ? `${prev}, ${newValue}` : newValue);
3604
+ return this;
3605
+ },
3606
+ cookie(name, value, options) {
3607
+ baldaRes.cookie?.(name, value, options);
3608
+ return this;
3609
+ },
3610
+ clearCookie(name, options) {
3611
+ baldaRes.clearCookie?.(name, options);
3612
+ return this;
3613
+ },
3614
+ render(view, options, callback) {
3615
+ throw new Error(
3616
+ "render() is not supported in Express compatibility layer"
3617
+ );
3618
+ },
3619
+ format(obj) {
3620
+ return this;
3621
+ },
3622
+ attachment(filename) {
3623
+ if (filename) {
3624
+ baldaRes.setHeader(
3625
+ "Content-Disposition",
3626
+ `attachment; filename="${filename}"`
3627
+ );
3628
+ } else {
3629
+ baldaRes.setHeader("Content-Disposition", "attachment");
3630
+ }
3631
+ return this;
3632
+ },
3633
+ sendFile(path2, options, fn) {
3634
+ baldaRes.file(path2);
3635
+ },
3636
+ download(path2, filename, options, fn) {
3637
+ const fname = typeof filename === "string" ? filename : path2.split("/").pop();
3638
+ this.attachment(fname);
3639
+ baldaRes.file(path2);
3640
+ },
3641
+ links(links) {
3642
+ const link = Object.entries(links).map(([rel, url]) => `<${url}>; rel="${rel}"`).join(", ");
3643
+ baldaRes.setHeader("Link", link);
3644
+ return this;
3645
+ },
3646
+ location(url) {
3647
+ baldaRes.setHeader("Location", url);
3648
+ return this;
3649
+ },
3650
+ vary(field) {
3651
+ baldaRes.setHeader("Vary", field);
3652
+ return this;
3653
+ },
3654
+ app: {},
3655
+ req: null
3656
+ };
3657
+ return expressRes;
3658
+ }
3659
+ function expressMiddleware(expressHandler2, basePath = "") {
3660
+ return async (baldaReq, baldaRes, next) => {
3661
+ const expressReq = toBaldaToExpressRequest(baldaReq, basePath);
3662
+ const expressRes = createExpressResponse(baldaRes);
3663
+ await new Promise((resolve, reject) => {
3664
+ const expressNext = (err) => {
3665
+ if (err) {
3666
+ reject(err);
3667
+ return;
3668
+ }
3669
+ resolve();
3670
+ };
3671
+ try {
3672
+ const result = expressHandler2(expressReq, expressRes, expressNext);
3673
+ if (result instanceof Promise) {
3674
+ result.catch(reject);
3675
+ }
3676
+ } catch (error) {
3677
+ reject(error);
3678
+ }
3679
+ });
3680
+ await next();
3681
+ };
3682
+ }
3683
+ function expressHandler(handler, basePath = "") {
3684
+ return async (baldaReq, baldaRes) => {
3685
+ const expressReq = toBaldaToExpressRequest(baldaReq, basePath);
3686
+ const expressRes = createExpressResponse(baldaRes);
3687
+ const next = () => {
3688
+ };
3689
+ await handler(expressReq, expressRes, next);
3690
+ };
3691
+ }
3692
+ function mountExpressRouter(basePath, expressRouter) {
3693
+ const normalizedBase = normalizePath(basePath);
3694
+ const stack = expressRouter.stack;
3695
+ if (!stack) {
3696
+ console.warn("Express router has no stack - routes may not be registered");
3697
+ return;
3698
+ }
3699
+ for (const layer of stack) {
3700
+ processExpressLayer(layer, normalizedBase);
3701
+ }
3702
+ }
3703
+ function processExpressLayer(layer, basePath) {
3704
+ if (layer.route) {
3705
+ const routePath = normalizePath(basePath + layer.route.path);
3706
+ const methods = Object.keys(layer.route.methods).filter(
3707
+ (m) => layer.route.methods[m]
3708
+ );
3709
+ for (const method of methods) {
3710
+ const handlers = layer.route.stack.map((s) => s.handle);
3711
+ registerExpressHandlers(
3712
+ method.toUpperCase(),
3713
+ routePath,
3714
+ handlers,
3715
+ basePath
3716
+ );
3717
+ }
3718
+ return;
3719
+ }
3720
+ if (layer.handle && typeof layer.handle === "function") {
3721
+ const layerPath = layer.path || "";
3722
+ const fullPath = normalizePath(basePath + layerPath);
3723
+ const layerStack = layer.handle.stack;
3724
+ if (layerStack && Array.isArray(layerStack)) {
3725
+ for (const subLayer of layerStack) {
3726
+ processExpressLayer(subLayer, fullPath);
3727
+ }
3728
+ return;
3729
+ }
3730
+ const wildcardPath = fullPath === "/" ? "/*" : `${fullPath}/*`;
3731
+ const middleware2 = expressMiddleware(
3732
+ layer.handle,
3733
+ basePath
3734
+ );
3735
+ const methods = [
3736
+ "GET",
3737
+ "POST",
3738
+ "PUT",
3739
+ "PATCH",
3740
+ "DELETE",
3741
+ "OPTIONS",
3742
+ "HEAD"
3743
+ ];
3744
+ for (const method of methods) {
3745
+ router.addOrUpdate(method, wildcardPath, [middleware2], async () => {
3746
+ }, {
3747
+ excludeFromSwagger: true
3748
+ });
3749
+ }
3750
+ }
3751
+ }
3752
+ function registerExpressHandlers(method, path2, handlers, basePath) {
3753
+ const middlewares = handlers.slice(0, -1).map((h) => expressMiddleware(h, basePath));
3754
+ const lastHandler = handlers[handlers.length - 1];
3755
+ const finalHandler = expressHandler(lastHandler, basePath);
3756
+ router.addOrUpdate(method, path2, middlewares, finalHandler, {
3757
+ excludeFromSwagger: true
3758
+ });
3759
+ }
3760
+ function normalizePath(path2) {
3761
+ let normalized = path2.replace(/\/+/g, "/");
3762
+ if (!normalized.startsWith("/")) {
3763
+ normalized = "/" + normalized;
3764
+ }
3765
+ if (normalized.length > 1 && normalized.endsWith("/")) {
3766
+ normalized = normalized.slice(0, -1);
3767
+ }
3768
+ return normalized;
3769
+ }
3770
+ function createExpressAdapter(server) {
3771
+ return {
3772
+ use(pathOrMiddleware, maybeMiddleware) {
3773
+ if (typeof pathOrMiddleware === "string") {
3774
+ const path2 = pathOrMiddleware;
3775
+ const middleware3 = maybeMiddleware;
3776
+ const middlewareStack2 = middleware3.stack;
3777
+ if (middlewareStack2 && Array.isArray(middlewareStack2)) {
3778
+ mountExpressRouter(path2, middleware3);
3779
+ return;
3780
+ }
3781
+ server.use(expressMiddleware(middleware3, path2));
3782
+ return;
3783
+ }
3784
+ const middleware2 = pathOrMiddleware;
3785
+ const middlewareStack = middleware2.stack;
3786
+ if (middlewareStack && Array.isArray(middlewareStack)) {
3787
+ mountExpressRouter("/", middleware2);
3788
+ return;
3789
+ }
3790
+ server.use(expressMiddleware(middleware2));
3791
+ }
3792
+ };
3793
+ }
3794
+
3443
3795
  // src/plugins/log/log.ts
3444
3796
  var log = (options) => {
3445
3797
  return async (req, res, next) => {
@@ -3729,32 +4081,6 @@ function setNestedValue(obj, key, value) {
3729
4081
  current[lastKey] = value;
3730
4082
  }
3731
4083
 
3732
- // src/runtime/native_env.ts
3733
- var NativeEnv = class {
3734
- get(key) {
3735
- switch (runtime.type) {
3736
- case "node":
3737
- case "bun":
3738
- case "deno":
3739
- return process.env[key] ?? "";
3740
- default:
3741
- throw new Error(`Unsupported runtime: ${runtime.type}`);
3742
- }
3743
- }
3744
- getEnvironment() {
3745
- switch (runtime.type) {
3746
- case "node":
3747
- case "deno":
3748
- case "bun":
3749
- return Object.fromEntries(
3750
- Object.entries(process.env).filter(
3751
- ([_, value]) => value !== void 0
3752
- )
3753
- );
3754
- }
3755
- }
3756
- };
3757
-
3758
4084
  // src/runtime/native_hash.ts
3759
4085
  var NativeHash = class {
3760
4086
  ITERATIONS = 6e5;
@@ -5011,7 +5337,18 @@ var PROTECTED_KEYS = [
5011
5337
  "startUpOptions",
5012
5338
  "tmpDir",
5013
5339
  "logger",
5014
- "getMockServer"
5340
+ "getMockServer",
5341
+ "useExpress",
5342
+ "expressMiddleware",
5343
+ "mountExpressRouter",
5344
+ "setNotFoundHandler",
5345
+ "setGlobalCronErrorHandler",
5346
+ "startRegisteredCrons",
5347
+ "bootstrap",
5348
+ "handleNotFound",
5349
+ "registerNotFoundRoutes",
5350
+ "importControllers",
5351
+ "applyPlugins"
5015
5352
  ];
5016
5353
 
5017
5354
  // src/server/server.ts
@@ -5229,6 +5566,16 @@ var Server = class {
5229
5566
  use(...middlewares) {
5230
5567
  this.globalMiddlewares.push(...middlewares);
5231
5568
  }
5569
+ useExpress(pathOrMiddleware, maybeMiddleware) {
5570
+ const adapter = createExpressAdapter(this);
5571
+ adapter.use(pathOrMiddleware, maybeMiddleware);
5572
+ }
5573
+ expressMiddleware(middleware2) {
5574
+ return expressMiddleware(middleware2);
5575
+ }
5576
+ mountExpressRouter(basePath, expressRouter) {
5577
+ mountExpressRouter(basePath, expressRouter);
5578
+ }
5232
5579
  setErrorHandler(errorHandler) {
5233
5580
  this.globalMiddlewares.unshift(async (req, res, next) => {
5234
5581
  try {
@@ -5414,6 +5761,7 @@ var Server = class {
5414
5761
  }
5415
5762
  /**
5416
5763
  * Handles not found routes by delegating to custom handler or default error response
5764
+ * Checks if the path exists for other methods and returns 405 if so
5417
5765
  * @internal
5418
5766
  */
5419
5767
  handleNotFound = (req, res) => {
@@ -5421,7 +5769,38 @@ var Server = class {
5421
5769
  this.notFoundHandler(req, res);
5422
5770
  return;
5423
5771
  }
5424
- const notFoundError = new RouteNotFoundError(req.url, req.method);
5772
+ const pathname = new URL(req.url).pathname;
5773
+ const allMethods = [
5774
+ "GET",
5775
+ "POST",
5776
+ "PUT",
5777
+ "PATCH",
5778
+ "DELETE",
5779
+ "OPTIONS",
5780
+ "HEAD"
5781
+ ];
5782
+ const allowedMethods = [];
5783
+ for (const method of allMethods) {
5784
+ if (method === req.method.toUpperCase()) {
5785
+ continue;
5786
+ }
5787
+ const match = router.find(method, pathname);
5788
+ if (match && match.handler !== this.handleNotFound) {
5789
+ allowedMethods.push(method);
5790
+ }
5791
+ }
5792
+ if (allowedMethods.length > 0) {
5793
+ res.setHeader("Allow", allowedMethods.join(", "));
5794
+ const methodNotAllowedError = new MethodNotAllowedError(
5795
+ pathname,
5796
+ req.method
5797
+ );
5798
+ res.methodNotAllowed({
5799
+ ...errorFactory(methodNotAllowedError)
5800
+ });
5801
+ return;
5802
+ }
5803
+ const notFoundError = new RouteNotFoundError(pathname, req.method);
5425
5804
  res.notFound({
5426
5805
  ...errorFactory(notFoundError)
5427
5806
  });
@@ -5437,7 +5816,8 @@ var Server = class {
5437
5816
  "PUT",
5438
5817
  "PATCH",
5439
5818
  "DELETE",
5440
- "OPTIONS"
5819
+ "OPTIONS",
5820
+ "HEAD"
5441
5821
  ];
5442
5822
  for (const method of methods) {
5443
5823
  router.addOrUpdate(method, "*", [], this.handleNotFound, {
@@ -5532,11 +5912,14 @@ exports.commandRegistry = commandRegistry;
5532
5912
  exports.controller = controller;
5533
5913
  exports.cookie = cookie;
5534
5914
  exports.cors = cors;
5915
+ exports.createExpressAdapter = createExpressAdapter;
5535
5916
  exports.createPolicyDecorator = createPolicyDecorator;
5536
5917
  exports.cron = cron;
5537
5918
  exports.defineLoggerConfig = defineLoggerConfig;
5538
5919
  exports.defineQueueConfiguration = defineQueueConfiguration;
5539
5920
  exports.del = del;
5921
+ exports.expressHandler = expressHandler;
5922
+ exports.expressMiddleware = expressMiddleware;
5540
5923
  exports.fileParser = fileParser;
5541
5924
  exports.flag = flag;
5542
5925
  exports.get = get;
@@ -5546,6 +5929,7 @@ exports.helmet = helmet;
5546
5929
  exports.json = json;
5547
5930
  exports.log = log;
5548
5931
  exports.middleware = middleware;
5932
+ exports.mountExpressRouter = mountExpressRouter;
5549
5933
  exports.patch = patch;
5550
5934
  exports.post = post;
5551
5935
  exports.publish = publish;