@guren/server 1.0.0-rc.13 → 1.0.0-rc.14

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.
@@ -12,7 +12,7 @@ import { E as Encrypter, A as AppKeyring } from './app-key-CsBfRC_Q.js';
12
12
  import { S as StorageManager } from './StorageManager-oZTHqaza.js';
13
13
  import { H as HealthManager } from './HealthManager-DUyMIzsZ.js';
14
14
  import { S as Scheduler } from './Scheduler-BstvSca7.js';
15
- import { G as Gate } from './Gate-CNkBYf8m.js';
15
+ import { G as Gate } from './Gate-CynjZCtS.js';
16
16
  import { M as Middleware } from './index-9_Jzj5jo.js';
17
17
 
18
18
  declare const CSRF_TOKEN_KEY = "_csrf_token";
@@ -259,7 +259,11 @@ interface SecurityHeadersOptions {
259
259
  referrerPolicy?: string | false;
260
260
  /** X-Permitted-Cross-Domain-Policies header. Set to false to disable. Default: 'none' */
261
261
  crossDomainPolicies?: string | false;
262
- /** Strict-Transport-Security header. Default: false (disabled) */
262
+ /**
263
+ * Strict-Transport-Security header.
264
+ * Default: `{ maxAge: 31536000 }` (1 year) when NODE_ENV is 'production', false otherwise.
265
+ * Browsers ignore HSTS on plain-HTTP responses, so the production default is safe behind TLS terminators.
266
+ */
263
267
  hsts?: HstsOptions | false;
264
268
  }
265
269
  /**
@@ -1383,6 +1387,31 @@ declare class Controller {
1383
1387
  * ```
1384
1388
  */
1385
1389
  protected apiTokenUserId(): string | number;
1390
+ /**
1391
+ * Authorize the current user (or guest) for an ability.
1392
+ * Throws AuthorizationException (403) when denied.
1393
+ *
1394
+ * ORM records are plain objects with no constructor information, so pass
1395
+ * the model class alongside the record to resolve the policy:
1396
+ *
1397
+ * @example
1398
+ * ```typescript
1399
+ * const post = await Post.findOrFail(id)
1400
+ * await this.authorize('update', [Post, post])
1401
+ * await this.authorize('create', Post)
1402
+ * ```
1403
+ */
1404
+ protected authorize(ability: string, ...args: unknown[]): Promise<void>;
1405
+ /**
1406
+ * Check whether the current user (or guest) can perform an ability.
1407
+ *
1408
+ * @example
1409
+ * ```typescript
1410
+ * if (await this.can('update', [Post, post])) { ... }
1411
+ * ```
1412
+ */
1413
+ protected can(ability: string, ...args: unknown[]): Promise<boolean>;
1414
+ private gateUser;
1386
1415
  protected inertia<TPage extends InertiaPageContractLike>(page: TPage, props: InertiaPageProps<TPage>, options?: InertiaResponseOptions): Promise<InertiaResponse<InertiaPageComponent<TPage>, InertiaPageProps<TPage> & ResolvedSharedInertiaProps>>;
1387
1416
  protected inertia<Component extends string, Props extends DefaultInertiaProps>(component: Component, props: Props, options?: InertiaResponseOptions): Promise<InertiaResponse<Component, Props & ResolvedSharedInertiaProps>>;
1388
1417
  protected json<T>(data: T, init?: ResponseInit): Response;
@@ -1773,6 +1802,15 @@ interface RouteDefinition {
1773
1802
  body?: SchemaLike<unknown>;
1774
1803
  output?: SchemaLike<unknown>;
1775
1804
  };
1805
+ /** Named middleware (aliases or groups) applied to this route */
1806
+ middlewareNames?: string[];
1807
+ /** Whether inline (unnamed) middleware handlers are attached */
1808
+ hasInlineMiddleware?: boolean;
1809
+ /** Controller binding when the handler is a [Controller, 'method'] tuple */
1810
+ controller?: {
1811
+ name: string;
1812
+ action: string;
1813
+ };
1776
1814
  summary?: string;
1777
1815
  description?: string;
1778
1816
  tags?: string[];
@@ -1,4 +1,4 @@
1
- import { C as Container } from './Application-DtWDHXr1.js';
1
+ import { C as Container } from './Application-CsylYL26.js';
2
2
 
3
3
  /**
4
4
  * Parsed argument definition.
@@ -213,6 +213,11 @@ declare class Gate {
213
213
  check(ability: string, user: AuthUser | null, ...args: unknown[]): Promise<boolean>;
214
214
  /**
215
215
  * Check a policy for the given ability.
216
+ *
217
+ * The subject may be a class instance (policy resolved via its constructor)
218
+ * or a `[ModelClass, record]` / `['key', record]` tuple. The tuple form is
219
+ * required for plain records returned by the ORM, which carry no constructor
220
+ * information.
216
221
  */
217
222
  protected checkPolicy(ability: string, user: AuthUser | null, model: unknown, additionalArgs: unknown[]): Promise<boolean | undefined>;
218
223
  /**
@@ -566,7 +566,7 @@ var SessionGuard = class {
566
566
  if (!this.currentSession || !this.provider.setRememberToken) {
567
567
  return;
568
568
  }
569
- const token = globalThis.crypto.randomUUID();
569
+ const token = generateToken(32);
570
570
  await this.provider.setRememberToken?.(user, token);
571
571
  this.currentSession.set(this.rememberSessionKey(), token);
572
572
  }
@@ -576,6 +576,7 @@ var SessionGuard = class {
576
576
  if (!session) {
577
577
  throw new Error("SessionGuard: session middleware is required to use the session guard.");
578
578
  }
579
+ session.regenerate();
579
580
  const identifier = this.provider.getId(castUser);
580
581
  session.set(this.sessionKey(), identifier);
581
582
  this.cachedUser = castUser;
@@ -800,7 +801,7 @@ var NodeHasher = class {
800
801
  }
801
802
  };
802
803
 
803
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/entity.js
804
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/entity.js
804
805
  var entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind");
805
806
  function is(value, type) {
806
807
  if (!value || typeof value !== "object") return false;
@@ -814,12 +815,16 @@ function is(value, type) {
814
815
  return false;
815
816
  }
816
817
 
817
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/column-common.js
818
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/column-common.js
818
819
  var OriginalColumn = /* @__PURE__ */ Symbol.for("drizzle:OriginalColumn");
819
820
 
820
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/column.js
821
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/column.js
822
+ var noop = (v) => v;
823
+ noop.isNoop = true;
821
824
  var Column = class {
822
825
  static [entityKind] = "Column";
826
+ /** @internal */
827
+ codec;
823
828
  name;
824
829
  keyAsName;
825
830
  primary;
@@ -869,12 +874,13 @@ var Column = class {
869
874
  this.length = config["length"];
870
875
  this.isLengthExact = config["isLengthExact"];
871
876
  }
872
- mapFromDriverValue(value) {
873
- return value;
874
- }
875
- mapToDriverValue(value) {
876
- return value;
877
+ mapFromDriverValue = noop;
878
+ mapToDriverValue = noop;
879
+ /** @internal */
880
+ postBuild() {
881
+ return this;
877
882
  }
883
+ /** @internal */
878
884
  shouldDisableInsert() {
879
885
  return this.config.generated !== void 0 && this.config.generated.type !== "byDefault";
880
886
  }
@@ -884,10 +890,28 @@ var Column = class {
884
890
  }
885
891
  };
886
892
 
887
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/table.utils.js
893
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/subquery.js
894
+ var Subquery = class {
895
+ static [entityKind] = "Subquery";
896
+ constructor(sql2, fields, alias, isWith = false, usedTables = []) {
897
+ this._ = {
898
+ brand: "Subquery",
899
+ sql: sql2,
900
+ selectedFields: fields,
901
+ alias,
902
+ isWith,
903
+ usedTables
904
+ };
905
+ }
906
+ };
907
+ var WithSubquery = class extends Subquery {
908
+ static [entityKind] = "WithSubquery";
909
+ };
910
+
911
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/table.utils.js
888
912
  var TableName = /* @__PURE__ */ Symbol.for("drizzle:Name");
889
913
 
890
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/table.js
914
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/table.js
891
915
  var TableSchema = /* @__PURE__ */ Symbol.for("drizzle:Schema");
892
916
  var TableColumns = /* @__PURE__ */ Symbol.for("drizzle:Columns");
893
917
  var ExtraConfigColumns = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigColumns");
@@ -943,33 +967,15 @@ var Table = class {
943
967
  }
944
968
  };
945
969
 
946
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/subquery.js
947
- var Subquery = class {
948
- static [entityKind] = "Subquery";
949
- constructor(sql2, fields, alias, isWith = false, usedTables = []) {
950
- this._ = {
951
- brand: "Subquery",
952
- sql: sql2,
953
- selectedFields: fields,
954
- alias,
955
- isWith,
956
- usedTables
957
- };
958
- }
959
- };
960
- var WithSubquery = class extends Subquery {
961
- static [entityKind] = "WithSubquery";
962
- };
963
-
964
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/tracing.js
970
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/tracing.js
965
971
  var tracer = { startActiveSpan(name, fn) {
966
972
  return fn();
967
973
  } };
968
974
 
969
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/view-common.js
975
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/view-common.js
970
976
  var ViewBaseConfig = /* @__PURE__ */ Symbol.for("drizzle:ViewBaseConfig");
971
977
 
972
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/sql/sql.js
978
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/sql/sql.js
973
979
  var FakePrimitiveParam = class {
974
980
  static [entityKind] = "FakePrimitiveParam";
975
981
  };
@@ -991,6 +997,23 @@ function mergeQueries(queries) {
991
997
  }
992
998
  return result;
993
999
  }
1000
+ function _mergeQueries(queries) {
1001
+ const result = {
1002
+ sql: "",
1003
+ params: []
1004
+ };
1005
+ const sqls = [];
1006
+ for (const query of queries) {
1007
+ sqls.push(query.sql);
1008
+ result.params.push(...query.params);
1009
+ if (query.typings?.length) {
1010
+ if (!result.typings) result.typings = [];
1011
+ result.typings.push(...query.typings);
1012
+ }
1013
+ }
1014
+ result._sql = Object.assign(sqls, { raw: sqls });
1015
+ return result;
1016
+ }
994
1017
  var StringChunk = class {
995
1018
  static [entityKind] = "StringChunk";
996
1019
  value;
@@ -1035,8 +1058,8 @@ var SQL = class SQL2 {
1035
1058
  inlineParams: _config.inlineParams || this.shouldInlineParams,
1036
1059
  paramStartIndex: _config.paramStartIndex || { value: 0 }
1037
1060
  });
1038
- const { casing, escapeName, escapeParam, prepareTyping, inlineParams, paramStartIndex, invokeSource } = config;
1039
- return mergeQueries(chunks.map((chunk) => {
1061
+ const { escapeName, escapeParam, prepareTyping, codecs, inlineParams, paramStartIndex, invokeSource } = config;
1062
+ const mappedChunks = chunks.map((chunk) => {
1040
1063
  if (is(chunk, StringChunk)) return {
1041
1064
  sql: chunk.value.join(""),
1042
1065
  params: []
@@ -1075,7 +1098,7 @@ var SQL = class SQL2 {
1075
1098
  };
1076
1099
  }
1077
1100
  if (is(chunk, Column)) {
1078
- const columnName = casing.getColumnCasing(chunk);
1101
+ const columnName = chunk.name;
1079
1102
  if (_config.invokeSource === "indexes") return {
1080
1103
  sql: escapeName(columnName),
1081
1104
  params: []
@@ -1095,21 +1118,33 @@ var SQL = class SQL2 {
1095
1118
  };
1096
1119
  }
1097
1120
  if (is(chunk, Param)) {
1098
- if (is(chunk.value, Placeholder)) return {
1099
- sql: escapeParam(paramStartIndex.value++, chunk),
1100
- params: [chunk],
1101
- typings: ["none"]
1102
- };
1103
- const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
1104
- if (is(mappedValue, SQL2)) return this.buildQueryFromSourceParams([mappedValue], config);
1121
+ if (is(chunk.value, SQL2)) return this.buildQueryFromSourceParams([chunk.value], config);
1122
+ const useCodecs = codecs && is(chunk.encoder, Column);
1123
+ if (is(chunk.value, Placeholder)) {
1124
+ const escaped2 = escapeParam(paramStartIndex.value++, chunk);
1125
+ chunk.codec = useCodecs ? (value) => codecs.apply(chunk.encoder, "normalizeParam", value) : void 0;
1126
+ return {
1127
+ sql: useCodecs ? codecs.apply(chunk.encoder, "castParam", escaped2) : escaped2,
1128
+ params: [chunk],
1129
+ typings: ["none"]
1130
+ };
1131
+ }
1132
+ let mappedValue;
1133
+ if (chunk.value === null) mappedValue = chunk.value;
1134
+ else {
1135
+ mappedValue = chunk.encoder.mapToDriverValue.isNoop ? chunk.value : chunk.encoder.mapToDriverValue(chunk.value);
1136
+ if (is(mappedValue, SQL2)) return this.buildQueryFromSourceParams([mappedValue], config);
1137
+ if (useCodecs) mappedValue = codecs.apply(chunk.encoder, "normalizeParam", mappedValue);
1138
+ }
1105
1139
  if (inlineParams) return {
1106
1140
  sql: this.mapInlineParam(mappedValue, config),
1107
1141
  params: []
1108
1142
  };
1109
1143
  let typings = ["none"];
1110
1144
  if (prepareTyping) typings = [prepareTyping(chunk.encoder)];
1145
+ const escaped = escapeParam(paramStartIndex.value++, mappedValue);
1111
1146
  return {
1112
- sql: escapeParam(paramStartIndex.value++, mappedValue),
1147
+ sql: useCodecs ? codecs.apply(chunk.encoder, "castParam", escaped) : escaped,
1113
1148
  params: [mappedValue],
1114
1149
  typings
1115
1150
  };
@@ -1162,7 +1197,9 @@ var SQL = class SQL2 {
1162
1197
  params: [chunk],
1163
1198
  typings: ["none"]
1164
1199
  };
1165
- }));
1200
+ });
1201
+ if (_config.tagged) return _mergeQueries(mappedChunks);
1202
+ return mergeQueries(mappedChunks);
1166
1203
  }
1167
1204
  mapInlineParam(chunk, { escapeString }) {
1168
1205
  if (chunk === null) return "null";
@@ -1214,7 +1251,9 @@ function isDriverValueEncoder(value) {
1214
1251
  return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
1215
1252
  }
1216
1253
  var noopDecoder = { mapFromDriverValue: (value) => value };
1254
+ noopDecoder.mapFromDriverValue.isNoop = true;
1217
1255
  var noopEncoder = { mapToDriverValue: (value) => value };
1256
+ noopEncoder.mapToDriverValue.isNoop = true;
1218
1257
  var noopMapper = {
1219
1258
  ...noopDecoder,
1220
1259
  ...noopEncoder
@@ -1226,9 +1265,10 @@ var Param = class {
1226
1265
  * @param value - Parameter value
1227
1266
  * @param encoder - Encoder to convert the value to a driver parameter
1228
1267
  */
1229
- constructor(value, encoder = noopEncoder) {
1268
+ constructor(value, encoder = noopEncoder, codec) {
1230
1269
  this.value = value;
1231
1270
  this.encoder = encoder;
1271
+ this.codec = codec;
1232
1272
  }
1233
1273
  getSQL() {
1234
1274
  return new SQL([this]);
@@ -1274,7 +1314,58 @@ function sql(strings, ...params) {
1274
1314
  return new Param(value, encoder);
1275
1315
  }
1276
1316
  _sql.param = param;
1317
+ function comment(input) {
1318
+ const encoded = sqlCommenter(input);
1319
+ if (!encoded.length) return void 0;
1320
+ return sql.raw(encoded);
1321
+ }
1322
+ _sql.comment = comment;
1277
1323
  })(sql || (sql = {}));
1324
+ function sqlCommenter(input) {
1325
+ const encoded = sqlCommenter.encodeInput(input);
1326
+ if (!encoded.length) return "";
1327
+ return `/*${encoded}*/`;
1328
+ }
1329
+ (function(_sqlCommenter) {
1330
+ function merge(input1, input2) {
1331
+ let encoded;
1332
+ if (typeof input1 === "object" && typeof input2 === "object") encoded = encodeInput({
1333
+ ...input1,
1334
+ ...input2
1335
+ });
1336
+ else if (input1 && input2) encoded = [encodeInput(input1), encodeInput(input2)].filter((i) => i.length).join(",");
1337
+ else if (input2) encoded = encodeInput(input2);
1338
+ else if (input1) encoded = encodeInput(input1);
1339
+ else return "";
1340
+ if (!encoded.length) return "";
1341
+ return `/*${encoded}*/`;
1342
+ }
1343
+ _sqlCommenter.merge = merge;
1344
+ function encodeInput(input) {
1345
+ if (typeof input === "string") {
1346
+ if (!input.length) return input;
1347
+ return sanitizeStringInput(input);
1348
+ }
1349
+ const parts = [];
1350
+ for (const [key, value] of Object.entries(input)) {
1351
+ if (value === null || value === void 0 || value === "") continue;
1352
+ const encodedKey = sanitizeObjectElement(key);
1353
+ const encodedValue = sanitizeObjectElement(String(value));
1354
+ parts.push(`${encodedKey}='${encodedValue}'`);
1355
+ }
1356
+ if (!parts.length) return "";
1357
+ return parts.sort().join(",");
1358
+ }
1359
+ _sqlCommenter.encodeInput = encodeInput;
1360
+ function sanitizeObjectElement(key) {
1361
+ return encodeURIComponent(key).replace(/'/g, `\\'`);
1362
+ }
1363
+ _sqlCommenter.sanitizeObjectElement = sanitizeObjectElement;
1364
+ function sanitizeStringInput(input) {
1365
+ return input.replace(/\/\*/g, "/ *").replace(/\*\//g, "* /");
1366
+ }
1367
+ _sqlCommenter.sanitizeStringInput = sanitizeStringInput;
1368
+ })(sqlCommenter || (sqlCommenter = {}));
1278
1369
  (function(_SQL) {
1279
1370
  class Aliased {
1280
1371
  static [entityKind] = "SQL.Aliased";
@@ -1351,7 +1442,7 @@ Subquery.prototype.getSQL = function() {
1351
1442
  return new SQL([this]);
1352
1443
  };
1353
1444
 
1354
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/sql/expressions/conditions.js
1445
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/sql/expressions/conditions.js
1355
1446
  function bindIfParam(value, column) {
1356
1447
  if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) return new Param(value, column);
1357
1448
  return value;
@@ -1368,7 +1459,7 @@ function and(...unfilteredConditions) {
1368
1459
  if (conditions.length === 1) return new SQL(conditions);
1369
1460
  return new SQL([
1370
1461
  new StringChunk("("),
1371
- sql.join(conditions, new StringChunk(" and ")),
1462
+ sql.join(conditions.map((c) => sql`(${c})`), new StringChunk(" and ")),
1372
1463
  new StringChunk(")")
1373
1464
  ]);
1374
1465
  }
@@ -1378,7 +1469,7 @@ function or(...unfilteredConditions) {
1378
1469
  if (conditions.length === 1) return new SQL(conditions);
1379
1470
  return new SQL([
1380
1471
  new StringChunk("("),
1381
- sql.join(conditions, new StringChunk(" or ")),
1472
+ sql.join(conditions.map((c) => sql`(${c})`), new StringChunk(" or ")),
1382
1473
  new StringChunk(")")
1383
1474
  ]);
1384
1475
  }
@@ -1418,7 +1509,7 @@ function like(column, value) {
1418
1509
  return sql`${column} like ${value}`;
1419
1510
  }
1420
1511
 
1421
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/sql/expressions/select.js
1512
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/sql/expressions/select.js
1422
1513
  function asc(column) {
1423
1514
  return sql`${column} asc`;
1424
1515
  }
@@ -1426,7 +1517,7 @@ function desc(column) {
1426
1517
  return sql`${column} desc`;
1427
1518
  }
1428
1519
 
1429
- // ../../node_modules/.bun/drizzle-orm@1.0.0-beta.18-7eb39f0+0354db235c5ceb35/node_modules/drizzle-orm/sql/functions/aggregate.js
1520
+ // ../../node_modules/.bun/drizzle-orm@1.0.0-rc.1+6cb67a8f81be6bcf/node_modules/drizzle-orm/sql/functions/aggregate.js
1430
1521
  function count(expression) {
1431
1522
  return sql`count(${expression || sql.raw("*")})`.mapWith(Number);
1432
1523
  }
@@ -4426,7 +4517,7 @@ var Flush = bytes_default().H().end();
4426
4517
  var SSLRequest = bytes_default().i32(8).i32(80877103).end(8);
4427
4518
  var ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]);
4428
4519
  var DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end();
4429
- var noop = () => {
4520
+ var noop2 = () => {
4430
4521
  };
4431
4522
  var retryRoutines = /* @__PURE__ */ new Set([
4432
4523
  "FetchPreparedStatement",
@@ -4471,7 +4562,7 @@ var errorFields = {
4471
4562
  82: "routine"
4472
4563
  // R
4473
4564
  };
4474
- function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
4565
+ function Connection(options, queues = {}, { onopen = noop2, onend = noop2, onclose = noop2 } = {}) {
4475
4566
  const {
4476
4567
  sslnegotiation,
4477
4568
  ssl,
@@ -4954,7 +5045,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4954
5045
  return query.resolve(query.statement), write(Sync);
4955
5046
  }
4956
5047
  async function Authentication(x, type = x.readUInt32BE(5)) {
4957
- (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop)(x, type);
5048
+ (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop2)(x, type);
4958
5049
  }
4959
5050
  async function AuthenticationCleartextPassword() {
4960
5051
  const payload = await Pass();
@@ -5241,7 +5332,7 @@ function xor(a, b2) {
5241
5332
  function timer(fn, seconds) {
5242
5333
  seconds = typeof seconds === "function" ? seconds() : seconds;
5243
5334
  if (!seconds)
5244
- return { cancel: noop, start: noop };
5335
+ return { cancel: noop2, start: noop2 };
5245
5336
  let timer2;
5246
5337
  return {
5247
5338
  cancel() {
@@ -5259,7 +5350,7 @@ function timer(fn, seconds) {
5259
5350
  }
5260
5351
 
5261
5352
  // ../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/subscribe.js
5262
- var noop2 = () => {
5353
+ var noop3 = () => {
5263
5354
  };
5264
5355
  function Subscribe(postgres2, options) {
5265
5356
  const subscribers = /* @__PURE__ */ new Map(), slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
@@ -5296,7 +5387,7 @@ function Subscribe(postgres2, options) {
5296
5387
  return close();
5297
5388
  };
5298
5389
  return subscribe;
5299
- async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) {
5390
+ async function subscribe(event, fn, onsubscribe = noop3, onerror = noop3) {
5300
5391
  event = parseEvent(event);
5301
5392
  if (!connection2)
5302
5393
  connection2 = init(sql2, slot, options.publications);
@@ -1,5 +1,5 @@
1
- import { f as Policy$1, A as AuthUser, a as AuthorizationResponse, G as Gate, b as AuthorizeOptions } from '../Gate-CNkBYf8m.js';
2
- export { c as GateCallback, d as GateDefinition, e as GateOptions, P as PolicyClass, g as PolicyMethod, h as PolicyRegistration, i as ResourceAction, R as Response, j as ResponseBuilder, k as authorize, l as can, m as cannot, n as createGate, o as defineGate, p as getGate, s as setGate } from '../Gate-CNkBYf8m.js';
1
+ import { f as Policy$1, A as AuthUser, a as AuthorizationResponse, G as Gate, b as AuthorizeOptions } from '../Gate-CynjZCtS.js';
2
+ export { c as GateCallback, d as GateDefinition, e as GateOptions, P as PolicyClass, g as PolicyMethod, h as PolicyRegistration, i as ResourceAction, R as Response, j as ResponseBuilder, k as authorize, l as can, m as cannot, n as createGate, o as defineGate, p as getGate, s as setGate } from '../Gate-CynjZCtS.js';
3
3
  import { Context } from 'hono';
4
4
  import { M as Middleware } from '../index-9_Jzj5jo.js';
5
5
 
@@ -364,13 +364,29 @@ var Gate = class {
364
364
  }
365
365
  /**
366
366
  * Check a policy for the given ability.
367
+ *
368
+ * The subject may be a class instance (policy resolved via its constructor)
369
+ * or a `[ModelClass, record]` / `['key', record]` tuple. The tuple form is
370
+ * required for plain records returned by the ORM, which carry no constructor
371
+ * information.
367
372
  */
368
373
  async checkPolicy(ability, user, model, additionalArgs) {
369
- const modelConstructor = model?.constructor;
370
- if (!modelConstructor) {
374
+ let policyKey;
375
+ let subject = model;
376
+ let hasSubject = true;
377
+ if (Array.isArray(model) && model.length === 2 && (typeof model[0] === "function" || typeof model[0] === "string")) {
378
+ policyKey = model[0];
379
+ subject = model[1];
380
+ } else if (typeof model === "function") {
381
+ policyKey = model;
382
+ hasSubject = false;
383
+ } else {
384
+ policyKey = model?.constructor;
385
+ }
386
+ if (!policyKey) {
371
387
  return void 0;
372
388
  }
373
- const policyClass = this.policies.get(modelConstructor);
389
+ const policyClass = this.policies.get(policyKey);
374
390
  if (!policyClass) {
375
391
  return void 0;
376
392
  }
@@ -383,7 +399,7 @@ var Gate = class {
383
399
  }
384
400
  const method = policy[ability];
385
401
  if (typeof method === "function") {
386
- return method.call(policy, user, model, ...additionalArgs);
402
+ return hasSubject ? method.call(policy, user, subject, ...additionalArgs) : method.call(policy, user, ...additionalArgs);
387
403
  }
388
404
  return void 0;
389
405
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as ErrorResponse, S as ServiceProvider, C as Container, c as ServiceBindings, Q as QueueManager, N as NotificationManager } from './Application-DtWDHXr1.js';
2
- export { A as Application, d as ApplicationListenOptions, e as AuthPayload, f as CSRF_FORM_FIELD, g as CSRF_HEADER_NAME, h as CSRF_TOKEN_KEY, P as ContainerProvider, i as ContextualBinding, j as ContextualBindingBuilder, k as ContextualNeedsBuilder, m as Controller, n as ControllerInertiaProps, o as CsrfOptions, p as DatabaseChannelOptions, q as DatabaseNotification, r as ExceptionClass, t as ExceptionHandler, u as ExceptionHandlerOptions, v as ExceptionRenderer, w as ExceptionReporter, F as FailedJob, H as HostAuthorizationOptions, x as HstsOptions, I as InertiaOptions, y as InertiaPagePayload, z as InertiaResponse, B as InertiaSharedProps, J as InertiaSsrContext, K as InertiaSsrOptions, L as InertiaSsrRenderer, M as InertiaSsrResult, O as InferInertiaProps, R as Job, T as JobClass, U as JobFailureHandler, V as JobHandler, W as JobOptions, X as Notifiable, Y as Notification, Z as NotificationAttachment, _ as NotificationChannel, $ as NotificationChannelFactory, a0 as NotificationClass, a1 as NotificationMailMessage, a2 as NotificationManagerOptions, a3 as ProviderManager, a4 as QueueConfig, a5 as QueueDriver, a6 as QueueDriverFactory, a7 as QueuedJob, a8 as RendererRegistration, a9 as ResolvedSharedInertiaProps, aa as ResourceRouteOptions, ab as RouteBuilder, ac as RouteContractOptions, ad as RouteDefinition, ae as RouteOpenApiMetadata, af as RouteResourceAction, ag as Router, ah as SecurityHeadersOptions, ai as SentNotification, aj as ServiceBinding, ak as ServiceClass, al as ServiceFactory, am as ServiceProviderClass, an as ServiceProviderConstructor, ao as ServiceProviderOptions, ap as SharedInertiaPropsResolver, aq as SlackAttachment, ar as SlackBlock, as as SlackMessage, at as VALIDATED_DATA_KEY, au as ValidateRequestOptions, av as ValidationSchema, aw as WorkerOptions, ax as abort, ay as abortIf, az as abortUnless, aA as clearJobRegistry, aB as createApp, aC as createContainer, aD as createCsrfMiddleware, aE as createExceptionHandler, aF as createHostAuthorizationMiddleware, aG as createNotificationManager, aH as createQueueManager, aI as createSecurityHeaders, aJ as csrfField, aK as formatValidationErrors, aL as getContainer, aM as getCsrfToken, aN as getExceptionHandler, aO as getJob, aP as getNotificationManager, aQ as getQueueDriver, aR as getRegisteredJobs, aS as getValidatedData, aT as inertia, aU as parseRequestPayload, aV as registerJob, aW as resolve, aX as setContainer, aY as setExceptionHandler, aZ as setInertiaSharedProps, a_ as setNotificationManager, a$ as setQueueDriver, b0 as validate, b1 as validateRequest, b2 as validateRequestWith, b3 as validateSafe, b4 as verifyCsrfToken } from './Application-DtWDHXr1.js';
1
+ import { E as ErrorResponse, S as ServiceProvider, C as Container, c as ServiceBindings, Q as QueueManager, N as NotificationManager } from './Application-CsylYL26.js';
2
+ export { A as Application, d as ApplicationListenOptions, e as AuthPayload, f as CSRF_FORM_FIELD, g as CSRF_HEADER_NAME, h as CSRF_TOKEN_KEY, P as ContainerProvider, i as ContextualBinding, j as ContextualBindingBuilder, k as ContextualNeedsBuilder, m as Controller, n as ControllerInertiaProps, o as CsrfOptions, p as DatabaseChannelOptions, q as DatabaseNotification, r as ExceptionClass, t as ExceptionHandler, u as ExceptionHandlerOptions, v as ExceptionRenderer, w as ExceptionReporter, F as FailedJob, H as HostAuthorizationOptions, x as HstsOptions, I as InertiaOptions, y as InertiaPagePayload, z as InertiaResponse, B as InertiaSharedProps, J as InertiaSsrContext, K as InertiaSsrOptions, L as InertiaSsrRenderer, M as InertiaSsrResult, O as InferInertiaProps, R as Job, T as JobClass, U as JobFailureHandler, V as JobHandler, W as JobOptions, X as Notifiable, Y as Notification, Z as NotificationAttachment, _ as NotificationChannel, $ as NotificationChannelFactory, a0 as NotificationClass, a1 as NotificationMailMessage, a2 as NotificationManagerOptions, a3 as ProviderManager, a4 as QueueConfig, a5 as QueueDriver, a6 as QueueDriverFactory, a7 as QueuedJob, a8 as RendererRegistration, a9 as ResolvedSharedInertiaProps, aa as ResourceRouteOptions, ab as RouteBuilder, ac as RouteContractOptions, ad as RouteDefinition, ae as RouteOpenApiMetadata, af as RouteResourceAction, ag as Router, ah as SecurityHeadersOptions, ai as SentNotification, aj as ServiceBinding, ak as ServiceClass, al as ServiceFactory, am as ServiceProviderClass, an as ServiceProviderConstructor, ao as ServiceProviderOptions, ap as SharedInertiaPropsResolver, aq as SlackAttachment, ar as SlackBlock, as as SlackMessage, at as VALIDATED_DATA_KEY, au as ValidateRequestOptions, av as ValidationSchema, aw as WorkerOptions, ax as abort, ay as abortIf, az as abortUnless, aA as clearJobRegistry, aB as createApp, aC as createContainer, aD as createCsrfMiddleware, aE as createExceptionHandler, aF as createHostAuthorizationMiddleware, aG as createNotificationManager, aH as createQueueManager, aI as createSecurityHeaders, aJ as csrfField, aK as formatValidationErrors, aL as getContainer, aM as getCsrfToken, aN as getExceptionHandler, aO as getJob, aP as getNotificationManager, aQ as getQueueDriver, aR as getRegisteredJobs, aS as getValidatedData, aT as inertia, aU as parseRequestPayload, aV as registerJob, aW as resolve, aX as setContainer, aY as setExceptionHandler, aZ as setInertiaSharedProps, a_ as setNotificationManager, a$ as setQueueDriver, b0 as validate, b1 as validateRequest, b2 as validateRequestWith, b3 as validateSafe, b4 as verifyCsrfToken } from './Application-CsylYL26.js';
3
3
  import * as hono from 'hono';
4
4
  import { Context, MiddlewareHandler } from 'hono';
5
5
  export { Context } from 'hono';
@@ -35,10 +35,10 @@ export { DatabaseChannel, MailChannel, MailChannelOptions, MemoryChannel, SlackC
35
35
  import { B as BroadcastManager } from './BroadcastManager-AkIWUGJo.js';
36
36
  export { A as AuthMiddlewareOptions, a as BroadcastDriver, b as BroadcastDriverFactory, c as BroadcastEvent, d as BroadcastManagerOptions, e as BroadcastableEvent, C as Channel, f as ChannelAuthorizer, g as ChannelRegistration, P as PresenceBroadcastDriver, h as PresenceChannel, i as PresenceChannelAuthorizer, j as PresenceMember, k as PrivateChannel, S as SSEClient, l as SSEMiddlewareOptions, W as WebSocketClient, m as createBroadcastManager, n as getBroadcastManager, s as setBroadcastManager } from './BroadcastManager-AkIWUGJo.js';
37
37
  export { RedisClient as BroadcastRedisClient, RedisDriverOptions as BroadcastRedisDriverOptions, MemoryDriver as MemoryBroadcastDriver, RedisDriver as RedisBroadcastDriver, createTypedBroadcaster } from './broadcasting/index.js';
38
- import { I as InputInterface, P as ParsedSignature, O as OptionDefinition, a as CommandInstance, b as OutputInterface } from './ConsoleKernel-CqCVrdZs.js';
39
- export { A as ArgumentDefinition, c as CommandClass, C as ConsoleKernel, d as ConsoleKernelOptions, e as ProgressInterface, f as PromptInterface, S as ScheduledCommand, g as createConsoleKernel } from './ConsoleKernel-CqCVrdZs.js';
38
+ import { I as InputInterface, P as ParsedSignature, O as OptionDefinition, a as CommandInstance, b as OutputInterface } from './ConsoleKernel-BsbMQ38T.js';
39
+ export { A as ArgumentDefinition, c as CommandClass, C as ConsoleKernel, d as ConsoleKernelOptions, e as ProgressInterface, f as PromptInterface, S as ScheduledCommand, g as createConsoleKernel } from './ConsoleKernel-BsbMQ38T.js';
40
40
  import * as readline from 'readline';
41
- export { R as AuthResponse, A as AuthUser, a as AuthorizationResponse, b as AuthorizeOptions, G as Gate, c as GateCallback, d as GateDefinition, e as GateOptions, P as PolicyClass, f as PolicyInterface, g as PolicyMethod, h as PolicyRegistration, i as ResourceAction, j as ResponseBuilder, k as authorizeAbility, l as can, m as cannot, n as createGate, o as defineGate, p as getGate, s as setGate } from './Gate-CNkBYf8m.js';
41
+ export { R as AuthResponse, A as AuthUser, a as AuthorizationResponse, b as AuthorizeOptions, G as Gate, c as GateCallback, d as GateDefinition, e as GateOptions, P as PolicyClass, f as PolicyInterface, g as PolicyMethod, h as PolicyRegistration, i as ResourceAction, j as ResponseBuilder, k as authorizeAbility, l as can, m as cannot, n as createGate, o as defineGate, p as getGate, s as setGate } from './Gate-CynjZCtS.js';
42
42
  export { AuthorizedContext, Policy, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, definePolicy, withAuthorization } from './authorization/index.js';
43
43
  export { A as AppKeyring, D as DecryptOptions, a as EncryptOptions, b as EncryptedPayload, E as Encrypter, c as EncrypterConfig, H as HashAlgorithm, d as HmacOptions, P as PasswordHashOptions, R as RandomStringOptions, e as createEncrypter, f as decrypt, g as deriveAppKey, h as deriveAppKeyring, i as encrypt, j as generateAppKey, k as generateKey, l as getAppKeyringFromEnv, m as getEncrypter, n as normalizeAppKey, p as parseAppKey, o as parsePreviousAppKeys, s as setEncrypter } from './app-key-CsBfRC_Q.js';
44
44
  export { MessageSigner, SignMessageOptions, SignedMessageClaims, SignedUrlOptions, VerifySignedMessageOptions, VerifySignedUrlOptions, check as checkHash, generateOtp, generatePassword, generateSlug, hash, hashPassword, hmac, md5, needsRehash, pick, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, sample, secureCompare, sha256, sha512, shuffle, signUrl, urlSafeToken, uuid, verifyHmac, verifyPassword, verifySignedUrl } from './encryption/index.js';
@@ -160,6 +160,17 @@ interface RateLimitOptions {
160
160
  * @default 'rl:'
161
161
  */
162
162
  keyPrefix?: string;
163
+ /**
164
+ * Trust reverse-proxy headers for client IP resolution, checked in order:
165
+ * `CF-Connecting-IP`, `True-Client-IP`, `X-Real-IP`, then the first entry
166
+ * of `X-Forwarded-For`. Falls back to `server.requestIP()` when none are set.
167
+ *
168
+ * Enable ONLY when every request passes through a proxy that sets or strips
169
+ * these headers — on direct deployments clients can spoof them to bypass
170
+ * per-client limits. Ignored when a custom `keyGenerator` is supplied.
171
+ * @default false
172
+ */
173
+ trustProxy?: boolean;
163
174
  }
164
175
  /**
165
176
  * Create a rate limiting middleware.
@@ -732,11 +743,6 @@ declare class MethodNotAllowedException extends HttpException {
732
743
  static forMethod(method: string, allowedMethods: string[]): MethodNotAllowedException;
733
744
  }
734
745
 
735
- /**
736
- * Generate a production-friendly HTML error page.
737
- * Shows status code, a generic message, and a link back to the home page.
738
- * No stack traces or internal details are exposed.
739
- */
740
746
  declare function renderErrorPage(statusCode: number, message?: string): string;
741
747
 
742
748
  type ViewRenderer = (template: string, props: Record<string, unknown>) => Response | Promise<Response>;
@@ -868,7 +874,9 @@ declare class SchedulingServiceProvider extends ServiceProvider {
868
874
  }
869
875
 
870
876
  /**
871
- * Binds the Gate as a singleton in the container.
877
+ * Binds the Gate as a singleton in the container and exposes it as the
878
+ * global gate so `getGate()`, `can()`, and controller authorization helpers
879
+ * work without manual wiring.
872
880
  */
873
881
  declare class AuthorizationServiceProvider extends ServiceProvider {
874
882
  register(): void;