@zenstackhq/server 3.5.6 → 3.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/api.cjs +2729 -4451
  2. package/dist/api.cjs.map +1 -1
  3. package/dist/api.d.cts +219 -207
  4. package/dist/api.d.mts +249 -0
  5. package/dist/api.mjs +2745 -0
  6. package/dist/api.mjs.map +1 -0
  7. package/dist/common-BjzwQE8S.d.mts +16 -0
  8. package/dist/common-Cdj4rLFr.mjs +9 -0
  9. package/dist/common-Cdj4rLFr.mjs.map +1 -0
  10. package/dist/common-D2RyWTAZ.cjs +14 -0
  11. package/dist/common-D2RyWTAZ.cjs.map +1 -0
  12. package/dist/common-D3fx-IHt.d.cts +16 -0
  13. package/dist/elysia.cjs +46 -114
  14. package/dist/elysia.cjs.map +1 -1
  15. package/dist/elysia.d.cts +37 -36
  16. package/dist/elysia.d.mts +54 -0
  17. package/dist/elysia.mjs +48 -0
  18. package/dist/elysia.mjs.map +1 -0
  19. package/dist/express.cjs +40 -110
  20. package/dist/express.cjs.map +1 -1
  21. package/dist/express.d.cts +21 -20
  22. package/dist/express.d.mts +32 -0
  23. package/dist/express.mjs +42 -0
  24. package/dist/express.mjs.map +1 -0
  25. package/dist/fastify.cjs +36 -100
  26. package/dist/fastify.cjs.map +1 -1
  27. package/dist/fastify.d.cts +15 -14
  28. package/dist/fastify.d.mts +23 -0
  29. package/dist/fastify.mjs +36 -0
  30. package/dist/fastify.mjs.map +1 -0
  31. package/dist/hono.cjs +31 -108
  32. package/dist/hono.cjs.map +1 -1
  33. package/dist/hono.d.cts +11 -10
  34. package/dist/hono.d.mts +19 -0
  35. package/dist/hono.mjs +33 -0
  36. package/dist/hono.mjs.map +1 -0
  37. package/dist/next.cjs +81 -169
  38. package/dist/next.cjs.map +1 -1
  39. package/dist/next.d.cts +32 -29
  40. package/dist/{next.d.ts → next.d.mts} +32 -29
  41. package/dist/next.mjs +86 -0
  42. package/dist/next.mjs.map +1 -0
  43. package/dist/nuxt.cjs +414 -104
  44. package/dist/nuxt.cjs.map +1 -1
  45. package/dist/nuxt.d.cts +538 -12
  46. package/dist/nuxt.d.mts +545 -0
  47. package/dist/nuxt.mjs +416 -0
  48. package/dist/nuxt.mjs.map +1 -0
  49. package/dist/openapi-BPFL4Hn6.mjs +585 -0
  50. package/dist/openapi-BPFL4Hn6.mjs.map +1 -0
  51. package/dist/openapi-BUzfCKi-.cjs +586 -0
  52. package/dist/openapi-BUzfCKi-.cjs.map +1 -0
  53. package/dist/spec-utils-C7vlChMD.cjs +278 -0
  54. package/dist/spec-utils-C7vlChMD.cjs.map +1 -0
  55. package/dist/spec-utils-Syk4SLCX.mjs +200 -0
  56. package/dist/spec-utils-Syk4SLCX.mjs.map +1 -0
  57. package/dist/sveltekit.cjs +87 -188
  58. package/dist/sveltekit.cjs.map +1 -1
  59. package/dist/sveltekit.d.cts +24 -22
  60. package/dist/sveltekit.d.mts +43 -0
  61. package/dist/sveltekit.mjs +88 -0
  62. package/dist/sveltekit.mjs.map +1 -0
  63. package/dist/tanstack-start.cjs +59 -133
  64. package/dist/tanstack-start.cjs.map +1 -1
  65. package/dist/tanstack-start.d.cts +19 -14
  66. package/dist/tanstack-start.d.mts +37 -0
  67. package/dist/tanstack-start.mjs +60 -0
  68. package/dist/tanstack-start.mjs.map +1 -0
  69. package/dist/types-6NFtxov5.d.mts +74 -0
  70. package/dist/types-DYdFPTkH.d.cts +74 -0
  71. package/dist/utils-B9NX7OcP.cjs +85 -0
  72. package/dist/utils-B9NX7OcP.cjs.map +1 -0
  73. package/dist/utils-Doc_CQNd.mjs +39 -0
  74. package/dist/utils-Doc_CQNd.mjs.map +1 -0
  75. package/package.json +28 -27
  76. package/dist/api.d.ts +0 -237
  77. package/dist/api.js +0 -4437
  78. package/dist/api.js.map +0 -1
  79. package/dist/common-Cuu8bjzK.d.cts +0 -14
  80. package/dist/common-WHbiInuf.d.ts +0 -14
  81. package/dist/elysia.d.ts +0 -53
  82. package/dist/elysia.js +0 -82
  83. package/dist/elysia.js.map +0 -1
  84. package/dist/express.d.ts +0 -31
  85. package/dist/express.js +0 -78
  86. package/dist/express.js.map +0 -1
  87. package/dist/fastify.d.ts +0 -22
  88. package/dist/fastify.js +0 -68
  89. package/dist/fastify.js.map +0 -1
  90. package/dist/hono.d.ts +0 -18
  91. package/dist/hono.js +0 -76
  92. package/dist/hono.js.map +0 -1
  93. package/dist/next.js +0 -140
  94. package/dist/next.js.map +0 -1
  95. package/dist/nuxt.d.ts +0 -19
  96. package/dist/nuxt.js +0 -73
  97. package/dist/nuxt.js.map +0 -1
  98. package/dist/sveltekit.d.ts +0 -41
  99. package/dist/sveltekit.js +0 -156
  100. package/dist/sveltekit.js.map +0 -1
  101. package/dist/tanstack-start.d.ts +0 -32
  102. package/dist/tanstack-start.js +0 -104
  103. package/dist/tanstack-start.js.map +0 -1
  104. package/dist/types-CU_PWKr9.d.cts +0 -72
  105. package/dist/types-CU_PWKr9.d.ts +0 -72
package/dist/next.mjs ADDED
@@ -0,0 +1,86 @@
1
+ import { t as logInternalError } from "./common-Cdj4rLFr.mjs";
2
+ //#region src/adapter/next/app-route-handler.ts
3
+ /**
4
+ * Creates a Next.js "app router" API route request handler that handles ZenStack CRUD requests.
5
+ *
6
+ * @param options Options for initialization
7
+ * @returns An API route request handler
8
+ */
9
+ function factory$1(options) {
10
+ return async (req, context) => {
11
+ const client = await options.getClient(req);
12
+ if (!client) return Response.json({ message: "unable to get ZenStackClient from request context" }, { status: 500 });
13
+ let params;
14
+ const url = new URL(req.url);
15
+ const query = Object.fromEntries(url.searchParams);
16
+ try {
17
+ params = await context.params;
18
+ } catch {
19
+ return Response.json({ message: "Failed to resolve request parameters" }, { status: 500 });
20
+ }
21
+ if (!params.path) return Response.json({ message: "missing path parameter" }, { status: 400 });
22
+ const path = params.path.join("/");
23
+ let requestBody;
24
+ if (req.body) try {
25
+ requestBody = await req.json();
26
+ } catch {}
27
+ try {
28
+ const r = await options.apiHandler.handleRequest({
29
+ method: req.method,
30
+ path,
31
+ query,
32
+ requestBody,
33
+ client
34
+ });
35
+ return Response.json(r.body, { status: r.status });
36
+ } catch (err) {
37
+ logInternalError(options.apiHandler.log, err);
38
+ return Response.json({ message: "An internal server error occurred" }, { status: 500 });
39
+ }
40
+ };
41
+ }
42
+ //#endregion
43
+ //#region src/adapter/next/pages-route-handler.ts
44
+ /**
45
+ * Creates a Next.js API endpoint "pages" router request handler that handles ZenStack CRUD requests.
46
+ *
47
+ * @param options Options for initialization
48
+ * @returns An API endpoint request handler
49
+ */
50
+ function factory(options) {
51
+ return async (req, res) => {
52
+ const client = await options.getClient(req, res);
53
+ if (!client) {
54
+ res.status(500).json({ message: "unable to get ZenStackClient from request context" });
55
+ return;
56
+ }
57
+ if (!req.query["path"]) {
58
+ res.status(400).json({ message: "missing path parameter" });
59
+ return;
60
+ }
61
+ const path = req.query["path"].join("/");
62
+ try {
63
+ const r = await options.apiHandler.handleRequest({
64
+ method: req.method,
65
+ path,
66
+ query: req.query,
67
+ requestBody: req.body,
68
+ client
69
+ });
70
+ res.status(r.status).send(r.body);
71
+ } catch (err) {
72
+ logInternalError(options.apiHandler.log, err);
73
+ res.status(500).send({ message: "An internal server error occurred" });
74
+ }
75
+ };
76
+ }
77
+ //#endregion
78
+ //#region src/adapter/next/index.ts
79
+ function NextRequestHandler(options) {
80
+ if (options.useAppDir === true) return factory$1(options);
81
+ else return factory(options);
82
+ }
83
+ //#endregion
84
+ export { NextRequestHandler };
85
+
86
+ //# sourceMappingURL=next.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.mjs","names":["factory","AppRouteHandler","PagesRouteHandler"],"sources":["../src/adapter/next/app-route-handler.ts","../src/adapter/next/pages-route-handler.ts","../src/adapter/next/index.ts"],"sourcesContent":["import type { SchemaDef } from '@zenstackhq/orm/schema';\nimport type { NextRequest } from 'next/server';\nimport type { AppRouteRequestHandlerOptions } from '.';\nimport { logInternalError } from '../common';\n\ntype Context = { params: Promise<{ path: string[] }> };\n\n/**\n * Creates a Next.js \"app router\" API route request handler that handles ZenStack CRUD requests.\n *\n * @param options Options for initialization\n * @returns An API route request handler\n */\nexport default function factory<Schema extends SchemaDef>(\n options: AppRouteRequestHandlerOptions<Schema>,\n): (req: NextRequest, context: Context) => Promise<Response> {\n return async (req: NextRequest, context: Context) => {\n const client = await options.getClient(req);\n if (!client) {\n return Response.json({ message: 'unable to get ZenStackClient from request context' }, { status: 500 });\n }\n\n let params: Awaited<Context['params']>;\n const url = new URL(req.url);\n const query = Object.fromEntries(url.searchParams);\n\n try {\n params = await context.params;\n } catch {\n return Response.json({ message: 'Failed to resolve request parameters' }, { status: 500 });\n }\n\n if (!params.path) {\n return Response.json(\n { message: 'missing path parameter' },\n {\n status: 400,\n },\n );\n }\n const path = params.path.join('/');\n\n let requestBody: unknown;\n if (req.body) {\n try {\n requestBody = await req.json();\n } catch {\n // noop\n }\n }\n\n try {\n const r = await options.apiHandler.handleRequest({\n method: req.method!,\n path,\n query,\n requestBody,\n client,\n });\n return Response.json(r.body, { status: r.status });\n } catch (err) {\n logInternalError(options.apiHandler.log, err);\n return Response.json({ message: 'An internal server error occurred' }, { status: 500 });\n }\n };\n}\n","import type { SchemaDef } from '@zenstackhq/orm/schema';\nimport type { NextApiRequest, NextApiResponse } from 'next';\nimport type { PageRouteRequestHandlerOptions } from '.';\nimport { logInternalError } from '../common';\n\n/**\n * Creates a Next.js API endpoint \"pages\" router request handler that handles ZenStack CRUD requests.\n *\n * @param options Options for initialization\n * @returns An API endpoint request handler\n */\nexport default function factory<Schema extends SchemaDef>(\n options: PageRouteRequestHandlerOptions<Schema>,\n): (req: NextApiRequest, res: NextApiResponse) => Promise<void> {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n const client = await options.getClient(req, res);\n if (!client) {\n res.status(500).json({ message: 'unable to get ZenStackClient from request context' });\n return;\n }\n\n if (!req.query['path']) {\n res.status(400).json({ message: 'missing path parameter' });\n return;\n }\n const path = (req.query['path'] as string[]).join('/');\n\n try {\n const r = await options.apiHandler.handleRequest({\n method: req.method!,\n path,\n query: req.query as Record<string, string | string[]>,\n requestBody: req.body,\n client,\n });\n res.status(r.status).send(r.body);\n } catch (err) {\n logInternalError(options.apiHandler.log, err);\n res.status(500).send({ message: 'An internal server error occurred' });\n }\n };\n}\n","import type { ClientContract } from '@zenstackhq/orm';\nimport type { SchemaDef } from '@zenstackhq/orm/schema';\nimport type { NextApiRequest, NextApiResponse } from 'next';\nimport type { NextRequest } from 'next/server';\nimport type { CommonAdapterOptions } from '../common';\nimport { default as AppRouteHandler } from './app-route-handler';\nimport { default as PagesRouteHandler } from './pages-route-handler';\n\n/**\n * Options for initializing a Next.js API endpoint request handler.\n */\nexport interface PageRouteRequestHandlerOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {\n /**\n * Callback for getting a ZenStackClient for the given request\n */\n getClient: (req: NextApiRequest, res: NextApiResponse) => ClientContract<Schema> | Promise<ClientContract<Schema>>;\n\n /**\n * Use app dir or not\n */\n useAppDir?: false | undefined;\n}\n\n/**\n * Options for initializing a Next.js 13 app dir API route handler.\n */\nexport interface AppRouteRequestHandlerOptions<Schema extends SchemaDef> extends CommonAdapterOptions<Schema> {\n /**\n * Callback for getting a ZenStackClient for the given request.\n */\n getClient: (req: NextRequest) => ClientContract<Schema> | Promise<ClientContract<Schema>>;\n\n /**\n * Use app dir or not\n */\n useAppDir: true;\n}\n\n/**\n * Creates a Next.js API route handler.\n */\nexport function NextRequestHandler<Schema extends SchemaDef>(\n options: PageRouteRequestHandlerOptions<Schema>,\n): ReturnType<typeof PagesRouteHandler>;\nexport function NextRequestHandler<Schema extends SchemaDef>(\n options: AppRouteRequestHandlerOptions<Schema>,\n): ReturnType<typeof AppRouteHandler>;\nexport function NextRequestHandler<Schema extends SchemaDef>(\n options: PageRouteRequestHandlerOptions<Schema> | AppRouteRequestHandlerOptions<Schema>,\n) {\n if (options.useAppDir === true) {\n return AppRouteHandler(options);\n } else {\n return PagesRouteHandler(options);\n }\n}\n"],"mappings":";;;;;;;;AAaA,SAAwBA,UACpB,SACyD;AACzD,QAAO,OAAO,KAAkB,YAAqB;EACjD,MAAM,SAAS,MAAM,QAAQ,UAAU,IAAI;AAC3C,MAAI,CAAC,OACD,QAAO,SAAS,KAAK,EAAE,SAAS,qDAAqD,EAAE,EAAE,QAAQ,KAAK,CAAC;EAG3G,IAAI;EACJ,MAAM,MAAM,IAAI,IAAI,IAAI,IAAI;EAC5B,MAAM,QAAQ,OAAO,YAAY,IAAI,aAAa;AAElD,MAAI;AACA,YAAS,MAAM,QAAQ;UACnB;AACJ,UAAO,SAAS,KAAK,EAAE,SAAS,wCAAwC,EAAE,EAAE,QAAQ,KAAK,CAAC;;AAG9F,MAAI,CAAC,OAAO,KACR,QAAO,SAAS,KACZ,EAAE,SAAS,0BAA0B,EACrC,EACI,QAAQ,KACX,CACJ;EAEL,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;EAElC,IAAI;AACJ,MAAI,IAAI,KACJ,KAAI;AACA,iBAAc,MAAM,IAAI,MAAM;UAC1B;AAKZ,MAAI;GACA,MAAM,IAAI,MAAM,QAAQ,WAAW,cAAc;IAC7C,QAAQ,IAAI;IACZ;IACA;IACA;IACA;IACH,CAAC;AACF,UAAO,SAAS,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC;WAC7C,KAAK;AACV,oBAAiB,QAAQ,WAAW,KAAK,IAAI;AAC7C,UAAO,SAAS,KAAK,EAAE,SAAS,qCAAqC,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;;;;;;;;;ACnDnG,SAAwB,QACpB,SAC4D;AAC5D,QAAO,OAAO,KAAqB,QAAyB;EACxD,MAAM,SAAS,MAAM,QAAQ,UAAU,KAAK,IAAI;AAChD,MAAI,CAAC,QAAQ;AACT,OAAI,OAAO,IAAI,CAAC,KAAK,EAAE,SAAS,qDAAqD,CAAC;AACtF;;AAGJ,MAAI,CAAC,IAAI,MAAM,SAAS;AACpB,OAAI,OAAO,IAAI,CAAC,KAAK,EAAE,SAAS,0BAA0B,CAAC;AAC3D;;EAEJ,MAAM,OAAQ,IAAI,MAAM,QAAqB,KAAK,IAAI;AAEtD,MAAI;GACA,MAAM,IAAI,MAAM,QAAQ,WAAW,cAAc;IAC7C,QAAQ,IAAI;IACZ;IACA,OAAO,IAAI;IACX,aAAa,IAAI;IACjB;IACH,CAAC;AACF,OAAI,OAAO,EAAE,OAAO,CAAC,KAAK,EAAE,KAAK;WAC5B,KAAK;AACV,oBAAiB,QAAQ,WAAW,KAAK,IAAI;AAC7C,OAAI,OAAO,IAAI,CAAC,KAAK,EAAE,SAAS,qCAAqC,CAAC;;;;;;ACSlF,SAAgB,mBACZ,SACF;AACE,KAAI,QAAQ,cAAc,KACtB,QAAOC,UAAgB,QAAQ;KAE/B,QAAOC,QAAkB,QAAQ"}
package/dist/nuxt.cjs CHANGED
@@ -1,108 +1,418 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/adapter/nuxt/index.ts
32
- var nuxt_exports = {};
33
- __export(nuxt_exports, {
34
- createEventHandler: () => createEventHandler
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ require("./utils-B9NX7OcP.cjs");
3
+ const require_common = require("./common-D2RyWTAZ.cjs");
4
+ String.fromCharCode;
5
+ const PLUS_RE = /\+/g;
6
+ function decode(text = "") {
7
+ try {
8
+ return decodeURIComponent("" + text);
9
+ } catch {
10
+ return "" + text;
11
+ }
12
+ }
13
+ function decodeQueryKey(text) {
14
+ return decode(text.replace(PLUS_RE, " "));
15
+ }
16
+ function decodeQueryValue(text) {
17
+ return decode(text.replace(PLUS_RE, " "));
18
+ }
19
+ function parseQuery(parametersString = "") {
20
+ const object = /* @__PURE__ */ Object.create(null);
21
+ if (parametersString[0] === "?") parametersString = parametersString.slice(1);
22
+ for (const parameter of parametersString.split("&")) {
23
+ const s = parameter.match(/([^=]+)=?(.*)/) || [];
24
+ if (s.length < 2) continue;
25
+ const key = decodeQueryKey(s[1]);
26
+ if (key === "__proto__" || key === "constructor") continue;
27
+ const value = decodeQueryValue(s[2] || "");
28
+ if (object[key] === void 0) object[key] = value;
29
+ else if (Array.isArray(object[key])) object[key].push(value);
30
+ else object[key] = [object[key], value];
31
+ }
32
+ return object;
33
+ }
34
+ const PROTOCOL_STRICT_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/;
35
+ const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/;
36
+ const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/;
37
+ function hasProtocol(inputString, opts = {}) {
38
+ if (typeof opts === "boolean") opts = { acceptRelative: opts };
39
+ if (opts.strict) return PROTOCOL_STRICT_REGEX.test(inputString);
40
+ return PROTOCOL_REGEX.test(inputString) || (opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false);
41
+ }
42
+ function getQuery$1(input) {
43
+ return parseQuery(parseURL(input).search);
44
+ }
45
+ const protocolRelative = Symbol.for("ufo:protocolRelative");
46
+ function parseURL(input = "", defaultProto) {
47
+ const _specialProtoMatch = input.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);
48
+ if (_specialProtoMatch) {
49
+ const [, _proto, _pathname = ""] = _specialProtoMatch;
50
+ return {
51
+ protocol: _proto.toLowerCase(),
52
+ pathname: _pathname,
53
+ href: _proto + _pathname,
54
+ auth: "",
55
+ host: "",
56
+ search: "",
57
+ hash: ""
58
+ };
59
+ }
60
+ if (!hasProtocol(input, { acceptRelative: true })) return defaultProto ? parseURL(defaultProto + input) : parsePath(input);
61
+ const [, protocol = "", auth, hostAndPath = ""] = input.replace(/\\/g, "/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/) || [];
62
+ let [, host = "", path = ""] = hostAndPath.match(/([^#/?]*)(.*)?/) || [];
63
+ if (protocol === "file:") path = path.replace(/\/(?=[A-Za-z]:)/, "");
64
+ const { pathname, search, hash } = parsePath(path);
65
+ return {
66
+ protocol: protocol.toLowerCase(),
67
+ auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "",
68
+ host,
69
+ pathname,
70
+ search,
71
+ hash,
72
+ [protocolRelative]: !protocol
73
+ };
74
+ }
75
+ function parsePath(input = "") {
76
+ const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1);
77
+ return {
78
+ pathname,
79
+ search,
80
+ hash
81
+ };
82
+ }
83
+ //#endregion
84
+ //#region ../../node_modules/.pnpm/destr@2.0.5/node_modules/destr/dist/index.mjs
85
+ const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
86
+ const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
87
+ const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
88
+ function jsonParseTransform(key, value) {
89
+ if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
90
+ warnKeyDropped(key);
91
+ return;
92
+ }
93
+ return value;
94
+ }
95
+ function warnKeyDropped(key) {
96
+ console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
97
+ }
98
+ function destr(value, options = {}) {
99
+ if (typeof value !== "string") return value;
100
+ if (value[0] === "\"" && value[value.length - 1] === "\"" && value.indexOf("\\") === -1) return value.slice(1, -1);
101
+ const _value = value.trim();
102
+ if (_value.length <= 9) switch (_value.toLowerCase()) {
103
+ case "true": return true;
104
+ case "false": return false;
105
+ case "undefined": return;
106
+ case "null": return null;
107
+ case "nan": return NaN;
108
+ case "infinity": return Number.POSITIVE_INFINITY;
109
+ case "-infinity": return Number.NEGATIVE_INFINITY;
110
+ }
111
+ if (!JsonSigRx.test(value)) {
112
+ if (options.strict) throw new SyntaxError("[destr] Invalid JSON");
113
+ return value;
114
+ }
115
+ try {
116
+ if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
117
+ if (options.strict) throw new Error("[destr] Possible prototype pollution");
118
+ return JSON.parse(value, jsonParseTransform);
119
+ }
120
+ return JSON.parse(value);
121
+ } catch (error) {
122
+ if (options.strict) throw error;
123
+ return value;
124
+ }
125
+ }
126
+ //#endregion
127
+ //#region ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
128
+ function isPlainObject(value) {
129
+ if (value === null || typeof value !== "object") return false;
130
+ const prototype = Object.getPrototypeOf(value);
131
+ if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) return false;
132
+ if (Symbol.iterator in value) return false;
133
+ if (Symbol.toStringTag in value) return Object.prototype.toString.call(value) === "[object Module]";
134
+ return true;
135
+ }
136
+ function _defu(baseObject, defaults, namespace = ".", merger) {
137
+ if (!isPlainObject(defaults)) return _defu(baseObject, {}, namespace, merger);
138
+ const object = Object.assign({}, defaults);
139
+ for (const key in baseObject) {
140
+ if (key === "__proto__" || key === "constructor") continue;
141
+ const value = baseObject[key];
142
+ if (value === null || value === void 0) continue;
143
+ if (merger && merger(object, key, value, namespace)) continue;
144
+ if (Array.isArray(value) && Array.isArray(object[key])) object[key] = [...value, ...object[key]];
145
+ else if (isPlainObject(value) && isPlainObject(object[key])) object[key] = _defu(value, object[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
146
+ else object[key] = value;
147
+ }
148
+ return object;
149
+ }
150
+ function createDefu(merger) {
151
+ return (...arguments_) => arguments_.reduce((p, c) => _defu(p, c, "", merger), {});
152
+ }
153
+ createDefu();
154
+ createDefu((object, key, currentValue) => {
155
+ if (object[key] !== void 0 && typeof currentValue === "function") {
156
+ object[key] = currentValue(object[key]);
157
+ return true;
158
+ }
35
159
  });
36
- module.exports = __toCommonJS(nuxt_exports);
37
-
38
- // src/adapter/nuxt/handler.ts
39
- var import_h3 = require("h3");
40
-
41
- // src/api/utils.ts
42
- var import_decimal = require("decimal.js");
43
- var import_superjson = __toESM(require("superjson"), 1);
44
- var import_ts_pattern = require("ts-pattern");
45
- var import_v3 = require("zod-validation-error/v3");
46
- var import_v4 = require("zod-validation-error/v4");
47
- function log(logger, level, message, error) {
48
- if (!logger) {
49
- return;
50
- }
51
- const getMessage = typeof message === "function" ? message : () => message;
52
- if (typeof logger === "function") {
53
- logger(level, getMessage(), error);
54
- } else if (logger.includes(level)) {
55
- const logFn = (0, import_ts_pattern.match)(level).with("debug", () => console.debug).with("info", () => console.info).with("warn", () => console.warn).with("error", () => console.error).exhaustive();
56
- logFn(`@zenstackhq/server: [${level}] ${getMessage()}${error ? `
57
- ${error}` : ""}`);
58
- }
59
- }
60
- __name(log, "log");
61
-
62
- // src/adapter/common.ts
63
- function logInternalError(logger, err) {
64
- log(logger, "error", `An unhandled error occurred while processing the request: ${err}${err instanceof Error ? "\n" + err.stack : ""}`);
160
+ createDefu((object, key, currentValue) => {
161
+ if (Array.isArray(object[key]) && typeof currentValue === "function") {
162
+ object[key] = currentValue(object[key]);
163
+ return true;
164
+ }
165
+ });
166
+ //#endregion
167
+ //#region ../../node_modules/.pnpm/h3@1.15.5/node_modules/h3/dist/index.mjs
168
+ function hasProp(obj, prop) {
169
+ try {
170
+ return prop in obj;
171
+ } catch {
172
+ return false;
173
+ }
65
174
  }
66
- __name(logInternalError, "logInternalError");
67
-
68
- // src/adapter/nuxt/handler.ts
175
+ var H3Error = class extends Error {
176
+ static __h3_error__ = true;
177
+ statusCode = 500;
178
+ fatal = false;
179
+ unhandled = false;
180
+ statusMessage;
181
+ data;
182
+ cause;
183
+ constructor(message, opts = {}) {
184
+ super(message, opts);
185
+ if (opts.cause && !this.cause) this.cause = opts.cause;
186
+ }
187
+ toJSON() {
188
+ const obj = {
189
+ message: this.message,
190
+ statusCode: sanitizeStatusCode(this.statusCode, 500)
191
+ };
192
+ if (this.statusMessage) obj.statusMessage = sanitizeStatusMessage(this.statusMessage);
193
+ if (this.data !== void 0) obj.data = this.data;
194
+ return obj;
195
+ }
196
+ };
197
+ function createError(input) {
198
+ if (typeof input === "string") return new H3Error(input);
199
+ if (isError(input)) return input;
200
+ const err = new H3Error(input.message ?? input.statusMessage ?? "", { cause: input.cause || input });
201
+ if (hasProp(input, "stack")) try {
202
+ Object.defineProperty(err, "stack", { get() {
203
+ return input.stack;
204
+ } });
205
+ } catch {
206
+ try {
207
+ err.stack = input.stack;
208
+ } catch {}
209
+ }
210
+ if (input.data) err.data = input.data;
211
+ if (input.statusCode) err.statusCode = sanitizeStatusCode(input.statusCode, err.statusCode);
212
+ else if (input.status) err.statusCode = sanitizeStatusCode(input.status, err.statusCode);
213
+ if (input.statusMessage) err.statusMessage = input.statusMessage;
214
+ else if (input.statusText) err.statusMessage = input.statusText;
215
+ if (err.statusMessage) {
216
+ const originalMessage = err.statusMessage;
217
+ if (sanitizeStatusMessage(err.statusMessage) !== originalMessage) console.warn("[h3] Please prefer using `message` for longer error messages instead of `statusMessage`. In the future, `statusMessage` will be sanitized by default.");
218
+ }
219
+ if (input.fatal !== void 0) err.fatal = input.fatal;
220
+ if (input.unhandled !== void 0) err.unhandled = input.unhandled;
221
+ return err;
222
+ }
223
+ function isError(input) {
224
+ return input?.constructor?.__h3_error__ === true;
225
+ }
226
+ function getQuery(event) {
227
+ return getQuery$1(event.path || "");
228
+ }
229
+ function getRouterParams(event, opts = {}) {
230
+ let params = event.context.params || {};
231
+ if (opts.decode) {
232
+ params = { ...params };
233
+ for (const key in params) params[key] = decode(params[key]);
234
+ }
235
+ return params;
236
+ }
237
+ function isMethod(event, expected, allowHead) {
238
+ if (allowHead && event.method === "HEAD") return true;
239
+ if (typeof expected === "string") {
240
+ if (event.method === expected) return true;
241
+ } else if (expected.includes(event.method)) return true;
242
+ return false;
243
+ }
244
+ function assertMethod(event, expected, allowHead) {
245
+ if (!isMethod(event, expected, allowHead)) throw createError({
246
+ statusCode: 405,
247
+ statusMessage: "HTTP method is not allowed."
248
+ });
249
+ }
250
+ const RawBodySymbol = Symbol.for("h3RawBody");
251
+ const ParsedBodySymbol = Symbol.for("h3ParsedBody");
252
+ const PayloadMethods$1 = [
253
+ "PATCH",
254
+ "POST",
255
+ "PUT",
256
+ "DELETE"
257
+ ];
258
+ function readRawBody(event, encoding = "utf8") {
259
+ assertMethod(event, PayloadMethods$1);
260
+ const _rawBody = event._requestBody || event.web?.request?.body || event.node.req[RawBodySymbol] || event.node.req.rawBody || event.node.req.body;
261
+ if (_rawBody) {
262
+ const promise2 = Promise.resolve(_rawBody).then((_resolved) => {
263
+ if (Buffer.isBuffer(_resolved)) return _resolved;
264
+ if (typeof _resolved.pipeTo === "function") return new Promise((resolve, reject) => {
265
+ const chunks = [];
266
+ _resolved.pipeTo(new WritableStream({
267
+ write(chunk) {
268
+ chunks.push(chunk);
269
+ },
270
+ close() {
271
+ resolve(Buffer.concat(chunks));
272
+ },
273
+ abort(reason) {
274
+ reject(reason);
275
+ }
276
+ })).catch(reject);
277
+ });
278
+ else if (typeof _resolved.pipe === "function") return new Promise((resolve, reject) => {
279
+ const chunks = [];
280
+ _resolved.on("data", (chunk) => {
281
+ chunks.push(chunk);
282
+ }).on("end", () => {
283
+ resolve(Buffer.concat(chunks));
284
+ }).on("error", reject);
285
+ });
286
+ if (_resolved.constructor === Object) return Buffer.from(JSON.stringify(_resolved));
287
+ if (_resolved instanceof URLSearchParams) return Buffer.from(_resolved.toString());
288
+ if (_resolved instanceof FormData) return new Response(_resolved).bytes().then((uint8arr) => Buffer.from(uint8arr));
289
+ return Buffer.from(_resolved);
290
+ });
291
+ return encoding ? promise2.then((buff) => buff.toString(encoding)) : promise2;
292
+ }
293
+ if (!Number.parseInt(event.node.req.headers["content-length"] || "") && !/\bchunked\b/i.test(String(event.node.req.headers["transfer-encoding"] ?? ""))) return Promise.resolve(void 0);
294
+ const promise = event.node.req[RawBodySymbol] = new Promise((resolve, reject) => {
295
+ const bodyData = [];
296
+ event.node.req.on("error", (err) => {
297
+ reject(err);
298
+ }).on("data", (chunk) => {
299
+ bodyData.push(chunk);
300
+ }).on("end", () => {
301
+ resolve(Buffer.concat(bodyData));
302
+ });
303
+ });
304
+ return encoding ? promise.then((buff) => buff.toString(encoding)) : promise;
305
+ }
306
+ async function readBody(event, options = {}) {
307
+ const request = event.node.req;
308
+ if (hasProp(request, ParsedBodySymbol)) return request[ParsedBodySymbol];
309
+ const contentType = request.headers["content-type"] || "";
310
+ const body = await readRawBody(event);
311
+ let parsed;
312
+ if (contentType === "application/json") parsed = _parseJSON(body, options.strict ?? true);
313
+ else if (contentType.startsWith("application/x-www-form-urlencoded")) parsed = _parseURLEncodedBody(body);
314
+ else if (contentType.startsWith("text/")) parsed = body;
315
+ else parsed = _parseJSON(body, options.strict ?? false);
316
+ request[ParsedBodySymbol] = parsed;
317
+ return parsed;
318
+ }
319
+ function _parseJSON(body = "", strict) {
320
+ if (!body) return;
321
+ try {
322
+ return destr(body, { strict });
323
+ } catch {
324
+ throw createError({
325
+ statusCode: 400,
326
+ statusMessage: "Bad Request",
327
+ message: "Invalid JSON body"
328
+ });
329
+ }
330
+ }
331
+ function _parseURLEncodedBody(body) {
332
+ const form = new URLSearchParams(body);
333
+ const parsedForm = /* @__PURE__ */ Object.create(null);
334
+ for (const [key, value] of form.entries()) if (hasProp(parsedForm, key)) {
335
+ if (!Array.isArray(parsedForm[key])) parsedForm[key] = [parsedForm[key]];
336
+ parsedForm[key].push(value);
337
+ } else parsedForm[key] = value;
338
+ return parsedForm;
339
+ }
340
+ const DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
341
+ function sanitizeStatusMessage(statusMessage = "") {
342
+ return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
343
+ }
344
+ function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
345
+ if (!statusCode) return defaultStatusCode;
346
+ if (typeof statusCode === "string") statusCode = Number.parseInt(statusCode, 10);
347
+ if (statusCode < 100 || statusCode > 999) return defaultStatusCode;
348
+ return statusCode;
349
+ }
350
+ function setResponseStatus(event, code, text) {
351
+ if (code) event.node.res.statusCode = sanitizeStatusCode(code, event.node.res.statusCode);
352
+ if (text) event.node.res.statusMessage = sanitizeStatusMessage(text);
353
+ }
354
+ function defineEventHandler(handler) {
355
+ if (typeof handler === "function") {
356
+ handler.__is_handler__ = true;
357
+ return handler;
358
+ }
359
+ const _hooks = {
360
+ onRequest: _normalizeArray(handler.onRequest),
361
+ onBeforeResponse: _normalizeArray(handler.onBeforeResponse)
362
+ };
363
+ const _handler = (event) => {
364
+ return _callHandler(event, handler.handler, _hooks);
365
+ };
366
+ _handler.__is_handler__ = true;
367
+ _handler.__resolve__ = handler.handler.__resolve__;
368
+ _handler.__websocket__ = handler.websocket;
369
+ return _handler;
370
+ }
371
+ function _normalizeArray(input) {
372
+ return input ? Array.isArray(input) ? input : [input] : void 0;
373
+ }
374
+ async function _callHandler(event, handler, hooks) {
375
+ if (hooks.onRequest) for (const hook of hooks.onRequest) {
376
+ await hook(event);
377
+ if (event.handled) return;
378
+ }
379
+ const response = { body: await handler(event) };
380
+ if (hooks.onBeforeResponse) for (const hook of hooks.onBeforeResponse) await hook(event, response);
381
+ return response.body;
382
+ }
383
+ globalThis.Headers;
384
+ globalThis.Response;
385
+ //#endregion
386
+ //#region src/adapter/nuxt/handler.ts
69
387
  function createEventHandler(options) {
70
- return (0, import_h3.defineEventHandler)(async (event) => {
71
- const client = await options.getClient(event);
72
- if (!client) {
73
- (0, import_h3.setResponseStatus)(event, 500);
74
- return {
75
- message: "unable to get ZenStackClient from request context"
76
- };
77
- }
78
- const routerParam = (0, import_h3.getRouterParams)(event);
79
- const query = await (0, import_h3.getQuery)(event);
80
- let reqBody;
81
- if (event.method === "POST" || event.method === "PUT" || event.method === "PATCH") {
82
- reqBody = await (0, import_h3.readBody)(event);
83
- }
84
- try {
85
- const { status, body } = await options.apiHandler.handleRequest({
86
- method: event.method,
87
- path: routerParam["_"],
88
- query,
89
- requestBody: reqBody,
90
- client
91
- });
92
- (0, import_h3.setResponseStatus)(event, status);
93
- return body;
94
- } catch (err) {
95
- (0, import_h3.setResponseStatus)(event, 500);
96
- logInternalError(options.apiHandler.log, err);
97
- return {
98
- message: "An internal server error occurred"
99
- };
100
- }
101
- });
102
- }
103
- __name(createEventHandler, "createEventHandler");
104
- // Annotate the CommonJS export names for ESM import in node:
105
- 0 && (module.exports = {
106
- createEventHandler
107
- });
388
+ return defineEventHandler(async (event) => {
389
+ const client = await options.getClient(event);
390
+ if (!client) {
391
+ setResponseStatus(event, 500);
392
+ return { message: "unable to get ZenStackClient from request context" };
393
+ }
394
+ const routerParam = getRouterParams(event);
395
+ const query = await getQuery(event);
396
+ let reqBody;
397
+ if (event.method === "POST" || event.method === "PUT" || event.method === "PATCH") reqBody = await readBody(event);
398
+ try {
399
+ const { status, body } = await options.apiHandler.handleRequest({
400
+ method: event.method,
401
+ path: routerParam["_"],
402
+ query,
403
+ requestBody: reqBody,
404
+ client
405
+ });
406
+ setResponseStatus(event, status);
407
+ return body;
408
+ } catch (err) {
409
+ setResponseStatus(event, 500);
410
+ require_common.logInternalError(options.apiHandler.log, err);
411
+ return { message: "An internal server error occurred" };
412
+ }
413
+ });
414
+ }
415
+ //#endregion
416
+ exports.createEventHandler = createEventHandler;
417
+
108
418
  //# sourceMappingURL=nuxt.cjs.map