@wecode-team/cms-supabase-api 0.1.47 → 0.1.49

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/dist/index.esm.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
+ import { sendCode, verifyCode } from '@wecode-team/email-verify';
2
3
  import * as jwt from 'jsonwebtoken';
3
4
  import * as bcrypt from 'bcryptjs';
4
5
 
@@ -673,6 +674,10 @@ function getSupabaseSetupSQL() {
673
674
  return "-- Supabase Setup SQL for we0-cms-supabase-hono-api\n-- \u8BF7\u5728 Supabase SQL \u7F16\u8F91\u5668\u4E2D\u6267\u884C\u4EE5\u4E0B\u5B8C\u6574\u811A\u672C\n\n-- Function to execute SQL queries\nCREATE OR REPLACE FUNCTION execute_sql(sql_query text)\nRETURNS json\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nDECLARE\n result json;\n row_count integer;\nBEGIN\n EXECUTE sql_query;\n GET DIAGNOSTICS row_count = ROW_COUNT;\n RETURN json_build_object('success', true, 'rows_affected', row_count);\nEXCEPTION\n WHEN OTHERS THEN\n RETURN json_build_object('success', false, 'error', SQLERRM);\nEND;\n$$;\n\n-- Function to execute SQL with parameters (simplified version)\nCREATE OR REPLACE FUNCTION execute_sql_with_params(sql_query text, params json)\nRETURNS json\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nDECLARE\n result json;\n row_count integer;\nBEGIN\n -- Note: This is a simplified version for basic use cases\n -- In production, you might want more sophisticated parameter binding\n EXECUTE sql_query;\n GET DIAGNOSTICS row_count = ROW_COUNT;\n RETURN json_build_object('success', true, 'rows_affected', row_count);\nEXCEPTION\n WHEN OTHERS THEN\n RETURN json_build_object('success', false, 'error', SQLERRM);\nEND;\n$$;\n\n-- Function to check if table exists\nCREATE OR REPLACE FUNCTION check_table_exists(input_table_name text)\nRETURNS boolean\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nBEGIN\n RETURN EXISTS (\n SELECT 1 FROM information_schema.tables\n WHERE table_schema = 'public' \n AND table_name = input_table_name\n );\nEND;\n$$;\n\n-- Function to get table structure\nCREATE OR REPLACE FUNCTION get_table_structure(table_name text)\nRETURNS json\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nDECLARE\n result json;\nBEGIN\n SELECT json_agg(\n json_build_object(\n 'column_name', column_name,\n 'data_type', data_type,\n 'is_nullable', is_nullable,\n 'column_default', column_default,\n 'character_maximum_length', character_maximum_length\n )\n ) INTO result\n FROM information_schema.columns\n WHERE table_schema = 'public' AND table_name = $1\n ORDER BY ordinal_position;\n \n RETURN COALESCE(result, '[]'::json);\nEND;\n$$;\n\n-- Function to create CMS models table if not exists\nCREATE OR REPLACE FUNCTION create_cms_models_table_if_not_exists()\nRETURNS json\nLANGUAGE plpgsql\nSECURITY DEFINER\nAS $$\nBEGIN\n -- Create the CMS models table\n CREATE TABLE IF NOT EXISTS \"_cms_models\" (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL,\n table_name VARCHAR(100) NOT NULL UNIQUE,\n json_schema JSONB NOT NULL,\n created_at TIMESTAMPTZ DEFAULT NOW(),\n updated_at TIMESTAMPTZ DEFAULT NOW()\n );\n \n -- Create or replace the trigger function for updating timestamps\n CREATE OR REPLACE FUNCTION update_updated_at_column()\n RETURNS TRIGGER AS $trigger$\n BEGIN\n NEW.updated_at = NOW();\n RETURN NEW;\n END;\n $trigger$ language 'plpgsql';\n \n -- Drop existing trigger if it exists and create new one\n DROP TRIGGER IF EXISTS update_cms_models_updated_at ON \"_cms_models\";\n CREATE TRIGGER update_cms_models_updated_at\n BEFORE UPDATE ON \"_cms_models\"\n FOR EACH ROW\n EXECUTE FUNCTION update_updated_at_column();\n \n RETURN json_build_object('success', true, 'message', 'CMS models table created successfully');\nEXCEPTION\n WHEN OTHERS THEN\n RETURN json_build_object('success', false, 'error', SQLERRM);\nEND;\n$$;\n\n-- Initialize the CMS models table\nSELECT create_cms_models_table_if_not_exists();\n\n-- Grant necessary permissions (adjust as needed for your security requirements)\n-- Note: Be careful with these permissions in production\nGRANT USAGE ON SCHEMA public TO anon, authenticated;\nGRANT ALL ON ALL TABLES IN SCHEMA public TO anon, authenticated;\nGRANT ALL ON ALL SEQUENCES IN SCHEMA public TO anon, authenticated;\nGRANT ALL ON ALL FUNCTIONS IN SCHEMA public TO anon, authenticated;\n\n-- Create RLS policies for the CMS models table (optional, adjust as needed)\nALTER TABLE \"_cms_models\" ENABLE ROW LEVEL SECURITY;\n\n-- Allow all operations for all users (development environment)\nCREATE POLICY \"Allow all operations\" ON \"_cms_models\"\n FOR ALL USING (true);\n\nCOMMENT ON TABLE \"_cms_models\" IS 'CMS models configuration table for we0-cms-supabase-hono-api';\nCOMMENT ON FUNCTION execute_sql(text) IS 'Execute SQL queries for dynamic table management';\nCOMMENT ON FUNCTION check_table_exists(text) IS 'Check if a table exists in the public schema';\nCOMMENT ON FUNCTION get_table_structure(text) IS 'Get the structure of a table';";
674
675
  }
675
676
 
677
+ var feishuAlertConfig = {
678
+ crudErrorWebhookUrls: ["https://open.feishu.cn/open-apis/bot/v2/hook/784e9470-c1fd-4e38-97a2-b9a1856c00b1"]
679
+ };
680
+
676
681
  function _classCallCheck(a, n) {
677
682
  if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
678
683
  }
@@ -1007,8 +1012,8 @@ function _defineProperty(e, r, t) {
1007
1012
  }) : e[r] = t, e;
1008
1013
  }
1009
1014
 
1010
- function ownKeys$5(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
1011
- function _objectSpread$5(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$5(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
1015
+ function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
1016
+ function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
1012
1017
  function _createForOfIteratorHelper$2(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$3(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
1013
1018
  function _unsupportedIterableToArray$3(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$3(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$3(r, a) : void 0; } }
1014
1019
  function _arrayLikeToArray$3(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
@@ -1016,6 +1021,7 @@ function _arrayLikeToArray$3(r, a) { (null == a || a > r.length) && (a = r.lengt
1016
1021
  var fieldTypeMapping = {
1017
1022
  string: "text",
1018
1023
  text: "text",
1024
+ richText: "text",
1019
1025
  integer: "int4",
1020
1026
  "float": "float8",
1021
1027
  "boolean": "bool",
@@ -2063,7 +2069,7 @@ var DynamicTableService = /*#__PURE__*/function () {
2063
2069
  throw error;
2064
2070
  case 2:
2065
2071
  return _context14.abrupt("return", (data || []).map(function (item) {
2066
- return _objectSpread$5({
2072
+ return _objectSpread$3({
2067
2073
  id: item.id,
2068
2074
  label: item[displayField] || "ID: ".concat(item.id)
2069
2075
  }, item);
@@ -2176,8 +2182,8 @@ function getDynamicTableService() {
2176
2182
  return defaultService$1;
2177
2183
  }
2178
2184
 
2179
- function ownKeys$4(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2180
- function _objectSpread$4(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$4(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2185
+ function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2186
+ function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2181
2187
  var AuthService = /*#__PURE__*/function () {
2182
2188
  function AuthService() {
2183
2189
  _classCallCheck(this, AuthService);
@@ -2354,7 +2360,7 @@ var AuthService = /*#__PURE__*/function () {
2354
2360
  return _regeneratorRuntime.wrap(function (_context4) {
2355
2361
  while (1) switch (_context4.prev = _context4.next) {
2356
2362
  case 0:
2357
- finalUserData = _objectSpread$4({
2363
+ finalUserData = _objectSpread$2({
2358
2364
  tableName: this.defaultTableName
2359
2365
  }, userData);
2360
2366
  _context4.prev = 1;
@@ -2412,7 +2418,7 @@ var AuthService = /*#__PURE__*/function () {
2412
2418
  case 0:
2413
2419
  updateData = _args5.length > 1 && _args5[1] !== undefined ? _args5[1] : {};
2414
2420
  // 设置默认值
2415
- finalUpdateData = _objectSpread$4({
2421
+ finalUpdateData = _objectSpread$2({
2416
2422
  tableName: this.defaultTableName
2417
2423
  }, updateData);
2418
2424
  _context5.prev = 1;
@@ -2820,8 +2826,8 @@ function _toConsumableArray(r) {
2820
2826
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray$2(r) || _nonIterableSpread();
2821
2827
  }
2822
2828
 
2823
- function ownKeys$3(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2824
- function _objectSpread$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2829
+ function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2830
+ function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2825
2831
  function _callSuper$1(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct$1() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
2826
2832
  function _isNativeReflectConstruct$1() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct$1 = function _isNativeReflectConstruct() { return !!t; })(); }
2827
2833
  // src/error.ts
@@ -3349,7 +3355,7 @@ var DEFAULT_LIMITS = {
3349
3355
  other: 10 * 1024 * 1024
3350
3356
  };
3351
3357
  function getSizeLimit(fileName, limits) {
3352
- var merged = _objectSpread$3(_objectSpread$3({}, DEFAULT_LIMITS), limits);
3358
+ var merged = _objectSpread$1(_objectSpread$1({}, DEFAULT_LIMITS), limits);
3353
3359
  if (isImage(fileName)) return merged.image;
3354
3360
  if (isVideo(fileName)) return merged.video;
3355
3361
  return merged.other;
@@ -3377,7 +3383,7 @@ function _compressImageBlob() {
3377
3383
  return _regeneratorRuntime.wrap(function (_context10) {
3378
3384
  while (1) switch (_context10.prev = _context10.next) {
3379
3385
  case 0:
3380
- opts = _objectSpread$3(_objectSpread$3({}, DEFAULT_COMPRESS), options);
3386
+ opts = _objectSpread$1(_objectSpread$1({}, DEFAULT_COMPRESS), options);
3381
3387
  if (!(typeof createImageBitmap === "undefined" || typeof OffscreenCanvas === "undefined")) {
3382
3388
  _context10.next = 1;
3383
3389
  break;
@@ -3443,7 +3449,7 @@ function _processFile() {
3443
3449
  return _regeneratorRuntime.wrap(function (_context11) {
3444
3450
  while (1) switch (_context11.prev = _context11.next) {
3445
3451
  case 0:
3446
- opts = _objectSpread$3(_objectSpread$3({}, DEFAULT_COMPRESS), compress);
3452
+ opts = _objectSpread$1(_objectSpread$1({}, DEFAULT_COMPRESS), compress);
3447
3453
  if (!(opts.enabled && isImage(fileName))) {
3448
3454
  _context11.next = 2;
3449
3455
  break;
@@ -3507,7 +3513,7 @@ function createOssClient() {
3507
3513
  var allowedExtensions = options.allowedExtensions;
3508
3514
  function mergeRetry(override) {
3509
3515
  if (!defaultRetry && !override) return void 0;
3510
- return _objectSpread$3(_objectSpread$3({}, defaultRetry), override);
3516
+ return _objectSpread$1(_objectSpread$1({}, defaultRetry), override);
3511
3517
  }
3512
3518
  function resolveCompress(override) {
3513
3519
  if (override === false) return {
@@ -3517,7 +3523,7 @@ function createOssClient() {
3517
3523
  enabled: false
3518
3524
  };
3519
3525
  var base = _typeof$1(defaultCompress) === "object" ? defaultCompress : {};
3520
- return override ? _objectSpread$3(_objectSpread$3({}, base), override) : Object.keys(base).length ? base : void 0;
3526
+ return override ? _objectSpread$1(_objectSpread$1({}, base), override) : Object.keys(base).length ? base : void 0;
3521
3527
  }
3522
3528
  function uploadOne(_x25, _x26, _x27, _x28) {
3523
3529
  return _uploadOne.apply(this, arguments);
@@ -3603,7 +3609,7 @@ function createOssClient() {
3603
3609
  var i = index++;
3604
3610
  var item = files[i];
3605
3611
  running++;
3606
- var fileOpts = _objectSpread$3({
3612
+ var fileOpts = _objectSpread$1({
3607
3613
  retry: opts === null || opts === void 0 ? void 0 : opts.retry,
3608
3614
  compress: opts === null || opts === void 0 ? void 0 : opts.compress
3609
3615
  }, item.options);
@@ -4019,12 +4025,12 @@ function _getSessionAdminRow() {
4019
4025
  }));
4020
4026
  return _getSessionAdminRow.apply(this, arguments);
4021
4027
  }
4022
- function isUserSessionAdmin(_x4, _x5, _x6) {
4023
- return _isUserSessionAdmin.apply(this, arguments);
4028
+ function getSessionAdminRowByEmail(_x4, _x5, _x6) {
4029
+ return _getSessionAdminRowByEmail.apply(this, arguments);
4024
4030
  }
4025
- function _isUserSessionAdmin() {
4026
- _isUserSessionAdmin = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(supabase, sessionId, userId) {
4027
- var row;
4031
+ function _getSessionAdminRowByEmail() {
4032
+ _getSessionAdminRowByEmail = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(supabase, sessionId, email) {
4033
+ var row, normalizedEmail, rowEmail;
4028
4034
  return _regeneratorRuntime.wrap(function (_context3) {
4029
4035
  while (1) switch (_context3.prev = _context3.next) {
4030
4036
  case 0:
@@ -4036,18 +4042,189 @@ function _isUserSessionAdmin() {
4036
4042
  _context3.next = 2;
4037
4043
  break;
4038
4044
  }
4039
- return _context3.abrupt("return", false);
4045
+ return _context3.abrupt("return", null);
4040
4046
  case 2:
4041
- return _context3.abrupt("return", row.user_id === userId);
4047
+ normalizedEmail = (email || "").trim().toLowerCase();
4048
+ rowEmail = (row.email || "").trim().toLowerCase();
4049
+ if (!(!normalizedEmail || rowEmail !== normalizedEmail)) {
4050
+ _context3.next = 3;
4051
+ break;
4052
+ }
4053
+ return _context3.abrupt("return", null);
4042
4054
  case 3:
4055
+ return _context3.abrupt("return", row);
4056
+ case 4:
4043
4057
  case "end":
4044
4058
  return _context3.stop();
4045
4059
  }
4046
4060
  }, _callee3);
4047
4061
  }));
4062
+ return _getSessionAdminRowByEmail.apply(this, arguments);
4063
+ }
4064
+ function isUserSessionAdmin(_x7, _x8, _x9) {
4065
+ return _isUserSessionAdmin.apply(this, arguments);
4066
+ }
4067
+ function _isUserSessionAdmin() {
4068
+ _isUserSessionAdmin = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(supabase, sessionId, userId) {
4069
+ var row;
4070
+ return _regeneratorRuntime.wrap(function (_context4) {
4071
+ while (1) switch (_context4.prev = _context4.next) {
4072
+ case 0:
4073
+ _context4.next = 1;
4074
+ return getSessionAdminRow(supabase, sessionId);
4075
+ case 1:
4076
+ row = _context4.sent;
4077
+ if (row) {
4078
+ _context4.next = 2;
4079
+ break;
4080
+ }
4081
+ return _context4.abrupt("return", false);
4082
+ case 2:
4083
+ return _context4.abrupt("return", row.user_id === userId);
4084
+ case 3:
4085
+ case "end":
4086
+ return _context4.stop();
4087
+ }
4088
+ }, _callee4);
4089
+ }));
4048
4090
  return _isUserSessionAdmin.apply(this, arguments);
4049
4091
  }
4050
4092
 
4093
+ var ACTION_LABELS = {
4094
+ create: "创建",
4095
+ read: "查询",
4096
+ update: "更新",
4097
+ "delete": "删除"
4098
+ };
4099
+ var TARGET_LABELS = {
4100
+ data: "数据",
4101
+ model: "模型"
4102
+ };
4103
+ function getWebhookUrls() {
4104
+ return feishuAlertConfig.crudErrorWebhookUrls.map(function (item) {
4105
+ return item.trim();
4106
+ }).filter(Boolean);
4107
+ }
4108
+ function getErrorMessage(error) {
4109
+ if (error instanceof Error) {
4110
+ return error.message;
4111
+ }
4112
+ return String(error);
4113
+ }
4114
+ function getErrorStack(error) {
4115
+ if (error instanceof Error) {
4116
+ return error.stack || "";
4117
+ }
4118
+ return "";
4119
+ }
4120
+ function buildRequestSummary(c) {
4121
+ var url = new URL(c.req.url);
4122
+ return ["method: ".concat(c.req.method), "path: ".concat(url.pathname), "query: ".concat(url.search || "-"), "userAgent: ".concat(c.req.header("user-agent") || "-")].join("\n");
4123
+ }
4124
+ function getSessionId(c) {
4125
+ return c.req.header("X-Session-Id") || c.req.header("x-session-id") || "-";
4126
+ }
4127
+ function buildAlertText(c, options) {
4128
+ var _options$modelId, _options$recordId;
4129
+ var actionLabel = ACTION_LABELS[options.action];
4130
+ var targetLabel = TARGET_LABELS[options.target];
4131
+ var lines = ["\u5305\u540D: @wecode-team/cms-supabase-api", "\u5BBF\u4E3B\u9879\u76EE\u6807\u8BC6(sessionId): ".concat(getSessionId(c)), "\u64CD\u4F5C\u5BF9\u8C61: ".concat(targetLabel), "\u64CD\u4F5C\u7C7B\u578B: ".concat(actionLabel), "\u6570\u636E\u8868\u540D: ".concat(options.tableName || "-"), "\u6A21\u578B ID: ".concat((_options$modelId = options.modelId) !== null && _options$modelId !== void 0 ? _options$modelId : "-"), "\u8BB0\u5F55 ID: ".concat((_options$recordId = options.recordId) !== null && _options$recordId !== void 0 ? _options$recordId : "-"), "\u65F6\u95F4: ".concat(new Date().toISOString()), "\u9519\u8BEF\u4FE1\u606F: ".concat(getErrorMessage(options.error)), "\u8BF7\u6C42\u4FE1\u606F:\n".concat(buildRequestSummary(c))];
4132
+ var stack = getErrorStack(options.error);
4133
+ if (stack) {
4134
+ lines.push("\u9519\u8BEF\u5806\u6808:\n".concat(stack));
4135
+ }
4136
+ return lines.join("\n\n");
4137
+ }
4138
+ function postWebhook(_x, _x2) {
4139
+ return _postWebhook.apply(this, arguments);
4140
+ }
4141
+ function _postWebhook() {
4142
+ _postWebhook = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(webhook, body) {
4143
+ var response;
4144
+ return _regeneratorRuntime.wrap(function (_context) {
4145
+ while (1) switch (_context.prev = _context.next) {
4146
+ case 0:
4147
+ _context.next = 1;
4148
+ return fetch(webhook, {
4149
+ method: "POST",
4150
+ headers: {
4151
+ "Content-Type": "application/json"
4152
+ },
4153
+ body: JSON.stringify(body)
4154
+ });
4155
+ case 1:
4156
+ response = _context.sent;
4157
+ if (response.ok) {
4158
+ _context.next = 2;
4159
+ break;
4160
+ }
4161
+ throw new Error("\u98DE\u4E66\u62A5\u8B66\u53D1\u9001\u5931\u8D25: ".concat(response.status, " ").concat(response.statusText));
4162
+ case 2:
4163
+ case "end":
4164
+ return _context.stop();
4165
+ }
4166
+ }, _callee);
4167
+ }));
4168
+ return _postWebhook.apply(this, arguments);
4169
+ }
4170
+ function notifyCmsCrudErrorToFeishu(_x3, _x4) {
4171
+ return _notifyCmsCrudErrorToFeishu.apply(this, arguments);
4172
+ }
4173
+ function _notifyCmsCrudErrorToFeishu() {
4174
+ _notifyCmsCrudErrorToFeishu = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(c, options) {
4175
+ var webhookUrls, body, results, failed;
4176
+ return _regeneratorRuntime.wrap(function (_context2) {
4177
+ while (1) switch (_context2.prev = _context2.next) {
4178
+ case 0:
4179
+ webhookUrls = getWebhookUrls();
4180
+ if (!(webhookUrls.length === 0)) {
4181
+ _context2.next = 1;
4182
+ break;
4183
+ }
4184
+ return _context2.abrupt("return");
4185
+ case 1:
4186
+ body = {
4187
+ msg_type: "post",
4188
+ content: {
4189
+ post: {
4190
+ zh_cn: {
4191
+ title: "[cms-supabase-api] ".concat(TARGET_LABELS[options.target]).concat(ACTION_LABELS[options.action], "\u5F02\u5E38"),
4192
+ content: [[{
4193
+ tag: "text",
4194
+ text: buildAlertText(c, options)
4195
+ }]]
4196
+ }
4197
+ }
4198
+ }
4199
+ };
4200
+ _context2.next = 2;
4201
+ return Promise.allSettled(webhookUrls.map(function (url) {
4202
+ return postWebhook(url, body);
4203
+ }));
4204
+ case 2:
4205
+ results = _context2.sent;
4206
+ failed = results.find(function (result) {
4207
+ return result.status === "rejected";
4208
+ });
4209
+ if (!((failed === null || failed === void 0 ? void 0 : failed.status) === "rejected")) {
4210
+ _context2.next = 3;
4211
+ break;
4212
+ }
4213
+ throw failed.reason;
4214
+ case 3:
4215
+ case "end":
4216
+ return _context2.stop();
4217
+ }
4218
+ }, _callee2);
4219
+ }));
4220
+ return _notifyCmsCrudErrorToFeishu.apply(this, arguments);
4221
+ }
4222
+ function reportCmsCrudErrorToFeishu(c, options) {
4223
+ void notifyCmsCrudErrorToFeishu(c, options)["catch"](function (feishuError) {
4224
+ console.error("飞书报警发送失败:", feishuError);
4225
+ });
4226
+ }
4227
+
4051
4228
  function _createForOfIteratorHelper$1(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray$1(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
4052
4229
  function _unsupportedIterableToArray$1(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray$1(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray$1(r, a) : void 0; } }
4053
4230
  function _arrayLikeToArray$1(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
@@ -4349,6 +4526,11 @@ function _createModel() {
4349
4526
  _context3.prev = 15;
4350
4527
  _t3 = _context3["catch"](0);
4351
4528
  console.error("创建模型失败:", _t3);
4529
+ reportCmsCrudErrorToFeishu(c, {
4530
+ action: "create",
4531
+ target: "model",
4532
+ error: _t3
4533
+ });
4352
4534
  _response9 = {
4353
4535
  success: false,
4354
4536
  message: "创建模型失败",
@@ -4440,6 +4622,11 @@ function _updateModel() {
4440
4622
  _context4.prev = 8;
4441
4623
  _t4 = _context4["catch"](0);
4442
4624
  console.error("更新模型失败:", _t4);
4625
+ reportCmsCrudErrorToFeishu(c, {
4626
+ action: "update",
4627
+ target: "model",
4628
+ error: _t4
4629
+ });
4443
4630
  _response11 = {
4444
4631
  success: false,
4445
4632
  message: "更新模型失败",
@@ -4521,6 +4708,11 @@ function _deleteModel() {
4521
4708
  _context5.prev = 8;
4522
4709
  _t5 = _context5["catch"](0);
4523
4710
  console.error("删除模型失败:", _t5);
4711
+ reportCmsCrudErrorToFeishu(c, {
4712
+ action: "delete",
4713
+ target: "model",
4714
+ error: _t5
4715
+ });
4524
4716
  _response15 = {
4525
4717
  success: false,
4526
4718
  message: "删除模型失败",
@@ -4582,8 +4774,8 @@ var _excluded = ["id", "created_at", "updated_at"],
4582
4774
  function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n2 = 0, F = function F() {}; return { s: F, n: function n() { return _n2 >= r.length ? { done: !0 } : { done: !1, value: r[_n2++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
4583
4775
  function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4584
4776
  function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
4585
- function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4586
- function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4777
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4778
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4587
4779
  function normalizeJsonLikeFields(schemaFields, payload) {
4588
4780
  if (!schemaFields || schemaFields.length === 0) return payload;
4589
4781
  var jsonLikeFieldNames = new Set(schemaFields.filter(function (f) {
@@ -4592,7 +4784,7 @@ function normalizeJsonLikeFields(schemaFields, payload) {
4592
4784
  return f.name;
4593
4785
  }));
4594
4786
  if (jsonLikeFieldNames.size === 0) return payload;
4595
- var normalized = _objectSpread$2({}, payload);
4787
+ var normalized = _objectSpread({}, payload);
4596
4788
  for (var _i = 0, _Object$entries = Object.entries(payload); _i < _Object$entries.length; _i++) {
4597
4789
  var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
4598
4790
  key = _Object$entries$_i[0],
@@ -4887,7 +5079,7 @@ function _getTableData() {
4887
5079
  }
4888
5080
  // 找到所有文本类型的字段
4889
5081
  searchableFields = schemaFields.filter(function (field) {
4890
- return field.type === 'string' || field.type === 'text';
5082
+ return field.type === 'string' || field.type === 'text' || field.type === 'richText';
4891
5083
  }).map(function (field) {
4892
5084
  return field.name;
4893
5085
  });
@@ -4932,6 +5124,12 @@ function _getTableData() {
4932
5124
  _context.prev = 16;
4933
5125
  _t2 = _context["catch"](0);
4934
5126
  console.error("获取表数据失败:", _t2);
5127
+ reportCmsCrudErrorToFeishu(c, {
5128
+ action: "read",
5129
+ target: "data",
5130
+ tableName: tableName,
5131
+ error: _t2
5132
+ });
4935
5133
  _response3 = {
4936
5134
  success: false,
4937
5135
  message: "获取表数据失败",
@@ -5018,6 +5216,12 @@ function _createTableData() {
5018
5216
  _context2.prev = 8;
5019
5217
  _t4 = _context2["catch"](0);
5020
5218
  console.error("创建数据失败:", _t4);
5219
+ reportCmsCrudErrorToFeishu(c, {
5220
+ action: "create",
5221
+ target: "data",
5222
+ tableName: tableName,
5223
+ error: _t4
5224
+ });
5021
5225
  _response5 = {
5022
5226
  success: false,
5023
5227
  message: "创建数据失败",
@@ -5149,6 +5353,12 @@ function _updateTableData() {
5149
5353
  _context3.prev = 13;
5150
5354
  _t6 = _context3["catch"](0);
5151
5355
  console.error("更新数据失败:", _t6);
5356
+ reportCmsCrudErrorToFeishu(c, {
5357
+ action: "update",
5358
+ target: "data",
5359
+ tableName: tableName,
5360
+ error: _t6
5361
+ });
5152
5362
  _response1 = {
5153
5363
  success: false,
5154
5364
  message: "更新数据失败",
@@ -5232,6 +5442,12 @@ function _deleteTableData() {
5232
5442
  _context4.prev = 7;
5233
5443
  _t7 = _context4["catch"](0);
5234
5444
  console.error("删除数据失败:", _t7);
5445
+ reportCmsCrudErrorToFeishu(c, {
5446
+ action: "delete",
5447
+ target: "data",
5448
+ tableName: tableName,
5449
+ error: _t7
5450
+ });
5235
5451
  _response13 = {
5236
5452
  success: false,
5237
5453
  message: "删除数据失败",
@@ -5688,8 +5904,6 @@ var AuthUtils = /*#__PURE__*/function () {
5688
5904
  }]);
5689
5905
  }();
5690
5906
 
5691
- function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
5692
- function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
5693
5907
  function getRoleFromSupabaseUser$2(user) {
5694
5908
  var _user$app_metadata, _user$user_metadata;
5695
5909
  var appRole = user === null || user === void 0 || (_user$app_metadata = user.app_metadata) === null || _user$app_metadata === void 0 ? void 0 : _user$app_metadata.role;
@@ -5699,10 +5913,46 @@ function getRoleFromSupabaseUser$2(user) {
5699
5913
  function getAdminRegistrySetupSQL() {
5700
5914
  return "-- Create admin registry table (run in Supabase SQL editor)\nCREATE TABLE IF NOT EXISTS \"_cms_admin_registry\" (\n session_id TEXT PRIMARY KEY,\n user_id UUID NOT NULL,\n email TEXT,\n created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\nALTER TABLE \"_cms_admin_registry\" ENABLE ROW LEVEL SECURITY;\nDROP POLICY IF EXISTS \"Allow all operations\" ON \"_cms_admin_registry\";\nCREATE POLICY \"Allow all operations\" ON \"_cms_admin_registry\"\n FOR ALL USING (true) WITH CHECK (true);";
5701
5915
  }
5702
- function isSupabaseUserAlreadyExistsError(error) {
5703
- var msg = String((error === null || error === void 0 ? void 0 : error.message) || "").toLowerCase();
5704
- // 兼容不同 Supabase 文案
5705
- return msg.includes("already registered") || msg.includes("already exists") || msg.includes("user already") || msg.includes("email address") && msg.includes("already");
5916
+ function isEmailLike(value) {
5917
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
5918
+ }
5919
+ var PASSWORD_RESET_MESSAGES = {
5920
+ "zh-CN": {
5921
+ emailRequired: "邮箱不能为空",
5922
+ emailInvalid: "请输入邮箱格式的用户名",
5923
+ codeRequired: "验证码不能为空",
5924
+ passwordTooShort: "新密码至少需要 6 位",
5925
+ codeSent: "如果账号存在,验证码已发送",
5926
+ codeSendFailed: "发送重置密码验证码失败",
5927
+ codeSendRetry: "验证码发送失败,请稍后重试",
5928
+ userNotFound: "验证码无效或账号不存在",
5929
+ codeInvalidOrExpired: "验证码无效或已过期",
5930
+ resetSuccess: "密码已重置,请重新登录",
5931
+ resetFailed: "重置密码失败"
5932
+ },
5933
+ "en-US": {
5934
+ emailRequired: "Email is required",
5935
+ emailInvalid: "Please enter a valid email address",
5936
+ codeRequired: "Verification code is required",
5937
+ passwordTooShort: "New password must be at least 6 characters",
5938
+ codeSent: "If the account exists, a verification code has been sent",
5939
+ codeSendFailed: "Failed to send password reset code",
5940
+ codeSendRetry: "Failed to send verification code. Please try again later",
5941
+ userNotFound: "Invalid code or account not found",
5942
+ codeInvalidOrExpired: "Invalid or expired verification code",
5943
+ resetSuccess: "Password has been reset. Please log in again",
5944
+ resetFailed: "Failed to reset password"
5945
+ }
5946
+ };
5947
+ function getLocaleFromRequest(c) {
5948
+ var raw = (c.req.header("accept-language") || c.req.header("Accept-Language") || "").toLowerCase();
5949
+ if (raw.includes("en")) {
5950
+ return "en-US";
5951
+ }
5952
+ return "zh-CN";
5953
+ }
5954
+ function getPasswordResetMessages(c) {
5955
+ return PASSWORD_RESET_MESSAGES[getLocaleFromRequest(c)];
5706
5956
  }
5707
5957
  function toSupabaseEmail(account, sessionId) {
5708
5958
  // 简单规则:`{session_id}_{邮箱前缀}@{邮箱后缀}`
@@ -5714,168 +5964,235 @@ function toSupabaseEmail(account, sessionId) {
5714
5964
  var sid = normalizeSessionId(sessionId);
5715
5965
  return "".concat(sid, "_").concat(localPart, "@").concat(domain);
5716
5966
  }
5717
- function buildAdminMetadata(existingMetadata, sessionId, account) {
5718
- return _objectSpread$1(_objectSpread$1({}, existingMetadata || {}), {}, {
5719
- role: "admin",
5720
- session_id: normalizeSessionId(sessionId),
5721
- original_username: account
5722
- });
5967
+ function isEmailVerifyError(error) {
5968
+ var name = String((error === null || error === void 0 ? void 0 : error.name) || "");
5969
+ return name === "EmailVerifyError";
5723
5970
  }
5724
- function findAuthUserByEmail(_x, _x2) {
5725
- return _findAuthUserByEmail.apply(this, arguments);
5971
+ // POST - 发送重置密码验证码
5972
+ function forgotPassword(_x, _x2) {
5973
+ return _forgotPassword.apply(this, arguments);
5726
5974
  }
5727
- function _findAuthUserByEmail() {
5728
- _findAuthUserByEmail = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(supabase, email) {
5729
- var normalizedEmail, page, _yield$supabase$auth$2, data, error, users, matchedUser;
5975
+ // POST - 通过邮箱验证码重置密码
5976
+ function _forgotPassword() {
5977
+ _forgotPassword = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(c, tableName) {
5978
+ var _body$username, i18n, body, account, supabase, sessionId, adminRow, _i18n, _t3;
5730
5979
  return _regeneratorRuntime.wrap(function (_context2) {
5731
5980
  while (1) switch (_context2.prev = _context2.next) {
5732
5981
  case 0:
5733
- normalizedEmail = email.trim().toLowerCase();
5734
- page = 1;
5982
+ _context2.prev = 0;
5983
+ i18n = getPasswordResetMessages(c);
5984
+ _context2.next = 1;
5985
+ return c.req.json();
5735
5986
  case 1:
5736
- if (!(page <= 10)) {
5737
- _context2.next = 6;
5987
+ body = _context2.sent;
5988
+ account = (_body$username = body.username) === null || _body$username === void 0 ? void 0 : _body$username.trim();
5989
+ if (account) {
5990
+ _context2.next = 2;
5738
5991
  break;
5739
5992
  }
5740
- _context2.next = 2;
5741
- return supabase.auth.admin.listUsers({
5742
- page: page,
5743
- perPage: 200
5744
- });
5993
+ return _context2.abrupt("return", c.json({
5994
+ success: false,
5995
+ message: i18n.emailRequired
5996
+ }, 200));
5745
5997
  case 2:
5746
- _yield$supabase$auth$2 = _context2.sent;
5747
- data = _yield$supabase$auth$2.data;
5748
- error = _yield$supabase$auth$2.error;
5749
- if (!error) {
5998
+ if (isEmailLike(account)) {
5750
5999
  _context2.next = 3;
5751
6000
  break;
5752
6001
  }
5753
- throw error;
6002
+ return _context2.abrupt("return", c.json({
6003
+ success: false,
6004
+ message: i18n.emailInvalid
6005
+ }, 200));
5754
6006
  case 3:
5755
- users = (data === null || data === void 0 ? void 0 : data.users) || [];
5756
- matchedUser = users.find(function (user) {
5757
- var _user$email;
5758
- return ((_user$email = user.email) === null || _user$email === void 0 ? void 0 : _user$email.trim().toLowerCase()) === normalizedEmail;
5759
- });
5760
- if (!matchedUser) {
5761
- _context2.next = 4;
5762
- break;
5763
- }
5764
- return _context2.abrupt("return", matchedUser);
6007
+ supabase = getSupabase();
6008
+ sessionId = extractSessionIdFromAuthTableName(tableName);
6009
+ _context2.next = 4;
6010
+ return getSessionAdminRowByEmail(supabase, sessionId, account);
5765
6011
  case 4:
5766
- if (!(users.length < 200)) {
6012
+ adminRow = _context2.sent;
6013
+ if (adminRow !== null && adminRow !== void 0 && adminRow.user_id) {
5767
6014
  _context2.next = 5;
5768
6015
  break;
5769
6016
  }
5770
- return _context2.abrupt("return", null);
6017
+ return _context2.abrupt("return", c.json({
6018
+ success: true,
6019
+ message: i18n.codeSent
6020
+ }, 200));
5771
6021
  case 5:
5772
- page += 1;
5773
- _context2.next = 1;
5774
- break;
6022
+ _context2.next = 6;
6023
+ return sendCode(account);
5775
6024
  case 6:
5776
- return _context2.abrupt("return", null);
6025
+ return _context2.abrupt("return", c.json({
6026
+ success: true,
6027
+ message: i18n.codeSent
6028
+ }, 200));
5777
6029
  case 7:
6030
+ _context2.prev = 7;
6031
+ _t3 = _context2["catch"](0);
6032
+ console.error("发送重置密码验证码失败:", _t3);
6033
+ _i18n = getPasswordResetMessages(c);
6034
+ return _context2.abrupt("return", c.json({
6035
+ success: false,
6036
+ message: isEmailVerifyError(_t3) ? _i18n.codeSendRetry : _i18n.codeSendFailed,
6037
+ error: _t3.message
6038
+ }, 500));
6039
+ case 8:
5778
6040
  case "end":
5779
6041
  return _context2.stop();
5780
6042
  }
5781
- }, _callee2);
6043
+ }, _callee2, null, [[0, 7]]);
5782
6044
  }));
5783
- return _findAuthUserByEmail.apply(this, arguments);
6045
+ return _forgotPassword.apply(this, arguments);
5784
6046
  }
5785
- function insertAdminRegistryRow(_x3, _x4, _x5, _x6) {
5786
- return _insertAdminRegistryRow.apply(this, arguments);
6047
+ function resetPassword(_x3, _x4) {
6048
+ return _resetPassword.apply(this, arguments);
5787
6049
  }
5788
- function _insertAdminRegistryRow() {
5789
- _insertAdminRegistryRow = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(supabase, sessionId, userId, account) {
6050
+ function _resetPassword() {
6051
+ _resetPassword = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(c, tableName) {
6052
+ var _body$username2, _body$code, i18n, body, account, code, password, supabase, sessionId, adminRow, verifyResult, _yield$supabase$auth$2, updateError, _i18n2, _t4;
5790
6053
  return _regeneratorRuntime.wrap(function (_context3) {
5791
6054
  while (1) switch (_context3.prev = _context3.next) {
5792
6055
  case 0:
6056
+ _context3.prev = 0;
6057
+ i18n = getPasswordResetMessages(c);
5793
6058
  _context3.next = 1;
5794
- return supabase.from("_cms_admin_registry").insert({
5795
- session_id: normalizeSessionId(sessionId),
5796
- user_id: userId,
5797
- email: account
5798
- });
5799
- case 1:
5800
- return _context3.abrupt("return", _context3.sent);
5801
- case 2:
5802
- case "end":
5803
- return _context3.stop();
5804
- }
5805
- }, _callee3);
5806
- }));
5807
- return _insertAdminRegistryRow.apply(this, arguments);
5808
- }
5809
- function promoteExistingUserToSessionAdmin(_x7, _x8, _x9, _x0) {
5810
- return _promoteExistingUserToSessionAdmin.apply(this, arguments);
5811
- }
5812
- function _promoteExistingUserToSessionAdmin() {
5813
- _promoteExistingUserToSessionAdmin = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(supabase, email, sessionId, account) {
5814
- var existingUser, _yield$supabase$auth$3, updatedData, updateError, insertRes;
5815
- return _regeneratorRuntime.wrap(function (_context4) {
5816
- while (1) switch (_context4.prev = _context4.next) {
5817
- case 0:
5818
- _context4.next = 1;
5819
- return findAuthUserByEmail(supabase, email);
6059
+ return c.req.json();
5820
6060
  case 1:
5821
- existingUser = _context4.sent;
5822
- if (existingUser) {
5823
- _context4.next = 2;
6061
+ body = _context3.sent;
6062
+ account = (_body$username2 = body.username) === null || _body$username2 === void 0 ? void 0 : _body$username2.trim();
6063
+ code = (_body$code = body.code) === null || _body$code === void 0 ? void 0 : _body$code.trim();
6064
+ password = body.password;
6065
+ if (account) {
6066
+ _context3.next = 2;
5824
6067
  break;
5825
6068
  }
5826
- return _context4.abrupt("return", {
6069
+ return _context3.abrupt("return", c.json({
5827
6070
  success: false,
5828
- message: "用户名已存在,但未能找到对应用户"
5829
- });
6071
+ message: i18n.emailRequired
6072
+ }, 200));
5830
6073
  case 2:
5831
- _context4.next = 3;
5832
- return supabase.auth.admin.updateUserById(existingUser.id, {
5833
- app_metadata: buildAdminMetadata(existingUser.app_metadata, sessionId, account),
5834
- user_metadata: buildAdminMetadata(existingUser.user_metadata, sessionId, account)
5835
- });
6074
+ if (isEmailLike(account)) {
6075
+ _context3.next = 3;
6076
+ break;
6077
+ }
6078
+ return _context3.abrupt("return", c.json({
6079
+ success: false,
6080
+ message: i18n.emailInvalid
6081
+ }, 200));
5836
6082
  case 3:
5837
- _yield$supabase$auth$3 = _context4.sent;
5838
- updatedData = _yield$supabase$auth$3.data;
5839
- updateError = _yield$supabase$auth$3.error;
5840
- if (!(updateError || !(updatedData !== null && updatedData !== void 0 && updatedData.user))) {
5841
- _context4.next = 4;
6083
+ if (code) {
6084
+ _context3.next = 4;
5842
6085
  break;
5843
6086
  }
5844
- return _context4.abrupt("return", {
6087
+ return _context3.abrupt("return", c.json({
5845
6088
  success: false,
5846
- message: (updateError === null || updateError === void 0 ? void 0 : updateError.message) || "管理员账号升级失败"
5847
- });
6089
+ message: i18n.codeRequired
6090
+ }, 200));
5848
6091
  case 4:
5849
- _context4.next = 5;
5850
- return insertAdminRegistryRow(supabase, sessionId, updatedData.user.id, account);
6092
+ if (!(!password || password.length < 6)) {
6093
+ _context3.next = 5;
6094
+ break;
6095
+ }
6096
+ return _context3.abrupt("return", c.json({
6097
+ success: false,
6098
+ message: i18n.passwordTooShort
6099
+ }, 200));
5851
6100
  case 5:
5852
- insertRes = _context4.sent;
5853
- if (!insertRes.error) {
5854
- _context4.next = 6;
6101
+ supabase = getSupabase();
6102
+ sessionId = extractSessionIdFromAuthTableName(tableName);
6103
+ _context3.next = 6;
6104
+ return getSessionAdminRowByEmail(supabase, sessionId, account);
6105
+ case 6:
6106
+ adminRow = _context3.sent;
6107
+ if (adminRow !== null && adminRow !== void 0 && adminRow.user_id) {
6108
+ _context3.next = 7;
5855
6109
  break;
5856
6110
  }
5857
- return _context4.abrupt("return", {
6111
+ return _context3.abrupt("return", c.json({
5858
6112
  success: false,
5859
- message: "管理员已被创建,请使用已有账号登录"
6113
+ message: i18n.userNotFound
6114
+ }, 200));
6115
+ case 7:
6116
+ _context3.next = 8;
6117
+ return verifyCode(account, code);
6118
+ case 8:
6119
+ verifyResult = _context3.sent;
6120
+ if (verifyResult !== null && verifyResult !== void 0 && verifyResult.verified) {
6121
+ _context3.next = 9;
6122
+ break;
6123
+ }
6124
+ return _context3.abrupt("return", c.json({
6125
+ success: false,
6126
+ message: i18n.codeInvalidOrExpired
6127
+ }, 200));
6128
+ case 9:
6129
+ _context3.next = 10;
6130
+ return supabase.auth.admin.updateUserById(adminRow.user_id, {
6131
+ password: password
5860
6132
  });
5861
- case 6:
5862
- return _context4.abrupt("return", {
6133
+ case 10:
6134
+ _yield$supabase$auth$2 = _context3.sent;
6135
+ updateError = _yield$supabase$auth$2.error;
6136
+ if (!updateError) {
6137
+ _context3.next = 11;
6138
+ break;
6139
+ }
6140
+ return _context3.abrupt("return", c.json({
6141
+ success: false,
6142
+ message: updateError.message || i18n.resetFailed
6143
+ }, 200));
6144
+ case 11:
6145
+ return _context3.abrupt("return", c.json({
5863
6146
  success: true,
5864
- user: updatedData.user
6147
+ message: i18n.resetSuccess
6148
+ }, 200));
6149
+ case 12:
6150
+ _context3.prev = 12;
6151
+ _t4 = _context3["catch"](0);
6152
+ console.error("重置密码失败:", _t4);
6153
+ _i18n2 = getPasswordResetMessages(c);
6154
+ return _context3.abrupt("return", c.json({
6155
+ success: false,
6156
+ message: _i18n2.resetFailed,
6157
+ error: _t4.message
6158
+ }, 500));
6159
+ case 13:
6160
+ case "end":
6161
+ return _context3.stop();
6162
+ }
6163
+ }, _callee3, null, [[0, 12]]);
6164
+ }));
6165
+ return _resetPassword.apply(this, arguments);
6166
+ }
6167
+ function insertAdminRegistryRow(_x5, _x6, _x7, _x8) {
6168
+ return _insertAdminRegistryRow.apply(this, arguments);
6169
+ }
6170
+ function _insertAdminRegistryRow() {
6171
+ _insertAdminRegistryRow = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(supabase, sessionId, userId, account) {
6172
+ return _regeneratorRuntime.wrap(function (_context4) {
6173
+ while (1) switch (_context4.prev = _context4.next) {
6174
+ case 0:
6175
+ _context4.next = 1;
6176
+ return supabase.from("_cms_admin_registry").insert({
6177
+ session_id: normalizeSessionId(sessionId),
6178
+ user_id: userId,
6179
+ email: account
5865
6180
  });
5866
- case 7:
6181
+ case 1:
6182
+ return _context4.abrupt("return", _context4.sent);
6183
+ case 2:
5867
6184
  case "end":
5868
6185
  return _context4.stop();
5869
6186
  }
5870
6187
  }, _callee4);
5871
6188
  }));
5872
- return _promoteExistingUserToSessionAdmin.apply(this, arguments);
6189
+ return _insertAdminRegistryRow.apply(this, arguments);
5873
6190
  }
5874
6191
  function getUserSessionId(user) {
5875
6192
  var _user$user_metadata2;
5876
6193
  return normalizeSessionId(user === null || user === void 0 || (_user$user_metadata2 = user.user_metadata) === null || _user$user_metadata2 === void 0 ? void 0 : _user$user_metadata2.session_id);
5877
6194
  }
5878
- function getEffectiveRoleForSession(_x1, _x10) {
6195
+ function getEffectiveRoleForSession(_x9, _x0) {
5879
6196
  return _getEffectiveRoleForSession.apply(this, arguments);
5880
6197
  } // POST - 用户登录
5881
6198
  function _getEffectiveRoleForSession() {
@@ -5912,13 +6229,13 @@ function _getEffectiveRoleForSession() {
5912
6229
  }));
5913
6230
  return _getEffectiveRoleForSession.apply(this, arguments);
5914
6231
  }
5915
- function login(_x11, _x12) {
6232
+ function login(_x1, _x10) {
5916
6233
  return _login.apply(this, arguments);
5917
6234
  }
5918
6235
  // GET - 是否允许注册(首次进入需要创建管理员账号)
5919
6236
  function _login() {
5920
6237
  _login = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(c, tableName) {
5921
- var _data$session, body, username, password, supabase, sessionId, email, _yield$supabase$auth$4, data, error, token, user, role, _t3;
6238
+ var _data$session, body, username, password, supabase, sessionId, email, _yield$supabase$auth$3, data, error, token, user, role, _t5;
5922
6239
  return _regeneratorRuntime.wrap(function (_context6) {
5923
6240
  while (1) switch (_context6.prev = _context6.next) {
5924
6241
  case 0:
@@ -5956,9 +6273,9 @@ function _login() {
5956
6273
  password: password
5957
6274
  });
5958
6275
  case 4:
5959
- _yield$supabase$auth$4 = _context6.sent;
5960
- data = _yield$supabase$auth$4.data;
5961
- error = _yield$supabase$auth$4.error;
6276
+ _yield$supabase$auth$3 = _context6.sent;
6277
+ data = _yield$supabase$auth$3.data;
6278
+ error = _yield$supabase$auth$3.error;
5962
6279
  if (!(error || !(data !== null && data !== void 0 && (_data$session = data.session) !== null && _data$session !== void 0 && _data$session.access_token) || !(data !== null && data !== void 0 && data.user))) {
5963
6280
  _context6.next = 5;
5964
6281
  break;
@@ -5992,12 +6309,12 @@ function _login() {
5992
6309
  }, 200));
5993
6310
  case 8:
5994
6311
  _context6.prev = 8;
5995
- _t3 = _context6["catch"](0);
5996
- console.error("登录失败:", _t3);
6312
+ _t5 = _context6["catch"](0);
6313
+ console.error("登录失败:", _t5);
5997
6314
  return _context6.abrupt("return", c.json({
5998
6315
  success: false,
5999
6316
  message: "登录失败",
6000
- error: _t3.message
6317
+ error: _t5.message
6001
6318
  }, 500));
6002
6319
  case 9:
6003
6320
  case "end":
@@ -6007,13 +6324,13 @@ function _login() {
6007
6324
  }));
6008
6325
  return _login.apply(this, arguments);
6009
6326
  }
6010
- function signupStatus(_x13, _x14) {
6327
+ function signupStatus(_x11, _x12) {
6011
6328
  return _signupStatus.apply(this, arguments);
6012
6329
  }
6013
6330
  // POST - 首次注册管理员(每个 session_id 只允许一个)
6014
6331
  function _signupStatus() {
6015
6332
  _signupStatus = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(c, tableName) {
6016
- var supabase, sessionId, ok, row, data, _t4;
6333
+ var supabase, sessionId, ok, row, data, _t6;
6017
6334
  return _regeneratorRuntime.wrap(function (_context7) {
6018
6335
  while (1) switch (_context7.prev = _context7.next) {
6019
6336
  case 0:
@@ -6051,12 +6368,12 @@ function _signupStatus() {
6051
6368
  }, 200));
6052
6369
  case 4:
6053
6370
  _context7.prev = 4;
6054
- _t4 = _context7["catch"](0);
6055
- console.error("获取注册状态失败:", _t4);
6371
+ _t6 = _context7["catch"](0);
6372
+ console.error("获取注册状态失败:", _t6);
6056
6373
  return _context7.abrupt("return", c.json({
6057
6374
  success: false,
6058
6375
  message: "获取注册状态失败",
6059
- error: _t4.message
6376
+ error: _t6.message
6060
6377
  }, 500));
6061
6378
  case 5:
6062
6379
  case "end":
@@ -6066,13 +6383,13 @@ function _signupStatus() {
6066
6383
  }));
6067
6384
  return _signupStatus.apply(this, arguments);
6068
6385
  }
6069
- function signup(_x15, _x16) {
6386
+ function signup(_x13, _x14) {
6070
6387
  return _signup.apply(this, arguments);
6071
6388
  }
6072
6389
  // POST - 验证token
6073
6390
  function _signup() {
6074
6391
  _signup = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(c, tableName) {
6075
- var _body$username, _data$session2, body, account, password, supabase, sessionId, email, ok, existing, _yield$supabase$auth$5, data, error, promoted, insertRes, token, user, role, _t5;
6392
+ var _body$username3, _data$session2, body, account, password, supabase, sessionId, email, ok, existing, _yield$supabase$auth$4, data, error, insertRes, token, user, role, _t7;
6076
6393
  return _regeneratorRuntime.wrap(function (_context8) {
6077
6394
  while (1) switch (_context8.prev = _context8.next) {
6078
6395
  case 0:
@@ -6081,7 +6398,7 @@ function _signup() {
6081
6398
  return c.req.json();
6082
6399
  case 1:
6083
6400
  body = _context8.sent;
6084
- account = (_body$username = body.username) === null || _body$username === void 0 ? void 0 : _body$username.trim();
6401
+ account = (_body$username3 = body.username) === null || _body$username3 === void 0 ? void 0 : _body$username3.trim();
6085
6402
  password = body.password;
6086
6403
  if (!(!account || !password)) {
6087
6404
  _context8.next = 2;
@@ -6147,67 +6464,61 @@ function _signup() {
6147
6464
  }
6148
6465
  });
6149
6466
  case 8:
6150
- _yield$supabase$auth$5 = _context8.sent;
6151
- data = _yield$supabase$auth$5.data;
6152
- error = _yield$supabase$auth$5.error;
6467
+ _yield$supabase$auth$4 = _context8.sent;
6468
+ data = _yield$supabase$auth$4.data;
6469
+ error = _yield$supabase$auth$4.error;
6153
6470
  if (!(error || !(data !== null && data !== void 0 && data.user))) {
6154
- _context8.next = 12;
6155
- break;
6156
- }
6157
- if (!isSupabaseUserAlreadyExistsError(error)) {
6158
- _context8.next = 11;
6159
- break;
6160
- }
6161
- _context8.next = 9;
6162
- return promoteExistingUserToSessionAdmin(supabase, email, sessionId, account);
6163
- case 9:
6164
- promoted = _context8.sent;
6165
- if (promoted.success) {
6166
- _context8.next = 10;
6471
+ _context8.next = 9;
6167
6472
  break;
6168
6473
  }
6169
- return _context8.abrupt("return", c.json({
6170
- success: false,
6171
- message: promoted.message
6172
- }, 200));
6173
- case 10:
6174
- return _context8.abrupt("return", c.json({
6175
- success: true,
6176
- message: "管理员账号已启用,请登录"
6177
- }, 200));
6178
- case 11:
6474
+ console.log("注册失败:", error);
6475
+ // if (isSupabaseUserAlreadyExistsError(error)) {
6476
+ // const promoted = await promoteExistingUserToSessionAdmin(
6477
+ // supabase,
6478
+ // email,
6479
+ // sessionId,
6480
+ // account,
6481
+ // )
6482
+ // if (!promoted.success) {
6483
+ // return c.json({ success: false, message: promoted.message } as ApiResponse, 200)
6484
+ // }
6485
+ // return c.json(
6486
+ // { success: true, message: "管理员账号已启用,请登录" } as ApiResponse,
6487
+ // 200
6488
+ // )
6489
+ // }
6179
6490
  return _context8.abrupt("return", c.json({
6180
6491
  success: false,
6181
6492
  message: (error === null || error === void 0 ? void 0 : error.message) || "注册失败"
6182
6493
  }, 200));
6183
- case 12:
6494
+ case 9:
6184
6495
  if ((_data$session2 = data.session) !== null && _data$session2 !== void 0 && _data$session2.access_token) {
6185
- _context8.next = 13;
6496
+ _context8.next = 10;
6186
6497
  break;
6187
6498
  }
6188
6499
  return _context8.abrupt("return", c.json({
6189
6500
  success: true,
6190
6501
  message: "注册成功,请完成邮箱验证后登录"
6191
6502
  }, 200));
6192
- case 13:
6193
- _context8.next = 14;
6503
+ case 10:
6504
+ _context8.next = 11;
6194
6505
  return insertAdminRegistryRow(supabase, sessionId, data.user.id, account);
6195
- case 14:
6506
+ case 11:
6196
6507
  insertRes = _context8.sent;
6197
6508
  if (!insertRes.error) {
6198
- _context8.next = 15;
6509
+ _context8.next = 12;
6199
6510
  break;
6200
6511
  }
6201
6512
  return _context8.abrupt("return", c.json({
6202
6513
  success: false,
6203
6514
  message: "管理员已被创建,请使用已有账号登录"
6204
6515
  }, 200));
6205
- case 15:
6516
+ case 12:
6206
6517
  token = data.session.access_token;
6207
6518
  user = data.user;
6208
- _context8.next = 16;
6519
+ _context8.next = 13;
6209
6520
  return getEffectiveRoleForSession(user, sessionId);
6210
- case 16:
6521
+ case 13:
6211
6522
  role = _context8.sent;
6212
6523
  return _context8.abrupt("return", c.json({
6213
6524
  success: true,
@@ -6222,30 +6533,30 @@ function _signup() {
6222
6533
  }
6223
6534
  }
6224
6535
  }, 200));
6225
- case 17:
6226
- _context8.prev = 17;
6227
- _t5 = _context8["catch"](0);
6228
- console.error("注册失败:", _t5);
6536
+ case 14:
6537
+ _context8.prev = 14;
6538
+ _t7 = _context8["catch"](0);
6539
+ console.error("注册失败:", _t7);
6229
6540
  return _context8.abrupt("return", c.json({
6230
6541
  success: false,
6231
6542
  message: "注册失败",
6232
- error: _t5.message
6543
+ error: _t7.message
6233
6544
  }, 500));
6234
- case 18:
6545
+ case 15:
6235
6546
  case "end":
6236
6547
  return _context8.stop();
6237
6548
  }
6238
- }, _callee8, null, [[0, 17]]);
6549
+ }, _callee8, null, [[0, 14]]);
6239
6550
  }));
6240
6551
  return _signup.apply(this, arguments);
6241
6552
  }
6242
- function verifyAuth(_x17, _x18) {
6553
+ function verifyAuth(_x15, _x16) {
6243
6554
  return _verifyAuth.apply(this, arguments);
6244
6555
  }
6245
6556
  // GET - 获取当前用户信息
6246
6557
  function _verifyAuth() {
6247
6558
  _verifyAuth = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(c, tableName) {
6248
- var authHeader, token, supabase, _yield$supabase$auth$6, data, error, sessionId, role, decoded, message, responseMessage, _t6, _t7;
6559
+ var authHeader, token, supabase, _yield$supabase$auth$5, data, error, sessionId, role, decoded, message, responseMessage, _t8, _t9;
6249
6560
  return _regeneratorRuntime.wrap(function (_context9) {
6250
6561
  while (1) switch (_context9.prev = _context9.next) {
6251
6562
  case 0:
@@ -6266,9 +6577,9 @@ function _verifyAuth() {
6266
6577
  _context9.next = 2;
6267
6578
  return supabase.auth.getUser(token);
6268
6579
  case 2:
6269
- _yield$supabase$auth$6 = _context9.sent;
6270
- data = _yield$supabase$auth$6.data;
6271
- error = _yield$supabase$auth$6.error;
6580
+ _yield$supabase$auth$5 = _context9.sent;
6581
+ data = _yield$supabase$auth$5.data;
6582
+ error = _yield$supabase$auth$5.error;
6272
6583
  if (!(error || !(data !== null && data !== void 0 && data.user))) {
6273
6584
  _context9.next = 3;
6274
6585
  break;
@@ -6295,8 +6606,8 @@ function _verifyAuth() {
6295
6606
  }));
6296
6607
  case 6:
6297
6608
  _context9.prev = 6;
6298
- _t6 = _context9["catch"](1);
6299
- message = _t6.message;
6609
+ _t8 = _context9["catch"](1);
6610
+ message = _t8.message;
6300
6611
  responseMessage = message === 'TOKEN_EXPIRED' ? "登录已过期,请重新登录" : "认证信息无效";
6301
6612
  return _context9.abrupt("return", c.json({
6302
6613
  success: false,
@@ -6304,12 +6615,12 @@ function _verifyAuth() {
6304
6615
  }, 200));
6305
6616
  case 7:
6306
6617
  _context9.prev = 7;
6307
- _t7 = _context9["catch"](0);
6308
- console.error("验证认证失败:", _t7);
6618
+ _t9 = _context9["catch"](0);
6619
+ console.error("验证认证失败:", _t9);
6309
6620
  return _context9.abrupt("return", c.json({
6310
6621
  success: false,
6311
6622
  message: "验证认证失败",
6312
- error: _t7.message
6623
+ error: _t9.message
6313
6624
  }, 500));
6314
6625
  case 8:
6315
6626
  case "end":
@@ -6319,13 +6630,13 @@ function _verifyAuth() {
6319
6630
  }));
6320
6631
  return _verifyAuth.apply(this, arguments);
6321
6632
  }
6322
- function getCurrentUser(_x19, _x20) {
6633
+ function getCurrentUser(_x17, _x18) {
6323
6634
  return _getCurrentUser.apply(this, arguments);
6324
6635
  }
6325
6636
  // 中间件:验证 Supabase JWT token
6326
6637
  function _getCurrentUser() {
6327
6638
  _getCurrentUser = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee0(c, tableName) {
6328
- var authHeader, token, supabase, _yield$supabase$auth$7, data, error, user, sessionId, role, _t8;
6639
+ var authHeader, token, supabase, _yield$supabase$auth$6, data, error, user, sessionId, role, _t0;
6329
6640
  return _regeneratorRuntime.wrap(function (_context0) {
6330
6641
  while (1) switch (_context0.prev = _context0.next) {
6331
6642
  case 0:
@@ -6345,9 +6656,9 @@ function _getCurrentUser() {
6345
6656
  _context0.next = 2;
6346
6657
  return supabase.auth.getUser(token);
6347
6658
  case 2:
6348
- _yield$supabase$auth$7 = _context0.sent;
6349
- data = _yield$supabase$auth$7.data;
6350
- error = _yield$supabase$auth$7.error;
6659
+ _yield$supabase$auth$6 = _context0.sent;
6660
+ data = _yield$supabase$auth$6.data;
6661
+ error = _yield$supabase$auth$6.error;
6351
6662
  if (!(error || !(data !== null && data !== void 0 && data.user))) {
6352
6663
  _context0.next = 3;
6353
6664
  break;
@@ -6380,12 +6691,12 @@ function _getCurrentUser() {
6380
6691
  }, 200));
6381
6692
  case 6:
6382
6693
  _context0.prev = 6;
6383
- _t8 = _context0["catch"](0);
6384
- console.error("获取用户信息失败:", _t8);
6694
+ _t0 = _context0["catch"](0);
6695
+ console.error("获取用户信息失败:", _t0);
6385
6696
  return _context0.abrupt("return", c.json({
6386
6697
  success: false,
6387
6698
  message: "获取用户信息失败",
6388
- error: _t8.message
6699
+ error: _t0.message
6389
6700
  }, 500));
6390
6701
  case 7:
6391
6702
  case "end":
@@ -6465,7 +6776,7 @@ function requireAuth(handler) {
6465
6776
  }
6466
6777
  }, _callee, null, [[0, 5], [1, 4]]);
6467
6778
  }));
6468
- return function (_x21) {
6779
+ return function (_x19) {
6469
6780
  return _ref.apply(this, arguments);
6470
6781
  };
6471
6782
  }();
@@ -6518,7 +6829,7 @@ function _resolveUploadMaxSize() {
6518
6829
  return _resolveUploadMaxSize.apply(this, arguments);
6519
6830
  }
6520
6831
  function readSessionId(c) {
6521
- return c.req.header("X-Session-Id") || c.req.header("x-session-id") || '';
6832
+ return normalizeSessionId(c.req.header("X-Session-Id") || c.req.header("x-session-id")) || '';
6522
6833
  }
6523
6834
  function uploadToOss(_x3) {
6524
6835
  return _uploadToOss.apply(this, arguments);
@@ -6597,225 +6908,6 @@ function _uploadToOss() {
6597
6908
  return _uploadToOss.apply(this, arguments);
6598
6909
  }
6599
6910
 
6600
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
6601
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
6602
- var CONFIG_NAMESPACE_RE = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
6603
- var CONFIG_SESSION_RE = /^[a-zA-Z0-9_]{1,128}$/;
6604
- function getConfigSessionId(c) {
6605
- return normalizeSessionId(c.req.header("X-Session-Id") || c.req.header("x-session-id"));
6606
- }
6607
- function validateConfigSessionId(sessionId) {
6608
- if (!sessionId) return "缺少 X-Session-Id,无法访问配置中心";
6609
- if (!CONFIG_SESSION_RE.test(sessionId)) {
6610
- return "X-Session-Id 格式不合法";
6611
- }
6612
- return null;
6613
- }
6614
- function getConfigsTableName(sessionId) {
6615
- return "".concat(sessionId.replace('-', '_'), "__config__");
6616
- }
6617
- function normalizeValues(values) {
6618
- if (!values || _typeof$1(values) !== "object" || Array.isArray(values)) {
6619
- return {};
6620
- }
6621
- return values;
6622
- }
6623
- function buildFieldStatus(values) {
6624
- return Object.fromEntries(Object.entries(values).map(function (_ref) {
6625
- var _ref2 = _slicedToArray(_ref, 2),
6626
- key = _ref2[0],
6627
- value = _ref2[1];
6628
- return [key, {
6629
- configured: value !== null && value !== undefined && String(value).trim() !== ""
6630
- }];
6631
- }));
6632
- }
6633
- function validateNamespace(namespace) {
6634
- if (!namespace) return "缺少 namespace";
6635
- if (!CONFIG_NAMESPACE_RE.test(namespace)) {
6636
- return "namespace 只能包含字母、数字、下划线和连字符,且必须以字母开头";
6637
- }
6638
- return null;
6639
- }
6640
- function toConfigResponse(row, fallbackNamespace) {
6641
- var values = normalizeValues(row === null || row === void 0 ? void 0 : row.values);
6642
- return {
6643
- id: row === null || row === void 0 ? void 0 : row.id,
6644
- namespace: (row === null || row === void 0 ? void 0 : row.namespace) || fallbackNamespace,
6645
- values: values,
6646
- fields: buildFieldStatus(values),
6647
- created_at: row === null || row === void 0 ? void 0 : row.created_at,
6648
- updated_at: row === null || row === void 0 ? void 0 : row.updated_at
6649
- };
6650
- }
6651
- function getConfig(_x) {
6652
- return _getConfig.apply(this, arguments);
6653
- }
6654
- function _getConfig() {
6655
- _getConfig = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(c) {
6656
- var namespace, namespaceError, _response, sessionId, sessionError, _response2, tableName, supabase, _yield$supabase$from$, data, error, response, _response3, _t;
6657
- return _regeneratorRuntime.wrap(function (_context) {
6658
- while (1) switch (_context.prev = _context.next) {
6659
- case 0:
6660
- _context.prev = 0;
6661
- namespace = (c.req.query("namespace") || "").trim();
6662
- namespaceError = validateNamespace(namespace);
6663
- if (!namespaceError) {
6664
- _context.next = 1;
6665
- break;
6666
- }
6667
- _response = {
6668
- success: false,
6669
- message: namespaceError
6670
- };
6671
- return _context.abrupt("return", c.json(_response, 200));
6672
- case 1:
6673
- sessionId = getConfigSessionId(c);
6674
- sessionError = validateConfigSessionId(sessionId);
6675
- if (!sessionError) {
6676
- _context.next = 2;
6677
- break;
6678
- }
6679
- _response2 = {
6680
- success: false,
6681
- message: sessionError
6682
- };
6683
- return _context.abrupt("return", c.json(_response2, 200));
6684
- case 2:
6685
- tableName = getConfigsTableName(sessionId); // await ensureConfigsTable(tableName)
6686
- supabase = getSupabase();
6687
- _context.next = 3;
6688
- return supabase.from(tableName).select("*").eq("namespace", namespace).maybeSingle();
6689
- case 3:
6690
- _yield$supabase$from$ = _context.sent;
6691
- data = _yield$supabase$from$.data;
6692
- error = _yield$supabase$from$.error;
6693
- if (!error) {
6694
- _context.next = 4;
6695
- break;
6696
- }
6697
- throw error;
6698
- case 4:
6699
- response = {
6700
- success: true,
6701
- data: toConfigResponse(data, namespace)
6702
- };
6703
- return _context.abrupt("return", c.json(response, 200));
6704
- case 5:
6705
- _context.prev = 5;
6706
- _t = _context["catch"](0);
6707
- console.error("获取配置失败:", _t);
6708
- _response3 = {
6709
- success: false,
6710
- message: "获取配置失败",
6711
- error: _t.message
6712
- };
6713
- return _context.abrupt("return", c.json(_response3, 500));
6714
- case 6:
6715
- case "end":
6716
- return _context.stop();
6717
- }
6718
- }, _callee, null, [[0, 5]]);
6719
- }));
6720
- return _getConfig.apply(this, arguments);
6721
- }
6722
- function updateConfig(_x2) {
6723
- return _updateConfig.apply(this, arguments);
6724
- }
6725
- function _updateConfig() {
6726
- _updateConfig = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(c) {
6727
- var namespace, namespaceError, _response4, body, values, sessionId, sessionError, _response5, tableName, supabase, _yield$supabase$from$2, existing, existingError, nextValues, _yield$supabase$from$3, data, error, response, _response6, _t2;
6728
- return _regeneratorRuntime.wrap(function (_context2) {
6729
- while (1) switch (_context2.prev = _context2.next) {
6730
- case 0:
6731
- _context2.prev = 0;
6732
- namespace = (c.req.param("namespace") || "").trim();
6733
- namespaceError = validateNamespace(namespace);
6734
- if (!namespaceError) {
6735
- _context2.next = 1;
6736
- break;
6737
- }
6738
- _response4 = {
6739
- success: false,
6740
- message: namespaceError
6741
- };
6742
- return _context2.abrupt("return", c.json(_response4, 200));
6743
- case 1:
6744
- _context2.next = 2;
6745
- return c.req.json();
6746
- case 2:
6747
- body = _context2.sent;
6748
- values = normalizeValues(body === null || body === void 0 ? void 0 : body.values);
6749
- sessionId = getConfigSessionId(c);
6750
- sessionError = validateConfigSessionId(sessionId);
6751
- if (!sessionError) {
6752
- _context2.next = 3;
6753
- break;
6754
- }
6755
- _response5 = {
6756
- success: false,
6757
- message: sessionError
6758
- };
6759
- return _context2.abrupt("return", c.json(_response5, 200));
6760
- case 3:
6761
- tableName = getConfigsTableName(sessionId); // await ensureConfigsTable(tableName)
6762
- supabase = getSupabase();
6763
- _context2.next = 4;
6764
- return supabase.from(tableName).select("values").eq("namespace", namespace).maybeSingle();
6765
- case 4:
6766
- _yield$supabase$from$2 = _context2.sent;
6767
- existing = _yield$supabase$from$2.data;
6768
- existingError = _yield$supabase$from$2.error;
6769
- if (!existingError) {
6770
- _context2.next = 5;
6771
- break;
6772
- }
6773
- throw existingError;
6774
- case 5:
6775
- nextValues = _objectSpread(_objectSpread({}, normalizeValues(existing === null || existing === void 0 ? void 0 : existing.values)), values);
6776
- _context2.next = 6;
6777
- return supabase.from(tableName).upsert({
6778
- namespace: namespace,
6779
- values: nextValues,
6780
- updated_at: new Date().toISOString()
6781
- }, {
6782
- onConflict: "namespace"
6783
- }).select("*").single();
6784
- case 6:
6785
- _yield$supabase$from$3 = _context2.sent;
6786
- data = _yield$supabase$from$3.data;
6787
- error = _yield$supabase$from$3.error;
6788
- if (!error) {
6789
- _context2.next = 7;
6790
- break;
6791
- }
6792
- throw error;
6793
- case 7:
6794
- response = {
6795
- success: true,
6796
- message: "配置保存成功",
6797
- data: toConfigResponse(data, namespace)
6798
- };
6799
- return _context2.abrupt("return", c.json(response, 200));
6800
- case 8:
6801
- _context2.prev = 8;
6802
- _t2 = _context2["catch"](0);
6803
- console.error("保存配置失败:", _t2);
6804
- _response6 = {
6805
- success: false,
6806
- message: "保存配置失败",
6807
- error: _t2.message
6808
- };
6809
- return _context2.abrupt("return", c.json(_response6, 500));
6810
- case 9:
6811
- case "end":
6812
- return _context2.stop();
6813
- }
6814
- }, _callee2, null, [[0, 8]]);
6815
- }));
6816
- return _updateConfig.apply(this, arguments);
6817
- }
6818
-
6819
6911
  var AUTH_REQUIRED = "CMS_AUTH_REQUIRED";
6820
6912
  var AUTH_INVALID = "CMS_AUTH_INVALID";
6821
6913
  var CMS_FORBIDDEN = "CMS_FORBIDDEN";
@@ -7255,10 +7347,26 @@ function createDynamicAuthRoute(app) {
7255
7347
  var tableName = c.req.param("tableName");
7256
7348
  return signup(c, tableName);
7257
7349
  });
7350
+ app.post("/auth/password/forgot/:tableName", function (c) {
7351
+ var tableName = c.req.param("tableName");
7352
+ return forgotPassword(c, tableName);
7353
+ });
7354
+ app.post("/auth/password/reset/:tableName", function (c) {
7355
+ var tableName = c.req.param("tableName");
7356
+ return resetPassword(c, tableName);
7357
+ });
7258
7358
  app.post("/auth/:tableName/login", function (c) {
7259
7359
  var tableName = c.req.param("tableName");
7260
7360
  return login(c, tableName);
7261
7361
  });
7362
+ app.post("/auth/:tableName/password/forgot", function (c) {
7363
+ var tableName = c.req.param("tableName");
7364
+ return forgotPassword(c, tableName);
7365
+ });
7366
+ app.post("/auth/:tableName/password/reset", function (c) {
7367
+ var tableName = c.req.param("tableName");
7368
+ return resetPassword(c, tableName);
7369
+ });
7262
7370
  app.get("/auth/:tableName/current", function (c) {
7263
7371
  var tableName = c.req.param("tableName");
7264
7372
  return getCurrentUser(c, tableName);
@@ -7311,21 +7419,13 @@ function createOssUploadRoute(app) {
7311
7419
  app.post("/upload", requireJwtAuth, requireAdminRole, uploadToOss);
7312
7420
  return app;
7313
7421
  }
7314
- function createConfigRoute(app) {
7315
- app.get("/configs", requireAdminRole, getConfig);
7316
- app.put("/configs/:namespace", requireAdminRole, function (c) {
7317
- return updateConfig(c);
7318
- });
7319
- return app;
7320
- }
7321
7422
  // 一键创建所有CMS路由
7322
7423
  function createCmsRoutes(app) {
7323
7424
  createModelRoute(app);
7324
- createConfigRoute(app);
7325
7425
  createDynamicDataRoute(app);
7326
7426
  createDynamicAuthRoute(app);
7327
7427
  return app;
7328
7428
  }
7329
7429
 
7330
- export { AuthService, getCmsModelService as CmsModel, CmsModelService, DynamicTableService, OssUploadError, OssUploadService, closeSupabase as closeDatabase, closeSupabase, createAuthRoute, createCmsRoutes, createConfigRoute, createDataRoute, createDynamicAuthRoute, createDynamicDataRoute, createModel, createModelRoute, createOssUploadRoute, createTableData, deleteModel, deleteTableData, dropForeignKeys, executeSupabaseSetup, getAuthService, getCmsModelService, getConfig, getCurrentUser, getSupabase as getDatabase, getDynamicTableService, getModels, getOssUploadService, getRelationOptions, getSupabase, getSupabaseSetupSQL, getTableData, getTableDataWithRelations, initializeCmsModel, initializeCmsSystem, initializeSupabase as initializeDatabase, initializeOssUpload, initializeSupabase, login, requireAuth, signup, signupStatus, initializeCmsSystem as syncDatabase, testConnection, updateConfig, updateModel, updateTableData, uploadToOss, verifyAuth };
7430
+ export { AuthService, getCmsModelService as CmsModel, CmsModelService, DynamicTableService, OssUploadError, OssUploadService, closeSupabase as closeDatabase, closeSupabase, createAuthRoute, createCmsRoutes, createDataRoute, createDynamicAuthRoute, createDynamicDataRoute, createModel, createModelRoute, createOssUploadRoute, createTableData, deleteModel, deleteTableData, dropForeignKeys, executeSupabaseSetup, feishuAlertConfig, getAuthService, getCmsModelService, getCurrentUser, getSupabase as getDatabase, getDynamicTableService, getModels, getOssUploadService, getRelationOptions, getSupabase, getSupabaseSetupSQL, getTableData, getTableDataWithRelations, initializeCmsModel, initializeCmsSystem, initializeSupabase as initializeDatabase, initializeOssUpload, initializeSupabase, login, notifyCmsCrudErrorToFeishu, reportCmsCrudErrorToFeishu, requireAuth, signup, signupStatus, initializeCmsSystem as syncDatabase, testConnection, updateModel, updateTableData, uploadToOss, verifyAuth };
7331
7431
  //# sourceMappingURL=index.esm.js.map