@ai0x0/utils 0.0.50 → 0.1.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 (86) hide show
  1. package/.agents/skills/ai0x0-utils/backend/SKILL.md +35 -11
  2. package/README.md +3 -3
  3. package/SKILL.md +35 -11
  4. package/es/backend/actions/create-delete-action.d.ts +4 -2
  5. package/es/backend/actions/create-delete-action.js +22 -28
  6. package/es/backend/actions/create-get-action.d.ts +4 -1
  7. package/es/backend/actions/create-get-action.js +10 -10
  8. package/es/backend/actions/create-get-list-action.d.ts +4 -1
  9. package/es/backend/actions/create-get-list-action.js +9 -9
  10. package/es/backend/actions/create-put-action.d.ts +3 -2
  11. package/es/backend/actions/create-put-action.js +23 -38
  12. package/es/backend/actions/get-list-query.d.ts +8 -1
  13. package/es/backend/actions/get-list-query.js +19 -8
  14. package/es/backend/index.d.ts +1 -0
  15. package/es/backend/index.js +2 -1
  16. package/es/backend/route-operation/delete-operation.d.ts +3 -1
  17. package/es/backend/route-operation/get-list-operation.d.ts +3 -1
  18. package/es/backend/route-operation/get-operation.d.ts +3 -1
  19. package/es/backend/route-operation/operation-common.d.ts +80 -8
  20. package/es/backend/route-operation/operation-common.js +216 -67
  21. package/es/backend/route-operation/post-operation.d.ts +3 -1
  22. package/es/backend/route-operation/put-operation.d.ts +3 -1
  23. package/es/backend/route-operation/read-operation-core.d.ts +17 -14
  24. package/es/backend/route-operation/read-operation-core.js +42 -34
  25. package/es/backend/route-operation/write-operation-core.d.ts +25 -22
  26. package/es/backend/route-operation/write-operation-core.js +195 -165
  27. package/es/backend/schemas/index.d.ts +240 -240
  28. package/es/backend/scope.d.ts +27 -0
  29. package/es/backend/scope.js +60 -0
  30. package/es/backend/sqlite/actions/create-delete-action.d.ts +4 -2
  31. package/es/backend/sqlite/actions/create-delete-action.js +21 -28
  32. package/es/backend/sqlite/actions/create-get-action.d.ts +4 -1
  33. package/es/backend/sqlite/actions/create-get-action.js +9 -7
  34. package/es/backend/sqlite/actions/create-get-list-action.d.ts +4 -1
  35. package/es/backend/sqlite/actions/create-get-list-action.js +8 -6
  36. package/es/backend/sqlite/actions/create-put-action.d.ts +3 -2
  37. package/es/backend/sqlite/actions/create-put-action.js +20 -38
  38. package/es/backend/sqlite/actions/get-list-query.d.ts +4 -1
  39. package/es/backend/sqlite/actions/get-list-query.js +8 -3
  40. package/es/backend/sqlite/route-operation/delete-operation.d.ts +3 -1
  41. package/es/backend/sqlite/route-operation/get-list-operation.d.ts +3 -1
  42. package/es/backend/sqlite/route-operation/get-operation.d.ts +3 -1
  43. package/es/backend/sqlite/route-operation/post-operation.d.ts +3 -1
  44. package/es/backend/sqlite/route-operation/put-operation.d.ts +3 -1
  45. package/lib/backend/actions/create-delete-action.d.ts +4 -2
  46. package/lib/backend/actions/create-delete-action.js +10 -16
  47. package/lib/backend/actions/create-get-action.d.ts +4 -1
  48. package/lib/backend/actions/create-get-action.js +2 -1
  49. package/lib/backend/actions/create-get-list-action.d.ts +4 -1
  50. package/lib/backend/actions/create-get-list-action.js +2 -1
  51. package/lib/backend/actions/create-put-action.d.ts +3 -2
  52. package/lib/backend/actions/create-put-action.js +10 -21
  53. package/lib/backend/actions/get-list-query.d.ts +8 -1
  54. package/lib/backend/actions/get-list-query.js +11 -4
  55. package/lib/backend/index.d.ts +1 -0
  56. package/lib/backend/index.js +3 -1
  57. package/lib/backend/route-operation/delete-operation.d.ts +3 -1
  58. package/lib/backend/route-operation/get-list-operation.d.ts +3 -1
  59. package/lib/backend/route-operation/get-operation.d.ts +3 -1
  60. package/lib/backend/route-operation/operation-common.d.ts +80 -8
  61. package/lib/backend/route-operation/operation-common.js +57 -7
  62. package/lib/backend/route-operation/post-operation.d.ts +3 -1
  63. package/lib/backend/route-operation/put-operation.d.ts +3 -1
  64. package/lib/backend/route-operation/read-operation-core.d.ts +17 -14
  65. package/lib/backend/route-operation/read-operation-core.js +12 -6
  66. package/lib/backend/route-operation/write-operation-core.d.ts +25 -22
  67. package/lib/backend/route-operation/write-operation-core.js +52 -16
  68. package/lib/backend/schemas/index.d.ts +240 -240
  69. package/lib/backend/scope.d.ts +27 -0
  70. package/lib/backend/scope.js +57 -0
  71. package/lib/backend/sqlite/actions/create-delete-action.d.ts +4 -2
  72. package/lib/backend/sqlite/actions/create-delete-action.js +10 -16
  73. package/lib/backend/sqlite/actions/create-get-action.d.ts +4 -1
  74. package/lib/backend/sqlite/actions/create-get-action.js +2 -1
  75. package/lib/backend/sqlite/actions/create-get-list-action.d.ts +4 -1
  76. package/lib/backend/sqlite/actions/create-get-list-action.js +2 -1
  77. package/lib/backend/sqlite/actions/create-put-action.d.ts +3 -2
  78. package/lib/backend/sqlite/actions/create-put-action.js +10 -21
  79. package/lib/backend/sqlite/actions/get-list-query.d.ts +4 -1
  80. package/lib/backend/sqlite/actions/get-list-query.js +5 -1
  81. package/lib/backend/sqlite/route-operation/delete-operation.d.ts +3 -1
  82. package/lib/backend/sqlite/route-operation/get-list-operation.d.ts +3 -1
  83. package/lib/backend/sqlite/route-operation/get-operation.d.ts +3 -1
  84. package/lib/backend/sqlite/route-operation/post-operation.d.ts +3 -1
  85. package/lib/backend/sqlite/route-operation/put-operation.d.ts +3 -1
  86. package/package.json +39 -1
@@ -0,0 +1,27 @@
1
+ import { SQL } from "drizzle-orm";
2
+ import { BaseTable } from "./types.js";
3
+ /** 归属值:单个(等值匹配)或多个(IN)。 */
4
+ export type ScopeValue = string | string[];
5
+ /** 解析完的作用域:限定哪一列、限定成什么值。 */
6
+ export interface ScopeCondition {
7
+ /** 承载归属的列名,如 "creatorId" / "ownerId"。 */
8
+ column: string;
9
+ value: ScopeValue;
10
+ }
11
+ /**
12
+ * 明确表示「这条查询不做行级隔离」。
13
+ *
14
+ * 用一个可辨识的值而不是 undefined:调用方漏传参数时 TypeScript 会报错,而不是悄悄
15
+ * 退化成「查全表」。凡是接受作用域的地方都必须收到 ScopeCondition 或 NO_SCOPE 之一。
16
+ */
17
+ export declare const NO_SCOPE: null;
18
+ export type ScopeArg = ScopeCondition | typeof NO_SCOPE;
19
+ /** 空作用域值(undefined / 空串 / 空数组)—— 拿到它一律视为「解析失败」,不是「不筛」。 */
20
+ export declare function isEmptyScopeValue(value: ScopeValue | undefined): value is undefined;
21
+ /**
22
+ * 作用域 → drizzle 条件。NO_SCOPE 返回 undefined(调用方据此不加条件)。
23
+ *
24
+ * 列不在表上直接抛:这多半是配错了列名,而一个「配错了就不加条件」的实现等于把配置错误
25
+ * 变成越权漏洞。
26
+ */
27
+ export declare function scopeCondition(table: BaseTable, scope: ScopeArg): SQL | undefined;
@@ -0,0 +1,60 @@
1
+ import { eq, inArray } from "drizzle-orm";
2
+
3
+ // ==============================================================================
4
+ // 行级作用域
5
+ // ==============================================================================
6
+ // `access.byCreator` 原本把两件事写死了:**哪一列**承载归属(creatorId)、**取什么值**
7
+ // (session.userId)。够用到出现「一条记录可能属于一个团队而不是一个人」为止 —— 那时归属列
8
+ // 是 ownerId,值是「当前站在哪个空间」,两个维度都得放开。这个文件就是放开后的那个概念。
9
+ //
10
+ // 三条设计约束,改这里之前先读:
11
+ //
12
+ // 1) **作用域不是普通筛选条件。** get-list-query 里的筛选是「空值就跳过」(`if (!value)
13
+ // continue`),因为 `?name=` 这种空参数本来就该当没传。作用域走同一条路的话,一个取不到值
14
+ // 的作用域会让整条 where 消失 —— 列表返回全表。所以作用域**单独一条通道**传到查询构造器,
15
+ // 而且它没有「空值跳过」这一说:拿不到值就是错误,不是「不筛」。
16
+ //
17
+ // 2) **漏传和「明确不要」必须能区分。** 类型上作用域参数是必填的,不想要行级隔离就显式传
18
+ // NO_SCOPE。写成可选参数的话,漏传就退化成不隔离,而那是静默的越权。
19
+ //
20
+ // 3) **列不存在要当场炸。** 配错列名(比如表上根本没有 ownerId)如果只是「查不到东西」,
21
+ // 症状是功能坏掉;但如果实现上退化成不加条件,症状就是越权。宁可抛。
22
+
23
+ /** 归属值:单个(等值匹配)或多个(IN)。 */
24
+
25
+ /** 解析完的作用域:限定哪一列、限定成什么值。 */
26
+
27
+ /**
28
+ * 明确表示「这条查询不做行级隔离」。
29
+ *
30
+ * 用一个可辨识的值而不是 undefined:调用方漏传参数时 TypeScript 会报错,而不是悄悄
31
+ * 退化成「查全表」。凡是接受作用域的地方都必须收到 ScopeCondition 或 NO_SCOPE 之一。
32
+ */
33
+ export var NO_SCOPE = null;
34
+ /** 空作用域值(undefined / 空串 / 空数组)—— 拿到它一律视为「解析失败」,不是「不筛」。 */
35
+ export function isEmptyScopeValue(value) {
36
+ if (value === undefined) {
37
+ return true;
38
+ }
39
+ return Array.isArray(value) ? value.length === 0 : value.trim() === "";
40
+ }
41
+
42
+ /**
43
+ * 作用域 → drizzle 条件。NO_SCOPE 返回 undefined(调用方据此不加条件)。
44
+ *
45
+ * 列不在表上直接抛:这多半是配错了列名,而一个「配错了就不加条件」的实现等于把配置错误
46
+ * 变成越权漏洞。
47
+ */
48
+ export function scopeCondition(table, scope) {
49
+ if (scope === NO_SCOPE) {
50
+ return undefined;
51
+ }
52
+ var column = table[scope.column];
53
+ if (!column) {
54
+ throw new Error("\u4F5C\u7528\u57DF\u5217 \"".concat(scope.column, "\" \u4E0D\u5728\u8FD9\u5F20\u8868\u4E0A\u3002\u68C0\u67E5 access.scope.column \u662F\u5426\u5199\u9519\uFF0C\u6216\u8FD9\u5F20\u8868\u662F\u5426\u771F\u7684\u6709\u5F52\u5C5E\u5217\u3002"));
55
+ }
56
+ if (isEmptyScopeValue(scope.value)) {
57
+ throw new Error("\u4F5C\u7528\u57DF\u5217 \"".concat(scope.column, "\" \u62FF\u5230\u7684\u662F\u7A7A\u503C\u3002\u8FD9\u4E0D\u662F\u300C\u4E0D\u7B5B\u300D\u2014\u2014 \u4E0A\u6E38\u5E94\u5F53\u5728\u89E3\u6790\u9636\u6BB5\u5C31\u62D2\u7EDD\u8FD9\u4E2A\u8BF7\u6C42\u3002"));
58
+ }
59
+ return Array.isArray(scope.value) ? inArray(column, scope.value) : eq(column, scope.value);
60
+ }
@@ -1,8 +1,10 @@
1
1
  import { BaseTable } from "../types.js";
2
+ import { ScopeArg } from "../../scope.js";
2
3
  export declare function createDeleteAction<TTable extends BaseTable>({ table, db, }: {
3
4
  db: any;
4
5
  table: TTable;
5
- }): ({ id, creatorId }: {
6
+ }): ({ id }: {
6
7
  id: string;
7
- creatorId?: string | undefined;
8
+ }, { scope }: {
9
+ scope: ScopeArg;
8
10
  }) => Promise<any>;
@@ -2,53 +2,46 @@ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" ==
2
2
  function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
3
3
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4
4
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
5
- import { eq } from "drizzle-orm";
6
- import { createGetAction } from "./../index.js";
7
- import { z } from "zod";
5
+ import { and, eq } from "drizzle-orm";
6
+ import { NO_SCOPE, scopeCondition } from "../../scope.js";
8
7
  import { HttpError } from "../errors.js";
9
8
  export function createDeleteAction(_ref) {
10
9
  var table = _ref.table,
11
10
  db = _ref.db;
12
11
  return /*#__PURE__*/function () {
13
- var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2) {
14
- var id, creatorId, data;
12
+ var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref2, _ref3) {
13
+ var id, scope, guard, rows;
15
14
  return _regeneratorRuntime().wrap(function _callee$(_context) {
16
15
  while (1) switch (_context.prev = _context.next) {
17
16
  case 0:
18
- id = _ref2.id, creatorId = _ref2.creatorId;
19
- if (!creatorId) {
20
- _context.next = 7;
17
+ id = _ref2.id;
18
+ scope = _ref3.scope;
19
+ if (id) {
20
+ _context.next = 4;
21
21
  break;
22
22
  }
23
- _context.next = 4;
24
- return createGetAction({
25
- db: db,
26
- table: table,
27
- bodySchema: z.object({
28
- creatorId: z.string(),
29
- id: z.string()
30
- })
31
- })({
32
- creatorId: creatorId,
33
- id: id
34
- });
23
+ throw new HttpError(400, "缺少 id");
35
24
  case 4:
36
- data = _context.sent;
37
- if (data) {
38
- _context.next = 7;
25
+ guard = scopeCondition(table, scope);
26
+ _context.next = 7;
27
+ return db.delete(table).where(guard ? and(eq(table.id, id), guard) : eq(table.id, id)).returning();
28
+ case 7:
29
+ rows = _context.sent;
30
+ if (!(rows.length === 0 && scope !== NO_SCOPE)) {
31
+ _context.next = 10;
39
32
  break;
40
33
  }
41
34
  throw new HttpError(404, "未找到删除对象,或没有权限");
42
- case 7:
43
- return _context.abrupt("return", db.delete(table).where(eq(table.id, id)).returning());
44
- case 8:
35
+ case 10:
36
+ return _context.abrupt("return", rows);
37
+ case 11:
45
38
  case "end":
46
39
  return _context.stop();
47
40
  }
48
41
  }, _callee);
49
42
  }));
50
- return function (_x) {
51
- return _ref3.apply(this, arguments);
43
+ return function (_x, _x2) {
44
+ return _ref4.apply(this, arguments);
52
45
  };
53
46
  }();
54
47
  }
@@ -1,3 +1,4 @@
1
+ import { ScopeArg } from "../../scope.js";
1
2
  import { BaseTable, GetListRelations } from "../types.js";
2
3
  export declare function createGetAction<TTable extends BaseTable>({ bodySchema, db, jsonArrayFields, relations, table, }: {
3
4
  bodySchema: any;
@@ -5,4 +6,6 @@ export declare function createGetAction<TTable extends BaseTable>({ bodySchema,
5
6
  jsonArrayFields?: string[];
6
7
  relations?: GetListRelations;
7
8
  table: TTable;
8
- }): (params: Record<string, unknown>) => Promise<unknown>;
9
+ }): (params: Record<string, unknown>, { scope }: {
10
+ scope: ScopeArg;
11
+ }) => Promise<unknown>;
@@ -17,11 +17,12 @@ export function createGetAction(_ref) {
17
17
  relations = _ref.relations,
18
18
  table = _ref.table;
19
19
  return /*#__PURE__*/function () {
20
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(params) {
21
- var fields, _i, _Object$keys, key, field, _getListQuery, query, countQuery, _yield$getListData, _yield$getListData$da, result;
20
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(params, _ref2) {
21
+ var scope, fields, _i, _Object$keys, key, field, _getListQuery, query, countQuery, _yield$getListData, _yield$getListData$da, result;
22
22
  return _regeneratorRuntime().wrap(function _callee$(_context) {
23
23
  while (1) switch (_context.prev = _context.next) {
24
24
  case 0:
25
+ scope = _ref2.scope;
25
26
  fields = {};
26
27
  for (_i = 0, _Object$keys = Object.keys(bodySchema.shape); _i < _Object$keys.length; _i++) {
27
28
  key = _Object$keys[_i];
@@ -35,10 +36,11 @@ export function createGetAction(_ref) {
35
36
  fields: fields,
36
37
  jsonArrayFields: jsonArrayFields,
37
38
  params: params,
39
+ scope: scope,
38
40
  relations: relations,
39
41
  table: table
40
42
  }), query = _getListQuery.query, countQuery = _getListQuery.countQuery;
41
- _context.next = 5;
43
+ _context.next = 6;
42
44
  return getListData({
43
45
  bodySchema: bodySchema,
44
46
  countQuery: countQuery,
@@ -46,19 +48,19 @@ export function createGetAction(_ref) {
46
48
  pageSize: 1,
47
49
  query: query
48
50
  })();
49
- case 5:
51
+ case 6:
50
52
  _yield$getListData = _context.sent;
51
53
  _yield$getListData$da = _slicedToArray(_yield$getListData.data, 1);
52
54
  result = _yield$getListData$da[0];
53
55
  return _context.abrupt("return", result);
54
- case 9:
56
+ case 10:
55
57
  case "end":
56
58
  return _context.stop();
57
59
  }
58
60
  }, _callee);
59
61
  }));
60
- return function (_x) {
61
- return _ref2.apply(this, arguments);
62
+ return function (_x, _x2) {
63
+ return _ref3.apply(this, arguments);
62
64
  };
63
65
  }();
64
66
  }
@@ -1,3 +1,4 @@
1
+ import { ScopeArg } from "../../scope.js";
1
2
  import { BaseTable, GetListRelations } from "../types.js";
2
3
  export declare function createGetListAction<TTable extends BaseTable>({ bodySchema, db, jsonArrayFields, relations, table, }: {
3
4
  bodySchema: any;
@@ -5,7 +6,9 @@ export declare function createGetListAction<TTable extends BaseTable>({ bodySche
5
6
  jsonArrayFields?: string[];
6
7
  relations?: GetListRelations;
7
8
  table: TTable;
8
- }): (params: Record<string, unknown>) => Promise<{
9
+ }): (params: Record<string, unknown>, { scope }: {
10
+ scope: ScopeArg;
11
+ }) => Promise<{
9
12
  data: unknown[];
10
13
  total: number;
11
14
  }>;
@@ -14,12 +14,13 @@ export function createGetListAction(_ref) {
14
14
  relations = _ref.relations,
15
15
  table = _ref.table;
16
16
  return /*#__PURE__*/function () {
17
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(params) {
18
- var _ref3, current, pageSize, other, fields, _i, _Object$keys, key, field, _getListQuery, query, countQuery;
17
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(params, _ref2) {
18
+ var scope, _ref4, current, pageSize, other, fields, _i, _Object$keys, key, field, _getListQuery, query, countQuery;
19
19
  return _regeneratorRuntime().wrap(function _callee$(_context) {
20
20
  while (1) switch (_context.prev = _context.next) {
21
21
  case 0:
22
- _ref3 = params, current = _ref3.current, pageSize = _ref3.pageSize, other = _objectWithoutProperties(_ref3, _excluded);
22
+ scope = _ref2.scope;
23
+ _ref4 = params, current = _ref4.current, pageSize = _ref4.pageSize, other = _objectWithoutProperties(_ref4, _excluded);
23
24
  fields = {};
24
25
  for (_i = 0, _Object$keys = Object.keys(bodySchema.shape); _i < _Object$keys.length; _i++) {
25
26
  key = _Object$keys[_i];
@@ -33,6 +34,7 @@ export function createGetListAction(_ref) {
33
34
  fields: fields,
34
35
  jsonArrayFields: jsonArrayFields,
35
36
  params: other,
37
+ scope: scope,
36
38
  relations: relations,
37
39
  table: table
38
40
  }), query = _getListQuery.query, countQuery = _getListQuery.countQuery;
@@ -43,14 +45,14 @@ export function createGetListAction(_ref) {
43
45
  pageSize: pageSize,
44
46
  query: query
45
47
  })());
46
- case 5:
48
+ case 6:
47
49
  case "end":
48
50
  return _context.stop();
49
51
  }
50
52
  }, _callee);
51
53
  }));
52
- return function (_x) {
53
- return _ref2.apply(this, arguments);
54
+ return function (_x, _x2) {
55
+ return _ref3.apply(this, arguments);
54
56
  };
55
57
  }();
56
58
  }
@@ -1,8 +1,9 @@
1
1
  import { BaseTable } from "../types.js";
2
+ import { ScopeArg } from "../../scope.js";
2
3
  export declare function createPutAction<TTable extends BaseTable>({ db, table, }: {
3
4
  bodySchema: any;
4
5
  db: any;
5
6
  table: TTable;
6
- }): (body: Record<string, unknown>, { byCreator, }?: {
7
- byCreator?: boolean | undefined;
7
+ }): (body: Record<string, unknown>, { scope }: {
8
+ scope: ScopeArg;
8
9
  }) => Promise<any>;
@@ -8,58 +8,40 @@ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" !=
8
8
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
9
9
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
10
10
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
11
- import { z } from "zod";
12
11
  import { transformBody } from "./transform-body.js";
13
- import { eq } from "drizzle-orm";
14
- import { createGetAction } from "./../index.js";
12
+ import { and, eq } from "drizzle-orm";
13
+ import { NO_SCOPE, scopeCondition } from "../../scope.js";
15
14
  import { HttpError } from "../errors.js";
16
15
  export function createPutAction(_ref) {
17
16
  var db = _ref.db,
18
17
  table = _ref.table;
19
18
  return /*#__PURE__*/function () {
20
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(body) {
21
- var _ref3,
22
- _ref3$byCreator,
23
- byCreator,
24
- _data,
25
- _yield$db$update$set$,
26
- _yield$db$update$set$2,
27
- data,
28
- _args = arguments;
19
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(body, _ref2) {
20
+ var scope, id, guard, _yield$db$update$set$, _yield$db$update$set$2, data;
29
21
  return _regeneratorRuntime().wrap(function _callee$(_context) {
30
22
  while (1) switch (_context.prev = _context.next) {
31
23
  case 0:
32
- _ref3 = _args.length > 1 && _args[1] !== undefined ? _args[1] : {}, _ref3$byCreator = _ref3.byCreator, byCreator = _ref3$byCreator === void 0 ? true : _ref3$byCreator;
33
- if (!byCreator) {
34
- _context.next = 7;
24
+ scope = _ref2.scope;
25
+ id = body.id;
26
+ if (id) {
27
+ _context.next = 4;
35
28
  break;
36
29
  }
37
- _context.next = 4;
38
- return createGetAction({
39
- db: db,
40
- table: table,
41
- bodySchema: z.object({
42
- creatorId: z.string(),
43
- id: z.string()
44
- })
45
- })({
46
- creatorId: body.editorId,
47
- id: body.id
48
- });
30
+ throw new HttpError(400, "缺少 id");
49
31
  case 4:
50
- _data = _context.sent;
51
- if (_data) {
52
- _context.next = 7;
53
- break;
54
- }
55
- throw new HttpError(404, "未找到编辑对象,或没有权限");
32
+ guard = scopeCondition(table, scope);
33
+ _context.next = 7;
34
+ return db.update(table).set(transformBody(body)).where(guard ? and(eq(table.id, id), guard) : eq(table.id, id)).returning();
56
35
  case 7:
57
- _context.next = 9;
58
- return db.update(table).set(transformBody(body)).where(eq(table.id, body.id)).returning();
59
- case 9:
60
36
  _yield$db$update$set$ = _context.sent;
61
37
  _yield$db$update$set$2 = _slicedToArray(_yield$db$update$set$, 1);
62
38
  data = _yield$db$update$set$2[0];
39
+ if (!(!data && scope !== NO_SCOPE)) {
40
+ _context.next = 12;
41
+ break;
42
+ }
43
+ throw new HttpError(404, "未找到编辑对象,或没有权限");
44
+ case 12:
63
45
  return _context.abrupt("return", data);
64
46
  case 13:
65
47
  case "end":
@@ -67,8 +49,8 @@ export function createPutAction(_ref) {
67
49
  }
68
50
  }, _callee);
69
51
  }));
70
- return function (_x) {
71
- return _ref2.apply(this, arguments);
52
+ return function (_x, _x2) {
53
+ return _ref3.apply(this, arguments);
72
54
  };
73
55
  }();
74
56
  }
@@ -1,9 +1,12 @@
1
+ import { ScopeArg } from "../../scope.js";
1
2
  import { BaseTable, GetListRelations } from "../types.js";
2
3
  import { SelectedFields } from "drizzle-orm/sqlite-core/query-builders/select.types";
3
- export declare function getListQuery<TTable extends BaseTable, TSelection extends SelectedFields>({ db, fields, jsonArrayFields, params, relations, table, }: {
4
+ export declare function getListQuery<TTable extends BaseTable, TSelection extends SelectedFields>({ db, fields, jsonArrayFields, params, scope, relations, table, }: {
4
5
  db: any;
5
6
  fields: TSelection;
6
7
  jsonArrayFields?: string[];
8
+ /** 必填。与 pg 那套同义,见 backend/scope.ts。 */
9
+ scope: ScopeArg;
7
10
  params: {
8
11
  [field: string]: unknown;
9
12
  orderBy?: keyof BaseTable;
@@ -20,12 +20,14 @@ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol"
20
20
  function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
21
21
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
22
22
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
23
+ import { scopeCondition } from "../../scope.js";
23
24
  import { and, asc, desc, eq, gte, like, inArray, lte, or, sql } from "drizzle-orm";
24
25
  export function getListQuery(_ref) {
25
26
  var db = _ref.db,
26
27
  fields = _ref.fields,
27
28
  jsonArrayFields = _ref.jsonArrayFields,
28
29
  params = _ref.params,
30
+ scope = _ref.scope,
29
31
  relations = _ref.relations,
30
32
  table = _ref.table;
31
33
  var _params$page = params.page,
@@ -175,15 +177,18 @@ export function getListQuery(_ref) {
175
177
  var baseQuery = buildBaseQuery(table, fields, relations);
176
178
 
177
179
  // 构建条件
178
- var conditions = buildConditions(filters, table, relations);
180
+ // 作用域先加,且不受「空值跳过」那条规矩管(见 backend/scope.ts 第 1 条)。
181
+ var scopeSql = scopeCondition(table, scope);
182
+ var conditions = scopeSql ? [scopeSql] : [];
183
+ conditions.push.apply(conditions, _toConsumableArray(buildConditions(filters, table, relations)));
179
184
 
180
185
  // 构建主查询
181
- var query = baseQuery.where(conditions.length > 0 ? and.apply(void 0, _toConsumableArray(conditions)) : undefined).orderBy(buildOrderBy(table, orderBy, orderDir)).limit(pageSize).offset((page - 1) * pageSize);
186
+ var query = baseQuery.where(conditions.length > 0 ? and.apply(void 0, conditions) : undefined).orderBy(buildOrderBy(table, orderBy, orderDir)).limit(pageSize).offset((page - 1) * pageSize);
182
187
 
183
188
  // 构建计数查询(优化后)
184
189
  var countQuery = db.select({
185
190
  count: sql(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["COUNT(DISTINCT ", ")"])), table.id)
186
- }).from(table).where(conditions.length > 0 ? and.apply(void 0, _toConsumableArray(conditions)) : undefined);
191
+ }).from(table).where(conditions.length > 0 ? and.apply(void 0, conditions) : undefined);
187
192
 
188
193
  // 添加关联
189
194
  if (relations !== null && relations !== void 0 && relations.length) {
@@ -10,4 +10,6 @@ export declare const createDeleteOperation: ({ db, getSession, }: {
10
10
  } | undefined>;
11
11
  }) => <B extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>> = import("zod").ZodObject<{
12
12
  id: import("zod").ZodString;
13
- }, import("zod/v4/core").$strip>>({ table, schemas, access, openApiOperation, handler, catch: catchHandler, }: CoreDeleteOperationOptions<BaseTable, B>) => import("next-rest-framework").RouteOperationDefinition<"DELETE">;
13
+ }, import("zod/v4/core").$strip>>({ table, schemas, access, openApiOperation, handler, catch: catchHandler, }: CoreDeleteOperationOptions<BaseTable, B, {
14
+ userId?: string | undefined;
15
+ }>) => import("next-rest-framework").RouteOperationDefinition<"DELETE">;
@@ -8,4 +8,6 @@ export declare const createGetListOperation: ({ db, getSession, }: {
8
8
  getSession(req: NextRequest): Promise<{
9
9
  userId?: string;
10
10
  } | undefined>;
11
- }) => <T extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>, Q extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>({ schemas, access, table, openApiOperation, relations, jsonArrayFields, setParams, handler, catch: catchHandler, }: CoreGetListOperationOptions<T, Q, BaseTable, GetListRelations>) => import("next-rest-framework").RouteOperationDefinition<"GET">;
11
+ }) => <T extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>, Q extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>({ schemas, access, table, openApiOperation, relations, jsonArrayFields, setParams, handler, catch: catchHandler, }: CoreGetListOperationOptions<T, Q, BaseTable, GetListRelations, {
12
+ userId?: string | undefined;
13
+ }>) => import("next-rest-framework").RouteOperationDefinition<"GET">;
@@ -8,4 +8,6 @@ export declare const createGetOperation: ({ getSession, db, }: {
8
8
  getSession(req: NextRequest): Promise<{
9
9
  userId?: string;
10
10
  } | undefined>;
11
- }) => <T extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>, Q extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>({ schemas, access, table, openApiOperation, relations, setParams, jsonArrayFields, handler, catch: catchHandler, }: CoreGetOperationOptions<T, Q, BaseTable, GetListRelations>) => import("next-rest-framework").RouteOperationDefinition<"GET">;
11
+ }) => <T extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>, Q extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>({ schemas, access, table, openApiOperation, relations, setParams, jsonArrayFields, handler, catch: catchHandler, }: CoreGetOperationOptions<T, Q, BaseTable, GetListRelations, {
12
+ userId?: string | undefined;
13
+ }>) => import("next-rest-framework").RouteOperationDefinition<"GET">;
@@ -8,4 +8,6 @@ export declare const createPostOperation: ({ getSession, db, }: {
8
8
  getSession(req: NextRequest): Promise<{
9
9
  userId?: string;
10
10
  } | undefined>;
11
- }) => <IB extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>, OB extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>({ schemas, contentType, openApiOperation, parseBody, setBody, table, handler, catch: catchHandler, }: CorePostOperationOptions<IB, OB, SQLiteTable<import("drizzle-orm/sqlite-core").TableConfig>>) => import("next-rest-framework").RouteOperationDefinition<"POST">;
11
+ }) => <IB extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>, OB extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>({ schemas, access, contentType, openApiOperation, parseBody, setBody, table, handler, catch: catchHandler, }: CorePostOperationOptions<IB, OB, SQLiteTable<import("drizzle-orm/sqlite-core").TableConfig>, {
12
+ userId?: string | undefined;
13
+ }>) => import("next-rest-framework").RouteOperationDefinition<"POST">;
@@ -8,4 +8,6 @@ export declare const createPutOperation: ({ getSession, db, }: {
8
8
  userId?: string;
9
9
  } | undefined>;
10
10
  db?: unknown;
11
- }) => <IB extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>, OB extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>({ schemas, access, openApiOperation, table, setBody, handler, catch: catchHandler, }: CorePutOperationOptions<IB, OB, SQLiteTable<import("drizzle-orm/sqlite-core").TableConfig>>) => import("next-rest-framework").RouteOperationDefinition<"PUT">;
11
+ }) => <IB extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>, OB extends ZodSchema<unknown, unknown, import("zod/v4/core").$ZodTypeInternals<unknown, unknown>>>({ schemas, access, openApiOperation, table, setBody, handler, catch: catchHandler, }: CorePutOperationOptions<IB, OB, SQLiteTable<import("drizzle-orm/sqlite-core").TableConfig>, {
12
+ userId?: string | undefined;
13
+ }>) => import("next-rest-framework").RouteOperationDefinition<"PUT">;
@@ -1,9 +1,11 @@
1
1
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
2
2
  import { BaseTable } from "../types.js";
3
+ import { ScopeArg } from "../scope.js";
3
4
  export declare function createDeleteAction<TTable extends BaseTable>({ table, db, }: {
4
5
  db: NodePgDatabase<Record<string, unknown>>;
5
6
  table: TTable;
6
- }): ({ id, creatorId }: {
7
+ }): ({ id }: {
7
8
  id: string;
8
- creatorId?: string | undefined;
9
+ }, { scope }: {
10
+ scope: ScopeArg;
9
11
  }) => Promise<TTable["$inferSelect"] extends infer T ? T extends TTable["$inferSelect"] ? T extends undefined ? QueryResult<import("drizzle-orm").Assume<this["row"], QueryResultRow>> : T[] : never : never>;
@@ -23,28 +23,22 @@ __export(create_delete_action_exports, {
23
23
  });
24
24
  module.exports = __toCommonJS(create_delete_action_exports);
25
25
  var import_drizzle_orm = require("drizzle-orm");
26
- var import_backend = require("..");
27
- var import_zod = require("zod");
26
+ var import_scope = require("../scope");
28
27
  var import_errors = require("../errors");
29
28
  function createDeleteAction({
30
29
  table,
31
30
  db
32
31
  }) {
33
- return async ({ id, creatorId }) => {
34
- if (creatorId) {
35
- const data = await (0, import_backend.createGetAction)({
36
- db,
37
- table,
38
- bodySchema: import_zod.z.object({
39
- creatorId: import_zod.z.string(),
40
- id: import_zod.z.string()
41
- })
42
- })({ creatorId, id });
43
- if (!data) {
44
- throw new import_errors.HttpError(404, "未找到删除对象,或没有权限");
45
- }
32
+ return async ({ id }, { scope }) => {
33
+ if (!id) {
34
+ throw new import_errors.HttpError(400, "缺少 id");
46
35
  }
47
- return db.delete(table).where((0, import_drizzle_orm.eq)(table.id, id)).returning();
36
+ const guard = (0, import_scope.scopeCondition)(table, scope);
37
+ const rows = await db.delete(table).where(guard ? (0, import_drizzle_orm.and)((0, import_drizzle_orm.eq)(table.id, id), guard) : (0, import_drizzle_orm.eq)(table.id, id)).returning();
38
+ if (rows.length === 0 && scope !== import_scope.NO_SCOPE) {
39
+ throw new import_errors.HttpError(404, "未找到删除对象,或没有权限");
40
+ }
41
+ return rows;
48
42
  };
49
43
  }
50
44
  // Annotate the CommonJS export names for ESM import in node:
@@ -1,10 +1,13 @@
1
1
  import { z, ZodSchema } from "zod";
2
2
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
3
3
  import { BaseTable, GetListRelations } from "../types.js";
4
+ import { ScopeArg } from "../scope.js";
4
5
  export declare function createGetAction<T extends ZodSchema, TTable extends BaseTable>({ bodySchema, db, jsonArrayFields, relations, table, }: {
5
6
  bodySchema: T;
6
7
  db: NodePgDatabase<Record<string, unknown>>;
7
8
  jsonArrayFields?: string[];
8
9
  relations?: GetListRelations;
9
10
  table: TTable;
10
- }): (params: Partial<z.infer<T>> & Record<string, unknown>) => Promise<z.core.output<T> | undefined>;
11
+ }): (params: Partial<z.infer<T>> & Record<string, unknown>, { scope }: {
12
+ scope: ScopeArg;
13
+ }) => Promise<z.core.output<T> | undefined>;
@@ -31,7 +31,7 @@ function createGetAction({
31
31
  relations,
32
32
  table
33
33
  }) {
34
- return async (params) => {
34
+ return async (params, { scope }) => {
35
35
  const fields = {};
36
36
  for (const key of Object.keys(bodySchema.shape)) {
37
37
  const field = table[key];
@@ -45,6 +45,7 @@ function createGetAction({
45
45
  jsonArrayFields,
46
46
  params,
47
47
  relations,
48
+ scope,
48
49
  table
49
50
  });
50
51
  const {