@rebasepro/server-core 0.7.0 → 0.9.0
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/README.md +2 -2
- package/dist/api/ast-schema-editor.d.ts +21 -0
- package/dist/api/collections_for_test/callbacks_test_collection.d.ts +2 -0
- package/dist/api/errors.d.ts +53 -0
- package/dist/api/index.d.ts +7 -0
- package/dist/api/logs-routes.d.ts +37 -0
- package/dist/api/openapi-generator.d.ts +16 -0
- package/dist/api/rest/api-generator.d.ts +68 -0
- package/{src/api/rest/index.ts → dist/api/rest/index.d.ts} +0 -1
- package/dist/api/rest/query-parser.d.ts +6 -0
- package/dist/api/schema-editor-routes.d.ts +3 -0
- package/dist/api/types.d.ts +56 -0
- package/dist/auth/adapter-middleware.d.ts +43 -0
- package/dist/auth/admin-roles-route.d.ts +18 -0
- package/dist/auth/admin-user-ops.d.ts +79 -0
- package/dist/auth/admin-users-route.d.ts +28 -0
- package/dist/auth/api-keys/api-key-middleware.d.ts +39 -0
- package/{src/auth/api-keys/api-key-permission-guard.ts → dist/auth/api-keys/api-key-permission-guard.d.ts} +2 -34
- package/dist/auth/api-keys/api-key-routes.d.ts +20 -0
- package/dist/auth/api-keys/api-key-store.d.ts +35 -0
- package/{src/auth/api-keys/api-key-types.ts → dist/auth/api-keys/api-key-types.d.ts} +0 -6
- package/{src/auth/api-keys/index.ts → dist/auth/api-keys/index.d.ts} +2 -22
- package/dist/auth/apple-oauth.d.ts +30 -0
- package/{src/auth/auth-hooks.ts → dist/auth/auth-hooks.d.ts} +15 -73
- package/dist/auth/bitbucket-oauth.d.ts +11 -0
- package/dist/auth/builtin-auth-adapter.d.ts +55 -0
- package/dist/auth/cookie-utils.d.ts +32 -0
- package/{src/auth/crypto-utils.ts → dist/auth/crypto-utils.d.ts} +1 -16
- package/dist/auth/custom-auth-adapter.d.ts +39 -0
- package/dist/auth/discord-oauth.d.ts +14 -0
- package/dist/auth/facebook-oauth.d.ts +14 -0
- package/dist/auth/github-oauth.d.ts +15 -0
- package/dist/auth/gitlab-oauth.d.ts +13 -0
- package/dist/auth/google-oauth.d.ts +47 -0
- package/{src/auth/index.ts → dist/auth/index.d.ts} +4 -22
- package/{src/auth/interfaces.ts → dist/auth/interfaces.d.ts} +20 -89
- package/dist/auth/jwt.d.ts +67 -0
- package/dist/auth/linkedin-oauth.d.ts +18 -0
- package/dist/auth/magic-link-routes.d.ts +32 -0
- package/dist/auth/mfa-crypto.d.ts +23 -0
- package/dist/auth/mfa-routes.d.ts +7 -0
- package/dist/auth/mfa.d.ts +49 -0
- package/dist/auth/microsoft-oauth.d.ts +16 -0
- package/dist/auth/middleware.d.ts +158 -0
- package/dist/auth/password.d.ts +22 -0
- package/dist/auth/rate-limiter.d.ts +50 -0
- package/dist/auth/reset-password-admin.d.ts +29 -0
- package/dist/auth/rls-scope.d.ts +31 -0
- package/dist/auth/routes.d.ts +66 -0
- package/dist/auth/session-routes.d.ts +29 -0
- package/dist/auth/slack-oauth.d.ts +12 -0
- package/dist/auth/spotify-oauth.d.ts +12 -0
- package/dist/auth/twitter-oauth.d.ts +18 -0
- package/dist/collections/BackendCollectionRegistry.d.ts +13 -0
- package/dist/collections/loader.d.ts +5 -0
- package/dist/cron/cron-loader.d.ts +18 -0
- package/dist/cron/cron-routes.d.ts +14 -0
- package/dist/cron/cron-scheduler.d.ts +106 -0
- package/dist/cron/cron-store.d.ts +32 -0
- package/dist/cron/define-cron.d.ts +28 -0
- package/{src/cron/index.ts → dist/cron/index.d.ts} +1 -0
- package/dist/db/interfaces.d.ts +18 -0
- package/dist/dynamic-import-Dvh-K5fl.js +22 -0
- package/dist/dynamic-import-Dvh-K5fl.js.map +1 -0
- package/dist/email/index.d.ts +6 -0
- package/dist/email/smtp-email-service.d.ts +30 -0
- package/dist/email/templates.d.ts +50 -0
- package/{src/email/types.ts → dist/email/types.d.ts} +40 -36
- package/dist/env.d.ts +102 -0
- package/dist/functions/define-function.d.ts +55 -0
- package/dist/functions/function-loader.d.ts +18 -0
- package/dist/functions/function-routes.d.ts +10 -0
- package/{src/functions/index.ts → dist/functions/index.d.ts} +2 -0
- package/dist/history/history-routes.d.ts +23 -0
- package/{src/history/index.ts → dist/history/index.d.ts} +0 -1
- package/dist/index.d.ts +35 -0
- package/dist/index.es.js +18184 -0
- package/dist/index.es.js.map +1 -0
- package/dist/index.umd.js +48629 -0
- package/dist/index.umd.js.map +1 -0
- package/dist/init/docs.d.ts +4 -0
- package/dist/init/health.d.ts +2 -0
- package/dist/init/middlewares.d.ts +10 -0
- package/dist/init/shutdown.d.ts +65 -0
- package/dist/init/storage.d.ts +5 -0
- package/dist/init.d.ts +344 -0
- package/dist/jwt-BwIn8xmk.js +4200 -0
- package/dist/jwt-BwIn8xmk.js.map +1 -0
- package/dist/logger-BYU66ENZ.js +94 -0
- package/dist/logger-BYU66ENZ.js.map +1 -0
- package/dist/ms-DnYXB-Wd.js +162 -0
- package/dist/ms-DnYXB-Wd.js.map +1 -0
- package/dist/openapi-generator-Z9oYWLf_.js +586 -0
- package/dist/openapi-generator-Z9oYWLf_.js.map +1 -0
- package/dist/schema-editor-routes-D3ef8zu1.js +219 -0
- package/dist/schema-editor-routes-D3ef8zu1.js.map +1 -0
- package/dist/serve-spa.d.ts +36 -0
- package/dist/services/driver-registry.d.ts +78 -0
- package/dist/services/routed-realtime-service.d.ts +43 -0
- package/dist/services/webhook-service.d.ts +29 -0
- package/dist/singleton.d.ts +51 -0
- package/dist/src-B4OLmNVa.js +437 -0
- package/dist/src-B4OLmNVa.js.map +1 -0
- package/dist/src-B5WkP1Rv.js +24778 -0
- package/dist/src-B5WkP1Rv.js.map +1 -0
- package/dist/storage/GCSStorageController.d.ts +43 -0
- package/dist/storage/LocalStorageController.d.ts +46 -0
- package/dist/storage/S3StorageController.d.ts +40 -0
- package/dist/storage/image-transform.d.ts +50 -0
- package/{src/storage/index.ts → dist/storage/index.d.ts} +6 -21
- package/dist/storage/routes.d.ts +70 -0
- package/dist/storage/storage-registry.d.ts +78 -0
- package/dist/storage/tus-handler.d.ts +53 -0
- package/{src/storage/types.ts → dist/storage/types.d.ts} +32 -38
- package/dist/types/index.d.ts +11 -0
- package/dist/utils/dev-port.d.ts +45 -0
- package/dist/utils/dynamic-import.d.ts +25 -0
- package/dist/utils/logger.d.ts +31 -0
- package/dist/utils/logging.d.ts +9 -0
- package/dist/utils/request-id.d.ts +4 -0
- package/dist/utils/request-logger.d.ts +19 -0
- package/{src/utils/sql.ts → dist/utils/sql.d.ts} +5 -16
- package/package.json +49 -22
- package/coverage/clover.xml +0 -3739
- package/coverage/coverage-final.json +0 -31
- package/coverage/lcov-report/base.css +0 -224
- package/coverage/lcov-report/block-navigation.js +0 -87
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/index.html +0 -266
- package/coverage/lcov-report/prettify.css +0 -1
- package/coverage/lcov-report/prettify.js +0 -2
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +0 -210
- package/coverage/lcov-report/src/api/ast-schema-editor.ts.html +0 -952
- package/coverage/lcov-report/src/api/errors.ts.html +0 -472
- package/coverage/lcov-report/src/api/graphql/graphql-schema-generator.ts.html +0 -1069
- package/coverage/lcov-report/src/api/graphql/index.html +0 -116
- package/coverage/lcov-report/src/api/index.html +0 -176
- package/coverage/lcov-report/src/api/openapi-generator.ts.html +0 -565
- package/coverage/lcov-report/src/api/rest/api-generator.ts.html +0 -994
- package/coverage/lcov-report/src/api/rest/index.html +0 -131
- package/coverage/lcov-report/src/api/rest/query-parser.ts.html +0 -550
- package/coverage/lcov-report/src/api/schema-editor-routes.ts.html +0 -202
- package/coverage/lcov-report/src/api/server.ts.html +0 -823
- package/coverage/lcov-report/src/auth/admin-routes.ts.html +0 -973
- package/coverage/lcov-report/src/auth/index.html +0 -176
- package/coverage/lcov-report/src/auth/jwt.ts.html +0 -574
- package/coverage/lcov-report/src/auth/middleware.ts.html +0 -745
- package/coverage/lcov-report/src/auth/password.ts.html +0 -310
- package/coverage/lcov-report/src/auth/services.ts.html +0 -2074
- package/coverage/lcov-report/src/collections/index.html +0 -116
- package/coverage/lcov-report/src/collections/loader.ts.html +0 -232
- package/coverage/lcov-report/src/db/auth-schema.ts.html +0 -523
- package/coverage/lcov-report/src/db/data-transformer.ts.html +0 -1753
- package/coverage/lcov-report/src/db/entityService.ts.html +0 -700
- package/coverage/lcov-report/src/db/index.html +0 -146
- package/coverage/lcov-report/src/db/services/EntityFetchService.ts.html +0 -4048
- package/coverage/lcov-report/src/db/services/EntityPersistService.ts.html +0 -883
- package/coverage/lcov-report/src/db/services/RelationService.ts.html +0 -3121
- package/coverage/lcov-report/src/db/services/entity-helpers.ts.html +0 -442
- package/coverage/lcov-report/src/db/services/index.html +0 -176
- package/coverage/lcov-report/src/db/services/index.ts.html +0 -124
- package/coverage/lcov-report/src/generate-drizzle-schema-logic.ts.html +0 -1960
- package/coverage/lcov-report/src/index.html +0 -116
- package/coverage/lcov-report/src/services/driver-registry.ts.html +0 -631
- package/coverage/lcov-report/src/services/index.html +0 -131
- package/coverage/lcov-report/src/services/postgresDataDriver.ts.html +0 -3025
- package/coverage/lcov-report/src/storage/LocalStorageController.ts.html +0 -1189
- package/coverage/lcov-report/src/storage/S3StorageController.ts.html +0 -970
- package/coverage/lcov-report/src/storage/index.html +0 -161
- package/coverage/lcov-report/src/storage/storage-registry.ts.html +0 -646
- package/coverage/lcov-report/src/storage/types.ts.html +0 -451
- package/coverage/lcov-report/src/utils/drizzle-conditions.ts.html +0 -3082
- package/coverage/lcov-report/src/utils/index.html +0 -116
- package/coverage/lcov.info +0 -7179
- package/jest.config.cjs +0 -19
- package/src/api/ast-schema-editor.ts +0 -289
- package/src/api/collections_for_test/callbacks_test_collection.ts +0 -61
- package/src/api/errors.ts +0 -278
- package/src/api/graphql/graphql-schema-generator.ts +0 -383
- package/src/api/graphql/index.ts +0 -2
- package/src/api/index.ts +0 -11
- package/src/api/logs-routes.ts +0 -132
- package/src/api/openapi-generator.ts +0 -727
- package/src/api/rest/api-generator-count.test.ts +0 -126
- package/src/api/rest/api-generator.ts +0 -747
- package/src/api/rest/query-parser.ts +0 -300
- package/src/api/schema-editor-routes.ts +0 -41
- package/src/api/server.ts +0 -271
- package/src/api/types.ts +0 -104
- package/src/auth/adapter-middleware.ts +0 -114
- package/src/auth/admin-roles-route.ts +0 -36
- package/src/auth/admin-user-ops.ts +0 -236
- package/src/auth/admin-users-route.ts +0 -302
- package/src/auth/api-keys/api-key-middleware.ts +0 -133
- package/src/auth/api-keys/api-key-routes.ts +0 -193
- package/src/auth/api-keys/api-key-store.ts +0 -340
- package/src/auth/apple-oauth.ts +0 -122
- package/src/auth/bitbucket-oauth.ts +0 -84
- package/src/auth/builtin-auth-adapter.ts +0 -380
- package/src/auth/custom-auth-adapter.ts +0 -86
- package/src/auth/discord-oauth.ts +0 -85
- package/src/auth/facebook-oauth.ts +0 -74
- package/src/auth/github-oauth.ts +0 -112
- package/src/auth/gitlab-oauth.ts +0 -72
- package/src/auth/google-oauth.ts +0 -223
- package/src/auth/jwt.ts +0 -208
- package/src/auth/linkedin-oauth.ts +0 -83
- package/src/auth/magic-link-routes.ts +0 -167
- package/src/auth/mfa-crypto.ts +0 -91
- package/src/auth/mfa-routes.ts +0 -323
- package/src/auth/mfa.ts +0 -161
- package/src/auth/microsoft-oauth.ts +0 -90
- package/src/auth/middleware.ts +0 -369
- package/src/auth/password.ts +0 -77
- package/src/auth/rate-limiter.ts +0 -225
- package/src/auth/reset-password-admin.ts +0 -160
- package/src/auth/rls-scope.ts +0 -58
- package/src/auth/routes.ts +0 -802
- package/src/auth/session-routes.ts +0 -353
- package/src/auth/slack-oauth.ts +0 -73
- package/src/auth/spotify-oauth.ts +0 -69
- package/src/auth/twitter-oauth.ts +0 -128
- package/src/collections/BackendCollectionRegistry.ts +0 -20
- package/src/collections/loader.ts +0 -50
- package/src/cron/cron-loader.ts +0 -84
- package/src/cron/cron-routes.test.ts +0 -265
- package/src/cron/cron-routes.ts +0 -85
- package/src/cron/cron-scheduler.test.ts +0 -559
- package/src/cron/cron-scheduler.ts +0 -581
- package/src/cron/cron-store.ts +0 -166
- package/src/db/interfaces.ts +0 -60
- package/src/email/index.ts +0 -19
- package/src/email/smtp-email-service.ts +0 -123
- package/src/email/templates.ts +0 -470
- package/src/env.ts +0 -227
- package/src/functions/function-loader.ts +0 -116
- package/src/functions/function-routes.ts +0 -31
- package/src/history/history-routes.ts +0 -129
- package/src/index.ts +0 -70
- package/src/init/docs.ts +0 -47
- package/src/init/health.ts +0 -37
- package/src/init/middlewares.ts +0 -61
- package/src/init/shutdown.ts +0 -56
- package/src/init/storage.ts +0 -57
- package/src/init.ts +0 -1041
- package/src/serve-spa.ts +0 -89
- package/src/services/driver-registry.ts +0 -183
- package/src/services/routed-realtime-service.ts +0 -113
- package/src/services/webhook-service.ts +0 -155
- package/src/singleton.ts +0 -70
- package/src/storage/LocalStorageController.ts +0 -389
- package/src/storage/S3StorageController.ts +0 -300
- package/src/storage/image-transform.ts +0 -218
- package/src/storage/routes.ts +0 -368
- package/src/storage/storage-registry.ts +0 -188
- package/src/storage/tus-handler.ts +0 -315
- package/src/types/index.ts +0 -27
- package/src/utils/dev-port.ts +0 -196
- package/src/utils/logger.ts +0 -143
- package/src/utils/logging.ts +0 -40
- package/src/utils/request-id.ts +0 -40
- package/src/utils/request-logger.ts +0 -72
- package/test/api-generator.test.ts +0 -588
- package/test/api-key-permission-guard.test.ts +0 -144
- package/test/ast-schema-editor.test.ts +0 -89
- package/test/auth-middleware-hono.test.ts +0 -556
- package/test/auth-routes.test.ts +0 -1098
- package/test/backend-hooks-data.test.ts +0 -477
- package/test/custom-auth-adapter.test.ts +0 -189
- package/test/driver-registry.test.ts +0 -282
- package/test/email-templates.test.ts +0 -174
- package/test/env.test.ts +0 -128
- package/test/error-propagation.test.ts +0 -226
- package/test/errors-hono.test.ts +0 -133
- package/test/errors.test.ts +0 -155
- package/test/function-loader.test.ts +0 -127
- package/test/graphql-schema-generator.test.ts +0 -554
- package/test/jwt-security.test.ts +0 -182
- package/test/jwt.test.ts +0 -326
- package/test/mfa.test.ts +0 -197
- package/test/middleware.test.ts +0 -305
- package/test/multi-datasource-routing.test.ts +0 -113
- package/test/password.test.ts +0 -165
- package/test/query-parser.test.ts +0 -233
- package/test/rate-limiter.test.ts +0 -102
- package/test/reset-password-admin.test.ts +0 -113
- package/test/routed-realtime-service.test.ts +0 -86
- package/test/safe-compare.test.ts +0 -66
- package/test/singleton.test.ts +0 -59
- package/test/smtp-email-service.test.ts +0 -169
- package/test/storage-local.test.ts +0 -271
- package/test/storage-registry.test.ts +0 -282
- package/test/storage-routes.test.ts +0 -222
- package/test/storage-s3.test.ts +0 -304
- package/test/transform-auth-response.test.ts +0 -305
- package/test/webhook-service.test.ts +0 -260
- package/tsconfig.json +0 -54
- package/tsconfig.prod.json +0 -23
- package/vite.config.ts +0 -86
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.es.js","names":["_a","F","initializer","util.jsonStringifyReplacer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodError","safeParse","errors.$ZodRealError","safeParseAsync","duration","_emoji","date","time","datetime","string","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","content","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","regexes.base64url","regexes.e164","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.normalizeParams","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","process","process","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","util.jsonStringifyReplacer","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","util.mergeDefs","core.clone","checks.overwrite","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.enumProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine"],"sources":["../../types/src/controllers/storage.ts","../../../node_modules/.pnpm/object-hash@3.0.0/node_modules/object-hash/dist/object_hash.js","../../utils/dist/index.es.js","../../common/src/util/enums.ts","../../common/src/util/relations.ts","../../common/src/util/resolutions.ts","../../common/src/util/builders.ts","../../../node_modules/.pnpm/json-logic-js@2.0.5/node_modules/json-logic-js/logic.js","../../common/src/util/conditions.ts","../../common/src/util/filter-operator-resolution.ts","../../../node_modules/.pnpm/fast-equals@6.0.0/node_modules/fast-equals/dist/es/index.mjs","../../common/src/data/resolveDataSource.ts","../../common/src/collections/CollectionRegistry.ts","../../common/src/collections/default-collections.ts","../../common/src/data/query_builder.ts","../../common/src/data/filter-dialect.ts","../../common/src/data/buildRebaseData.ts","../../common/src/data/buildRoutedRebaseData.ts","../../common/src/data/sort-dialect.ts","../src/collections/BackendCollectionRegistry.ts","../src/collections/loader.ts","../src/services/driver-registry.ts","../src/services/routed-realtime-service.ts","../src/api/errors.ts","../src/api/rest/query-parser.ts","../src/auth/api-keys/api-key-permission-guard.ts","../src/api/rest/api-generator.ts","../src/auth/rls-scope.ts","../src/auth/crypto-utils.ts","../src/auth/api-keys/api-key-middleware.ts","../src/auth/middleware.ts","../src/auth/adapter-middleware.ts","../src/email/templates.ts","../src/auth/admin-user-ops.ts","../src/auth/password.ts","../src/auth/auth-hooks.ts","../src/auth/rate-limiter.ts","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/compat.js","../src/auth/mfa.ts","../src/auth/mfa-crypto.ts","../src/auth/mfa-routes.ts","../src/auth/cookie-utils.ts","../src/auth/session-routes.ts","../src/auth/magic-link-routes.ts","../src/auth/routes.ts","../src/auth/reset-password-admin.ts","../src/auth/admin-roles-route.ts","../src/auth/admin-users-route.ts","../src/auth/builtin-auth-adapter.ts","../src/utils/logging.ts","../src/utils/request-id.ts","../src/utils/request-logger.ts","../src/init/middlewares.ts","../src/storage/types.ts","../src/storage/LocalStorageController.ts","../src/storage/S3StorageController.ts","../src/storage/GCSStorageController.ts","../src/auth/google-oauth.ts","../src/auth/linkedin-oauth.ts","../src/auth/github-oauth.ts","../src/auth/microsoft-oauth.ts","../src/auth/apple-oauth.ts","../src/auth/facebook-oauth.ts","../src/auth/twitter-oauth.ts","../src/auth/discord-oauth.ts","../src/auth/gitlab-oauth.ts","../src/auth/bitbucket-oauth.ts","../src/auth/slack-oauth.ts","../src/auth/spotify-oauth.ts","../src/auth/api-keys/api-key-store.ts","../src/auth/api-keys/api-key-routes.ts","../src/auth/custom-auth-adapter.ts","../src/auth/index.ts","../src/storage/image-transform.ts","../src/storage/tus-handler.ts","../src/storage/routes.ts","../src/storage/storage-registry.ts","../src/storage/index.ts","../src/init/storage.ts","../src/init/docs.ts","../src/init/health.ts","../src/init/shutdown.ts","../../client/dist/index.es.js","../src/history/history-routes.ts","../src/email/smtp-email-service.ts","../src/singleton.ts","../src/init.ts","../src/functions/function-loader.ts","../src/functions/function-routes.ts","../src/functions/define-function.ts","../src/cron/cron-loader.ts","../src/cron/define-cron.ts","../src/cron/cron-scheduler.ts","../src/cron/cron-routes.ts","../src/cron/cron-store.ts","../src/utils/sql.ts","../src/env.ts","../src/utils/dev-port.ts","../src/serve-spa.ts"],"sourcesContent":["/**\n * Path prefix that marks an object as **public**. Files stored under this\n * prefix are served without any auth token via a stable, permanent,\n * CDN-cacheable URL (see {@link StorageSource.getSignedUrl}). Shared by the\n * client SDK and the backend so both agree on which objects are public.\n *\n * @group Models\n */\nexport const PUBLIC_STORAGE_PREFIX = \"public/\";\n\n/**\n * True when a storage key/path points at a public object (lives under\n * {@link PUBLIC_STORAGE_PREFIX}). The check is applied to the key *within the\n * bucket* — strip any `bucket/` and `scheme://` prefixes first.\n *\n * @group Models\n */\nexport function isPublicStoragePath(path: string | null | undefined): boolean {\n if (!path) return false;\n let p = path;\n const scheme = p.indexOf(\"://\");\n if (scheme !== -1) p = p.substring(scheme + 3);\n p = p.replace(/^\\/+/, \"\");\n\n // Defense-in-depth: a path containing traversal segments is never public,\n // so an attacker can't reach a private object via `public/../secret`.\n if (p.split(\"/\").some((seg) => seg === \"..\")) return false;\n\n // Public iff the object **key** starts with the public prefix. A single\n // leading `default/` bucket segment is tolerated (the default bucket).\n // A substring match is deliberately NOT used — a private object under a\n // folder literally named `public` (e.g. `reports/public/q3.pdf`) must stay\n // private. Named buckets: pass the key (not `bucket/key`) so the prefix is\n // anchored; otherwise it falls back to a private, token-scoped URL (safe).\n return p.startsWith(PUBLIC_STORAGE_PREFIX) || p.startsWith(`default/${PUBLIC_STORAGE_PREFIX}`);\n}\n\n/**\n * @group Models\n */\nexport interface UploadFileProps {\n file: File,\n key: string,\n metadata?: Record<string, unknown>,\n bucket?: string,\n /**\n * Store this object as **public**: it is placed under\n * {@link PUBLIC_STORAGE_PREFIX} and served via a stable, token-less,\n * permanent URL (safe to persist in a database and cache on a CDN).\n * Defaults to `false` (private, short-lived signed URLs).\n */\n public?: boolean\n}\n\n/**\n * @group Models\n */\nexport interface UploadFileResult {\n /**\n * Storage key including the file name where the file was uploaded.\n */\n key: string;\n /**\n * Bucket where the file was uploaded\n */\n bucket: string;\n\n /**\n * Fully qualified storage URL for the uploaded file.\n *\n * For example: `s3://my-bucket/path/to/file.png`.\n *\n * This is optional for backwards compatibility.\n */\n storageUrl?: string;\n}\n\n/**\n * @group Models\n */\nexport interface DownloadConfig {\n /**\n * Temporal url that can be used to download the file\n */\n url: string | null;\n\n metadata?: DownloadMetadata;\n\n fileNotFound?: boolean;\n}\n\n/**\n * The full set of object metadata, including read-only properties.\n * @public\n */\nexport declare interface DownloadMetadata {\n /**\n * The bucket this object is contained in.\n */\n bucket: string;\n /**\n * The full path of this object.\n */\n fullPath: string;\n /**\n * The short name of this object, which is the last component of the full path.\n * For example, if path is 'full/path/image.png', name is 'image.png'.\n */\n name: string;\n /**\n * The size of this object, in bytes.\n */\n size: number;\n /**\n * Type of the uploaded file\n * e.g. \"image/jpeg\"\n */\n contentType: string;\n\n customMetadata: Record<string, unknown>;\n /**\n * Optional short-lived download token (for local/server-mediated storage).\n * Absent for public objects, which need no token.\n */\n token?: string;\n /**\n * Optional remaining lifetime of the token, in seconds.\n */\n tokenExpiresIn?: number;\n /**\n * True when this object is public: it is served without a token via a\n * stable, permanent, CDN-cacheable URL. When set, the client builds a\n * token-less URL and caches it indefinitely.\n */\n public?: boolean;\n}\n\n/**\n * @group Models\n */\nexport interface StorageSource {\n /**\n * Upload an object, specifying a key\n * @param file\n * @param key\n * @param metadata\n * @param bucket\n */\n putObject: ({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps) => Promise<UploadFileResult>;\n\n /**\n * Convert a storage key or URL into a download configuration (signed URL equivalent)\n * @param keyOrUrl\n * @param bucket\n */\n getSignedUrl: (keyOrUrl: string, bucket?: string) => Promise<DownloadConfig>;\n\n /**\n * Get an object from a storage key.\n * It returns null if the object does not exist.\n * @param key\n * @param bucket\n */\n getObject: (key: string, bucket?: string) => Promise<File | null>;\n\n /**\n * Delete an object.\n * @param key\n * @param bucket\n */\n deleteObject: (key: string, bucket?: string) => Promise<void>;\n\n /**\n * List the contents of a prefix.\n * @param prefix\n * @param options\n */\n listObjects: (prefix: string, options?: {\n bucket?: string,\n maxResults?: number,\n pageToken?: string\n }) => Promise<StorageListResult>;\n\n}\n\n/**\n * Result returned by list().\n * @public\n */\nexport declare interface StorageListResult {\n /**\n * References to prefixes (sub-folders). You can call list() on them to\n * get its contents.\n *\n * Folders are implicit based on '/' in the object paths.\n * For example, if a bucket has two objects '/a/b/1' and '/a/b/2', list('/a')\n * will return '/a/b' as a prefix.\n */\n prefixes: StorageReference[];\n /**\n * Objects in this directory.\n * You can call getMetadata() and getDownloadUrl() on them.\n */\n items: StorageReference[];\n /**\n * If set, there might be more results for this list. Use this token to resume the list.\n */\n nextPageToken?: string;\n}\n\n/**\n * Represents a reference to an S3-compatible storage object. Developers can\n * upload, download, and delete objects, as well as get/set object metadata.\n * @public\n */\nexport declare interface StorageReference {\n /**\n * Returns a s3:// URL for this object in the form\n * `s3://<bucket>/<path>/<to>/<object>`\n * @returns The s3:// URL.\n */\n toString(): string;\n\n /**\n * A reference to the root of this object's bucket.\n */\n root: StorageReference;\n /**\n * The name of the bucket containing this reference's object.\n */\n bucket: string;\n /**\n * The full path of this object.\n */\n fullPath: string;\n /**\n * The short name of this object, which is the last component of the full path.\n * For example, if path is 'full/path/image.png', name is 'image.png'.\n */\n name: string;\n\n /**\n * A reference pointing to the parent location of this reference, or null if\n * this reference is the root.\n */\n parent: StorageReference | null;\n}\n","!function(e){var t;\"object\"==typeof exports?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(\"undefined\"!=typeof window?t=window:\"undefined\"!=typeof global?t=global:\"undefined\"!=typeof self&&(t=self),t.objectHash=e())}(function(){return function r(o,i,u){function s(n,e){if(!i[n]){if(!o[n]){var t=\"function\"==typeof require&&require;if(!e&&t)return t(n,!0);if(a)return a(n,!0);throw new Error(\"Cannot find module '\"+n+\"'\")}e=i[n]={exports:{}};o[n][0].call(e.exports,function(e){var t=o[n][1][e];return s(t||e)},e,e.exports,r,o,i,u)}return i[n].exports}for(var a=\"function\"==typeof require&&require,e=0;e<u.length;e++)s(u[e]);return s}({1:[function(w,b,m){!function(e,n,s,c,d,h,p,g,y){\"use strict\";var r=w(\"crypto\");function t(e,t){t=u(e,t);var n;return void 0===(n=\"passthrough\"!==t.algorithm?r.createHash(t.algorithm):new l).write&&(n.write=n.update,n.end=n.update),f(t,n).dispatch(e),n.update||n.end(\"\"),n.digest?n.digest(\"buffer\"===t.encoding?void 0:t.encoding):(e=n.read(),\"buffer\"!==t.encoding?e.toString(t.encoding):e)}(m=b.exports=t).sha1=function(e){return t(e)},m.keys=function(e){return t(e,{excludeValues:!0,algorithm:\"sha1\",encoding:\"hex\"})},m.MD5=function(e){return t(e,{algorithm:\"md5\",encoding:\"hex\"})},m.keysMD5=function(e){return t(e,{algorithm:\"md5\",encoding:\"hex\",excludeValues:!0})};var o=r.getHashes?r.getHashes().slice():[\"sha1\",\"md5\"],i=(o.push(\"passthrough\"),[\"buffer\",\"hex\",\"binary\",\"base64\"]);function u(e,t){var n={};if(n.algorithm=(t=t||{}).algorithm||\"sha1\",n.encoding=t.encoding||\"hex\",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error(\"Object argument required.\");for(var r=0;r<o.length;++r)o[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=o[r]);if(-1===o.indexOf(n.algorithm))throw new Error('Algorithm \"'+n.algorithm+'\" not supported. supported values: '+o.join(\", \"));if(-1===i.indexOf(n.encoding)&&\"passthrough\"!==n.algorithm)throw new Error('Encoding \"'+n.encoding+'\" not supported. supported values: '+i.join(\", \"));return n}function a(e){if(\"function\"==typeof e)return null!=/^function\\s+\\w*\\s*\\(\\s*\\)\\s*{\\s+\\[native code\\]\\s+}$/i.exec(Function.prototype.toString.call(e))}function f(o,t,i){i=i||[];function u(e){return t.update?t.update(e,\"utf8\"):t.write(e,\"utf8\")}return{dispatch:function(e){return this[\"_\"+(null===(e=o.replacer?o.replacer(e):e)?\"null\":typeof e)](e)},_object:function(t){var n,e=Object.prototype.toString.call(t),r=/\\[object (.*)\\]/i.exec(e);r=(r=r?r[1]:\"unknown:[\"+e+\"]\").toLowerCase();if(0<=(e=i.indexOf(t)))return this.dispatch(\"[CIRCULAR:\"+e+\"]\");if(i.push(t),void 0!==s&&s.isBuffer&&s.isBuffer(t))return u(\"buffer:\"),u(t);if(\"object\"===r||\"function\"===r||\"asyncfunction\"===r)return e=Object.keys(t),o.unorderedObjects&&(e=e.sort()),!1===o.respectType||a(t)||e.splice(0,0,\"prototype\",\"__proto__\",\"constructor\"),o.excludeKeys&&(e=e.filter(function(e){return!o.excludeKeys(e)})),u(\"object:\"+e.length+\":\"),n=this,e.forEach(function(e){n.dispatch(e),u(\":\"),o.excludeValues||n.dispatch(t[e]),u(\",\")});if(!this[\"_\"+r]){if(o.ignoreUnknown)return u(\"[\"+r+\"]\");throw new Error('Unknown object type \"'+r+'\"')}this[\"_\"+r](t)},_array:function(e,t){t=void 0!==t?t:!1!==o.unorderedArrays;var n=this;if(u(\"array:\"+e.length+\":\"),!t||e.length<=1)return e.forEach(function(e){return n.dispatch(e)});var r=[],t=e.map(function(e){var t=new l,n=i.slice();return f(o,t,n).dispatch(e),r=r.concat(n.slice(i.length)),t.read().toString()});return i=i.concat(r),t.sort(),this._array(t,!1)},_date:function(e){return u(\"date:\"+e.toJSON())},_symbol:function(e){return u(\"symbol:\"+e.toString())},_error:function(e){return u(\"error:\"+e.toString())},_boolean:function(e){return u(\"bool:\"+e.toString())},_string:function(e){u(\"string:\"+e.length+\":\"),u(e.toString())},_function:function(e){u(\"fn:\"),a(e)?this.dispatch(\"[native]\"):this.dispatch(e.toString()),!1!==o.respectFunctionNames&&this.dispatch(\"function-name:\"+String(e.name)),o.respectFunctionProperties&&this._object(e)},_number:function(e){return u(\"number:\"+e.toString())},_xml:function(e){return u(\"xml:\"+e.toString())},_null:function(){return u(\"Null\")},_undefined:function(){return u(\"Undefined\")},_regexp:function(e){return u(\"regex:\"+e.toString())},_uint8array:function(e){return u(\"uint8array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return u(\"uint8clampedarray:\"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return u(\"int8array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return u(\"uint16array:\"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return u(\"int16array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return u(\"uint32array:\"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return u(\"int32array:\"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return u(\"float32array:\"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return u(\"float64array:\"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return u(\"arraybuffer:\"),this.dispatch(new Uint8Array(e))},_url:function(e){return u(\"url:\"+e.toString())},_map:function(e){u(\"map:\");e=Array.from(e);return this._array(e,!1!==o.unorderedSets)},_set:function(e){u(\"set:\");e=Array.from(e);return this._array(e,!1!==o.unorderedSets)},_file:function(e){return u(\"file:\"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(o.ignoreUnknown)return u(\"[blob]\");throw Error('Hashing Blob objects is currently not supported\\n(see https://github.com/puleos/object-hash/issues/26)\\nUse \"options.replacer\" or \"options.ignoreUnknown\"\\n')},_domwindow:function(){return u(\"domwindow\")},_bigint:function(e){return u(\"bigint:\"+e.toString())},_process:function(){return u(\"process\")},_timer:function(){return u(\"timer\")},_pipe:function(){return u(\"pipe\")},_tcp:function(){return u(\"tcp\")},_udp:function(){return u(\"udp\")},_tty:function(){return u(\"tty\")},_statwatcher:function(){return u(\"statwatcher\")},_securecontext:function(){return u(\"securecontext\")},_connection:function(){return u(\"connection\")},_zlib:function(){return u(\"zlib\")},_context:function(){return u(\"context\")},_nodescript:function(){return u(\"nodescript\")},_httpparser:function(){return u(\"httpparser\")},_dataview:function(){return u(\"dataview\")},_signal:function(){return u(\"signal\")},_fsevent:function(){return u(\"fsevent\")},_tlswrap:function(){return u(\"tlswrap\")}}}function l(){return{buf:\"\",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}m.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),f(t=u(e,t),n).dispatch(e)}}.call(this,w(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},w(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/fake_9a5aa49d.js\",\"/\")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(e,t,f){!function(e,t,n,r,o,i,u,s,a){!function(e){\"use strict\";var a=\"undefined\"!=typeof Uint8Array?Uint8Array:Array,t=\"+\".charCodeAt(0),n=\"/\".charCodeAt(0),r=\"0\".charCodeAt(0),o=\"a\".charCodeAt(0),i=\"A\".charCodeAt(0),u=\"-\".charCodeAt(0),s=\"_\".charCodeAt(0);function f(e){e=e.charCodeAt(0);return e===t||e===u?62:e===n||e===s?63:e<r?-1:e<r+10?e-r+26+26:e<i+26?e-i:e<o+26?e-o+26:void 0}e.toByteArray=function(e){var t,n;if(0<e.length%4)throw new Error(\"Invalid string. Length must be a multiple of 4\");var r=e.length,r=\"=\"===e.charAt(r-2)?2:\"=\"===e.charAt(r-1)?1:0,o=new a(3*e.length/4-r),i=0<r?e.length-4:e.length,u=0;function s(e){o[u++]=e}for(t=0;t<i;t+=4,0)s((16711680&(n=f(e.charAt(t))<<18|f(e.charAt(t+1))<<12|f(e.charAt(t+2))<<6|f(e.charAt(t+3))))>>16),s((65280&n)>>8),s(255&n);return 2==r?s(255&(n=f(e.charAt(t))<<2|f(e.charAt(t+1))>>4)):1==r&&(s((n=f(e.charAt(t))<<10|f(e.charAt(t+1))<<4|f(e.charAt(t+2))>>2)>>8&255),s(255&n)),o},e.fromByteArray=function(e){var t,n,r,o,i=e.length%3,u=\"\";function s(e){return\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(e)}for(t=0,r=e.length-i;t<r;t+=3)n=(e[t]<<16)+(e[t+1]<<8)+e[t+2],u+=s((o=n)>>18&63)+s(o>>12&63)+s(o>>6&63)+s(63&o);switch(i){case 1:u=(u+=s((n=e[e.length-1])>>2))+s(n<<4&63)+\"==\";break;case 2:u=(u=(u+=s((n=(e[e.length-2]<<8)+e[e.length-1])>>10))+s(n>>4&63))+s(n<<2&63)+\"=\"}return u}}(void 0===f?this.base64js={}:f)}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js\",\"/node_modules/gulp-browserify/node_modules/base64-js/lib\")},{buffer:3,lYpoI2:11}],3:[function(O,e,H){!function(e,n,f,r,h,p,g,y,w){var a=O(\"base64-js\"),i=O(\"ieee754\");function f(e,t,n){if(!(this instanceof f))return new f(e,t,n);var r,o,i,u,s=typeof e;if(\"base64\"===t&&\"string\"==s)for(e=(u=e).trim?u.trim():u.replace(/^\\s+|\\s+$/g,\"\");e.length%4!=0;)e+=\"=\";if(\"number\"==s)r=j(e);else if(\"string\"==s)r=f.byteLength(e,t);else{if(\"object\"!=s)throw new Error(\"First argument needs to be a number, array or string.\");r=j(e.length)}if(f._useTypedArrays?o=f._augment(new Uint8Array(r)):((o=this).length=r,o._isBuffer=!0),f._useTypedArrays&&\"number\"==typeof e.byteLength)o._set(e);else if(C(u=e)||f.isBuffer(u)||u&&\"object\"==typeof u&&\"number\"==typeof u.length)for(i=0;i<r;i++)f.isBuffer(e)?o[i]=e.readUInt8(i):o[i]=e[i];else if(\"string\"==s)o.write(e,0,t);else if(\"number\"==s&&!f._useTypedArrays&&!n)for(i=0;i<r;i++)o[i]=0;return o}function b(e,t,n,r){return f._charsWritten=c(function(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function m(e,t,n,r){return f._charsWritten=c(function(e){for(var t,n,r=[],o=0;o<e.length;o++)n=e.charCodeAt(o),t=n>>8,n=n%256,r.push(n),r.push(t);return r}(t),e,n,r)}function v(e,t,n){var r=\"\";n=Math.min(e.length,n);for(var o=t;o<n;o++)r+=String.fromCharCode(e[o]);return r}function o(e,t,n,r){r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+1<e.length,\"Trying to read beyond buffer length\"));var o,r=e.length;if(!(r<=t))return n?(o=e[t],t+1<r&&(o|=e[t+1]<<8)):(o=e[t]<<8,t+1<r&&(o|=e[t+1])),o}function u(e,t,n,r){r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+3<e.length,\"Trying to read beyond buffer length\"));var o,r=e.length;if(!(r<=t))return n?(t+2<r&&(o=e[t+2]<<16),t+1<r&&(o|=e[t+1]<<8),o|=e[t],t+3<r&&(o+=e[t+3]<<24>>>0)):(t+1<r&&(o=e[t+1]<<16),t+2<r&&(o|=e[t+2]<<8),t+3<r&&(o|=e[t+3]),o+=e[t]<<24>>>0),o}function _(e,t,n,r){if(r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+1<e.length,\"Trying to read beyond buffer length\")),!(e.length<=t))return r=o(e,t,n,!0),32768&r?-1*(65535-r+1):r}function E(e,t,n,r){if(r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+3<e.length,\"Trying to read beyond buffer length\")),!(e.length<=t))return r=u(e,t,n,!0),2147483648&r?-1*(4294967295-r+1):r}function I(e,t,n,r){return r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(t+3<e.length,\"Trying to read beyond buffer length\")),i.read(e,t,n,23,4)}function A(e,t,n,r){return r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(t+7<e.length,\"Trying to read beyond buffer length\")),i.read(e,t,n,52,8)}function s(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+1<e.length,\"trying to write beyond buffer length\"),Y(t,65535));o=e.length;if(!(o<=n))for(var i=0,u=Math.min(o-n,2);i<u;i++)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function l(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"trying to write beyond buffer length\"),Y(t,4294967295));o=e.length;if(!(o<=n))for(var i=0,u=Math.min(o-n,4);i<u;i++)e[n+i]=t>>>8*(r?i:3-i)&255}function B(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+1<e.length,\"Trying to write beyond buffer length\"),F(t,32767,-32768)),e.length<=n||s(e,0<=t?t:65535+t+1,n,r,o)}function L(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"Trying to write beyond buffer length\"),F(t,2147483647,-2147483648)),e.length<=n||l(e,0<=t?t:4294967295+t+1,n,r,o)}function U(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"Trying to write beyond buffer length\"),D(t,34028234663852886e22,-34028234663852886e22)),e.length<=n||i.write(e,t,n,r,23,4)}function x(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+7<e.length,\"Trying to write beyond buffer length\"),D(t,17976931348623157e292,-17976931348623157e292)),e.length<=n||i.write(e,t,n,r,52,8)}H.Buffer=f,H.SlowBuffer=f,H.INSPECT_MAX_BYTES=50,f.poolSize=8192,f._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&\"function\"==typeof t.subarray}catch(e){return!1}}(),f.isEncoding=function(e){switch(String(e).toLowerCase()){case\"hex\":case\"utf8\":case\"utf-8\":case\"ascii\":case\"binary\":case\"base64\":case\"raw\":case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return!0;default:return!1}},f.isBuffer=function(e){return!(null==e||!e._isBuffer)},f.byteLength=function(e,t){var n;switch(e+=\"\",t||\"utf8\"){case\"hex\":n=e.length/2;break;case\"utf8\":case\"utf-8\":n=T(e).length;break;case\"ascii\":case\"binary\":case\"raw\":n=e.length;break;case\"base64\":n=M(e).length;break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":n=2*e.length;break;default:throw new Error(\"Unknown encoding\")}return n},f.concat=function(e,t){if(d(C(e),\"Usage: Buffer.concat(list, [totalLength])\\nlist should be an Array.\"),0===e.length)return new f(0);if(1===e.length)return e[0];if(\"number\"!=typeof t)for(o=t=0;o<e.length;o++)t+=e[o].length;for(var n=new f(t),r=0,o=0;o<e.length;o++){var i=e[o];i.copy(n,r),r+=i.length}return n},f.prototype.write=function(e,t,n,r){isFinite(t)?isFinite(n)||(r=n,n=void 0):(a=r,r=t,t=n,n=a),t=Number(t)||0;var o,i,u,s,a=this.length-t;switch((!n||a<(n=Number(n)))&&(n=a),r=String(r||\"utf8\").toLowerCase()){case\"hex\":o=function(e,t,n,r){n=Number(n)||0;var o=e.length-n;(!r||o<(r=Number(r)))&&(r=o),d((o=t.length)%2==0,\"Invalid hex string\"),o/2<r&&(r=o/2);for(var i=0;i<r;i++){var u=parseInt(t.substr(2*i,2),16);d(!isNaN(u),\"Invalid hex string\"),e[n+i]=u}return f._charsWritten=2*i,i}(this,e,t,n);break;case\"utf8\":case\"utf-8\":i=this,u=t,s=n,o=f._charsWritten=c(T(e),i,u,s);break;case\"ascii\":case\"binary\":o=b(this,e,t,n);break;case\"base64\":i=this,u=t,s=n,o=f._charsWritten=c(M(e),i,u,s);break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":o=m(this,e,t,n);break;default:throw new Error(\"Unknown encoding\")}return o},f.prototype.toString=function(e,t,n){var r,o,i,u,s=this;if(e=String(e||\"utf8\").toLowerCase(),t=Number(t)||0,(n=void 0!==n?Number(n):s.length)===t)return\"\";switch(e){case\"hex\":r=function(e,t,n){var r=e.length;(!t||t<0)&&(t=0);(!n||n<0||r<n)&&(n=r);for(var o=\"\",i=t;i<n;i++)o+=k(e[i]);return o}(s,t,n);break;case\"utf8\":case\"utf-8\":r=function(e,t,n){var r=\"\",o=\"\";n=Math.min(e.length,n);for(var i=t;i<n;i++)e[i]<=127?(r+=N(o)+String.fromCharCode(e[i]),o=\"\"):o+=\"%\"+e[i].toString(16);return r+N(o)}(s,t,n);break;case\"ascii\":case\"binary\":r=v(s,t,n);break;case\"base64\":o=s,u=n,r=0===(i=t)&&u===o.length?a.fromByteArray(o):a.fromByteArray(o.slice(i,u));break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":r=function(e,t,n){for(var r=e.slice(t,n),o=\"\",i=0;i<r.length;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}(s,t,n);break;default:throw new Error(\"Unknown encoding\")}return r},f.prototype.toJSON=function(){return{type:\"Buffer\",data:Array.prototype.slice.call(this._arr||this,0)}},f.prototype.copy=function(e,t,n,r){if(t=t||0,(r=r||0===r?r:this.length)!==(n=n||0)&&0!==e.length&&0!==this.length){d(n<=r,\"sourceEnd < sourceStart\"),d(0<=t&&t<e.length,\"targetStart out of bounds\"),d(0<=n&&n<this.length,\"sourceStart out of bounds\"),d(0<=r&&r<=this.length,\"sourceEnd out of bounds\"),r>this.length&&(r=this.length);var o=(r=e.length-t<r-n?e.length-t+n:r)-n;if(o<100||!f._useTypedArrays)for(var i=0;i<o;i++)e[i+t]=this[i+n];else e._set(this.subarray(n,n+o),t)}},f.prototype.slice=function(e,t){var n=this.length;if(e=S(e,n,0),t=S(t,n,n),f._useTypedArrays)return f._augment(this.subarray(e,t));for(var r=t-e,o=new f(r,void 0,!0),i=0;i<r;i++)o[i]=this[i+e];return o},f.prototype.get=function(e){return console.log(\".get() is deprecated. Access using array indexes instead.\"),this.readUInt8(e)},f.prototype.set=function(e,t){return console.log(\".set() is deprecated. Access using array indexes instead.\"),this.writeUInt8(e,t)},f.prototype.readUInt8=function(e,t){if(t||(d(null!=e,\"missing offset\"),d(e<this.length,\"Trying to read beyond buffer length\")),!(e>=this.length))return this[e]},f.prototype.readUInt16LE=function(e,t){return o(this,e,!0,t)},f.prototype.readUInt16BE=function(e,t){return o(this,e,!1,t)},f.prototype.readUInt32LE=function(e,t){return u(this,e,!0,t)},f.prototype.readUInt32BE=function(e,t){return u(this,e,!1,t)},f.prototype.readInt8=function(e,t){if(t||(d(null!=e,\"missing offset\"),d(e<this.length,\"Trying to read beyond buffer length\")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},f.prototype.readInt16LE=function(e,t){return _(this,e,!0,t)},f.prototype.readInt16BE=function(e,t){return _(this,e,!1,t)},f.prototype.readInt32LE=function(e,t){return E(this,e,!0,t)},f.prototype.readInt32BE=function(e,t){return E(this,e,!1,t)},f.prototype.readFloatLE=function(e,t){return I(this,e,!0,t)},f.prototype.readFloatBE=function(e,t){return I(this,e,!1,t)},f.prototype.readDoubleLE=function(e,t){return A(this,e,!0,t)},f.prototype.readDoubleBE=function(e,t){return A(this,e,!1,t)},f.prototype.writeUInt8=function(e,t,n){n||(d(null!=e,\"missing value\"),d(null!=t,\"missing offset\"),d(t<this.length,\"trying to write beyond buffer length\"),Y(e,255)),t>=this.length||(this[t]=e)},f.prototype.writeUInt16LE=function(e,t,n){s(this,e,t,!0,n)},f.prototype.writeUInt16BE=function(e,t,n){s(this,e,t,!1,n)},f.prototype.writeUInt32LE=function(e,t,n){l(this,e,t,!0,n)},f.prototype.writeUInt32BE=function(e,t,n){l(this,e,t,!1,n)},f.prototype.writeInt8=function(e,t,n){n||(d(null!=e,\"missing value\"),d(null!=t,\"missing offset\"),d(t<this.length,\"Trying to write beyond buffer length\"),F(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},f.prototype.writeInt16LE=function(e,t,n){B(this,e,t,!0,n)},f.prototype.writeInt16BE=function(e,t,n){B(this,e,t,!1,n)},f.prototype.writeInt32LE=function(e,t,n){L(this,e,t,!0,n)},f.prototype.writeInt32BE=function(e,t,n){L(this,e,t,!1,n)},f.prototype.writeFloatLE=function(e,t,n){U(this,e,t,!0,n)},f.prototype.writeFloatBE=function(e,t,n){U(this,e,t,!1,n)},f.prototype.writeDoubleLE=function(e,t,n){x(this,e,t,!0,n)},f.prototype.writeDoubleBE=function(e,t,n){x(this,e,t,!1,n)},f.prototype.fill=function(e,t,n){if(t=t||0,n=n||this.length,d(\"number\"==typeof(e=\"string\"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),\"value is not a number\"),d(t<=n,\"end < start\"),n!==t&&0!==this.length){d(0<=t&&t<this.length,\"start out of bounds\"),d(0<=n&&n<=this.length,\"end out of bounds\");for(var r=t;r<n;r++)this[r]=e}},f.prototype.inspect=function(){for(var e=[],t=this.length,n=0;n<t;n++)if(e[n]=k(this[n]),n===H.INSPECT_MAX_BYTES){e[n+1]=\"...\";break}return\"<Buffer \"+e.join(\" \")+\">\"},f.prototype.toArrayBuffer=function(){if(\"undefined\"==typeof Uint8Array)throw new Error(\"Buffer.toArrayBuffer not supported in this browser\");if(f._useTypedArrays)return new f(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t<n;t+=1)e[t]=this[t];return e.buffer};var t=f.prototype;function S(e,t,n){return\"number\"!=typeof e?n:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function j(e){return(e=~~Math.ceil(+e))<0?0:e}function C(e){return(Array.isArray||function(e){return\"[object Array]\"===Object.prototype.toString.call(e)})(e)}function k(e){return e<16?\"0\"+e.toString(16):e.toString(16)}function T(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t.push(e.charCodeAt(n));else for(var o=n,i=(55296<=r&&r<=57343&&n++,encodeURIComponent(e.slice(o,n+1)).substr(1).split(\"%\")),u=0;u<i.length;u++)t.push(parseInt(i[u],16))}return t}function M(e){return a.toByteArray(e)}function c(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);o++)t[o+n]=e[o];return o}function N(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function Y(e,t){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(0<=e,\"specified a negative value for writing an unsigned value\"),d(e<=t,\"value is larger than maximum value for type\"),d(Math.floor(e)===e,\"value has a fractional component\")}function F(e,t,n){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(e<=t,\"value larger than maximum allowed value\"),d(n<=e,\"value smaller than minimum allowed value\"),d(Math.floor(e)===e,\"value has a fractional component\")}function D(e,t,n){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(e<=t,\"value larger than maximum allowed value\"),d(n<=e,\"value smaller than minimum allowed value\")}function d(e,t){if(!e)throw new Error(t||\"Failed assertion\")}f._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=t.get,e.set=t.set,e.write=t.write,e.toString=t.toString,e.toLocaleString=t.toString,e.toJSON=t.toJSON,e.copy=t.copy,e.slice=t.slice,e.readUInt8=t.readUInt8,e.readUInt16LE=t.readUInt16LE,e.readUInt16BE=t.readUInt16BE,e.readUInt32LE=t.readUInt32LE,e.readUInt32BE=t.readUInt32BE,e.readInt8=t.readInt8,e.readInt16LE=t.readInt16LE,e.readInt16BE=t.readInt16BE,e.readInt32LE=t.readInt32LE,e.readInt32BE=t.readInt32BE,e.readFloatLE=t.readFloatLE,e.readFloatBE=t.readFloatBE,e.readDoubleLE=t.readDoubleLE,e.readDoubleBE=t.readDoubleBE,e.writeUInt8=t.writeUInt8,e.writeUInt16LE=t.writeUInt16LE,e.writeUInt16BE=t.writeUInt16BE,e.writeUInt32LE=t.writeUInt32LE,e.writeUInt32BE=t.writeUInt32BE,e.writeInt8=t.writeInt8,e.writeInt16LE=t.writeInt16LE,e.writeInt16BE=t.writeInt16BE,e.writeInt32LE=t.writeInt32LE,e.writeInt32BE=t.writeInt32BE,e.writeFloatLE=t.writeFloatLE,e.writeFloatBE=t.writeFloatBE,e.writeDoubleLE=t.writeDoubleLE,e.writeDoubleBE=t.writeDoubleBE,e.fill=t.fill,e.inspect=t.inspect,e.toArrayBuffer=t.toArrayBuffer,e}}.call(this,O(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},O(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/buffer/index.js\",\"/node_modules/gulp-browserify/node_modules/buffer\")},{\"base64-js\":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(c,d,e){!function(e,t,a,n,r,o,i,u,s){var a=c(\"buffer\").Buffer,f=4,l=new a(f);l.fill(0);d.exports={hash:function(e,t,n,r){for(var o=t(function(e,t){e.length%f!=0&&(n=e.length+(f-e.length%f),e=a.concat([e,l],n));for(var n,r=[],o=t?e.readInt32BE:e.readInt32LE,i=0;i<e.length;i+=f)r.push(o.call(e,i));return r}(e=a.isBuffer(e)?e:new a(e),r),8*e.length),t=r,i=new a(n),u=t?i.writeInt32BE:i.writeInt32LE,s=0;s<o.length;s++)u.call(i,o[s],4*s,!0);return i}}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{buffer:3,lYpoI2:11}],5:[function(v,e,_){!function(l,c,u,d,h,p,g,y,w){var u=v(\"buffer\").Buffer,e=v(\"./sha\"),t=v(\"./sha256\"),n=v(\"./rng\"),b={sha1:e,sha256:t,md5:v(\"./md5\")},s=64,a=new u(s);function r(e,n){var r=b[e=e||\"sha1\"],o=[];return r||i(\"algorithm:\",e,\"is not yet supported\"),{update:function(e){return u.isBuffer(e)||(e=new u(e)),o.push(e),e.length,this},digest:function(e){var t=u.concat(o),t=n?function(e,t,n){u.isBuffer(t)||(t=new u(t)),u.isBuffer(n)||(n=new u(n)),t.length>s?t=e(t):t.length<s&&(t=u.concat([t,a],s));for(var r=new u(s),o=new u(s),i=0;i<s;i++)r[i]=54^t[i],o[i]=92^t[i];return n=e(u.concat([r,n])),e(u.concat([o,n]))}(r,n,t):r(t);return o=null,e?t.toString(e):t}}}function i(){var e=[].slice.call(arguments).join(\" \");throw new Error([e,\"we accept pull requests\",\"http://github.com/dominictarr/crypto-browserify\"].join(\"\\n\"))}a.fill(0),_.createHash=function(e){return r(e)},_.createHmac=r,_.randomBytes=function(e,t){if(!t||!t.call)return new u(n(e));try{t.call(this,void 0,new u(n(e)))}catch(e){t(e)}};var o,f=[\"createCredentials\",\"createCipher\",\"createCipheriv\",\"createDecipher\",\"createDecipheriv\",\"createSign\",\"createVerify\",\"createDiffieHellman\",\"pbkdf2\"],m=function(e){_[e]=function(){i(\"sorry,\",e,\"is not implemented yet\")}};for(o in f)m(f[o],o)}.call(this,v(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},v(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./md5\":6,\"./rng\":7,\"./sha\":8,\"./sha256\":9,buffer:3,lYpoI2:11}],6:[function(w,b,e){!function(e,r,o,i,u,a,f,l,y){var t=w(\"./helpers\");function n(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var n=1732584193,r=-271733879,o=-1732584194,i=271733878,u=0;u<e.length;u+=16){var s=n,a=r,f=o,l=i,n=c(n,r,o,i,e[u+0],7,-680876936),i=c(i,n,r,o,e[u+1],12,-389564586),o=c(o,i,n,r,e[u+2],17,606105819),r=c(r,o,i,n,e[u+3],22,-1044525330);n=c(n,r,o,i,e[u+4],7,-176418897),i=c(i,n,r,o,e[u+5],12,1200080426),o=c(o,i,n,r,e[u+6],17,-1473231341),r=c(r,o,i,n,e[u+7],22,-45705983),n=c(n,r,o,i,e[u+8],7,1770035416),i=c(i,n,r,o,e[u+9],12,-1958414417),o=c(o,i,n,r,e[u+10],17,-42063),r=c(r,o,i,n,e[u+11],22,-1990404162),n=c(n,r,o,i,e[u+12],7,1804603682),i=c(i,n,r,o,e[u+13],12,-40341101),o=c(o,i,n,r,e[u+14],17,-1502002290),n=d(n,r=c(r,o,i,n,e[u+15],22,1236535329),o,i,e[u+1],5,-165796510),i=d(i,n,r,o,e[u+6],9,-1069501632),o=d(o,i,n,r,e[u+11],14,643717713),r=d(r,o,i,n,e[u+0],20,-373897302),n=d(n,r,o,i,e[u+5],5,-701558691),i=d(i,n,r,o,e[u+10],9,38016083),o=d(o,i,n,r,e[u+15],14,-660478335),r=d(r,o,i,n,e[u+4],20,-405537848),n=d(n,r,o,i,e[u+9],5,568446438),i=d(i,n,r,o,e[u+14],9,-1019803690),o=d(o,i,n,r,e[u+3],14,-187363961),r=d(r,o,i,n,e[u+8],20,1163531501),n=d(n,r,o,i,e[u+13],5,-1444681467),i=d(i,n,r,o,e[u+2],9,-51403784),o=d(o,i,n,r,e[u+7],14,1735328473),n=h(n,r=d(r,o,i,n,e[u+12],20,-1926607734),o,i,e[u+5],4,-378558),i=h(i,n,r,o,e[u+8],11,-2022574463),o=h(o,i,n,r,e[u+11],16,1839030562),r=h(r,o,i,n,e[u+14],23,-35309556),n=h(n,r,o,i,e[u+1],4,-1530992060),i=h(i,n,r,o,e[u+4],11,1272893353),o=h(o,i,n,r,e[u+7],16,-155497632),r=h(r,o,i,n,e[u+10],23,-1094730640),n=h(n,r,o,i,e[u+13],4,681279174),i=h(i,n,r,o,e[u+0],11,-358537222),o=h(o,i,n,r,e[u+3],16,-722521979),r=h(r,o,i,n,e[u+6],23,76029189),n=h(n,r,o,i,e[u+9],4,-640364487),i=h(i,n,r,o,e[u+12],11,-421815835),o=h(o,i,n,r,e[u+15],16,530742520),n=p(n,r=h(r,o,i,n,e[u+2],23,-995338651),o,i,e[u+0],6,-198630844),i=p(i,n,r,o,e[u+7],10,1126891415),o=p(o,i,n,r,e[u+14],15,-1416354905),r=p(r,o,i,n,e[u+5],21,-57434055),n=p(n,r,o,i,e[u+12],6,1700485571),i=p(i,n,r,o,e[u+3],10,-1894986606),o=p(o,i,n,r,e[u+10],15,-1051523),r=p(r,o,i,n,e[u+1],21,-2054922799),n=p(n,r,o,i,e[u+8],6,1873313359),i=p(i,n,r,o,e[u+15],10,-30611744),o=p(o,i,n,r,e[u+6],15,-1560198380),r=p(r,o,i,n,e[u+13],21,1309151649),n=p(n,r,o,i,e[u+4],6,-145523070),i=p(i,n,r,o,e[u+11],10,-1120210379),o=p(o,i,n,r,e[u+2],15,718787259),r=p(r,o,i,n,e[u+9],21,-343485551),n=g(n,s),r=g(r,a),o=g(o,f),i=g(i,l)}return Array(n,r,o,i)}function s(e,t,n,r,o,i){return g((t=g(g(t,e),g(r,i)))<<o|t>>>32-o,n)}function c(e,t,n,r,o,i,u){return s(t&n|~t&r,e,t,o,i,u)}function d(e,t,n,r,o,i,u){return s(t&r|n&~r,e,t,o,i,u)}function h(e,t,n,r,o,i,u){return s(t^n^r,e,t,o,i,u)}function p(e,t,n,r,o,i,u){return s(n^(t|~r),e,t,o,i,u)}function g(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}b.exports=function(e){return t.hash(e,n,16)}}.call(this,w(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},w(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],7:[function(e,l,t){!function(e,t,n,r,o,i,u,s,f){var a;l.exports=a||function(e){for(var t,n=new Array(e),r=0;r<e;r++)0==(3&r)&&(t=4294967296*Math.random()),n[r]=t>>>((3&r)<<3)&255;return n}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{buffer:3,lYpoI2:11}],8:[function(c,d,e){!function(e,t,n,r,o,s,a,f,l){var i=c(\"./helpers\");function u(l,c){l[c>>5]|=128<<24-c%32,l[15+(c+64>>9<<4)]=c;for(var e,t,n,r=Array(80),o=1732584193,i=-271733879,u=-1732584194,s=271733878,d=-1009589776,h=0;h<l.length;h+=16){for(var p=o,g=i,y=u,w=s,b=d,a=0;a<80;a++){r[a]=a<16?l[h+a]:v(r[a-3]^r[a-8]^r[a-14]^r[a-16],1);var f=m(m(v(o,5),(f=i,t=u,n=s,(e=a)<20?f&t|~f&n:!(e<40)&&e<60?f&t|f&n|t&n:f^t^n)),m(m(d,r[a]),(e=a)<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514)),d=s,s=u,u=v(i,30),i=o,o=f}o=m(o,p),i=m(i,g),u=m(u,y),s=m(s,w),d=m(d,b)}return Array(o,i,u,s,d)}function m(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function v(e,t){return e<<t|e>>>32-t}d.exports=function(e){return i.hash(e,u,20,!0)}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],9:[function(c,d,e){!function(e,t,n,r,u,s,a,f,l){function b(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function o(e,l){var c,d=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),t=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),n=new Array(64);e[l>>5]|=128<<24-l%32,e[15+(l+64>>9<<4)]=l;for(var r,o,h=0;h<e.length;h+=16){for(var i=t[0],u=t[1],s=t[2],p=t[3],a=t[4],g=t[5],y=t[6],w=t[7],f=0;f<64;f++)n[f]=f<16?e[f+h]:b(b(b((o=n[f-2],m(o,17)^m(o,19)^v(o,10)),n[f-7]),(o=n[f-15],m(o,7)^m(o,18)^v(o,3))),n[f-16]),c=b(b(b(b(w,m(o=a,6)^m(o,11)^m(o,25)),a&g^~a&y),d[f]),n[f]),r=b(m(r=i,2)^m(r,13)^m(r,22),i&u^i&s^u&s),w=y,y=g,g=a,a=b(p,c),p=s,s=u,u=i,i=b(c,r);t[0]=b(i,t[0]),t[1]=b(u,t[1]),t[2]=b(s,t[2]),t[3]=b(p,t[3]),t[4]=b(a,t[4]),t[5]=b(g,t[5]),t[6]=b(y,t[6]),t[7]=b(w,t[7])}return t}var i=c(\"./helpers\"),m=function(e,t){return e>>>t|e<<32-t},v=function(e,t){return e>>>t};d.exports=function(e){return i.hash(e,o,32,!0)}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],10:[function(e,t,f){!function(e,t,n,r,o,i,u,s,a){f.read=function(e,t,n,r,o){var i,u,l=8*o-r-1,c=(1<<l)-1,d=c>>1,s=-7,a=n?o-1:0,f=n?-1:1,o=e[t+a];for(a+=f,i=o&(1<<-s)-1,o>>=-s,s+=l;0<s;i=256*i+e[t+a],a+=f,s-=8);for(u=i&(1<<-s)-1,i>>=-s,s+=r;0<s;u=256*u+e[t+a],a+=f,s-=8);if(0===i)i=1-d;else{if(i===c)return u?NaN:1/0*(o?-1:1);u+=Math.pow(2,r),i-=d}return(o?-1:1)*u*Math.pow(2,i-r)},f.write=function(e,t,l,n,r,c){var o,i,u=8*c-r-1,s=(1<<u)-1,a=s>>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:c-1,h=n?1:-1,c=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=s):(o=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-o))<1&&(o--,n*=2),2<=(t+=1<=o+a?d/n:d*Math.pow(2,1-a))*n&&(o++,n/=2),s<=o+a?(i=0,o=s):1<=o+a?(i=(t*n-1)*Math.pow(2,r),o+=a):(i=t*Math.pow(2,a-1)*Math.pow(2,r),o=0));8<=r;e[l+f]=255&i,f+=h,i/=256,r-=8);for(o=o<<r|i,u+=r;0<u;e[l+f]=255&o,f+=h,o/=256,u-=8);e[l+f-h]|=128*c}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/ieee754/index.js\",\"/node_modules/gulp-browserify/node_modules/ieee754\")},{buffer:3,lYpoI2:11}],11:[function(e,h,t){!function(e,t,n,r,o,f,l,c,d){var i,u,s;function a(){}(e=h.exports={}).nextTick=(u=\"undefined\"!=typeof window&&window.setImmediate,s=\"undefined\"!=typeof window&&window.postMessage&&window.addEventListener,u?function(e){return window.setImmediate(e)}:s?(i=[],window.addEventListener(\"message\",function(e){var t=e.source;t!==window&&null!==t||\"process-tick\"!==e.data||(e.stopPropagation(),0<i.length&&i.shift()())},!0),function(e){i.push(e),window.postMessage(\"process-tick\",\"*\")}):function(e){setTimeout(e,0)}),e.title=\"browser\",e.browser=!0,e.env={},e.argv=[],e.on=a,e.addListener=a,e.once=a,e.off=a,e.removeListener=a,e.removeAllListeners=a,e.emit=a,e.binding=function(e){throw new Error(\"process.binding is not supported\")},e.cwd=function(){return\"/\"},e.chdir=function(e){throw new Error(\"process.chdir is not supported\")}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/process/browser.js\",\"/node_modules/gulp-browserify/node_modules/process\")},{buffer:3,lYpoI2:11}]},{},[1])(1)});","import hash from \"object-hash\";\nimport { GeoPoint } from \"@rebasepro/types\";\n//#region src/strings.ts\nvar tokenizeRegex = /[A-Z]{2,}(?=[A-Z][a-z]|\\b)|[A-Z]?[a-z]+|[0-9]+(?:[a-z](?![a-z]))?|[A-Z]/g;\nvar toKebabCase = (str) => {\n\tif (!str || typeof str !== \"string\") return \"\";\n\tconst regExpMatchArray = str.match(tokenizeRegex);\n\tif (!regExpMatchArray) return \"\";\n\treturn regExpMatchArray.map((x) => x.toLowerCase()).join(\"-\");\n};\nvar snakeCaseRegex = tokenizeRegex;\nvar toSnakeCase = (str) => {\n\tif (!str || typeof str !== \"string\") return \"\";\n\tconst regExpMatchArray = str.match(snakeCaseRegex);\n\tif (!regExpMatchArray) return \"\";\n\treturn regExpMatchArray.map((x) => x.toLowerCase()).join(\"_\");\n};\nfunction camelCase(str) {\n\tif (!str) return \"\";\n\tif (str.length === 1) return str.toLowerCase();\n\tconst parts = str.split(/[-_ ]+/).filter(Boolean);\n\tif (parts.length === 0) return \"\";\n\treturn parts[0].toLowerCase() + parts.slice(1).map((part) => part.charAt(0).toUpperCase() + part.substring(1).toLowerCase()).join(\"\");\n}\nfunction randomString(strLength = 5) {\n\treturn Math.random().toString(36).slice(2, 2 + strLength);\n}\nfunction randomColor() {\n\treturn Math.floor(Math.random() * 16777215).toString(16);\n}\nfunction slugify(text, separator = \"_\", lowercase = true) {\n\tif (!text) return \"\";\n\tconst from = \"ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;-\";\n\tconst to = `aaaaaeeeeeiiiiooooouuuunc${separator}${separator}${separator}${separator}${separator}${separator}${separator}`;\n\tfor (let i = 0, l = 32; i < l; i++) text = text.replace(new RegExp(from.charAt(i), \"g\"), to.charAt(i));\n\ttext = text.toString().trim().replace(/^\\s+|\\s+$/g, \"\").replace(/\\s+/g, separator).replace(/&/g, separator).replace(/[^\\w\\\\-]+/g, \"\").replace(new RegExp(\"\\\\\" + separator + \"\\\\\" + separator + \"+\", \"g\"), separator);\n\treturn lowercase ? text.toLowerCase() : text;\n}\nfunction unslugify(slug) {\n\tif (!slug) return \"\";\n\tif (slug.includes(\"-\") || slug.includes(\"_\") || !slug.includes(\" \")) return slug.replace(/[-_]/g, \" \").replace(/\\w\\S*/g, function(txt) {\n\t\treturn txt.charAt(0).toUpperCase() + txt.substring(1);\n\t}).trim();\n\telse return slug.trim();\n}\nfunction prettifyIdentifier(input) {\n\tif (!input) return \"\";\n\tlet text = input;\n\ttext = text.replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, \"$1$3 $2$4\");\n\ttext = text.replace(/[_-]+/g, \" \");\n\treturn text.trim().replace(/\\b\\w/g, (char) => char.toUpperCase());\n}\n//#endregion\n//#region src/objects.ts\n/** @private is the value an empty array? */\nvar isEmptyArray = (value) => Array.isArray(value) && value.length === 0;\n/** @private is the given object a Function? */\nvar isFunction = (obj) => typeof obj === \"function\";\n/** @private is the given object an integer? */\nvar isInteger = (obj) => String(Math.floor(Number(obj))) === String(obj);\n/** @private is the given object a NaN? */\nvar isNaN = (obj) => obj !== obj;\n/**\n* Deeply get a value from an object via its path.\n*/\nfunction getIn(obj, key, def, p = 0) {\n\tconst path = toPath(key);\n\twhile (obj && p < path.length) obj = obj[path[p++]];\n\tif (p !== path.length && !obj) return def;\n\treturn obj === void 0 ? def : obj;\n}\nfunction setIn(obj, path, value) {\n\tconst res = clone(obj);\n\tlet resVal = res;\n\tlet i = 0;\n\tconst pathArray = toPath(path);\n\tfor (; i < pathArray.length - 1; i++) {\n\t\tconst currentPath = pathArray[i];\n\t\tconst currentObj = getIn(obj, pathArray.slice(0, i + 1));\n\t\tif (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) resVal = resVal[currentPath] = clone(currentObj);\n\t\telse {\n\t\t\tconst nextPath = pathArray[i + 1];\n\t\t\tresVal = resVal[currentPath] = isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {};\n\t\t}\n\t}\n\tif ((i === 0 ? obj : resVal)[pathArray[i]] === value) return obj;\n\tif (value === void 0) delete resVal[pathArray[i]];\n\telse resVal[pathArray[i]] = value;\n\tif (i === 0 && value === void 0) delete res[pathArray[i]];\n\treturn res;\n}\nfunction clone(value) {\n\tif (Array.isArray(value)) return [...value];\n\telse if (typeof value === \"object\" && value !== null) return { ...value };\n\telse return value;\n}\n/**\n* Deep clone a value, preserving function references and class instances.\n* Unlike structuredClone, this handles objects that contain functions\n* (e.g. CollectionConfig with target(), childCollections(), callbacks).\n*/\nfunction deepClone(value) {\n\tif (value === null || value === void 0) return value;\n\tif (typeof value === \"function\") return value;\n\tif (typeof value !== \"object\") return value;\n\tif (Array.isArray(value)) return value.map((item) => deepClone(item));\n\tif (Object.getPrototypeOf(value) !== Object.prototype) return value;\n\tconst result = {};\n\tfor (const key of Object.keys(value)) result[key] = deepClone(value[key]);\n\treturn result;\n}\nfunction toPath(value) {\n\tif (Array.isArray(value)) return value;\n\treturn value.replace(/\\[(\\d+)]/g, \".$1\").replace(/^\\./, \"\").replace(/\\.$/, \"\").split(\".\");\n}\nvar pick = (obj, ...args) => ({ ...args.reduce((res, key) => ({\n\t...res,\n\t[key]: obj[key]\n}), {}) });\nfunction isObject(item) {\n\treturn !!item && typeof item === \"object\" && !Array.isArray(item);\n}\nfunction isPlainObject(obj) {\n\tif (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return false;\n\treturn Object.getPrototypeOf(obj) === Object.prototype;\n}\nfunction mergeDeep(target, source, ignoreUndefined = false) {\n\tif (!isObject(target)) return target;\n\tconst output = { ...target };\n\tif (!isObject(source)) return output;\n\tfor (const key in source) {\n\t\tif (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n\t\tif (Object.prototype.hasOwnProperty.call(source, key)) {\n\t\t\tconst sourceValue = source[key];\n\t\t\tconst outputValue = output[key];\n\t\t\tif (ignoreUndefined && sourceValue === void 0) continue;\n\t\t\tif (sourceValue instanceof Date) output[key] = new Date(sourceValue.getTime());\n\t\t\telse if (Array.isArray(sourceValue)) if (Array.isArray(outputValue)) if (!(sourceValue.some(isPlainObject) || outputValue.some(isPlainObject))) output[key] = [...sourceValue];\n\t\t\telse {\n\t\t\t\tconst newArray = [];\n\t\t\t\tconst maxLength = Math.max(outputValue.length, sourceValue.length);\n\t\t\t\tfor (let i = 0; i < maxLength; i++) {\n\t\t\t\t\tconst sourceItem = sourceValue[i];\n\t\t\t\t\tconst targetItem = outputValue[i];\n\t\t\t\t\tif (i >= sourceValue.length) newArray[i] = targetItem;\n\t\t\t\t\telse if (i >= outputValue.length) newArray[i] = sourceItem;\n\t\t\t\t\telse if (sourceItem === null) newArray[i] = targetItem;\n\t\t\t\t\telse if (isPlainObject(sourceItem) && isPlainObject(targetItem)) newArray[i] = mergeDeep(targetItem, sourceItem, ignoreUndefined);\n\t\t\t\t\telse newArray[i] = sourceItem;\n\t\t\t\t}\n\t\t\t\toutput[key] = newArray;\n\t\t\t}\n\t\t\telse output[key] = [...sourceValue];\n\t\t\telse if (isPlainObject(sourceValue)) if (isPlainObject(outputValue)) output[key] = mergeDeep(outputValue, sourceValue, ignoreUndefined);\n\t\t\telse output[key] = sourceValue;\n\t\t\telse if (isObject(sourceValue)) output[key] = sourceValue;\n\t\t\telse output[key] = sourceValue;\n\t\t}\n\t}\n\treturn output;\n}\nfunction getValueInPath(o, path) {\n\tif (!o) return void 0;\n\tif (typeof o === \"object\") {\n\t\tif (path in o) return o[path];\n\t\tif (path.includes(\".\") || path.includes(\"[\")) {\n\t\t\tlet pathSegments = path.split(/[.[]/);\n\t\t\tif (path.includes(\"[\")) pathSegments = pathSegments.map((segment) => segment.replace(\"]\", \"\"));\n\t\t\tconst firstSegment = pathSegments[0];\n\t\t\tconst isArrayAndIndexExists = Array.isArray(o[firstSegment]) && !isNaN(parseInt(pathSegments[1]));\n\t\t\tconst nextObject = isArrayAndIndexExists ? o[firstSegment][parseInt(pathSegments[1])] : o[firstSegment];\n\t\t\tconst nextPath = pathSegments.slice(isArrayAndIndexExists ? 2 : 1).join(\".\");\n\t\t\tif (nextPath === \"\") return nextObject;\n\t\t\treturn getValueInPath(nextObject, nextPath);\n\t\t}\n\t}\n}\nfunction removeInPath(o, path) {\n\tconst res = clone(o);\n\tlet current = res;\n\tconst parts = path.split(\".\");\n\tconst last = parts.pop();\n\tfor (const part of parts) if (part in current && current[part] !== null && typeof current[part] === \"object\") {\n\t\tcurrent[part] = clone(current[part]);\n\t\tcurrent = current[part];\n\t} else return res;\n\tif (last && current && typeof current === \"object\") delete current[last];\n\treturn res;\n}\nfunction removeFunctions(o) {\n\tif (o === void 0) return void 0;\n\tif (o === null) return null;\n\tif (typeof o === \"object\") {\n\t\tif (Array.isArray(o)) return o.map((v) => removeFunctions(v));\n\t\tif (!isPlainObject(o)) return o;\n\t\treturn Object.entries(o).filter(([_, value]) => typeof value !== \"function\").map(([key, value]) => {\n\t\t\tif (Array.isArray(value)) return { [key]: value.map((v) => removeFunctions(v)) };\n\t\t\telse if (typeof value === \"object\") return { [key]: removeFunctions(value) };\n\t\t\telse return { [key]: value };\n\t\t}).reduce((a, b) => ({\n\t\t\t...a,\n\t\t\t...b\n\t\t}), {});\n\t}\n\treturn o;\n}\nfunction getHashValue(v) {\n\tif (!v) return null;\n\tif (typeof v === \"object\" && v !== null) {\n\t\tif (\"id\" in v) return String(v.id);\n\t\telse if (v instanceof Date) return v.toLocaleString();\n\t\telse if (v instanceof GeoPoint) return hash(v);\n\t}\n\treturn hash(v, { ignoreUnknown: true });\n}\nfunction removeUndefined(value, removeEmptyStrings) {\n\tif (typeof value === \"function\") return value;\n\tif (Array.isArray(value)) return value.map((v) => removeUndefined(v, removeEmptyStrings));\n\tif (typeof value === \"object\") {\n\t\tif (value === null) return value;\n\t\tif (!isPlainObject(value)) return value;\n\t\tconst res = {};\n\t\tObject.keys(value).forEach((key) => {\n\t\t\tif (!isEmptyObject(value)) {\n\t\t\t\tconst childRes = removeUndefined(value[key], removeEmptyStrings);\n\t\t\t\tconst isString = typeof childRes === \"string\";\n\t\t\t\tconst shouldKeepIfString = !removeEmptyStrings || removeEmptyStrings && !isString || removeEmptyStrings && isString && childRes !== \"\";\n\t\t\t\tif (childRes !== void 0 && !isEmptyObject(childRes) && shouldKeepIfString) res[key] = childRes;\n\t\t\t}\n\t\t});\n\t\treturn res;\n\t}\n\treturn value;\n}\nfunction removeNulls(value) {\n\tif (typeof value === \"function\") return value;\n\tif (Array.isArray(value)) return value.map((v) => removeNulls(v));\n\tif (typeof value === \"object\") {\n\t\tif (value === null) return value;\n\t\tif (!isPlainObject(value)) return value;\n\t\tconst res = {};\n\t\tconst obj = value;\n\t\tObject.keys(obj).forEach((key) => {\n\t\t\tif (obj[key] !== null) res[key] = removeNulls(obj[key]);\n\t\t});\n\t\treturn res;\n\t}\n\treturn value;\n}\nfunction isEmptyObject(obj) {\n\treturn obj && Object.getPrototypeOf(obj) === Object.prototype && Object.keys(obj).length === 0;\n}\nfunction removePropsIfExisting(source, comparison) {\n\tconst isObject = (val) => typeof val === \"object\" && val !== null;\n\tconst isArray = (val) => Array.isArray(val);\n\tif (!isObject(source) || !isObject(comparison)) return source;\n\tconst res = isArray(source) ? [...source] : { ...source };\n\tif (isArray(res)) {\n\t\tfor (let i = res.length - 1; i >= 0; i--) if (res[i] === comparison[i]) res.splice(i, 1);\n\t\telse if (isObject(res[i]) && isObject(comparison[i])) res[i] = removePropsIfExisting(res[i], comparison[i]);\n\t} else Object.keys(comparison).forEach((key) => {\n\t\tif (key in res) {\n\t\t\tif (isObject(res[key]) && isObject(comparison[key])) res[key] = removePropsIfExisting(res[key], comparison[key]);\n\t\t\telse if (res[key] === comparison[key]) delete res[key];\n\t\t}\n\t});\n\treturn res;\n}\n//#endregion\n//#region src/arrays.ts\nfunction toArray(input) {\n\treturn Array.isArray(input) ? input : input ? [input] : [];\n}\n//#endregion\n//#region src/dates.ts\nvar defaultDateFormat = \"MMMM dd, yyyy, HH:mm:ss\";\n//#endregion\n//#region src/hash.ts\nfunction hashString(str) {\n\tif (!str) return 0;\n\tlet hash = 0;\n\tlet i;\n\tlet chr;\n\tfor (i = 0; i < str.length; i++) {\n\t\tchr = str.charCodeAt(i);\n\t\thash = (hash << 5) - hash + chr;\n\t\thash |= 0;\n\t}\n\treturn Math.abs(hash);\n}\n//#endregion\n//#region src/regexp.ts\nfunction serializeRegExp(input) {\n\tif (!input) return \"\";\n\treturn input.toString();\n}\n/**\n* Get a RegExp out of a serialized string\n* @param input\n*/\nfunction hydrateRegExp(input) {\n\tif (!input) return void 0;\n\tconst fragments = input.match(/\\/(.*?)\\/([a-z]*)?$/i);\n\tif (fragments) return new RegExp(fragments[1], fragments[2] || \"\");\n\telse return new RegExp(input, \"\");\n}\nfunction isValidRegExp(input) {\n\tif (input.match(/\\/((?![*+?])(?:[^\\r\\n[/\\\\]|\\\\.|\\[(?:[^\\r\\n\\]\\\\]|\\\\.)*])+)\\/((?:g(?:im?|mi?)?|i(?:gm?|mg?)?|m(?:gi?|ig?)?)?)/)) return true;\n\treturn !!input.match(/((?![*+?])(?:[^\\r\\n[/\\\\]|\\\\.|\\[(?:[^\\r\\n\\]\\\\]|\\\\.)*])+)/);\n}\n//#endregion\n//#region src/flatten_object.ts\nfunction flattenObject(obj, parentKey = \"\") {\n\tif (!obj) return obj;\n\treturn Object.keys(obj).reduce((flatObj, key) => {\n\t\tconst newKey = parentKey ? `${parentKey}.${key}` : key;\n\t\tif (typeof obj[key] === \"object\" && obj[key] !== null) if (Array.isArray(obj[key])) obj[key].forEach((item, index) => {\n\t\t\tif (typeof item === \"object\" && item !== null) Object.assign(flatObj, flattenObject(item, `${newKey}[${index}]`));\n\t\t\telse flatObj[`${newKey}[${index}]`] = item;\n\t\t});\n\t\telse Object.assign(flatObj, flattenObject(obj[key], newKey));\n\t\telse flatObj[newKey] = obj[key];\n\t\treturn flatObj;\n\t}, {});\n}\nfunction getArrayValuesCount(array) {\n\treturn array.reduce((acc, obj) => {\n\t\tObject.entries(obj).forEach(([key, value]) => {\n\t\t\tif (Array.isArray(value)) acc[key] = Math.max(acc[key] || 0, value.length);\n\t\t\tif (typeof value === \"object\" && value !== null) {\n\t\t\t\tconst nested = getArrayValuesCount([value]);\n\t\t\t\tObject.entries(nested).forEach(([nestedKey, nestedCount]) => {\n\t\t\t\t\tconst compoundKey = `${key}.${nestedKey}`;\n\t\t\t\t\tacc[compoundKey] = Math.max(acc[compoundKey] || 0, nestedCount);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\treturn acc;\n\t}, {});\n}\n//#endregion\n//#region src/plurals.ts\n/**\n* Returns the plural of an English word.\n*\n* @param {string} word\n* @param {number} [amount]\n* @returns {string}\n*/\nfunction plural(word, amount) {\n\tif (amount !== void 0 && amount === 1) return word;\n\tconst plurals = {\n\t\t\"(quiz)$\": \"$1zes\",\n\t\t\"^(ox)$\": \"$1en\",\n\t\t\"([m|l])ouse$\": \"$1ice\",\n\t\t\"(matr|vert|ind)ix|ex$\": \"$1ices\",\n\t\t\"(x|ch|ss|sh)$\": \"$1es\",\n\t\t\"([^aeiouy]|qu)y$\": \"$1ies\",\n\t\t\"(hive)$\": \"$1s\",\n\t\t\"(?:([^f])fe|([lr])f)$\": \"$1$2ves\",\n\t\t\"(shea|lea|loa|thie)f$\": \"$1ves\",\n\t\tsis$: \"ses\",\n\t\t\"([ti])um$\": \"$1a\",\n\t\t\"(tomat|potat|ech|her|vet)o$\": \"$1oes\",\n\t\t\"(bu)s$\": \"$1ses\",\n\t\t\"(alias)$\": \"$1es\",\n\t\t\"(octop)us$\": \"$1i\",\n\t\t\"(ax|test)is$\": \"$1es\",\n\t\t\"(us)$\": \"$1es\",\n\t\t\"([^s]+)$\": \"$1s\"\n\t};\n\tconst irregular = {\n\t\tmove: \"moves\",\n\t\tfoot: \"feet\",\n\t\tgoose: \"geese\",\n\t\tsex: \"sexes\",\n\t\tchild: \"children\",\n\t\tman: \"men\",\n\t\ttooth: \"teeth\",\n\t\tperson: \"people\"\n\t};\n\tif ([\n\t\t\"sheep\",\n\t\t\"fish\",\n\t\t\"deer\",\n\t\t\"moose\",\n\t\t\"series\",\n\t\t\"species\",\n\t\t\"money\",\n\t\t\"rice\",\n\t\t\"information\",\n\t\t\"equipment\",\n\t\t\"bison\",\n\t\t\"cod\",\n\t\t\"offspring\",\n\t\t\"pike\",\n\t\t\"salmon\",\n\t\t\"shrimp\",\n\t\t\"swine\",\n\t\t\"trout\",\n\t\t\"aircraft\",\n\t\t\"hovercraft\",\n\t\t\"spacecraft\",\n\t\t\"sugar\",\n\t\t\"tuna\",\n\t\t\"you\",\n\t\t\"wood\"\n\t].indexOf(word.toLowerCase()) >= 0) return word;\n\tfor (const w in irregular) {\n\t\tconst pattern = new RegExp(`${w}$`, \"i\");\n\t\tconst replace = irregular[w];\n\t\tif (pattern.test(word)) return word.replace(pattern, replace);\n\t}\n\tfor (const reg in plurals) {\n\t\tconst pattern = new RegExp(reg, \"i\");\n\t\tif (pattern.test(word)) return word.replace(pattern, plurals[reg]);\n\t}\n\treturn word;\n}\n/**\n* Returns the singular of an English word.\n*\n* @param {string} word\n* @param {number} [amount]\n* @returns {string}\n*/\nfunction singular(word, amount) {\n\tif (amount !== void 0 && amount !== 1) return word;\n\tconst singulars = {\n\t\t\"(quiz)zes$\": \"$1\",\n\t\t\"(matr)ices$\": \"$1ix\",\n\t\t\"(vert|ind)ices$\": \"$1ex\",\n\t\t\"^(ox)en$\": \"$1\",\n\t\t\"(alias)es$\": \"$1\",\n\t\t\"(octop|vir)i$\": \"$1us\",\n\t\t\"(cris|ax|test)es$\": \"$1is\",\n\t\t\"(shoe)s$\": \"$1\",\n\t\t\"(o)es$\": \"$1\",\n\t\t\"(bus)es$\": \"$1\",\n\t\t\"([m|l])ice$\": \"$1ouse\",\n\t\t\"(x|ch|ss|sh)es$\": \"$1\",\n\t\t\"(m)ovies$\": \"$1ovie\",\n\t\t\"(s)eries$\": \"$1eries\",\n\t\t\"([^aeiouy]|qu)ies$\": \"$1y\",\n\t\t\"([lr])ves$\": \"$1f\",\n\t\t\"(tive)s$\": \"$1\",\n\t\t\"(hive)s$\": \"$1\",\n\t\t\"(li|wi|kni)ves$\": \"$1fe\",\n\t\t\"(shea|loa|lea|thie)ves$\": \"$1f\",\n\t\t\"(^analy)ses$\": \"$1sis\",\n\t\t\"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$\": \"$1$2sis\",\n\t\t\"([ti])a$\": \"$1um\",\n\t\t\"(n)ews$\": \"$1ews\",\n\t\t\"(h|bl)ouses$\": \"$1ouse\",\n\t\t\"(corpse)s$\": \"$1\",\n\t\t\"(us)es$\": \"$1\",\n\t\ts$: \"\"\n\t};\n\tconst irregular = {\n\t\tmove: \"moves\",\n\t\tfoot: \"feet\",\n\t\tgoose: \"geese\",\n\t\tsex: \"sexes\",\n\t\tchild: \"children\",\n\t\tman: \"men\",\n\t\ttooth: \"teeth\",\n\t\tperson: \"people\"\n\t};\n\tif ([\n\t\t\"sheep\",\n\t\t\"fish\",\n\t\t\"deer\",\n\t\t\"moose\",\n\t\t\"series\",\n\t\t\"species\",\n\t\t\"money\",\n\t\t\"rice\",\n\t\t\"information\",\n\t\t\"equipment\",\n\t\t\"bison\",\n\t\t\"cod\",\n\t\t\"offspring\",\n\t\t\"pike\",\n\t\t\"salmon\",\n\t\t\"shrimp\",\n\t\t\"swine\",\n\t\t\"trout\",\n\t\t\"aircraft\",\n\t\t\"hovercraft\",\n\t\t\"spacecraft\",\n\t\t\"sugar\",\n\t\t\"tuna\",\n\t\t\"you\",\n\t\t\"wood\"\n\t].indexOf(word.toLowerCase()) >= 0) return word;\n\tfor (const w in irregular) {\n\t\tconst pattern = new RegExp(`${irregular[w]}$`, \"i\");\n\t\tif (pattern.test(word)) return word.replace(pattern, w);\n\t}\n\tfor (const reg in singulars) {\n\t\tconst pattern = new RegExp(reg, \"i\");\n\t\tif (pattern.test(word)) return word.replace(pattern, singulars[reg]);\n\t}\n\treturn word;\n}\n//#endregion\n//#region src/names.ts\n/**\n* Generates a foreign key column name from a given string, typically a collection slug or name.\n* It converts the name to snake_case, attempts to singularize it by removing a trailing 's'\n* (a common convention for collection names), and appends '_id'.\n*\n* @param name The base name to convert to a foreign key.\n* @returns A foreign key name in the format 'singular_name_id'.\n*\n* @example\n* // returns \"user_id\"\n* generateForeignKeyName(\"users\")\n*\n* @example\n* // returns \"post_id\"\n* generateForeignKeyName(\"posts\")\n*\n* @example\n* // returns \"product_id\"\n* generateForeignKeyName(\"Product\")\n*\n*/\nfunction generateForeignKeyName(name) {\n\tconst snakeCaseName = toSnakeCase(name);\n\treturn `${snakeCaseName.endsWith(\"s\") ? snakeCaseName.slice(0, -1) : snakeCaseName}_id`;\n}\n//#endregion\n//#region src/fields.ts\nfunction isDefaultFieldConfigId(id) {\n\treturn [\n\t\t\"text_field\",\n\t\t\"multiline\",\n\t\t\"markdown\",\n\t\t\"url\",\n\t\t\"email\",\n\t\t\"switch\",\n\t\t\"select\",\n\t\t\"multi_select\",\n\t\t\"number_input\",\n\t\t\"number_select\",\n\t\t\"multi_number_select\",\n\t\t\"file_upload\",\n\t\t\"multi_file_upload\",\n\t\t\"reference\",\n\t\t\"multi_references\",\n\t\t\"relation\",\n\t\t\"date_time\",\n\t\t\"group\",\n\t\t\"key_value\",\n\t\t\"repeat\",\n\t\t\"custom_array\",\n\t\t\"block\"\n\t].includes(id);\n}\n//#endregion\nexport { camelCase, clone, deepClone, defaultDateFormat, flattenObject, generateForeignKeyName, getArrayValuesCount, getHashValue, getIn, getValueInPath, hashString, hydrateRegExp, isDefaultFieldConfigId, isEmptyArray, isEmptyObject, isFunction, isInteger, isNaN, isObject, isPlainObject, isValidRegExp, mergeDeep, pick, plural, prettifyIdentifier, randomColor, randomString, removeFunctions, removeInPath, removeNulls, removePropsIfExisting, removeUndefined, serializeRegExp, setIn, singular, slugify, toArray, toKebabCase, toSnakeCase, unslugify };\n\n//# sourceMappingURL=index.es.js.map","import { EnumValueConfig, EnumValues } from \"@rebasepro/types\";\n\nexport function enumToObjectEntries(enumValues: EnumValues): EnumValueConfig[] {\n if (Array.isArray(enumValues)) {\n return enumValues;\n } else {\n return Object.entries(enumValues).map(([id, value]) => {\n if (typeof value === \"string\") {\n return {\n id,\n label: value\n }\n } else {\n return {\n ...value,\n id\n }\n }\n });\n }\n}\n\nexport function getLabelOrConfigFrom(enumValues: EnumValueConfig[], key?: string | number): EnumValueConfig | undefined {\n if (key === null || key === undefined) return undefined;\n return enumValues.find((entry) => String(entry.id) === String(key));\n}\n","import { CollectionConfig, getDataSourceCapabilities, Property, Relation, RelationProperty } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport { generateForeignKeyName } from \"@rebasepro/utils\";\n\nexport function sanitizeRelation(\n relation: Partial<Relation>,\n sourceCollection: CollectionConfig,\n resolveCollection?: (slugOrTable: string) => CollectionConfig | undefined\n): Relation {\n if (!relation.target) {\n throw new Error(\"Relation is missing a `target` collection.\");\n }\n\n const rawTarget = relation.target;\n let targetCollection: CollectionConfig | undefined;\n\n if (typeof rawTarget === \"string\") {\n if (resolveCollection) {\n targetCollection = resolveCollection(rawTarget);\n }\n if (!targetCollection) {\n targetCollection = { slug: rawTarget,\nname: rawTarget } as CollectionConfig;\n }\n } else if (typeof rawTarget === \"function\") {\n const evaluated = rawTarget();\n if (typeof evaluated === \"string\") {\n if (resolveCollection) {\n targetCollection = resolveCollection(evaluated);\n }\n if (!targetCollection) {\n targetCollection = { slug: evaluated,\nname: evaluated } as CollectionConfig;\n }\n } else {\n targetCollection = evaluated;\n }\n } else if (rawTarget && typeof rawTarget === \"object\") {\n targetCollection = rawTarget as CollectionConfig;\n }\n\n if (!targetCollection) {\n throw new Error(\"Relation is missing a valid `target` collection.\");\n }\n\n const newRelation: Partial<Relation> = { ...relation };\n\n newRelation.target = () => {\n if (typeof rawTarget === \"string\") {\n return (resolveCollection && resolveCollection(rawTarget)) || targetCollection!;\n } else if (typeof rawTarget === \"function\") {\n const evaluated = rawTarget();\n if (typeof evaluated === \"string\") {\n return (resolveCollection && resolveCollection(evaluated)) || targetCollection!;\n }\n return evaluated;\n }\n return targetCollection!;\n };\n\n // 1. Default relationName from target collection slug\n if (!newRelation.relationName) {\n newRelation.relationName = toSnakeCase(targetCollection.slug);\n }\n\n // 2. Infer or default direction if absent\n if (!newRelation.direction) {\n if (newRelation.foreignKeyOnTarget) newRelation.direction = \"inverse\";\n else if (newRelation.through) newRelation.direction = \"owning\";\n else if (newRelation.cardinality === \"many\") newRelation.direction = \"inverse\"; // Default has-many to be inverse\n else newRelation.direction = \"owning\"; // Default all others to owning\n }\n\n // Do not default keys if a custom joinPath is provided; it's an advanced override.\n if (!newRelation.joinPath) {\n const sourceName = toSnakeCase(sourceCollection.slug ?? sourceCollection.name);\n\n // 3. Default keys based on the relation type (cardinality and direction)\n if (newRelation.cardinality === \"one\" && newRelation.direction === \"owning\") {\n // Belongs-to / many-to-one\n if (!newRelation.localKey) {\n newRelation.localKey = generateForeignKeyName(newRelation.relationName);\n }\n } else if (newRelation.cardinality === \"one\" && newRelation.direction === \"inverse\") {\n // Inverse one-to-one: the foreign key is on the target table pointing back to this collection\n if (!newRelation.foreignKeyOnTarget) {\n // First, try to find the corresponding owning relation's localKey on the target collection\n let foundForeignKey = false;\n\n try {\n // Look for an owning relation on the target that points back to this collection\n const targetRelations = getDataSourceCapabilities(targetCollection.engine).supportsRelations ? (targetCollection.relations || []) : [];\n for (const targetRel of targetRelations) {\n if (targetRel.direction === \"owning\" &&\n targetRel.cardinality === \"one\" &&\n targetRel.localKey) {\n try {\n const targetRelTarget = targetRel.target();\n if (targetRelTarget.slug === sourceCollection.slug) {\n // Found the corresponding owning relation, use its localKey\n newRelation.foreignKeyOnTarget = targetRel.localKey;\n foundForeignKey = true;\n break;\n }\n } catch (e) {\n // Continue looking if we can't resolve this target\n continue;\n }\n }\n }\n } catch (e) {\n // If we can't inspect the target collection, fall back to naming convention\n }\n\n // If we couldn't find an explicit foreign key, fall back to naming convention\n if (!foundForeignKey) {\n const keyPrefix = newRelation.inverseRelationName\n ? toSnakeCase(newRelation.inverseRelationName)\n : sourceName;\n newRelation.foreignKeyOnTarget = generateForeignKeyName(keyPrefix);\n }\n }\n } else if (newRelation.cardinality === \"many\" && newRelation.direction === \"inverse\") {\n // This could be either one-to-many or many-to-many inverse relation\n // We need to check if there's a corresponding owning many-to-many relation\n\n let isManyToManyInverse = false;\n\n // Try to determine if this is a many-to-many inverse relation\n if (newRelation.inverseRelationName && !newRelation.foreignKeyOnTarget) {\n try {\n // Look for a corresponding owning many-to-many relation on the target collection.\n // Note: we intentionally do NOT require `through` here because the raw (unsanitized)\n // relations won't have `through` populated yet — sanitizeRelation fills it in later.\n // `cardinality: \"many\" + direction: \"owning\"` is sufficient to identify owning M2M.\n\n // 1. Check the explicit relations[] array\n const targetRelations = getDataSourceCapabilities(targetCollection.engine).supportsRelations ? (targetCollection.relations || []) : [];\n for (const targetRel of targetRelations) {\n if (targetRel.cardinality === \"many\" &&\n (targetRel.direction === \"owning\" || !targetRel.direction) &&\n (targetRel.relationName === newRelation.inverseRelationName)) {\n isManyToManyInverse = true;\n break;\n }\n }\n\n // 2. Also check the target's properties for inline relation definitions\n // (e.g. posts.properties.tags = { type: \"relation\", cardinality: \"many\", direction: \"owning\" })\n if (!isManyToManyInverse && targetCollection.properties) {\n for (const [propKey, prop] of Object.entries(targetCollection.properties)) {\n if ((prop as Property).type !== \"relation\") continue;\n const relProp = prop as RelationProperty;\n const relName = relProp.relationName || propKey;\n if (relName === newRelation.inverseRelationName &&\n relProp.cardinality === \"many\" &&\n (relProp.direction === \"owning\" || !relProp.direction)) {\n isManyToManyInverse = true;\n break;\n }\n }\n }\n } catch (e) {\n // If we can't inspect the target collection, assume one-to-many\n }\n }\n\n // Only add foreignKeyOnTarget for one-to-many inverse relations\n if (!isManyToManyInverse && !newRelation.foreignKeyOnTarget) {\n newRelation.foreignKeyOnTarget = generateForeignKeyName(sourceName);\n }\n } else if (newRelation.cardinality === \"many\" && newRelation.direction === \"owning\") {\n\n // Many-to-many via junction table\n const sourceTableName = getTableName(sourceCollection);\n const targetTableName = getTableName(targetCollection);\n\n newRelation.through = {\n table: newRelation.through?.table ?? [sourceTableName, targetTableName].sort().join(\"_\"),\n sourceColumn: newRelation.through?.sourceColumn ?? generateForeignKeyName(sourceName),\n targetColumn: newRelation.through?.targetColumn ?? generateForeignKeyName(newRelation.relationName)\n };\n }\n }\n\n // 4. Basic validation to catch configuration errors early\n if (newRelation.cardinality === \"one\" && newRelation.direction === \"owning\" && !newRelation.localKey && !newRelation.joinPath) {\n throw new Error(`Configuration Error in relation from '${sourceCollection.name}': An 'owning' one-to-one relation requires a 'localKey'. Check the relation config for '${newRelation.relationName}'`);\n }\n if (newRelation.cardinality === \"one\" && newRelation.direction === \"inverse\" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath) {\n throw new Error(`Configuration Error in relation from '${sourceCollection.name}': An 'inverse' one-to-one relation requires a 'foreignKeyOnTarget'. Check the relation config for '${newRelation.relationName}'`);\n }\n if (newRelation.cardinality === \"many\" && newRelation.direction === \"inverse\" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath && !newRelation.inverseRelationName) {\n throw new Error(`Configuration Error in relation from '${sourceCollection.name}': An 'inverse' one-to-many relation requires a 'foreignKeyOnTarget'. Check the relation config for '${newRelation.relationName}'`);\n }\n\n return newRelation as Relation;\n}\n\n/** WeakMap cache — same collection instance always yields the same relation map. */\nconst _resolvedRelationsCache = new WeakMap<CollectionConfig, Record<string, Relation>>();\n\nexport function resolveCollectionRelations(\n collection: CollectionConfig\n): Record<string, Relation> {\n const cached = _resolvedRelationsCache.get(collection);\n if (cached) return cached;\n\n if (!getDataSourceCapabilities(collection.engine).supportsRelations) return {};\n const relations: Record<string, Relation> = {};\n\n // Track which explicit relationName values have been registered so that\n // property-based entries in section 2 don't re-add the same underlying relation\n // under a different key (e.g. explicit \"company\" + property \"company_id\").\n const registeredRelationNames = new Set<string>();\n\n // 1. Process explicit relations from the `relations` field.\n // Each relation is stored once under its canonical relationName key.\n if (collection.relations) {\n collection.relations.forEach((relation: Relation) => {\n try {\n const normalizedRelation = sanitizeRelation(relation, collection);\n const relationKey = normalizedRelation.relationName;\n if (relationKey) {\n relations[relationKey] = normalizedRelation;\n registeredRelationNames.add(relationKey);\n }\n } catch (e) {\n // Ignore incomplete or invalid relations (e.g. missing target during registry setup)\n }\n });\n }\n\n // 2. Process properties of type \"relation\".\n // Only adds an entry if:\n // (a) the property key itself is not already in the map, AND\n // (b) the underlying relation (by relationName) hasn't already been registered.\n // This prevents duplicate entries when a property key differs from the\n // explicit relation's relationName (e.g. property \"company_id\" referencing\n // explicit relation \"company\").\n if (collection.properties) {\n Object.entries(collection.properties).forEach(([propKey, prop]) => {\n const relation = resolvePropertyRelation({\n propertyKey: propKey,\n property: prop as Property,\n sourceCollection: collection\n });\n if (relation) {\n // Skip if the property key is already registered\n if (relations[propKey]) return;\n\n // We previously skipped if the underlying relation was already registered under\n // its canonical relationName in section 1. But we need to keep the property mapping\n // for FetchService to hydrate the relation back to the correct property key.\n // Deduplication for Drizzle schema generation is handled in generate-drizzle-schema-logic.ts.\n\n if (!relation.relationName) {\n relation.relationName = propKey;\n }\n const normalizedRelation = sanitizeRelation(relation, collection);\n relations[propKey] = normalizedRelation;\n registeredRelationNames.add(normalizedRelation.relationName ?? propKey);\n }\n });\n }\n\n _resolvedRelationsCache.set(collection, relations);\n return relations;\n}\n\nexport function resolvePropertyRelation({\n propertyKey,\n property,\n sourceCollection\n}: {\n propertyKey: string;\n property: Property;\n sourceCollection: CollectionConfig;\n}): Relation | undefined {\n if (property.type !== \"relation\") return undefined;\n\n const relProp = property as RelationProperty;\n\n // If the property has inline config (target set), build a Relation from it.\n // We only support the flat format where properties are directly on the RelationProperty.\n if (relProp.target) {\n return {\n relationName: relProp.relationName || propertyKey,\n target: relProp.target,\n cardinality: relProp.cardinality || \"one\",\n direction: relProp.direction || \"owning\",\n inverseRelationName: relProp.inverseRelationName,\n localKey: relProp.localKey,\n foreignKeyOnTarget: relProp.foreignKeyOnTarget,\n through: relProp.through,\n joinPath: relProp.joinPath,\n onUpdate: relProp.onUpdate,\n onDelete: relProp.onDelete,\n overrides: relProp.overrides\n } as Relation;\n }\n\n console.warn(`Unrecognized or missing relation target for property '${propertyKey}' in collection '${sourceCollection.slug}'`);\n return undefined;\n}\n\nexport function getTableName(collection: CollectionConfig): string {\n if (getDataSourceCapabilities(collection.engine).supportsRelations) {\n return collection.table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);\n }\n return toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);\n}\n\nexport function getTableVarName(tableName: string): string {\n return tableName.replace(/_([a-z])/g, (_, char) => char.toUpperCase());\n}\n\nexport function getEnumVarName(tableName: string, propName: string): string {\n const tableVar = getTableVarName(tableName);\n const propVar = propName.charAt(0).toUpperCase() + propName.slice(1);\n return `${tableVar}${propVar}`;\n}\n\nexport function getColumnName(fullColumn: string): string {\n return fullColumn.includes(\".\") ? fullColumn.split(\".\").pop()! : fullColumn;\n}\n\n/**\n * Look up a relation by key with forgiving normalization.\n *\n * `resolveCollectionRelations` stores each relation under a single canonical\n * key (no aliases). This helper tries the given key as-is, then falls back to\n * slug form (underscores → hyphens) and snake_case form (hyphens → underscores)\n * so that callers that receive a key from external input (URL path segments,\n * user-provided config, etc.) can still find the right entry.\n */\nexport function findRelation(\n resolvedRelations: Record<string, Relation>,\n key: string\n): Relation | undefined {\n // Exact match first\n if (resolvedRelations[key]) return resolvedRelations[key];\n\n // Try slug form (e.g. \"company_id\" → \"company-id\")\n const slugKey = key.replace(/_/g, \"-\");\n if (slugKey !== key && resolvedRelations[slugKey]) return resolvedRelations[slugKey];\n\n // Try snake_case form (e.g. \"company-id\" → \"company_id\")\n const snakeKey = key.replace(/-/g, \"_\");\n if (snakeKey !== key && resolvedRelations[snakeKey]) return resolvedRelations[snakeKey];\n\n return undefined;\n}\n","import {\n ArrayProperty,\n AuthController,\n CollectionConfig,\n EnumValueConfig,\n EnumValues,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty,\n getDataSourceCapabilities,\n getDeclaredSubcollections\n} from \"@rebasepro/types\";\n\ntype PropertyConfig = { property: unknown; [key: string]: unknown };\nimport { isPropertyBuilder } from \"./entities\";\nimport { enumToObjectEntries } from \"./enums\";\nimport { DEFAULT_ONE_OF_TYPE } from \"./common\";\nimport { isDefaultFieldConfigId } from \"@rebasepro/utils\";\nimport { getIn, mergeDeep } from \"@rebasepro/utils\";\nimport { resolveCollectionRelations } from \"./relations\";\n\n/**\n * Resolve property builders, enums and arrays.\n */\n\nexport type ResolvePropertyProps<M extends Record<string, unknown> = Record<string, unknown>> = {\n property: Property\n propertyKey?: string,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthController;\n}\n\nexport function resolveProperty<M extends Record<string, unknown> = Record<string, unknown>>(props: ResolvePropertyProps<M>): Property | null {\n\n const {\n property,\n ignoreMissingFields = false,\n ...rest\n } = props;\n\n let resultProperty: Property;\n\n if (isPropertyBuilder(property)) {\n const path = rest.path;\n if (!path) {\n // When path is not available (e.g. in preview contexts), skip dynamic\n // resolution and use the property as-is without dynamic modifications.\n resultProperty = property as Property;\n } else {\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicProps = property.dynamicProps?.({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n resultProperty = mergeDeep(property, dynamicProps ?? {});\n }\n } else {\n resultProperty = property as Property;\n }\n\n // Apply dynamic properties if they exist\n if (resultProperty?.dynamicProps && rest.path) {\n const path = rest.path;\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicPropsResult = resultProperty.dynamicProps({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n\n if (dynamicPropsResult) {\n resultProperty = mergeDeep(resultProperty, dynamicPropsResult);\n }\n }\n\n let resolvedProperty: Property | null;\n\n if (resultProperty?.type === \"map\" && resultProperty.properties) {\n const properties = resolveProperties({\n ignoreMissingFields,\n ...rest,\n properties: resultProperty.properties\n });\n resolvedProperty = {\n ...resultProperty,\n properties\n } as Property;\n } else if (resultProperty?.type === \"array\") {\n resolvedProperty = resultProperty;\n } else if ((resultProperty?.type === \"string\" || resultProperty?.type === \"number\") && resultProperty.enum) {\n resolvedProperty = resolvePropertyEnum(resultProperty);\n } else {\n resolvedProperty = resultProperty;\n }\n\n if (resolvedProperty?.propertyConfig && !isDefaultFieldConfigId(resolvedProperty.propertyConfig)) {\n const cmsFields = rest.propertyConfigs;\n if (!cmsFields && !ignoreMissingFields) {\n throw Error(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property configs were provided. Use the property 'propertyConfigs' in your app config to provide them`);\n }\n const customField: PropertyConfig | undefined = cmsFields?.[resolvedProperty.propertyConfig];\n if (!customField) {\n console.warn(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property config with that key was found. Check the 'propertyConfigs' in your app config`)\n return resolvedProperty;\n }\n if (customField.property) {\n const restConfigProperty = { ...customField.property } as Record<string, unknown>;\n delete restConfigProperty.propertyConfig;\n const customFieldProperty = resolveProperty({\n property: { name: \"\",\n...restConfigProperty } as Property,\n ignoreMissingFields,\n ...rest\n });\n if (customFieldProperty) {\n resolvedProperty = mergeDeep(customFieldProperty, resolvedProperty);\n }\n }\n\n }\n\n return resolvedProperty;\n}\n\nexport function resolveRelationProperty(property: RelationProperty, relations: Relation[], propertyKey?: string) {\n // If the property already has a resolved relation, return as-is\n if (property.relation) {\n return property;\n }\n\n // Determine the relation name: explicit > property key\n const name = property.relationName || propertyKey;\n\n // Find the relation by name (it may have been extracted from the property during normalization)\n const relation = name ? relations.find((rel) => rel.relationName === name) : undefined;\n if (!relation) {\n throw Error(`Relation ${name ?? \"(unnamed)\"} not found`);\n }\n return {\n ...property,\n relation: relation\n } as RelationProperty;\n\n}\n\n/**\n * Resolve enum aliases for a string or number property\n * @param property\n */\nexport function resolvePropertyEnum(property: StringProperty | NumberProperty): StringProperty | NumberProperty {\n if (typeof property.enum === \"object\") {\n return {\n ...property,\n enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? []\n };\n }\n return property as StringProperty | NumberProperty;\n}\n\n/**\n * Resolve enums and arrays for properties\n * @param properties\n * @param value\n */\nexport function resolveProperties<M extends Record<string, unknown>>({\n propertyKey,\n properties,\n ignoreMissingFields,\n ...props\n}: {\n propertyKey?: string,\n properties: Properties,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthController;\n}): Properties {\n return Object.entries<Property>(properties as Record<string, Property>)\n .map(([key, property]) => {\n const childResolvedProperty = resolveProperty({\n propertyKey: propertyKey ? `${propertyKey}.${key}` : undefined,\n property: property,\n ignoreMissingFields,\n ...props\n });\n if (!childResolvedProperty) return {};\n return {\n [key]: childResolvedProperty\n };\n })\n .filter((a) => a !== null)\n .reduce((a, b) => ({ ...a,\n...b }), {}) as Properties;\n}\n\nexport function resolveArrayProperties<M>({\n propertyKey,\n property,\n ignoreMissingFields = false,\n ...props\n}: {\n propertyKey?: string,\n property: ArrayProperty,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthController;\n}): Property[] {\n const propertyValue = propertyKey ? getIn(props.values, propertyKey) : undefined;\n\n if (property.of) {\n if (Array.isArray(property.of)) {\n return property.of.map((p, index) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: p as Property,\n ignoreMissingFields,\n ...props,\n index\n });\n }) as Property[];\n } else {\n const of = property.of;\n const resolvedProperties = getArrayResolvedProperties({\n propertyValue,\n propertyKey,\n property,\n ignoreMissingFields,\n ...props\n });\n const {\n values,\n previousValues,\n ...rest\n } = props;\n const ofProperty = resolveProperty({ // we don't want to pass the values of the parent entity\n property: of,\n ignoreMissingFields,\n ...rest\n });\n if (!ofProperty && !ignoreMissingFields)\n throw Error(\"When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property\")\n return resolvedProperties;\n }\n } else if (property.oneOf) {\n const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;\n const resolvedProperties: Property[] = Array.isArray(propertyValue)\n ? propertyValue.map((v, index) => {\n const type = v && v[typeField];\n const childProperty = property.oneOf?.properties[type];\n if (!type || !childProperty) return null;\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: childProperty,\n ignoreMissingFields,\n ...props\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n return resolvedProperties;\n } else if (!(\"Field\" in (property.ui || {}) && property.ui?.Field)) {\n throw Error(`The array property (${propertyKey}) needs to declare an 'of' or a 'oneOf' property, or provide a custom \\`Field\\` component`);\n } else {\n return [];\n }\n\n}\n\nexport function getArrayResolvedProperties({\n propertyKey,\n propertyValue,\n property,\n ...props\n}: {\n propertyValue: unknown,\n propertyKey?: string,\n property: ArrayProperty,\n ignoreMissingFields: boolean,\n values?: object;\n previousValues?: object;\n path?: string;\n entityId?: string | number;\n index?: number;\n propertyConfigs?: Record<string, PropertyConfig>;\n authController: AuthController;\n}) {\n\n const of = property.of;\n if (!of)\n throw Error(\n `Trying to resolve an array property (${propertyKey}) without providing an 'of' property`\n )\n return Array.isArray(propertyValue)\n ? propertyValue.map((v: unknown, index: number) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: Array.isArray(of) ? of[index] : of,\n ...props,\n index\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n}\n\nexport function resolveEnumValues(input: EnumValues): EnumValueConfig[] | undefined {\n if (typeof input === \"object\") {\n return Object.entries(input).map(([id, value]) =>\n (typeof value === \"string\"\n ? {\n id,\n label: value\n }\n : value));\n } else if (Array.isArray(input)) {\n return input as EnumValueConfig[];\n } else {\n return undefined;\n }\n}\n\n\nexport function getSubcollections<M extends Record<string, unknown> = Record<string, unknown>>(collection: CollectionConfig<M>): CollectionConfig<Record<string, unknown>>[] {\n if (collection.childCollections) {\n return collection.childCollections() ?? [];\n }\n\n const declaredSubcollections = getDeclaredSubcollections(collection);\n if (getDataSourceCapabilities(collection.engine).supportsSubcollections && declaredSubcollections) {\n return declaredSubcollections() ?? [];\n }\n\n if (getDataSourceCapabilities(collection.engine).supportsRelations) {\n const resolvedRelations = resolveCollectionRelations(collection);\n const manyRelations = Object.values(resolvedRelations).filter((r: Relation) => r.cardinality === \"many\");\n\n return manyRelations.map((r: Relation) => {\n const target = r.target();\n if (!target) return undefined;\n const relationKey = r.relationName || target.slug;\n\n // Try to find corresponding property to get custom name\n let customName: string | undefined;\n if (collection.properties) {\n const prop = Object.entries(collection.properties as Record<string, Property>).find(\n ([_, p]) => p.type === \"relation\" && p.relationName === relationKey\n );\n if (prop && prop[1].name) {\n customName = prop[1].name;\n }\n }\n\n const baseOverrides: Partial<CollectionConfig> = { slug: relationKey };\n if (customName) {\n baseOverrides.name = customName;\n baseOverrides.singularName = customName;\n }\n\n const targetWithOverrides = { ...target,\n...baseOverrides };\n return (r.overrides ? mergeDeep(targetWithOverrides, r.overrides) : targetWithOverrides) as CollectionConfig<Record<string, unknown>>;\n }).filter((c: CollectionConfig<Record<string, unknown>> | undefined): c is CollectionConfig<Record<string, unknown>> => Boolean(c));\n }\n\n return [];\n}\n","import {\n ArrayProperty,\n BooleanProperty,\n DateProperty,\n CollectionConfig,\n FirebaseCollectionConfig,\n FirebaseProperties,\n GeopointProperty,\n InferEntityType,\n MapProperty,\n MongoDBCollectionConfig,\n MongoProperties,\n NumberProperty,\n PostgresCollectionConfig,\n PostgresProperties,\n Property,\n ReferenceProperty,\n StringProperty,\n User\n} from \"@rebasepro/types\";\n\n\n/**\n * @deprecated Use {@link defineCollection} instead — it infers property\n * types automatically (autocomplete on `titleProperty`, `sort`,\n * `propertiesOrder`, callbacks) without manual generics.\n * `buildCollection` is kept for FireCMS migration compatibility and will\n * be removed before 1.0.\n *\n * @group Builder\n */\nexport function buildCollection<\n M extends Record<string, unknown> = Record<string, unknown>,\n USER extends User = User>\n (\n collection: CollectionConfig<M, USER>\n ): CollectionConfig<M, USER> {\n return collection;\n}\n\n// ── defineCollection ─────────────────────────────────────────────────────\n// A smarter builder that uses `const` type-parameter inference (TS 5.0+)\n// to capture literal property types automatically. This gives you\n// autocomplete on `titleProperty`, `sort`, `propertiesOrder`, `fixedFilter`,\n// callbacks, etc. — without writing `as const` or passing manual generics.\n\n/**\n * Define a PostgreSQL-backed collection with full type inference.\n *\n * The `const P` generic captures literal property types from your\n * `properties` object, which enables autocomplete on `titleProperty`,\n * `sort`, `propertiesOrder`, `fixedFilter`, and entity callbacks.\n *\n * @example\n * ```ts\n * const products = defineCollection({\n * name: \"Products\",\n * slug: \"products\",\n * table: \"products\",\n * properties: {\n * name: { name: \"Name\", type: \"string\", validation: { required: true } },\n * price: { name: \"Price\", type: \"number\" },\n * },\n * titleProperty: \"name\", // ✅ autocomplete: \"name\" | \"price\"\n * sort: [\"price\", \"asc\"], // ✅ autocomplete on first element\n * });\n * ```\n *\n * @group Builder\n */\nexport function defineCollection<\n const P extends PostgresProperties,\n USER extends User = User\n>(\n collection: Omit<PostgresCollectionConfig<InferEntityType<P>, USER>, \"properties\"> & { properties: P }\n): PostgresCollectionConfig<InferEntityType<P>, USER> & { properties: P };\n\n/**\n * Define a Firestore-backed collection with full type inference.\n * @group Builder\n */\nexport function defineCollection<\n const P extends FirebaseProperties,\n USER extends User = User\n>(\n collection: Omit<FirebaseCollectionConfig<InferEntityType<P>, USER>, \"properties\"> & { properties: P }\n): FirebaseCollectionConfig<InferEntityType<P>, USER> & { properties: P };\n\n/**\n * Define a MongoDB-backed collection with full type inference.\n * @group Builder\n */\nexport function defineCollection<\n const P extends MongoProperties,\n USER extends User = User\n>(\n collection: Omit<MongoDBCollectionConfig<InferEntityType<P>, USER>, \"properties\"> & { properties: P }\n): MongoDBCollectionConfig<InferEntityType<P>, USER> & { properties: P };\n\n/**\n * Implementation — delegates to the correct overload at the type level.\n * At runtime this is a plain identity function.\n */\nexport function defineCollection(\n collection: CollectionConfig\n): CollectionConfig {\n return collection;\n}\n\n/**\n * @deprecated Use plain typed property objects with {@link defineCollection}\n * instead — `defineCollection` infers property types automatically, making\n * this wrapper unnecessary. `buildProperty` is kept for FireCMS migration\n * compatibility and will be removed before 1.0.\n *\n * @group Builder\n */\nexport function buildProperty<T, P extends Property = Property>(\n property: P\n):\n P extends StringProperty ? StringProperty :\n P extends NumberProperty ? NumberProperty :\n P extends BooleanProperty ? BooleanProperty :\n P extends DateProperty ? DateProperty :\n P extends GeopointProperty ? GeopointProperty :\n P extends ReferenceProperty ? ReferenceProperty :\n P extends ArrayProperty ? ArrayProperty :\n P extends MapProperty ? MapProperty : never {\n\n // SAFETY: Identity function — P is a subtype of the conditional return type by definition\n return property as unknown as ReturnType<typeof buildProperty<T, P>>;\n}\n","/* globals define,module */\n/*\nUsing a Universal Module Loader that should be browser, require, and AMD friendly\nhttp://ricostacruz.com/cheatsheets/umdjs.html\n*/\n;(function(root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(factory);\n } else if (typeof exports === \"object\") {\n module.exports = factory();\n } else {\n root.jsonLogic = factory();\n }\n}(this, function() {\n \"use strict\";\n /* globals console:false */\n\n if ( ! Array.isArray) {\n Array.isArray = function(arg) {\n return Object.prototype.toString.call(arg) === \"[object Array]\";\n };\n }\n\n /**\n * Return an array that contains no duplicates (original not modified)\n * @param {array} array Original reference array\n * @return {array} New array with no duplicates\n */\n function arrayUnique(array) {\n var a = [];\n for (var i=0, l=array.length; i<l; i++) {\n if (a.indexOf(array[i]) === -1) {\n a.push(array[i]);\n }\n }\n return a;\n }\n\n var jsonLogic = {};\n var operations = {\n \"==\": function(a, b) {\n return a == b;\n },\n \"===\": function(a, b) {\n return a === b;\n },\n \"!=\": function(a, b) {\n return a != b;\n },\n \"!==\": function(a, b) {\n return a !== b;\n },\n \">\": function(a, b) {\n return a > b;\n },\n \">=\": function(a, b) {\n return a >= b;\n },\n \"<\": function(a, b, c) {\n return (c === undefined) ? a < b : (a < b) && (b < c);\n },\n \"<=\": function(a, b, c) {\n return (c === undefined) ? a <= b : (a <= b) && (b <= c);\n },\n \"!!\": function(a) {\n return jsonLogic.truthy(a);\n },\n \"!\": function(a) {\n return !jsonLogic.truthy(a);\n },\n \"%\": function(a, b) {\n return a % b;\n },\n \"log\": function(a) {\n console.log(a); return a;\n },\n \"in\": function(a, b) {\n if (!b || typeof b.indexOf === \"undefined\") return false;\n return (b.indexOf(a) !== -1);\n },\n \"cat\": function() {\n return Array.prototype.join.call(arguments, \"\");\n },\n \"substr\": function(source, start, end) {\n if (end < 0) {\n // JavaScript doesn't support negative end, this emulates PHP behavior\n var temp = String(source).substr(start);\n return temp.substr(0, temp.length + end);\n }\n return String(source).substr(start, end);\n },\n \"+\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return parseFloat(a, 10) + parseFloat(b, 10);\n }, 0);\n },\n \"*\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return parseFloat(a, 10) * parseFloat(b, 10);\n });\n },\n \"-\": function(a, b) {\n if (b === undefined) {\n return -a;\n } else {\n return a - b;\n }\n },\n \"/\": function(a, b) {\n return a / b;\n },\n \"min\": function() {\n return Math.min.apply(this, arguments);\n },\n \"max\": function() {\n return Math.max.apply(this, arguments);\n },\n \"merge\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return a.concat(b);\n }, []);\n },\n \"var\": function(a, b) {\n var not_found = (b === undefined) ? null : b;\n var data = this;\n if (typeof a === \"undefined\" || a===\"\" || a===null) {\n return data;\n }\n var sub_props = String(a).split(\".\");\n for (var i = 0; i < sub_props.length; i++) {\n if (data === null || data === undefined) {\n return not_found;\n }\n // Descending into data\n data = data[sub_props[i]];\n if (data === undefined) {\n return not_found;\n }\n }\n return data;\n },\n \"missing\": function() {\n /*\n Missing can receive many keys as many arguments, like {\"missing:[1,2]}\n Missing can also receive *one* argument that is an array of keys,\n which typically happens if it's actually acting on the output of another command\n (like 'if' or 'merge')\n */\n\n var missing = [];\n var keys = Array.isArray(arguments[0]) ? arguments[0] : arguments;\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = jsonLogic.apply({\"var\": key}, this);\n if (value === null || value === \"\") {\n missing.push(key);\n }\n }\n\n return missing;\n },\n \"missing_some\": function(need_count, options) {\n // missing_some takes two arguments, how many (minimum) items must be present, and an array of keys (just like 'missing') to check for presence.\n var are_missing = jsonLogic.apply({\"missing\": options}, this);\n\n if (options.length - are_missing.length >= need_count) {\n return [];\n } else {\n return are_missing;\n }\n },\n };\n\n jsonLogic.is_logic = function(logic) {\n return (\n typeof logic === \"object\" && // An object\n logic !== null && // but not null\n ! Array.isArray(logic) && // and not an array\n Object.keys(logic).length === 1 // with exactly one key\n );\n };\n\n /*\n This helper will defer to the JsonLogic spec as a tie-breaker when different language interpreters define different behavior for the truthiness of primitives. E.g., PHP considers empty arrays to be falsy, but Javascript considers them to be truthy. JsonLogic, as an ecosystem, needs one consistent answer.\n\n Spec and rationale here: http://jsonlogic.com/truthy\n */\n jsonLogic.truthy = function(value) {\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n return !! value;\n };\n\n\n jsonLogic.get_operator = function(logic) {\n return Object.keys(logic)[0];\n };\n\n jsonLogic.get_values = function(logic) {\n return logic[jsonLogic.get_operator(logic)];\n };\n\n jsonLogic.apply = function(logic, data) {\n // Does this array contain logic? Only one way to find out.\n if (Array.isArray(logic)) {\n return logic.map(function(l) {\n return jsonLogic.apply(l, data);\n });\n }\n // You've recursed to a primitive, stop!\n if ( ! jsonLogic.is_logic(logic) ) {\n return logic;\n }\n\n var op = jsonLogic.get_operator(logic);\n var values = logic[op];\n var i;\n var current;\n var scopedLogic;\n var scopedData;\n var initial;\n\n // easy syntax for unary operators, like {\"var\" : \"x\"} instead of strict {\"var\" : [\"x\"]}\n if ( ! Array.isArray(values)) {\n values = [values];\n }\n\n // 'if', 'and', and 'or' violate the normal rule of depth-first calculating consequents, let each manage recursion as needed.\n if (op === \"if\" || op == \"?:\") {\n /* 'if' should be called with a odd number of parameters, 3 or greater\n This works on the pattern:\n if( 0 ){ 1 }else{ 2 };\n if( 0 ){ 1 }else if( 2 ){ 3 }else{ 4 };\n if( 0 ){ 1 }else if( 2 ){ 3 }else if( 4 ){ 5 }else{ 6 };\n\n The implementation is:\n For pairs of values (0,1 then 2,3 then 4,5 etc)\n If the first evaluates truthy, evaluate and return the second\n If the first evaluates falsy, jump to the next pair (e.g, 0,1 to 2,3)\n given one parameter, evaluate and return it. (it's an Else and all the If/ElseIf were false)\n given 0 parameters, return NULL (not great practice, but there was no Else)\n */\n for (i = 0; i < values.length - 1; i += 2) {\n if ( jsonLogic.truthy( jsonLogic.apply(values[i], data) ) ) {\n return jsonLogic.apply(values[i+1], data);\n }\n }\n if (values.length === i+1) {\n return jsonLogic.apply(values[i], data);\n }\n return null;\n } else if (op === \"and\") { // Return first falsy, or last\n for (i=0; i < values.length; i+=1) {\n current = jsonLogic.apply(values[i], data);\n if ( ! jsonLogic.truthy(current)) {\n return current;\n }\n }\n return current; // Last\n } else if (op === \"or\") {// Return first truthy, or last\n for (i=0; i < values.length; i+=1) {\n current = jsonLogic.apply(values[i], data);\n if ( jsonLogic.truthy(current) ) {\n return current;\n }\n }\n return current; // Last\n } else if (op === \"filter\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData)) {\n return [];\n }\n // Return only the elements from the array in the first argument,\n // that return truthy when passed to the logic in the second argument.\n // For parity with JavaScript, reindex the returned array\n return scopedData.filter(function(datum) {\n return jsonLogic.truthy( jsonLogic.apply(scopedLogic, datum));\n });\n } else if (op === \"map\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData)) {\n return [];\n }\n\n return scopedData.map(function(datum) {\n return jsonLogic.apply(scopedLogic, datum);\n });\n } else if (op === \"reduce\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n initial = typeof values[2] !== \"undefined\" ? jsonLogic.apply(values[2], data) : null;\n\n if ( ! Array.isArray(scopedData)) {\n return initial;\n }\n\n return scopedData.reduce(\n function(accumulator, current) {\n return jsonLogic.apply(\n scopedLogic,\n {current: current, accumulator: accumulator}\n );\n },\n initial\n );\n } else if (op === \"all\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n // All of an empty set is false. Note, some and none have correct fallback after the for loop\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return false;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( ! jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return false; // First falsy, short circuit\n }\n }\n return true; // All were truthy\n } else if (op === \"none\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return true;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return false; // First truthy, short circuit\n }\n }\n return true; // None were truthy\n } else if (op === \"some\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return false;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return true; // First truthy, short circuit\n }\n }\n return false; // None were truthy\n }\n\n // Everyone else gets immediate depth-first recursion\n values = values.map(function(val) {\n return jsonLogic.apply(val, data);\n });\n\n\n // The operation is called with \"data\" bound to its \"this\" and \"values\" passed as arguments.\n // Structured commands like % or > can name formal arguments while flexible commands (like missing or merge) can operate on the pseudo-array arguments\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments\n if (operations.hasOwnProperty(op) && typeof operations[op] === \"function\") {\n return operations[op].apply(data, values);\n } else if (op.indexOf(\".\") > 0) { // Contains a dot, and not in the 0th position\n var sub_ops = String(op).split(\".\");\n var operation = operations;\n for (i = 0; i < sub_ops.length; i++) {\n if (!operation.hasOwnProperty(sub_ops[i])) {\n throw new Error(\"Unrecognized operation \" + op +\n \" (failed at \" + sub_ops.slice(0, i+1).join(\".\") + \")\");\n }\n // Descending into operations\n operation = operation[sub_ops[i]];\n }\n\n return operation.apply(data, values);\n }\n\n throw new Error(\"Unrecognized operation \" + op );\n };\n\n jsonLogic.uses_data = function(logic) {\n var collection = [];\n\n if (jsonLogic.is_logic(logic)) {\n var op = jsonLogic.get_operator(logic);\n var values = logic[op];\n\n if ( ! Array.isArray(values)) {\n values = [values];\n }\n\n if (op === \"var\") {\n // This doesn't cover the case where the arg to var is itself a rule.\n collection.push(values[0]);\n } else {\n // Recursion!\n values.forEach(function(val) {\n collection.push.apply(collection, jsonLogic.uses_data(val) );\n });\n }\n }\n\n return arrayUnique(collection);\n };\n\n jsonLogic.add_operation = function(name, code) {\n operations[name] = code;\n };\n\n jsonLogic.rm_operation = function(name) {\n delete operations[name];\n };\n\n jsonLogic.rule_like = function(rule, pattern) {\n // console.log(\"Is \". JSON.stringify(rule) . \" like \" . JSON.stringify(pattern) . \"?\");\n if (pattern === rule) {\n return true;\n } // TODO : Deep object equivalency?\n if (pattern === \"@\") {\n return true;\n } // Wildcard!\n if (pattern === \"number\") {\n return (typeof rule === \"number\");\n }\n if (pattern === \"string\") {\n return (typeof rule === \"string\");\n }\n if (pattern === \"array\") {\n // !logic test might be superfluous in JavaScript\n return Array.isArray(rule) && ! jsonLogic.is_logic(rule);\n }\n\n if (jsonLogic.is_logic(pattern)) {\n if (jsonLogic.is_logic(rule)) {\n var pattern_op = jsonLogic.get_operator(pattern);\n var rule_op = jsonLogic.get_operator(rule);\n\n if (pattern_op === \"@\" || pattern_op === rule_op) {\n // echo \"\\nOperators match, go deeper\\n\";\n return jsonLogic.rule_like(\n jsonLogic.get_values(rule, false),\n jsonLogic.get_values(pattern, false)\n );\n }\n }\n return false; // pattern is logic, rule isn't, can't be eq\n }\n\n if (Array.isArray(pattern)) {\n if (Array.isArray(rule)) {\n if (pattern.length !== rule.length) {\n return false;\n }\n /*\n Note, array order MATTERS, because we're using this array test logic to consider arguments, where order can matter. (e.g., + is commutative, but '-' or 'if' or 'var' are NOT)\n */\n for (var i = 0; i < pattern.length; i += 1) {\n // If any fail, we fail\n if ( ! jsonLogic.rule_like(rule[i], pattern[i])) {\n return false;\n }\n }\n return true; // If they *all* passed, we pass\n } else {\n return false; // Pattern is array, rule isn't\n }\n }\n\n // Not logic, not array, not a === match for rule.\n return false;\n };\n\n return jsonLogic;\n}));\n","import jsonLogic from \"json-logic-js\";\nimport {\n ArrayProperty,\n AuthController,\n ConditionContext,\n EnumValueConfig,\n JsonLogicRule,\n NumberProperty,\n PropertyConditions,\n Property,\n ReferenceProperty,\n StringProperty\n} from \"@rebasepro/types\";\n\n/**\n * Access a nested property from an object via dot notation.\n */\nfunction getIn(obj: Record<string, unknown> | unknown, path: string): unknown {\n if (!obj || !path) return undefined;\n return path.split(\".\").reduce((acc: unknown, part: string) => acc && (acc as Record<string, unknown>)[part], obj);\n}\n\nlet operationsRegistered = false;\n\n/**\n * Register custom JSON Logic operations for Rebase.\n * Call this once at app initialization.\n */\nexport function registerConditionOperations(): void {\n if (operationsRegistered) return;\n\n // Check if user has a specific role by ID\n jsonLogic.add_operation(\"hasRole\", function (this: ConditionContext, roleId: string) {\n return this?.user?.roles?.includes(roleId) ?? false;\n });\n\n // Check if user has any of the specified roles\n jsonLogic.add_operation(\"hasAnyRole\", function (this: ConditionContext, roleIds: string[]) {\n if (!this?.user?.roles || !Array.isArray(roleIds)) return false;\n return roleIds.some(role => this.user.roles.includes(role));\n });\n\n // Check if a timestamp is today\n jsonLogic.add_operation(\"isToday\", (timestamp: number) => {\n if (!timestamp) return false;\n const date = new Date(timestamp);\n const today = new Date();\n return date.getFullYear() === today.getFullYear() &&\n date.getMonth() === today.getMonth() &&\n date.getDate() === today.getDate();\n });\n\n // Check if a timestamp is in the past\n jsonLogic.add_operation(\"isPast\", (timestamp: number) => {\n if (!timestamp) return false;\n return timestamp < Date.now();\n });\n\n // Check if a timestamp is in the future\n jsonLogic.add_operation(\"isFuture\", (timestamp: number) => {\n if (!timestamp) return false;\n return timestamp > Date.now();\n });\n\n operationsRegistered = true;\n}\n\n/**\n * Evaluate a JSON Logic rule against the given context.\n */\nexport function evaluateCondition(rule: JsonLogicRule, context: ConditionContext): unknown {\n // Ensure operations are registered\n registerConditionOperations();\n return jsonLogic.apply(rule, context);\n}\n\n/**\n * Convert a value to a format suitable for JSON Logic evaluation.\n * Specifically handles Date objects by converting them to Unix timestamps.\n */\nfunction serializeValueForConditions(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n // Handle Date objects\n if (value instanceof Date) {\n return value.getTime();\n }\n\n // Handle Firestore Timestamp-like objects (have toDate or toMillis)\n if (typeof (value as { toMillis?: () => number })?.toMillis === \"function\") {\n return (value as { toMillis: () => number }).toMillis();\n }\n if (typeof (value as { toDate?: () => Date })?.toDate === \"function\") {\n return (value as { toDate: () => Date }).toDate().getTime();\n }\n\n // Handle arrays recursively\n if (Array.isArray(value)) {\n return value.map(serializeValueForConditions);\n }\n\n // Handle plain objects recursively\n if (typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>)) {\n result[key] = serializeValueForConditions((value as Record<string, unknown>)[key]);\n }\n return result;\n }\n\n return value;\n}\n\n/**\n * Build a ConditionContext from the current property resolution context.\n */\nexport function buildConditionContext(params: {\n propertyKey?: string;\n values?: Record<string, unknown>;\n previousValues?: Record<string, unknown>;\n path: string;\n entityId?: string;\n index?: number;\n authController: AuthController;\n}): ConditionContext {\n const {\n propertyKey,\n values,\n previousValues,\n path,\n entityId,\n index,\n authController\n } = params;\n\n const user = authController.user;\n const serializedValues = serializeValueForConditions(values ?? {});\n const serializedPreviousValues = serializeValueForConditions(previousValues ?? values ?? {});\n\n return {\n values: serializedValues as Record<string, unknown>,\n previousValues: serializedPreviousValues as Record<string, unknown>,\n propertyValue: propertyKey ? getIn(serializedValues, propertyKey) : undefined,\n path,\n entityId,\n isNew: !entityId,\n index,\n user: {\n uid: user?.uid ?? \"\",\n email: user?.email ?? null,\n displayName: user?.displayName ?? null,\n photoURL: user?.photoURL ?? null,\n roles: (user?.roles ?? []).map((r: unknown) => typeof r === \"string\" ? r : (r as { id: string }).id)\n },\n now: Date.now()\n };\n}\n\n/**\n * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.\n */\nexport function applyPropertyConditions(\n property: Property,\n context: ConditionContext\n): Property {\n const { conditions } = property;\n if (!conditions) return property;\n\n const result = { ...property };\n\n // ═══════════════════════════════════════════════════════════════════════\n // FIELD STATE CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n // Evaluate disabled condition\n if (conditions.disabled) {\n const isDisabled = evaluateCondition(conditions.disabled, context);\n if (isDisabled) {\n result.ui = result.ui || {};\n result.ui.disabled = {\n clearOnDisabled: conditions.clearOnDisabled ?? false,\n disabledMessage: conditions.disabledMessage,\n hidden: false\n };\n }\n }\n\n // Evaluate hidden condition\n if (conditions.hidden) {\n const isHidden = evaluateCondition(conditions.hidden, context);\n if (isHidden) {\n result.ui = result.ui || {};\n result.ui.disabled = {\n ...(typeof result.ui?.disabled === \"object\" ? result.ui.disabled : {}),\n hidden: true,\n clearOnDisabled: conditions.clearOnDisabled ?? false\n };\n }\n }\n\n // Evaluate readOnly condition\n if (conditions.readOnly) {\n const isReadOnly = evaluateCondition(conditions.readOnly, context);\n if (isReadOnly) {\n result.ui = result.ui || {};\n result.ui.readOnly = true;\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // VALIDATION CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n // Evaluate required condition\n if (conditions.required !== undefined) {\n const isRequired = evaluateCondition(conditions.required, context) as boolean;\n result.validation = {\n ...result.validation,\n required: isRequired as boolean | undefined,\n requiredMessage: conditions.requiredMessage\n };\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // VALUE CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n // Apply default value for new entities\n if (context.isNew && conditions.defaultValue !== undefined) {\n result.defaultValue = evaluateCondition(conditions.defaultValue, context) as Property[\"defaultValue\"];\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // ENUM CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n if (\"enum\" in result && result.enum && (conditions.enumConditions || conditions.allowedEnumValues || conditions.excludedEnumValues)) {\n (result as Record<string, unknown>).enum = applyEnumConditions(\n result.enum as EnumValueConfig[],\n conditions,\n context\n );\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // REFERENCE CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n if (result.type === \"reference\") {\n if (conditions.referencePath) {\n (result as ReferenceProperty).path = evaluateCondition(conditions.referencePath, context) as string;\n }\n if (conditions.referenceFilter) {\n (result as ReferenceProperty).fixedFilter = evaluateCondition(conditions.referenceFilter, context) as ReferenceProperty[\"fixedFilter\"];\n }\n }\n\n // ═══════════════════════════════════════════════════════════════════════\n // ARRAY CONDITIONS\n // ═══════════════════════════════════════════════════════════════════════\n\n if (result.type === \"array\") {\n if (conditions.canAddElements !== undefined) {\n (result as ArrayProperty).canAddElements = evaluateCondition(conditions.canAddElements, context) as boolean;\n }\n if (conditions.sortable !== undefined) {\n (result as ArrayProperty).sortable = evaluateCondition(conditions.sortable, context) as boolean;\n }\n }\n\n return result;\n}\n\n/**\n * Convert an object with numeric keys back to an array.\n * Firestore stores arrays as {\"0\": \"a\", \"1\": \"b\"} to avoid nested arrays.\n */\nfunction objectToArray(obj: unknown): string[] {\n if (Array.isArray(obj)) return obj.map(String);\n if (obj && typeof obj === \"object\") {\n const keys = Object.keys(obj);\n if (keys.length > 0 && keys.every(k => !isNaN(Number(k)))) {\n return keys\n .sort((a, b) => Number(a) - Number(b))\n .map(k => (obj as Record<string, unknown>)[k])\n .filter((v): v is string => typeof v === \"string\" || typeof v === \"number\")\n .map(String);\n }\n }\n return [];\n}\n\n/**\n * Apply enum-specific conditions to filter and modify enum values.\n */\nfunction applyEnumConditions(\n enumValues: EnumValueConfig[],\n conditions: PropertyConditions,\n context: ConditionContext\n): EnumValueConfig[] {\n let result = [...enumValues];\n\n // Apply allowedEnumValues filter\n if (conditions.allowedEnumValues) {\n const allowed = evaluateCondition(conditions.allowedEnumValues, context);\n // Handle both array format and object-with-numeric-keys format (Firestore workaround)\n const allowedArray = objectToArray(allowed);\n if (allowedArray.length > 0) {\n result = result.filter(ev => allowedArray.includes(String(ev.id)));\n }\n }\n\n // Apply excludedEnumValues filter\n if (conditions.excludedEnumValues) {\n const excluded = evaluateCondition(conditions.excludedEnumValues, context);\n // Handle both array format and object-with-numeric-keys format\n const excludedArray = objectToArray(excluded);\n if (excludedArray.length > 0) {\n result = result.filter(ev => !excludedArray.includes(String(ev.id)));\n }\n }\n\n // Apply individual enum conditions\n if (conditions.enumConditions) {\n result = result\n .map(ev => {\n const evConditions = conditions.enumConditions?.[ev.id];\n if (!evConditions) return ev;\n\n // Check hidden condition first\n if (evConditions.hidden && evaluateCondition(evConditions.hidden, context)) {\n return null; // Will be filtered out\n }\n\n // Check disabled condition\n if (evConditions.disabled && evaluateCondition(evConditions.disabled, context)) {\n return {\n ...ev,\n disabled: true\n };\n }\n\n return ev;\n })\n .filter((ev): ev is EnumValueConfig => ev !== null);\n }\n\n return result;\n}\n","import {\n ALL_WHERE_FILTER_OPS,\n DataType,\n getDataSourceCapabilities,\n Property,\n WhereFilterOp\n} from \"@rebasepro/types\";\n\n/**\n * Default operators offered per property type, before engine capabilities and\n * per-property narrowing are applied. These mirror what the built-in filter\n * fields can render.\n */\nconst COMPARISON_OPS: readonly WhereFilterOp[] = [\"==\", \"!=\", \">\", \">=\", \"<\", \"<=\"];\nconst NULL_CHECK_OPS: readonly WhereFilterOp[] = [\"is-null\", \"is-not-null\"];\nconst MEMBERSHIP_OPS: readonly WhereFilterOp[] = [\"in\", \"not-in\"];\nconst PATTERN_OPS: readonly WhereFilterOp[] = [\"like\", \"ilike\", \"not-like\", \"not-ilike\"];\n\nconst DEFAULT_OPS_BY_TYPE: Partial<Record<DataType, readonly WhereFilterOp[]>> = {\n string: [...COMPARISON_OPS, ...MEMBERSHIP_OPS, ...PATTERN_OPS, ...NULL_CHECK_OPS],\n number: [...COMPARISON_OPS, ...MEMBERSHIP_OPS, ...NULL_CHECK_OPS],\n date: [...COMPARISON_OPS, ...NULL_CHECK_OPS],\n boolean: [\"==\", \"!=\", ...NULL_CHECK_OPS],\n reference: [\"==\", \"!=\", ...MEMBERSHIP_OPS, ...NULL_CHECK_OPS],\n relation: [\"==\", \"!=\", ...MEMBERSHIP_OPS, ...NULL_CHECK_OPS]\n // geopoint, map, vector, binary, array (as a container): not filterable\n // through the generic filter UI.\n};\n\n/** Operators offered when the property is an *array of* a filterable type. */\nconst ARRAY_OPS: readonly WhereFilterOp[] = [\"array-contains\", \"array-contains-any\"];\n\nexport interface ResolveFilterOperatorsParams {\n /**\n * The property to filter on. For array properties, pass the **item**\n * property (`property.of`) together with `isArray: true` — the same\n * convention the filter field dispatchers use.\n */\n property: Property;\n /** True when filtering an array of `property`. */\n isArray?: boolean;\n /**\n * The engine backing the collection (`collection.engine`, e.g.\n * `\"postgres\"`, `\"firestore\"`). Falls back to the default engine's\n * capabilities when omitted.\n */\n engine?: string;\n}\n\n/**\n * Resolve which filter operators the UI should offer for a property.\n *\n * The result is the **intersection** of three sets:\n * 1. what the engine can execute — {@link DataSourceCapabilities.filterOperators}\n * (e.g. Firestore cannot run the LIKE family);\n * 2. what makes sense for the property type (e.g. no `>` on booleans);\n * 3. the developer's optional narrowing — `property.ui.filterOperators`.\n *\n * Returns an empty array when the property is not filterable (either by\n * type, or because the developer disabled it with `filterOperators: []`).\n *\n * @group Models\n */\nexport function resolveFilterOperators({\n property,\n isArray,\n engine\n}: ResolveFilterOperatorsParams): WhereFilterOp[] {\n const typeDefaults: readonly WhereFilterOp[] = isArray\n ? ARRAY_OPS\n : DEFAULT_OPS_BY_TYPE[property.type] ?? [];\n if (typeDefaults.length === 0) return [];\n\n const engineOps = new Set(getDataSourceCapabilities(engine).filterOperators ?? ALL_WHERE_FILTER_OPS);\n\n const narrowing = property.ui?.filterOperators;\n const narrowingSet = narrowing !== undefined ? new Set(narrowing) : undefined;\n\n return typeDefaults.filter(op =>\n engineOps.has(op) && (narrowingSet === undefined || narrowingSet.has(op)));\n}\n","const { getOwnPropertyNames, getOwnPropertySymbols } = Object;\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst { hasOwnProperty } = Object.prototype;\n/**\n * Combine two comparators into a single comparators.\n */\nfunction combineComparators(comparatorA, comparatorB) {\n return function isEqual(a, b, state) {\n return comparatorA(a, b, state) && comparatorB(a, b, state);\n };\n}\n/**\n * Wrap the provided `areItemsEqual` method to manage the circular state, allowing\n * for circular references to be safely included in the comparison without creating\n * stack overflows.\n */\nfunction createIsCircular(areItemsEqual) {\n return function isCircular(a, b, state) {\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\n return areItemsEqual(a, b, state);\n }\n const { cache } = state;\n const cachedA = cache.get(a);\n const cachedB = cache.get(b);\n if (cachedA && cachedB) {\n return cachedA === b && cachedB === a;\n }\n cache.set(a, b);\n cache.set(b, a);\n const result = areItemsEqual(a, b, state);\n cache.delete(a);\n cache.delete(b);\n return result;\n };\n}\n/**\n * Get the properties to strictly examine, which include both own properties that are\n * not enumerable and symbol properties.\n */\nfunction getStrictProperties(object) {\n return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object));\n}\n/**\n * Whether the object contains the property passed as an own property.\n */\nconst hasOwn = \n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nObject.hasOwn || ((object, property) => hasOwnProperty.call(object, property));\n\nconst PREACT_VNODE = '__v';\nconst PREACT_OWNER = '__o';\nconst REACT_OWNER = '_owner';\nconst { getOwnPropertyDescriptor, keys } = Object;\n/**\n * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevalue) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`) or both are `NaN`.\n *\n * @note\n * When available in the environment, this is just a re-export of the global\n * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) method.\n */\nconst sameValueEqual = \n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nObject.is\n || function sameValueEqual(a, b) {\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n };\n/**\n * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevaluezero) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`), both are `NaN`, or both\n * are either positive or negative zero.\n */\nfunction sameValueZeroEqual(a, b) {\n return a === b || (a !== a && b !== b);\n}\n/**\n * Whether the values passed are equal based on a\n * [Strict Equality Comparison](https://262.ecma-international.org/7.0/#sec-strict-equality-comparison) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`).\n *\n * @note\n * This is mainly available as a convenience function, such as being a default when a function to determine equality between\n * two objects is used.\n */\nfunction strictEqual(a, b) {\n return a === b;\n}\n/**\n * Whether the array buffers are equal in value.\n */\nfunction areArrayBuffersEqual(a, b) {\n return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b));\n}\n/**\n * Whether the arrays are equal in value.\n */\nfunction areArraysEqual(a, b, state) {\n let index = a.length;\n if (b.length !== index) {\n return false;\n }\n while (index-- > 0) {\n if (!state.equals(a[index], b[index], index, index, a, b, state)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the dataviews are equal in value.\n */\nfunction areDataViewsEqual(a, b) {\n return (a.byteLength === b.byteLength\n && areTypedArraysEqual(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)));\n}\n/**\n * Whether the dates passed are equal in value.\n */\nfunction areDatesEqual(a, b) {\n return sameValueEqual(a.getTime(), b.getTime());\n}\n/**\n * Whether the errors passed are equal in value.\n */\nfunction areErrorsEqual(a, b) {\n return a.name === b.name && a.message === b.message && a.cause === b.cause && a.stack === b.stack;\n}\n/**\n * Whether the `Map`s are equal in value.\n */\nfunction areMapsEqual(a, b, state) {\n const size = a.size;\n if (size !== b.size) {\n return false;\n }\n if (!size) {\n return true;\n }\n const matchedIndices = new Array(size);\n const aIterable = a.entries();\n let aResult;\n let bResult;\n let index = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n const bIterable = b.entries();\n let hasMatch = false;\n let matchIndex = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n if (matchedIndices[matchIndex]) {\n matchIndex++;\n continue;\n }\n const aEntry = aResult.value;\n const bEntry = bResult.value;\n if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state)\n && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) {\n hasMatch = matchedIndices[matchIndex] = true;\n break;\n }\n matchIndex++;\n }\n if (!hasMatch) {\n return false;\n }\n index++;\n }\n return true;\n}\n/**\n * Whether the objects are equal in value.\n */\nfunction areObjectsEqual(a, b, state) {\n const properties = keys(a);\n let index = properties.length;\n if (keys(b).length !== index) {\n return false;\n }\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n if (!isPropertyEqual(a, b, state, properties[index])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the objects are equal in value with strict property checking.\n */\nfunction areObjectsEqualStrict(a, b, state) {\n const properties = getStrictProperties(a);\n let index = properties.length;\n if (getStrictProperties(b).length !== index) {\n return false;\n }\n let property;\n let descriptorA;\n let descriptorB;\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n property = properties[index];\n if (!isPropertyEqual(a, b, state, property)) {\n return false;\n }\n descriptorA = getOwnPropertyDescriptor(a, property);\n descriptorB = getOwnPropertyDescriptor(b, property);\n if ((descriptorA || descriptorB)\n && (!descriptorA\n || !descriptorB\n || descriptorA.configurable !== descriptorB.configurable\n || descriptorA.enumerable !== descriptorB.enumerable\n || descriptorA.writable !== descriptorB.writable)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the primitive wrappers passed are equal in value.\n */\nfunction arePrimitiveWrappersEqual(a, b) {\n return sameValueEqual(a.valueOf(), b.valueOf());\n}\n/**\n * Whether the regexps passed are equal in value.\n */\nfunction areRegExpsEqual(a, b) {\n return a.source === b.source && a.flags === b.flags;\n}\n/**\n * Whether the `Set`s are equal in value.\n */\nfunction areSetsEqual(a, b, state) {\n const size = a.size;\n if (size !== b.size) {\n return false;\n }\n if (!size) {\n return true;\n }\n const matchedIndices = new Array(size);\n const aIterable = a.values();\n let aResult;\n let bResult;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n const bIterable = b.values();\n let hasMatch = false;\n let matchIndex = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n if (!matchedIndices[matchIndex]\n && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) {\n hasMatch = matchedIndices[matchIndex] = true;\n break;\n }\n matchIndex++;\n }\n if (!hasMatch) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the TypedArray instances are equal in value.\n */\nfunction areTypedArraysEqual(a, b) {\n let index = a.byteLength;\n if (b.byteLength !== index || a.byteOffset !== b.byteOffset) {\n return false;\n }\n while (index-- > 0) {\n if (a[index] !== b[index]) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the URL instances are equal in value.\n */\nfunction areUrlsEqual(a, b) {\n return (a.hostname === b.hostname\n && a.pathname === b.pathname\n && a.protocol === b.protocol\n && a.port === b.port\n && a.hash === b.hash\n && a.username === b.username\n && a.password === b.password);\n}\nfunction isPropertyEqual(a, b, state, property) {\n if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE)\n && (a.$$typeof || b.$$typeof)) {\n return true;\n }\n return hasOwn(b, property) && state.equals(a[property], b[property], property, property, a, b, state);\n}\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst toString = Object.prototype.toString;\n/**\n * Create a comparator method based on the type-specific equality comparators passed.\n */\nfunction createEqualityComparator(config) {\n const supportedComparatorMap = createSupportedComparatorMap(config);\n const { areArraysEqual, areDatesEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, areRegExpsEqual, areSetsEqual, getUnsupportedCustomComparator, } = config;\n /**\n * compare the value of the two objects and return true if they are equivalent in values\n */\n return function comparator(a, b, state) {\n // If the items are strictly equal, no need to do a value comparison.\n if (a === b) {\n return true;\n }\n // If either of the items are nullish and fail the strictly equal check\n // above, then they must be unequal.\n if (a == null || b == null) {\n return false;\n }\n const type = typeof a;\n if (type !== typeof b) {\n return false;\n }\n if (type !== 'object') {\n if (type === 'number' || type === 'bigint') {\n return areNumbersEqual(a, b, state);\n }\n if (type === 'function') {\n return areFunctionsEqual(a, b, state);\n }\n // If a primitive value that is not strictly equal, it must be unequal.\n return false;\n }\n const constructor = a.constructor;\n // Checks are listed in order of commonality of use-case:\n // 1. Common complex object types (plain object, array)\n // 2. Common data values (date, regexp)\n // 3. Less-common complex object types (map, set)\n // 4. Less-common data values (promise, primitive wrappers)\n // Inherently this is both subjective and assumptive, however\n // when reviewing comparable libraries in the wild this order\n // appears to be generally consistent.\n // Constructors should match, otherwise there is potential for false positives\n // between class and subclass or custom object and POJO.\n if (constructor !== b.constructor) {\n return false;\n }\n // Try to fast-path equality checks for other complex object types in the\n // same realm to avoid capturing the string tag. Strict equality is used\n // instead of `instanceof` because it is more performant for the common\n // use-case. If someone is creating a subclass from a native class, it will be\n // handled with the string tag comparison.\n if (constructor === Object) {\n return areObjectsEqual(a, b, state);\n }\n if (constructor === Array) {\n return areArraysEqual(a, b, state);\n }\n if (constructor === Date) {\n return areDatesEqual(a, b, state);\n }\n if (constructor === RegExp) {\n return areRegExpsEqual(a, b, state);\n }\n if (constructor === Map) {\n return areMapsEqual(a, b, state);\n }\n if (constructor === Set) {\n return areSetsEqual(a, b, state);\n }\n if (constructor === Promise) {\n // Avoid tag checks for promise values, since we know if they are not referentially equal\n // then they are not equal.\n return false;\n }\n // `isArray()` works on subclasses and is cross-realm, so we can avoid capturing\n // the string tag or doing an `instanceof` in edge cases.\n if (Array.isArray(a)) {\n return areArraysEqual(a, b, state);\n }\n // Since this is a custom object, capture the string tag to determining its type.\n // This is reasonably performant in modern environments like v8 and SpiderMonkey.\n const tag = toString.call(a);\n const supportedComparator = supportedComparatorMap[tag];\n if (supportedComparator) {\n return supportedComparator(a, b, state);\n }\n const unsupportedCustomComparator = getUnsupportedCustomComparator && getUnsupportedCustomComparator(a, b, state, tag);\n if (unsupportedCustomComparator) {\n return unsupportedCustomComparator(a, b, state);\n }\n // If not matching any tags that require a specific type of comparison, then we hard-code false because\n // the only thing remaining is strict equality, which has already been compared. This is for a few reasons:\n // - Certain types that cannot be introspected (e.g., `WeakMap`). For these types, this is the only\n // comparison that can be made.\n // - For types that can be introspected but do not have an objective definition of what\n // equality is (`Error`, etc.), the subjective decision is to be conservative and strictly compare.\n // In all cases, these decisions should be reevaluated based on changes to the language and\n // common development practices.\n return false;\n };\n}\n/**\n * Create the configuration object used for building comparators.\n */\nfunction createEqualityComparatorConfig({ circular, createCustomConfig, strict, }) {\n let config = {\n areArrayBuffersEqual,\n areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual,\n areDataViewsEqual,\n areDatesEqual: areDatesEqual,\n areErrorsEqual: areErrorsEqual,\n areFunctionsEqual: strictEqual,\n areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual,\n areNumbersEqual: sameValueEqual,\n areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual,\n arePrimitiveWrappersEqual: arePrimitiveWrappersEqual,\n areRegExpsEqual: areRegExpsEqual,\n areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual,\n areTypedArraysEqual: strict\n ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict)\n : areTypedArraysEqual,\n areUrlsEqual: areUrlsEqual,\n getUnsupportedCustomComparator: undefined,\n };\n if (createCustomConfig) {\n config = Object.assign({}, config, createCustomConfig(config));\n }\n if (circular) {\n const areArraysEqual = createIsCircular(config.areArraysEqual);\n const areMapsEqual = createIsCircular(config.areMapsEqual);\n const areObjectsEqual = createIsCircular(config.areObjectsEqual);\n const areSetsEqual = createIsCircular(config.areSetsEqual);\n config = Object.assign({}, config, {\n areArraysEqual,\n areMapsEqual,\n areObjectsEqual,\n areSetsEqual,\n });\n }\n return config;\n}\n/**\n * Default equality comparator pass-through, used as the standard `isEqual` creator for\n * use inside the built comparator.\n */\nfunction createInternalEqualityComparator(compare) {\n return function (a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) {\n return compare(a, b, state);\n };\n}\n/**\n * Create the `isEqual` function used by the consuming application.\n */\nfunction createIsEqual({ circular, comparator, createState, equals, strict }) {\n if (createState) {\n return function isEqual(a, b) {\n const { cache = circular ? new WeakMap() : undefined, meta } = createState();\n return comparator(a, b, {\n cache,\n equals,\n meta,\n strict,\n });\n };\n }\n if (circular) {\n return function isEqual(a, b) {\n return comparator(a, b, {\n cache: new WeakMap(),\n equals,\n meta: undefined,\n strict,\n });\n };\n }\n const state = {\n cache: undefined,\n equals,\n meta: undefined,\n strict,\n };\n return function isEqual(a, b) {\n return comparator(a, b, state);\n };\n}\n/**\n * Create a map of `toString()` values to their respective handlers for `tag`-based lookups.\n */\nfunction createSupportedComparatorMap({ areArrayBuffersEqual, areArraysEqual, areDataViewsEqual, areDatesEqual, areErrorsEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, arePrimitiveWrappersEqual, areRegExpsEqual, areSetsEqual, areTypedArraysEqual, areUrlsEqual, }) {\n return {\n '[object Arguments]': areObjectsEqual,\n '[object Array]': areArraysEqual,\n '[object ArrayBuffer]': areArrayBuffersEqual,\n '[object AsyncGeneratorFunction]': areFunctionsEqual,\n '[object BigInt]': areNumbersEqual,\n '[object BigInt64Array]': areTypedArraysEqual,\n '[object BigUint64Array]': areTypedArraysEqual,\n '[object Boolean]': arePrimitiveWrappersEqual,\n '[object DataView]': areDataViewsEqual,\n '[object Date]': areDatesEqual,\n // If an error tag, it should be tested explicitly. Like RegExp, the properties are not\n // enumerable, and therefore will give false positives if tested like a standard object.\n '[object Error]': areErrorsEqual,\n '[object Float16Array]': areTypedArraysEqual,\n '[object Float32Array]': areTypedArraysEqual,\n '[object Float64Array]': areTypedArraysEqual,\n '[object Function]': areFunctionsEqual,\n '[object GeneratorFunction]': areFunctionsEqual,\n '[object Int8Array]': areTypedArraysEqual,\n '[object Int16Array]': areTypedArraysEqual,\n '[object Int32Array]': areTypedArraysEqual,\n '[object Map]': areMapsEqual,\n '[object Number]': arePrimitiveWrappersEqual,\n '[object Object]': (a, b, state) => \n // The exception for value comparison is custom `Promise`-like class instances. These should\n // be treated the same as standard `Promise` objects, which means strict equality, and if\n // it reaches this point then that strict equality comparison has already failed.\n typeof a.then !== 'function' && typeof b.then !== 'function' && areObjectsEqual(a, b, state),\n // For RegExp, the properties are not enumerable, and therefore will give false positives if\n // tested like a standard object.\n '[object RegExp]': areRegExpsEqual,\n '[object Set]': areSetsEqual,\n '[object String]': arePrimitiveWrappersEqual,\n '[object URL]': areUrlsEqual,\n '[object Uint8Array]': areTypedArraysEqual,\n '[object Uint8ClampedArray]': areTypedArraysEqual,\n '[object Uint16Array]': areTypedArraysEqual,\n '[object Uint32Array]': areTypedArraysEqual,\n };\n}\n\n/**\n * Whether the items passed are deeply-equal in value.\n */\nconst deepEqual = createCustomEqual();\n/**\n * Whether the items passed are deeply-equal in value based on strict comparison.\n */\nconst strictDeepEqual = createCustomEqual({ strict: true });\n/**\n * Whether the items passed are deeply-equal in value, including circular references.\n */\nconst circularDeepEqual = createCustomEqual({ circular: true });\n/**\n * Whether the items passed are deeply-equal in value, including circular references,\n * based on strict comparison.\n */\nconst strictCircularDeepEqual = createCustomEqual({\n circular: true,\n strict: true,\n});\n/**\n * Whether the items passed are shallowly-equal in value.\n */\nconst shallowEqual = createCustomEqual({\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value based on strict comparison\n */\nconst strictShallowEqual = createCustomEqual({\n strict: true,\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value, including circular references.\n */\nconst circularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value, including circular references,\n * based on strict comparison.\n */\nconst strictCircularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueEqual,\n strict: true,\n});\n/**\n * Create a custom equality comparison method.\n *\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\n * where the standard methods are not performant enough, but can also be used to provide\n * support for legacy environments that do not support expected features like\n * `RegExp.prototype.flags` out of the box.\n */\nfunction createCustomEqual(options = {}) {\n const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false, } = options;\n const config = createEqualityComparatorConfig(options);\n const comparator = createEqualityComparator(config);\n const equals = createCustomInternalComparator\n ? createCustomInternalComparator(comparator)\n : createInternalEqualityComparator(comparator);\n return createIsEqual({ circular, comparator, createState, equals, strict });\n}\n\nexport { circularDeepEqual, circularShallowEqual, createCustomEqual, deepEqual, sameValueEqual, sameValueZeroEqual, shallowEqual, strictCircularDeepEqual, strictCircularShallowEqual, strictDeepEqual, strictEqual, strictShallowEqual };\n","import {\n DataSourceDefinition,\n ResolvedDataSource,\n DEFAULT_DATA_SOURCE_KEY,\n getDataSourceCapabilities\n} from \"@rebasepro/types\";\n\n/**\n * The subset of a collection needed to resolve its data source. Accepting a\n * structural type (rather than the full `CollectionConfig`) keeps this usable\n * from anywhere — frontend router, backend registry, editor — without coupling\n * to the collection union.\n */\nexport interface DataSourceResolvable {\n /** Preferred routing key. */\n dataSource?: string;\n /** Engine type discriminant (set on variant collection types). */\n engine?: string;\n /** Within-engine instance. */\n databaseId?: string;\n}\n\n/** A lookup of data-source definitions by key. */\nexport type DataSourceRegistry = Record<string, DataSourceDefinition>;\n\n/**\n * Build a keyed registry from a list of {@link DataSourceDefinition}s.\n * Later entries win on key collision.\n */\nexport function createDataSourceRegistry(definitions?: DataSourceDefinition[]): DataSourceRegistry {\n const registry: DataSourceRegistry = {};\n for (const def of definitions ?? []) {\n registry[def.key] = def;\n }\n return registry;\n}\n\n/**\n * Resolve the effective data source for a collection — the single source of\n * truth shared by the frontend router, the backend driver registry, and the\n * editor's capability lookups.\n *\n * Resolution order:\n * 1. The routing **key** is `collection.dataSource`, else\n * {@link DEFAULT_DATA_SOURCE_KEY}.\n * 2. If a definition is registered for that key, it provides `engine`,\n * `transport`, and `databaseId`.\n * 3. Otherwise values are synthesized: `engine` from `collection.engine`\n * (or the key, or `\"postgres\"`), `transport` defaults to `\"server\"`,\n * and `databaseId` from the collection.\n *\n * `capabilities` are always derived from the resolved `engine`, so two\n * data sources sharing an engine share capabilities.\n *\n * @param collection the collection (or any object carrying the routing fields)\n * @param registry optional registry of declared data sources\n */\nexport function resolveDataSource(\n collection: DataSourceResolvable | undefined,\n registry?: DataSourceRegistry\n): ResolvedDataSource {\n const key = collection?.dataSource ?? DEFAULT_DATA_SOURCE_KEY;\n const def = registry?.[key];\n\n const engine = def?.engine\n ?? collection?.engine\n ?? (key !== DEFAULT_DATA_SOURCE_KEY ? key : \"postgres\");\n\n const transport = def?.transport ?? \"server\";\n const databaseId = collection?.databaseId ?? def?.databaseId;\n\n return {\n key,\n engine,\n transport,\n databaseId,\n capabilities: getDataSourceCapabilities(engine)\n };\n}\n","import {\n ArrayProperty,\n CollectionCallbacks,\n EngineProperties,\n CollectionConfig,\n getDataSourceCapabilities,\n getDeclaredSubcollections,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty\n} from \"@rebasepro/types\";\nimport { deepEqual } from \"fast-equals\";\n\nimport {\n enumToObjectEntries,\n findRelation,\n getSubcollections,\n getTableName,\n resolveCollectionRelations,\n sanitizeRelation\n} from \"../util\";\nimport { deepClone, mergeDeep, removeFunctions } from \"@rebasepro/utils\";\nimport { DataSourceRegistry, resolveDataSource } from \"../data/resolveDataSource\";\n\nexport class CollectionRegistry {\n\n /**\n * Declared data sources, used during normalization to resolve each\n * collection's engine (so `dataSource`-only collections get the right\n * capabilities). Empty by default.\n */\n private dataSources: DataSourceRegistry = {};\n\n /**\n * Global lifecycle callbacks applied to every collection.\n * Runs on all data paths (REST, WebSocket, `rebase.data`).\n * Execution order: global → collection → property callbacks.\n */\n private _globalCallbacks?: CollectionCallbacks;\n\n /**\n * Set global lifecycle callbacks that apply to every collection.\n * Typically called once during backend initialization.\n */\n setGlobalCallbacks(callbacks: CollectionCallbacks): void {\n this._globalCallbacks = callbacks;\n }\n\n /**\n * Get the currently registered global callbacks, if any.\n */\n getGlobalCallbacks(): CollectionCallbacks | undefined {\n return this._globalCallbacks;\n }\n\n // Normalized runtime layer (used by Data Grid / UI)\n private collectionsByTableName = new Map<string, CollectionConfig>();\n private collectionsBySlug = new Map<string, CollectionConfig>();\n private rootCollections: CollectionConfig[] = [];\n private cachedCollectionsList: CollectionConfig[] | null = null;\n\n // Raw configuration layer (used by Collection Editor AST generator)\n private rawCollectionsByTableName = new Map<string, CollectionConfig>();\n private rawCollectionsBySlug = new Map<string, CollectionConfig>();\n private rawRootCollections: CollectionConfig[] = [];\n private cachedRawCollectionsList: CollectionConfig[] | null = null;\n\n // Entity of raw input for idempotency check — compared BEFORE normalization\n // to avoid the issue where normalization creates new objects that always fail equality.\n private lastRawInputEntity: ReturnType<typeof removeFunctions>[] | null = null;\n\n constructor(collections?: CollectionConfig[], dataSources?: DataSourceRegistry) {\n if (dataSources) this.dataSources = dataSources;\n if (collections) {\n this.registerMultiple(collections);\n }\n }\n\n /**\n * Provide the declared data sources used to resolve each collection's\n * engine during normalization. Set this before registering collections.\n * Returns true if the registry changed (callers may re-register).\n */\n setDataSources(dataSources: DataSourceRegistry): boolean {\n if (deepEqual(this.dataSources, dataSources)) return false;\n this.dataSources = dataSources ?? {};\n return true;\n }\n\n reset() {\n this.collectionsByTableName.clear();\n this.collectionsBySlug.clear();\n this.rootCollections = [];\n this.cachedCollectionsList = null;\n\n this.rawCollectionsByTableName.clear();\n this.rawCollectionsBySlug.clear();\n this.rawRootCollections = [];\n this.cachedRawCollectionsList = null;\n }\n\n /**\n * Registers a collection and its subcollections recursively.\n * Returns true if the collections have changed, false otherwise.\n *\n * Idempotent: compares the raw input (before normalization) against a stored\n * entity. Only re-normalizes and re-registers when the raw input actually changed.\n * @param collections\n */\n registerMultiple(collections: CollectionConfig[]): boolean {\n // Compare raw input BEFORE normalization to detect actual changes.\n // This avoids the old issue where normalization creates new objects\n // that always fail deep-equal even when the source data is identical.\n const rawEntity = collections.map(c => removeFunctions(c));\n if (this.lastRawInputEntity && deepEqual(this.lastRawInputEntity, rawEntity)) {\n return false;\n }\n\n this.reset();\n // Phase 0: Populate maps with raw collections first for string target resolution\n collections.forEach((c) => {\n if (c.slug) {\n this.collectionsBySlug.set(c.slug, c);\n }\n this.collectionsByTableName.set(getTableName(c), c);\n });\n\n const normalizedCollections = collections.map(c => this.normalizeCollection({ ...c }));\n\n // Phase 1: Register all top-level collections first (without recursion).\n // This ensures that injected entityViews (e.g. History tab) are preserved.\n // Without this, _registerRecursively could register a relation-target collection\n // (e.g. Tags from Posts.relations) using the raw module object (without injected views)\n // before the top-level Tags collection (with injected views) gets its turn.\n normalizedCollections.forEach((c, index) => {\n const raw = deepClone(collections[index]);\n this.rootCollections.push(c);\n this.rawRootCollections.push(raw);\n\n const normalized = this.normalizeCollection(c);\n this.collectionsByTableName.set(getTableName(normalized), normalized);\n this.rawCollectionsByTableName.set(getTableName(raw), raw);\n if (normalized.slug) {\n this.collectionsBySlug.set(normalized.slug, normalized);\n }\n if (raw.slug) {\n this.rawCollectionsBySlug.set(raw.slug, raw);\n }\n });\n\n // Phase 2: Now recurse into subcollections (relations, etc.)\n normalizedCollections.forEach((c) => {\n const subcollections = getSubcollections(c);\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n });\n\n // Store the entity for future comparisons\n this.lastRawInputEntity = rawEntity;\n\n return true;\n }\n\n register(collection: CollectionConfig, rawCollection?: CollectionConfig) {\n const raw = rawCollection ? deepClone(rawCollection) : deepClone(collection);\n\n this.rootCollections.push(collection);\n this.rawRootCollections.push(raw);\n\n this._registerRecursively(collection, raw);\n }\n\n private _registerRecursively(collection: CollectionConfig, rawCollection: CollectionConfig) {\n if (this.collectionsByTableName.has(getTableName(collection))) {\n return;\n }\n\n const normalizedCollection = this.normalizeCollection(collection);\n this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);\n this.rawCollectionsByTableName.set(getTableName(rawCollection), rawCollection);\n\n if (normalizedCollection.slug) {\n this.collectionsBySlug.set(normalizedCollection.slug, normalizedCollection);\n }\n if (rawCollection.slug) {\n this.rawCollectionsBySlug.set(rawCollection.slug, rawCollection);\n }\n\n // Use the normalized collection for subcollection discovery so that\n // both inline-extracted and explicit relations are considered.\n const subcollections = getSubcollections(normalizedCollection);\n\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n }\n\n public normalizeCollection(collection: CollectionConfig): CollectionConfig {\n // Work on a shallow copy to avoid mutating the caller's reference.\n // This is critical for idempotency (the raw input must not be changed)\n // and for preventing mutation of module-level collection singletons.\n const result = { ...collection } as CollectionConfig;\n\n // 0. Resolve and stamp `dataSource` and `engine` on the normalized copy.\n // After this block every normalized collection has both fields set,\n // so downstream code can read them directly without calling\n // `resolveDataSource()`. Only the normalized layer is affected —\n // the raw layer used by the collection editor keeps the author's\n // original fields.\n {\n const resolved = resolveDataSource(result, this.dataSources);\n if (!result.dataSource) (result as { dataSource?: string }).dataSource = resolved.key;\n if (!result.engine) (result as { engine?: string }).engine = resolved.engine;\n }\n\n // 1. Extract relations from properties that have inline config (target set)\n const extractedRelations = this.extractRelationsFromProperties(result.properties);\n\n // 2. Merge with manual relations[] (manual entries win on name conflict)\n const relResult = result;\n const manualRelations = getDataSourceCapabilities(result.engine).supportsRelations ? (relResult.relations ?? []) : [];\n const mergedRelationsRaw = [...extractedRelations];\n for (const manual of manualRelations) {\n const name = manual.relationName;\n if (!name) {\n mergedRelationsRaw.push(manual);\n } else {\n const existingIndex = mergedRelationsRaw.findIndex(r => r.relationName === name);\n if (existingIndex === -1) {\n mergedRelationsRaw.push(manual);\n } else {\n // Merge manual into existing, preserving custom fields like 'collection'\n mergedRelationsRaw[existingIndex] = {\n ...manual,\n ...mergedRelationsRaw[existingIndex]\n };\n }\n }\n }\n\n let mergedRelations = mergedRelationsRaw;\n\n // 2b. Sanitize each relation so derived fields (through, localKey,\n // foreignKeyOnTarget, etc.) are populated. Without this the\n // property.relation stamp is missing junction-table metadata and\n // the backend cannot fetch many-to-many data.\n if (getDataSourceCapabilities(result.engine).supportsRelations) {\n mergedRelations = mergedRelationsRaw.map(r => {\n try {\n return sanitizeRelation(r, result, (slug) => this.get(slug));\n } catch {\n // sanitizeRelation may throw for incomplete configs\n // (e.g. missing target). Keep the raw relation as-is.\n return r;\n }\n });\n\n // 3. Set the merged relations on the result copy\n relResult.relations = mergedRelations;\n }\n\n // 4. Normalize properties (which stamps relation on each property)\n const properties: Properties = this.normalizeProperties(result.properties, mergedRelations);\n result.properties = properties as EngineProperties;\n\n // Populate childCollections from driver-specific fields\n if (!result.childCollections) {\n const capabilities = getDataSourceCapabilities(result.engine);\n const declaredSubcollections = getDeclaredSubcollections(result);\n if (capabilities.supportsSubcollections && declaredSubcollections) {\n result.childCollections = declaredSubcollections;\n } else if (capabilities.supportsRelations && relResult.relations) {\n const manyRelations = relResult.relations.filter((r: Relation) => r.cardinality === \"many\");\n if (manyRelations.length > 0) {\n result.childCollections = () => manyRelations.map((r: Relation) => {\n const target = r.target();\n return r.overrides ? mergeDeep(target, r.overrides) : target;\n });\n }\n }\n }\n\n return result;\n }\n\n /**\n * Extract Relation[] from properties that have inline relation config (i.e. `target` is set).\n * This allows developers to define relations directly on properties without a separate\n * `relations[]` entry on the collection.\n */\n private extractRelationsFromProperties(properties: Properties): Relation[] {\n const relations: Relation[] = [];\n for (const [key, property] of Object.entries(properties as Record<string, Property>)) {\n if (property.type === \"relation\") {\n const relProp = property as RelationProperty;\n // Support both inline config (target directly on property)\n // and nested config (target inside property.relation)\n const target = relProp.target ?? relProp.relation?.target;\n if (target) {\n const relationName = relProp.relationName ?? relProp.relation?.relationName ?? key;\n relations.push({\n relationName,\n target,\n cardinality: relProp.cardinality ?? relProp.relation?.cardinality ?? \"one\",\n direction: relProp.direction ?? relProp.relation?.direction ?? \"owning\",\n inverseRelationName: relProp.inverseRelationName ?? relProp.relation?.inverseRelationName,\n localKey: relProp.localKey ?? relProp.relation?.localKey,\n foreignKeyOnTarget: relProp.foreignKeyOnTarget ?? relProp.relation?.foreignKeyOnTarget,\n through: relProp.through ?? relProp.relation?.through,\n joinPath: relProp.joinPath ?? relProp.relation?.joinPath,\n onUpdate: relProp.onUpdate ?? relProp.relation?.onUpdate,\n onDelete: relProp.onDelete ?? relProp.relation?.onDelete,\n overrides: relProp.overrides ?? relProp.relation?.overrides\n });\n }\n } else if (property.type === \"map\" && property.properties) {\n // Recurse into map children to extract nested inline relations\n relations.push(...this.extractRelationsFromProperties(property.properties));\n }\n }\n return relations;\n }\n\n private normalizeProperties(properties: Properties, relations: Relation[]): Properties {\n const newProperties: Properties = {};\n for (const key in properties) {\n newProperties[key] = this.normalizeProperty(key, properties[key], relations);\n }\n return newProperties;\n }\n\n private normalizeProperty(key: string, property: Property, relations: Relation[]): Property {\n const newProperty = { ...property };\n\n if (newProperty.type === \"map\" && newProperty.properties) {\n newProperty.properties = this.normalizeProperties(newProperty.properties, relations);\n } else if (newProperty.type === \"array\") {\n // Cast to get a properly typed mutable reference\n const arrayProp = newProperty as ArrayProperty;\n if (arrayProp.of) {\n if (Array.isArray(arrayProp.of)) {\n (arrayProp as { of: Property | Property[] }).of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, relations));\n } else {\n arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, relations);\n }\n } else if (arrayProp.oneOf && arrayProp.oneOf.properties) {\n arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.oneOf.properties, relations);\n }\n } else if ((newProperty.type === \"string\" || newProperty.type === \"number\") && newProperty.enum) {\n const stringOrNumberProperty = newProperty as StringProperty | NumberProperty;\n if (typeof stringOrNumberProperty.enum === \"object\" && !Array.isArray(stringOrNumberProperty.enum)) {\n stringOrNumberProperty.enum = enumToObjectEntries(stringOrNumberProperty.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [];\n }\n } else if (newProperty.type === \"relation\") {\n const relationProperty = newProperty as RelationProperty;\n const name = relationProperty.relationName || key;\n const relation = relations.find(r => r.relationName === name);\n if (relation) {\n // we attach the resolved relation to the property\n relationProperty.relation = relation;\n } else {\n console.warn(`Could not find relation for property '${key}' with relationName: ${name}`);\n }\n }\n\n return newProperty;\n }\n\n get(path: string): CollectionConfig | undefined {\n // First try slug lookup\n const bySlug = this.collectionsBySlug.get(path);\n if (bySlug) return bySlug;\n\n // Fallback: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.collectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n // Fallback to table name lookup\n return this.collectionsByTableName.get(path);\n }\n\n /**\n * Gets the pristine, un-normalized collection exactly as it was provided.\n * Useful for the AST editor so it doesn't accidentally serialize injected metadata back to disk.\n */\n getRaw(path: string): CollectionConfig | undefined {\n const bySlug = this.rawCollectionsBySlug.get(path);\n if (bySlug) return bySlug;\n\n // Fallback: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.rawCollectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n return this.rawCollectionsByTableName.get(path);\n }\n\n /**\n * Get collection by resolving multi-segment paths through relations\n * e.g., \"authors/70/posts\" resolves to the posts collection\n */\n getCollectionByPath(collectionPath: string): CollectionConfig | undefined {\n // Handle simple single collection path\n if (!collectionPath.includes(\"/\")) {\n return this.get(collectionPath);\n }\n\n // Handle multi-segment paths by resolving through relations\n const pathSegments = collectionPath.split(\"/\").filter(p => p);\n\n if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {\n throw new Error(`Invalid relation path: ${collectionPath}. Expected format: collection/id/relation or collection/id/relation/id/relation`);\n }\n\n // Start with the root collection\n const rootCollectionPath = pathSegments[0];\n let currentCollection = this.get(rootCollectionPath);\n\n if (!currentCollection) {\n throw new Error(`Root collection not found: ${rootCollectionPath}`);\n }\n\n // Navigate through the path using relations\n for (let i = 2; i < pathSegments.length; i += 2) {\n const relationKey = pathSegments[i];\n\n // Get relations for current collection\n if (!getDataSourceCapabilities(currentCollection.engine).supportsRelations) {\n throw new Error(`Relation path navigation requires a collection that supports relations, but '${currentCollection.slug}' uses engine '${currentCollection.engine}'`);\n }\n const resolvedRelations = resolveCollectionRelations(currentCollection);\n const relation = findRelation(resolvedRelations, relationKey);\n\n if (!relation) {\n throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);\n }\n\n // Move to the target collection\n const target = relation.target();\n const targetRelationKey = relation.relationName || target.slug;\n const targetSlug = relation.overrides?.slug ?? targetRelationKey;\n currentCollection = this.get(targetSlug) || this.normalizeCollection(target);\n\n // If there are more segments, continue navigation\n if (i + 1 < pathSegments.length) {\n // Skip entity ID segment\n }\n }\n\n return currentCollection;\n }\n\n getCollections(): CollectionConfig[] {\n if (!this.cachedCollectionsList) {\n this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());\n }\n return this.cachedCollectionsList;\n }\n\n getRawCollections(): CollectionConfig[] {\n if (!this.cachedRawCollectionsList) {\n this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());\n }\n return this.cachedRawCollectionsList;\n }\n\n /**\n * Resolves a multi-segment path like \"products/123/locales\" and returns\n * information about the collections and entity IDs along the path\n */\n resolvePathToCollections(path: string): {\n collections: CollectionConfig[],\n entityIds: (string | number)[],\n finalCollection: CollectionConfig\n } {\n const pathSegments = path.split(\"/\").filter(p => p);\n\n if (pathSegments.length === 0) {\n throw new Error(`Invalid path: ${path}`);\n }\n\n if (pathSegments.length % 2 !== 1) {\n throw new Error(`Invalid collection path: ${path}. It must have an odd number of segments.`);\n }\n\n const collections: CollectionConfig[] = [];\n const entityIds: (string | number)[] = [];\n\n // Start with the first collection\n let currentCollection = this.get(pathSegments[0]);\n\n if (!currentCollection) {\n throw new Error(`Unknown collection path or slug: ${pathSegments[0]}`);\n }\n\n collections.push(currentCollection);\n\n // Process the rest of the path in pairs (entityId, subcollectionSlug)\n for (let i = 1; i < pathSegments.length; i += 2) {\n const entityId = pathSegments[i];\n entityIds.push(entityId);\n\n if (i + 1 < pathSegments.length) {\n const subcollectionSlug = pathSegments[i + 1];\n const subcollections: CollectionConfig[] | undefined = getSubcollections(currentCollection);\n if (!subcollections || subcollections.length === 0) {\n throw new Error(`No subcollections found for ${currentCollection.slug} in path: ${path}`);\n }\n\n const subcollection: CollectionConfig | undefined = subcollections.find(c => c.slug === subcollectionSlug);\n if (!subcollection) {\n throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug}`);\n }\n currentCollection = this.get(subcollection.slug) || this.normalizeCollection(subcollection);\n collections.push(currentCollection);\n }\n }\n\n return {\n collections,\n entityIds,\n finalCollection: currentCollection\n };\n }\n\n}\n\n","import { defineCollection } from \"../util/builders\";\n\n/**\n * Default users collection.\n *\n * Prepended to the developer's collections array by the admin and server.\n * Slug-based dedup (Map keyed by slug, last-write-wins) lets developers\n * override by defining their own collection with `slug: \"users\"`.\n */\nexport const defaultUsersCollection = defineCollection({\n name: \"Users\",\n singularName: \"User\",\n slug: \"users\",\n auth: true,\n table: \"users\",\n schema: \"rebase\",\n icon: \"Users\",\n group: \"Settings\",\n openEntityMode: \"dialog\",\n disableDefaultActions: [\"copy\"],\n securityRules: [\n { operation: \"select\",\nroles: [\"admin\"] },\n { operations: [\"insert\", \"update\", \"delete\"],\nroles: [\"admin\"] }\n ],\n sort: [\"createdAt\", \"desc\"],\n properties: {\n id: {\n name: \"ID\",\n type: \"string\",\n isId: \"uuid\",\n ui: { readOnly: true }\n },\n email: {\n name: \"Email\",\n type: \"string\",\n validation: { required: true,\nunique: true }\n },\n displayName: {\n name: \"Name\",\n type: \"string\",\n columnName: \"display_name\",\n validation: { required: true }\n },\n photoURL: {\n name: \"Photo URL\",\n type: \"string\",\n columnName: \"photo_url\",\n ui: { url: \"image\" }\n },\n roles: {\n name: \"Roles\",\n type: \"array\",\n columnType: \"text[]\",\n of: {\n name: \"Role\",\n type: \"string\",\n enum: {\n admin: \"Admin\",\n editor: \"Editor\",\n viewer: \"Viewer\"\n }\n }\n },\n passwordHash: {\n name: \"Password Hash\",\n type: \"string\",\n columnName: \"password_hash\",\n ui: { hideFromCollection: true,\ndisabled: { hidden: true } }\n },\n emailVerified: {\n name: \"Email Verified\",\n type: \"boolean\",\n columnName: \"email_verified\",\n defaultValue: false,\n ui: { hideFromCollection: true,\ndisabled: { hidden: true } }\n },\n emailVerificationToken: {\n name: \"Email Verification Token\",\n type: \"string\",\n columnName: \"email_verification_token\",\n ui: { hideFromCollection: true,\ndisabled: { hidden: true } }\n },\n emailVerificationSentAt: {\n name: \"Email Verification Sent At\",\n type: \"date\",\n columnName: \"email_verification_sent_at\",\n ui: { hideFromCollection: true,\ndisabled: { hidden: true } }\n },\n metadata: {\n name: \"Metadata\",\n type: \"map\",\n keyValue: true,\n properties: {},\n defaultValue: {},\n ui: { hideFromCollection: true,\ndisabled: { hidden: true } }\n },\n createdAt: {\n name: \"Created At\",\n type: \"date\",\n columnName: \"created_at\",\n autoValue: \"on_create\",\n ui: { readOnly: true }\n },\n updatedAt: {\n name: \"Updated At\",\n type: \"date\",\n columnName: \"updated_at\",\n autoValue: \"on_update\",\n ui: { hideFromCollection: true,\ndisabled: { hidden: true } }\n }\n },\n listProperties: [\"displayName\", \"email\", \"roles\", \"createdAt\"],\n propertiesOrder: [\"id\", \"email\", \"displayName\", \"roles\", \"createdAt\"]\n});\n","import {\n CollectionAccessor,\n FilterCondition,\n FindParams,\n FindResponse,\n LogicalCondition,\n QueryBuilderInterface,\n WhereFilterOp,\n WhereValue\n} from \"@rebasepro/types\";\n\nexport function or(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"or\",\nconditions };\n}\n\nexport function and(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"and\",\nconditions };\n}\n\nexport function cond(column: string, operator: WhereFilterOp, value: unknown): FilterCondition {\n return { column,\noperator,\nvalue };\n}\n\nexport class QueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> implements QueryBuilderInterface<M> {\n private params: FindParams = { where: {} };\n\n constructor(private collection: CollectionAccessor<M>) {}\n\n /**\n * Add a filter condition to your query.\n * @example\n * client.collection('users').where('age', '>=', 18).find()\n */\n where<K extends keyof M & string>(column: K, operator: WhereFilterOp, value: WhereValue<M[K]>): this;\n where(logicalCondition: LogicalCondition): this;\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown): this {\n // Handle LogicalCondition signature\n if (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n this.params.logical = columnOrCondition as LogicalCondition;\n return this;\n }\n\n if (!this.params.where) {\n this.params.where = {};\n }\n\n const column = columnOrCondition as string;\n const condition: [WhereFilterOp, unknown] = [operator!, value];\n const existing = this.params.where[column];\n\n if (existing === undefined) {\n this.params.where[column] = condition;\n } else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) {\n (this.params.where[column] as [WhereFilterOp, unknown][]).push(condition);\n } else {\n // Convert existing single tuple/value into array of tuples\n let firstCondition: [WhereFilterOp, unknown];\n if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") {\n firstCondition = existing as [WhereFilterOp, unknown];\n } else {\n firstCondition = [\"==\", existing];\n }\n this.params.where[column] = [firstCondition, condition];\n }\n\n return this;\n }\n\n /**\n * Order the results by a specific column.\n * @example\n * client.collection('users').orderBy('createdAt', 'desc').find()\n */\n orderBy(column: keyof M & string, direction: \"asc\" | \"desc\" = \"asc\"): this {\n this.params.orderBy = [column, direction];\n return this;\n }\n\n /**\n * Limit the number of results returned.\n */\n limit(count: number): this {\n this.params.limit = count;\n return this;\n }\n\n /**\n * Skip the first N results.\n */\n offset(count: number): this {\n this.params.offset = count;\n return this;\n }\n\n /**\n * Set a free-text search string if supported by the backend.\n */\n search(searchString: string): this {\n this.params.searchString = searchString;\n return this;\n }\n\n /**\n * Include related entities in the response.\n * Relations will be populated with full entity data instead of just IDs.\n *\n * @param relations - Relation names to include, or \"*\" for all.\n * @example\n * // Include specific relations\n * client.data.posts.include(\"tags\", \"author\").find()\n *\n * // Include all relations\n * client.data.posts.include(\"*\").find()\n */\n include(...relations: string[]): this {\n this.params.include = relations;\n return this;\n }\n\n /**\n * Execute the find query and return the results.\n */\n async find(): Promise<FindResponse<M>> {\n return this.collection.find(this.params) as Promise<FindResponse<M>>;\n }\n\n /**\n * Listen to realtime updates matching this query.\n */\n listen(onUpdate: (data: FindResponse<M>) => void, onError?: (error: Error) => void): () => void {\n if (!this.collection.listen) {\n throw new Error(\"Listen is only available when RebaseClient is configured with a websocketUrl.\");\n }\n return this.collection.listen(this.params, onUpdate, onError);\n }\n}\n","/**\n * REST wire-format adapter for the unified filter system.\n *\n * This module is the ONLY code in the entire codebase that knows about\n * PostgREST-style dot-syntax strings (`eq.active`, `gt.18`, `in.(a,b)`).\n * Everything else speaks `FilterValues` exclusively.\n *\n * Wire-format values are always strings — the wire format carries no type\n * metadata, so type coercion is the responsibility of the server-side data\n * driver which has access to the collection schema.\n *\n * Commas inside list values are backslash-escaped (`\\,`), and literal\n * backslashes are escaped as `\\\\`.\n *\n * @module\n */\n\nimport {\n WhereFilterOp,\n FilterValues,\n CANONICAL_TO_REST,\n REST_TO_CANONICAL,\n RestFilterOp,\n toCanonicalOp,\n LogicalCondition,\n FilterCondition,\n NULL_OPS\n} from \"@rebasepro/types\";\n\n// ---------------------------------------------------------------------------\n// Value stringification\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a JS value to its querystring representation.\n * `null` is serialized as the literal string `\"null\"`.\n */\nfunction stringifyValue(value: unknown): string {\n if (value === null) return \"null\";\n return String(value);\n}\n\n// ---------------------------------------------------------------------------\n// Comma escaping for list values\n// ---------------------------------------------------------------------------\n\n/**\n * Escape a single list item for the wire format.\n * `\\` → `\\\\`, `,` → `\\,`\n */\nfunction escapeListItem(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/,/g, \"\\\\,\");\n}\n\n/**\n * Unescape a single list item from the wire format.\n * `\\\\` → `\\`, `\\,` → `,`\n */\nfunction unescapeListItem(value: string): string {\n let result = \"\";\n for (let i = 0; i < value.length; i++) {\n if (value[i] === \"\\\\\" && i + 1 < value.length) {\n result += value[i + 1];\n i++; // skip next char\n } else {\n result += value[i];\n }\n }\n return result;\n}\n\n/**\n * Split a parenthesized list string on unescaped commas.\n * Input is the content between `(` and `)`.\n *\n * @example\n * splitListItems(\"admin,editor\") // [\"admin\", \"editor\"]\n * splitListItems(\"hello\\\\, world,foo\") // [\"hello, world\", \"foo\"]\n */\nfunction splitListItems(inner: string): string[] {\n const items: string[] = [];\n let current = \"\";\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === \"\\\\\" && i + 1 < inner.length) {\n // Escaped character — consume both chars\n current += inner[i] + inner[i + 1];\n i++;\n } else if (inner[i] === \",\") {\n items.push(unescapeListItem(current));\n current = \"\";\n } else {\n current += inner[i];\n }\n }\n items.push(unescapeListItem(current));\n return items;\n}\n\n// ---------------------------------------------------------------------------\n// Typed operator map lookups (no `as any`)\n// ---------------------------------------------------------------------------\n\nconst REST_OP_LOOKUP = REST_TO_CANONICAL as Readonly<Record<string, WhereFilterOp | undefined>>;\nconst CANONICAL_OP_LOOKUP = CANONICAL_TO_REST as Readonly<Record<string, RestFilterOp | undefined>>;\n\n// ---------------------------------------------------------------------------\n// Serialize: FilterValues → REST querystring\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a single canonical condition tuple to a PostgREST dot-string.\n *\n * Throws `TypeError` if the input is not a valid `[WhereFilterOp, unknown]` tuple.\n *\n * @example\n * serializeTuple([\"==\", \"active\"]) // \"eq.active\"\n * serializeTuple([\"in\", [\"admin\",\"editor\"]]) // \"in.(admin,editor)\"\n * serializeTuple([\">=\", 18]) // \"gte.18\"\n */\nfunction serializeTuple(tuple: [WhereFilterOp, unknown]): string {\n if (!Array.isArray(tuple) || tuple.length !== 2) {\n throw new TypeError(\n `serializeTuple: expected a [WhereFilterOp, value] tuple, got ${JSON.stringify(tuple)}`\n );\n }\n\n const [op, value] = tuple;\n\n if (typeof op !== \"string\") {\n throw new TypeError(\n `serializeTuple: operator must be a string, got ${typeof op}`\n );\n }\n\n const restOp = CANONICAL_OP_LOOKUP[op];\n if (!restOp) {\n throw new TypeError(\n `serializeTuple: unknown operator \"${op}\". Valid operators: ${Object.keys(CANONICAL_TO_REST).join(\", \")}`\n );\n }\n\n if (Array.isArray(value)) {\n const items = value.map(v => escapeListItem(stringifyValue(v))).join(\",\");\n return `${restOp}.(${items})`;\n }\n\n return `${restOp}.${stringifyValue(value)}`;\n}\n\n/**\n * Convert `FilterValues` (or `WireFilterValues`) to a PostgREST-style\n * querystring record.\n *\n * - Canonical `[WhereFilterOp, value]` tuples are serialized strictly.\n * - Pre-serialized PostgREST strings (e.g. `\"eq.published\"`) are passed through.\n * - Single conditions produce a string value.\n * - Multiple conditions on the same field produce a string array (repeated params).\n *\n * @example\n * serializeFilter({ status: [\"==\", \"active\"] })\n * // → { status: \"eq.active\" }\n *\n * serializeFilter({ age: [[\">=\", 18], [\"<\", 65]] })\n * // → { age: [\"gte.18\", \"lt.65\"] }\n *\n * // Pre-serialized strings pass through unchanged:\n * serializeFilter({ status: \"eq.published\" })\n * // → { status: \"eq.published\" }\n */\nexport function serializeFilter(\n filter: FilterValues<string> | Record<string, unknown>\n): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = {};\n\n for (const [field, condition] of Object.entries(filter)) {\n if (condition === undefined) continue;\n\n // Pre-serialized PostgREST string — pass through unchanged.\n // This supports WireFilterValues where values may already be\n // serialized dot-strings like \"eq.active\" or raw strings like \"true\".\n if (typeof condition === \"string\") {\n result[field] = condition;\n continue;\n }\n\n // Multiple conditions on the same field: array of tuples\n // We detect this by checking if the first element is also an array.\n if (Array.isArray(condition) && condition.length > 0 && Array.isArray(condition[0])) {\n result[field] = (condition as [WhereFilterOp, unknown][]).map(serializeTuple);\n } else {\n // Single condition — must be a [WhereFilterOp, value] tuple\n result[field] = serializeTuple(condition as [WhereFilterOp, unknown]);\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Deserialize: REST querystring → FilterValues\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a single PostgREST dot-string into a `[WhereFilterOp, unknown]` tuple.\n *\n * All values are returned as strings — the wire format carries no type\n * metadata, so coercion is the data driver's responsibility.\n *\n * If the string doesn't match a known operator prefix, it falls back to\n * `[\"==\", originalString]` (treating the whole string as an equality value).\n * This intentional defense handles values like `\"user@host.com\"` or\n * `\"1.2.3\"` that happen to contain dots.\n */\nfunction deserializeSingle(raw: string): [WhereFilterOp, unknown] {\n const dotIndex = raw.indexOf(\".\");\n if (dotIndex === -1) {\n // No dot → equality on the raw value (kept as string)\n return [\"==\", raw];\n }\n\n const prefix = raw.substring(0, dotIndex);\n const rest = raw.substring(dotIndex + 1);\n\n // Check if the prefix is a known REST operator.\n // This is the key defense against values like \"eq.something\" or \"gt.foo\"\n // being misinterpreted — only known REST short-codes are treated as operators.\n const canonicalOp = REST_OP_LOOKUP[prefix];\n if (!canonicalOp) {\n // Not a known operator (e.g., email \"user@host.com\" or version \"1.2.3\")\n // Treat the entire string as an equality value\n return [\"==\", raw];\n }\n\n // Null-testing operators ignore their serialized value — normalize to null\n // so the tuple round-trips stably (`isnull.null` → [\"is-null\", null]).\n if (NULL_OPS.has(canonicalOp)) {\n return [canonicalOp, null];\n }\n\n // Parse list values: \"(admin,editor)\" → [\"admin\", \"editor\"]\n if (rest.startsWith(\"(\") && rest.endsWith(\")\")) {\n const items = splitListItems(rest.slice(1, -1));\n return [canonicalOp, items];\n }\n\n return [canonicalOp, rest];\n}\n\n/**\n * Convert a PostgREST-style querystring record to `FilterValues`.\n *\n * - String values are parsed as single conditions.\n * - String arrays (repeated query params) become multiple conditions on the same field.\n *\n * @example\n * deserializeFilter({ status: \"eq.active\" })\n * // → { status: [\"==\", \"active\"] }\n *\n * deserializeFilter({ age: [\"gte.18\", \"lt.65\"] })\n * // → { age: [[\">=\", \"18\"], [\"<\", \"65\"]] }\n */\nexport function deserializeFilter(\n query: Record<string, unknown>\n): FilterValues<string> {\n const result: FilterValues<string> = {};\n\n for (const [field, raw] of Object.entries(query)) {\n if (raw === undefined) continue;\n\n // If it's already a canonical tuple [op, value], keep it as is\n if (Array.isArray(raw) && raw.length === 2 && typeof raw[0] === \"string\" && toCanonicalOp(raw[0]) === raw[0]) {\n result[field] = raw as [WhereFilterOp, unknown];\n continue;\n }\n\n if (Array.isArray(raw)) {\n if (raw.length === 0) continue;\n \n // Check if it's an array of canonical tuples\n if (Array.isArray(raw[0]) && raw[0].length === 2 && typeof raw[0][0] === \"string\" && toCanonicalOp(raw[0][0]) === raw[0][0]) {\n result[field] = raw as [WhereFilterOp, unknown][];\n continue;\n }\n\n if (raw.length === 1) {\n result[field] = typeof raw[0] === \"string\" ? deserializeSingle(raw[0]) : [\"==\", raw[0]];\n } else {\n // If the elements are strings, they might be PostgREST dot-strings (repeated params)\n if (typeof raw[0] === \"string\" && raw[0].includes(\".\")) {\n result[field] = raw.map(r => typeof r === \"string\" ? deserializeSingle(r) : ([\"==\", r] as [WhereFilterOp, unknown])) as [WhereFilterOp, unknown][];\n } else {\n // Otherwise assume it's a list of values for an implicit \"in\" or just multiple conditions\n result[field] = [\"in\", raw];\n }\n }\n } else if (typeof raw === \"string\") {\n result[field] = deserializeSingle(raw);\n } else {\n result[field] = [\"==\", raw];\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Logical conditions: serialize / deserialize\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a `LogicalCondition` or `FilterCondition` to its wire-format string.\n *\n * @example\n * serializeLogicalCondition({ column: \"status\", operator: \"==\", value: \"active\" })\n * // → \"status.eq.active\"\n *\n * serializeLogicalCondition({ type: \"or\", conditions: [...] })\n * // → \"or(status.eq.active,status.eq.pending)\"\n */\nexport function serializeLogicalCondition(\n cond: LogicalCondition | FilterCondition\n): string {\n if (\"type\" in cond) {\n // LogicalCondition (and/or)\n const inner = (cond.conditions ?? [])\n .map(serializeLogicalCondition)\n .join(\",\");\n return `${cond.type}(${inner})`;\n }\n\n // FilterCondition\n const restOp = CANONICAL_OP_LOOKUP[cond.operator] ?? \"eq\";\n if (Array.isArray(cond.value)) {\n const items = cond.value.map(v => escapeListItem(stringifyValue(v))).join(\",\");\n return `${cond.column}.${restOp}.(${items})`;\n }\n return `${cond.column}.${restOp}.${stringifyValue(cond.value)}`;\n}\n\n/**\n * Parse a logical condition wire-format string back into a\n * `LogicalCondition` or `FilterCondition`.\n *\n * @example\n * deserializeLogicalCondition(\"status.eq.active\")\n * // → { column: \"status\", operator: \"==\", value: \"active\" }\n *\n * deserializeLogicalCondition(\"or(status.eq.active,age.gte.18)\")\n * // → { type: \"or\", conditions: [...] }\n */\nexport function deserializeLogicalCondition(\n str: string\n): LogicalCondition | FilterCondition {\n // Check for logical group: \"and(...)\" or \"or(...)\"\n const logicalMatch = str.match(/^(and|or)\\((.+)\\)$/);\n if (logicalMatch) {\n const type = logicalMatch[1] as \"and\" | \"or\";\n const innerStr = logicalMatch[2];\n\n // Split on commas that are not inside parentheses\n const conditions: (LogicalCondition | FilterCondition)[] = [];\n let depth = 0;\n let start = 0;\n for (let i = 0; i < innerStr.length; i++) {\n if (innerStr[i] === \"(\") depth++;\n else if (innerStr[i] === \")\") depth--;\n else if (innerStr[i] === \",\" && depth === 0) {\n conditions.push(deserializeLogicalCondition(innerStr.slice(start, i)));\n start = i + 1;\n }\n }\n conditions.push(deserializeLogicalCondition(innerStr.slice(start)));\n\n return { type, conditions };\n }\n\n // FilterCondition: \"column.op.value\"\n const firstDot = str.indexOf(\".\");\n if (firstDot === -1) {\n return { column: str, operator: \"==\", value: true };\n }\n\n const column = str.substring(0, firstDot);\n const rest = str.substring(firstDot + 1);\n\n const secondDot = rest.indexOf(\".\");\n if (secondDot === -1) {\n // \"column.value\" — treat as equality (value kept as string)\n return { column, operator: \"==\", value: rest };\n }\n\n const opStr = rest.substring(0, secondDot);\n const valueStr = rest.substring(secondDot + 1);\n const operator = toCanonicalOp(opStr) ?? \"==\";\n\n // Parse list values with escape-aware splitting\n if (valueStr.startsWith(\"(\") && valueStr.endsWith(\")\")) {\n const items = splitListItems(valueStr.slice(1, -1));\n return { column, operator, value: items };\n }\n\n return { column, operator, value: valueStr };\n}\n","import {\n CollectionAccessor,\n DataDriver,\n Entity,\n EntityValues,\n FindParams,\n FindResponse,\n FindResult,\n LogicalCondition,\n RebaseData,\n RebaseSdkData,\n SDKCollectionClient,\n SDKQueryBuilderInterface,\n WhereFilterOp,\n WhereValue\n} from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport { QueryBuilder } from \"./query_builder\";\nimport { deserializeFilter } from \"./filter-dialect\";\n\n/**\n * Convert a flat REST record (e.g. from RestFetchService) to Entity<M> format.\n * Mirrors the client SDK's rowToEntity conversion.\n */\nfunction rowToEntity<M extends Record<string, unknown>>(row: Record<string, unknown>, slug: string): Entity<M> {\n return {\n id: row.id as string | number,\n path: slug,\n values: row as EntityValues<M>\n };\n}\n\nfunction createDriverAccessor<M extends Record<string, unknown> = Record<string, unknown>>(\n driver: DataDriver,\n slug: string\n): CollectionAccessor<M> {\n const accessor: CollectionAccessor<M> = {\n async find(params?: FindParams): Promise<FindResponse<M>> {\n // Ensure filters are in canonical [op, value] format even if passed as PostgREST strings\n const filter = params?.where ? deserializeFilter(params.where as Record<string, unknown>) : undefined;\n const limit = params?.limit ?? 20;\n const offset = params?.offset ?? 0;\n\n // Use the RestFetchService for include-aware queries when available\n const fetchService = driver.restFetchService;\n const rows = (fetchService && params?.include && params.include.length > 0)\n ? await fetchService.fetchCollectionForRest(\n slug,\n {\n filter,\n limit: params?.limit,\n offset: params?.offset,\n orderBy: params?.orderBy?.[0],\n order: params?.orderBy?.[1],\n searchString: params?.searchString\n },\n params.include\n )\n : await driver.fetchCollection<M>({\n path: slug,\n limit: params?.limit,\n offset: params?.offset,\n filter,\n orderBy: params?.orderBy?.[0],\n order: params?.orderBy?.[1],\n searchString: params?.searchString\n });\n\n // Compute real total when count is available\n let total = rows.length + offset;\n let hasMore = rows.length >= limit;\n if (driver.count) {\n total = await driver.count({ path: slug, filter });\n hasMore = offset + rows.length < total;\n }\n\n return {\n data: rows.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug)),\n meta: { total, limit, offset, hasMore }\n };\n },\n\n async findById(id: string | number): Promise<Entity<M> | undefined> {\n const row = await driver.fetchOne<M>({ path: slug, id: id });\n return row ? rowToEntity<M>(row, slug) : undefined;\n },\n\n async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {\n const row = await driver.save<M>({\n path: slug,\n values: data,\n id: id,\n status: \"new\"\n });\n return rowToEntity<M>(row, slug);\n },\n\n async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {\n const row = await driver.save<M>({\n path: slug,\n values: data,\n id: id,\n status: \"existing\"\n });\n return rowToEntity<M>(row, slug);\n },\n\n async delete(id: string | number): Promise<void> {\n return driver.delete({\n row: { id,\npath: slug,\nvalues: {} as Record<string, unknown> }\n });\n },\n\n count: driver.count\n ? async (params?: FindParams): Promise<number> => {\n const filter = params?.where ? deserializeFilter(params.where as Record<string, unknown>) : undefined;\n return driver.count!({\n path: slug,\n filter\n });\n }\n : undefined,\n\n listen: driver.listenCollection\n ? (params: FindParams | undefined, onUpdate: (response: FindResponse<M>) => void, onError?: (error: Error) => void) => {\n const limit = params?.limit ?? 20;\n const offset = params?.offset ?? 0;\n return driver.listenCollection!<M>({\n path: slug,\n limit: params?.limit,\n offset: params?.offset,\n filter: params?.where,\n orderBy: params?.orderBy?.[0],\n order: params?.orderBy?.[1],\n searchString: params?.searchString,\n onUpdate: (entities) => {\n onUpdate({\n data: entities.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug)),\n meta: {\n total: entities.length,\n limit,\n offset,\n hasMore: entities.length >= limit\n }\n });\n },\n onError\n });\n } : undefined,\n\n listenById: driver.listenOne\n ? (id: string | number, onUpdate: (entity: Entity<M> | undefined) => void, onError?: (error: Error) => void) => {\n return driver.listenOne!<M>({\n path: slug,\n id: id,\n onUpdate: (entity) => onUpdate(entity ? rowToEntity<M>(entity, slug) : undefined),\n onError\n });\n } : undefined,\n\n // Fluent Query Builder\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new QueryBuilder<M>(accessor);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValue<M[keyof M & string]>);\n },\n orderBy(column: keyof M & string, ascending?: \"asc\" | \"desc\") {\n return new QueryBuilder<M>(accessor).orderBy(column, ascending);\n },\n limit(count: number) {\n return new QueryBuilder<M>(accessor).limit(count);\n },\n offset(count: number) {\n return new QueryBuilder<M>(accessor).offset(count);\n },\n search(searchString: string) {\n return new QueryBuilder<M>(accessor).search(searchString);\n },\n include(...relations: string[]) {\n return new QueryBuilder<M>(accessor).include(...relations);\n }\n };\n\n return accessor;\n}\n\n/**\n * Build a `RebaseData` object from a `DataDriver` using JavaScript Proxy.\n *\n * This is the key bridge: any property access like `data.products` returns\n * a `CollectionAccessor` backed by the underlying DataDriver, without\n * needing per-collection code generation.\n *\n * @example\n * const data = buildRebaseData(driver);\n * await data.products.create({ name: \"Camera\", price: 299 });\n * const { data: items } = await data.products.find({ where: { status: [\"==\", \"published\"] } });\n */\nexport function buildRebaseData(driver: DataDriver): RebaseData {\n const cache = new Map<string, CollectionAccessor>();\n\n function getAccessor(slug: string): CollectionAccessor {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = createDriverAccessor(driver, slug);\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = {\n collection: getAccessor\n } as RebaseData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n // Ignore Symbol properties (e.g. Symbol.toPrimitive, Symbol.iterator)\n if (typeof prop === \"symbol\") return undefined;\n // Ignore internal JS properties\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n\n // Convert camelCase property names to snake_case slugs\n const slug = toSnakeCase(prop);\n return getAccessor(slug);\n }\n });\n}\n\n// =============================================================================\n// SDK data — flat rows (symmetric with the frontend SDK client)\n// =============================================================================\n\n/**\n * Unwrap a Entity into a flat row. `rowToEntity` stores the whole flat row\n * (id included) under `.values`, so this is just that payload.\n */\nfunction entityToRow<M extends Record<string, unknown>>(entity: Entity<M>): M {\n return entity.values as unknown as M;\n}\n\n/**\n * Fluent query builder for the flat SDK data layer. Mirrors {@link QueryBuilder}\n * but resolves to `FindResult<M>` (flat rows) instead of Entity-wrapped\n * `FindResponse<M>`.\n */\nclass SdkQueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> implements SDKQueryBuilderInterface<M> {\n private params: FindParams = { where: {} };\n\n constructor(private client: SDKCollectionClient<M>) {}\n\n where<K extends keyof M & string>(column: K, operator: WhereFilterOp, value: WhereValue<M[K]>): this;\n where(logicalCondition: LogicalCondition): this;\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown): this {\n if (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n this.params.logical = columnOrCondition as LogicalCondition;\n return this;\n }\n if (!this.params.where) this.params.where = {};\n const column = columnOrCondition as string;\n const condition: [WhereFilterOp, unknown] = [operator!, value];\n const existing = this.params.where[column];\n if (existing === undefined) {\n this.params.where[column] = condition;\n } else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) {\n (this.params.where[column] as [WhereFilterOp, unknown][]).push(condition);\n } else {\n let firstCondition: [WhereFilterOp, unknown];\n if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") {\n firstCondition = existing as [WhereFilterOp, unknown];\n } else {\n firstCondition = [\"==\", existing];\n }\n this.params.where[column] = [firstCondition, condition];\n }\n return this;\n }\n\n orderBy(column: keyof M & string, direction: \"asc\" | \"desc\" = \"asc\"): this {\n this.params.orderBy = [column, direction];\n return this;\n }\n\n limit(count: number): this { this.params.limit = count; return this; }\n offset(count: number): this { this.params.offset = count; return this; }\n search(searchString: string): this { this.params.searchString = searchString; return this; }\n include(...relations: string[]): this { this.params.include = relations; return this; }\n\n async find(): Promise<FindResult<M>> {\n return this.client.find(this.params);\n }\n\n async count(): Promise<number> {\n return this.client.count ? this.client.count(this.params) : 0;\n }\n\n listen(onUpdate: (data: FindResult<M>) => void, onError?: (error: Error) => void): () => void {\n if (!this.client.listen) {\n throw new Error(\"Listen is only available when the driver supports realtime.\");\n }\n return this.client.listen(this.params, onUpdate, onError);\n }\n}\n\n/**\n * Wrap a Entity-shaped {@link CollectionAccessor} into a flat\n * {@link SDKCollectionClient}. Every returned record is unwrapped to a flat row\n * so the backend SDK is byte-for-byte the same shape as the frontend client.\n */\nfunction toSdkCollectionClient<M extends Record<string, unknown>>(\n snap: CollectionAccessor<M>\n): SDKCollectionClient<M> {\n const client: SDKCollectionClient<M> = {\n async find(params?: FindParams): Promise<FindResult<M>> {\n const res = await snap.find(params);\n return { data: res.data.map(entityToRow), meta: res.meta };\n },\n async findById(id: string | number): Promise<M | undefined> {\n const s = await snap.findById(id);\n return s ? entityToRow(s) : undefined;\n },\n async create(data: Partial<M>, id?: string | number): Promise<M> {\n return entityToRow(await snap.create(data as Partial<EntityValues<M>>, id));\n },\n async update(id: string | number, data: Partial<M>): Promise<M> {\n return entityToRow(await snap.update(id, data as Partial<EntityValues<M>>));\n },\n delete(id: string | number): Promise<void> {\n return snap.delete(id);\n },\n count: snap.count ? (params?: FindParams) => snap.count!(params) : undefined,\n listen: snap.listen\n ? (params: FindParams | undefined, onUpdate: (r: FindResult<M>) => void, onError?: (e: Error) => void) =>\n snap.listen!(params, (res) => onUpdate({ data: res.data.map(entityToRow), meta: res.meta }), onError)\n : undefined,\n listenById: snap.listenById\n ? (id: string | number, onUpdate: (r: M | undefined) => void, onError?: (e: Error) => void) =>\n snap.listenById!(id, (s) => onUpdate(s ? entityToRow(s) : undefined), onError)\n : undefined,\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new SdkQueryBuilder<M>(client);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValue<M[keyof M & string]>);\n },\n orderBy: (column: keyof M & string, direction?: \"asc\" | \"desc\") => new SdkQueryBuilder<M>(client).orderBy(column, direction),\n limit: (count: number) => new SdkQueryBuilder<M>(client).limit(count),\n offset: (count: number) => new SdkQueryBuilder<M>(client).offset(count),\n search: (searchString: string) => new SdkQueryBuilder<M>(client).search(searchString),\n include: (...relations: string[]) => new SdkQueryBuilder<M>(client).include(...relations)\n };\n return client;\n}\n\n/**\n * Wrap a flat {@link SDKCollectionClient} into a Entity-shaped\n * {@link CollectionAccessor}. Every returned row is re-wrapped into the\n * `{ id, path, values }` view-model the admin CMS renders.\n */\nfunction toEntityAccessor<M extends Record<string, unknown>>(\n sdk: SDKCollectionClient<M>,\n slug: string\n): CollectionAccessor<M> {\n const accessor: CollectionAccessor<M> = {\n async find(params?: FindParams): Promise<FindResponse<M>> {\n const res = await sdk.find(params);\n return { data: res.data.map((row) => rowToEntity<M>(row, slug)), meta: res.meta };\n },\n async findById(id: string | number): Promise<Entity<M> | undefined> {\n const row = await sdk.findById(id);\n return row ? rowToEntity<M>(row, slug) : undefined;\n },\n async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {\n return rowToEntity<M>(await sdk.create(data as Partial<M>, id), slug);\n },\n async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {\n const row = await sdk.update(id, data as Partial<M>);\n if (!row) throw new Error(`Update returned no data for id ${id}`);\n return rowToEntity<M>(row, slug);\n },\n delete(id: string | number): Promise<void> {\n return sdk.delete(id);\n },\n count: sdk.count ? (params?: FindParams) => sdk.count!(params) : undefined,\n listen: sdk.listen\n ? (params: FindParams | undefined, onUpdate: (r: FindResponse<M>) => void, onError?: (e: Error) => void) =>\n sdk.listen!(params, (res) => onUpdate({ data: res.data.map((row) => rowToEntity<M>(row, slug)), meta: res.meta }), onError)\n : undefined,\n listenById: sdk.listenById\n ? (id: string | number, onUpdate: (s: Entity<M> | undefined) => void, onError?: (e: Error) => void) =>\n sdk.listenById!(id, (row) => onUpdate(row ? rowToEntity<M>(row, slug) : undefined), onError)\n : undefined,\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new QueryBuilder<M>(accessor);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValue<M[keyof M & string]>);\n },\n orderBy: (column: keyof M & string, direction?: \"asc\" | \"desc\") => new QueryBuilder<M>(accessor).orderBy(column, direction),\n limit: (count: number) => new QueryBuilder<M>(accessor).limit(count),\n offset: (count: number) => new QueryBuilder<M>(accessor).offset(count),\n search: (searchString: string) => new QueryBuilder<M>(accessor).search(searchString),\n include: (...relations: string[]) => new QueryBuilder<M>(accessor).include(...relations)\n };\n return accessor;\n}\n\n/**\n * Wrap a flat {@link RebaseSdkData} into a Entity-shaped {@link RebaseData}.\n *\n * This is the **CMS boundary**: the SDK client (`client.data`) returns flat\n * rows, but the admin renders the `Entity` view-model (`entity.values.*`).\n * `core/Rebase.tsx` wraps `client.data` through this before handing it to the\n * CMS `RebaseDataContext` — without it the admin renders rows with only their\n * `id`.\n */\nexport function wrapAsEntityData(sdkData: RebaseSdkData): RebaseData {\n const cache = new Map<string, CollectionAccessor>();\n\n function getAccessor(slug: string): CollectionAccessor {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = toEntityAccessor(sdkData.collection(slug), slug);\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = { collection: getAccessor } as RebaseData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n if (typeof prop === \"symbol\") return undefined;\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n return getAccessor(toSnakeCase(prop));\n }\n });\n}\n\n/**\n * Wrap a Entity-shaped {@link RebaseData} into a flat {@link RebaseSdkData}.\n *\n * Every collection accessor is adapted to return flat rows. Use this to derive\n * the flat SDK data layer (`context.data`) from an existing Entity data layer\n * — e.g. the admin routes its Entity data via `useData()` and exposes the\n * same routing as flat `context.data` for callbacks by wrapping it here.\n */\nexport function wrapAsSdkData(entityData: RebaseData): RebaseSdkData {\n const cache = new Map<string, SDKCollectionClient>();\n\n function getAccessor(slug: string): SDKCollectionClient {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = toSdkCollectionClient(entityData.collection(slug));\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = { collection: getAccessor } as RebaseSdkData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n if (typeof prop === \"symbol\") return undefined;\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n return getAccessor(toSnakeCase(prop));\n }\n });\n}\n\n/**\n * Build a flat {@link RebaseSdkData} from a `DataDriver`.\n *\n * This is the developer-facing SDK data layer used by backend framework\n * callbacks & scripts (`context.data` / `rebase.data`). It returns flat rows —\n * identical in shape to the frontend SDK client — so the API is symmetric\n * across front and back. The admin CMS uses {@link buildRebaseData} (Entity).\n */\nexport function buildSdkData(driver: DataDriver): RebaseSdkData {\n return wrapAsSdkData(buildRebaseData(driver));\n}\n","import { RebaseData, RebaseSdkData } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * The two data-layer shapes that can be routed: the Entity-shaped admin\n * {@link RebaseData} or the flat SDK {@link RebaseSdkData}. Both expose a\n * `.collection(slug)` accessor, which is all the router needs.\n */\nexport type RoutableData = RebaseData | RebaseSdkData;\n\n/**\n * Parameters for {@link buildRoutedRebaseData}.\n */\nexport interface RoutedRebaseDataParams<T extends RoutableData = RebaseData> {\n /**\n * The default data source. Handles every collection that does not\n * resolve to an entry in `sources` (i.e. server-transport collections,\n * which ride the Rebase client).\n */\n defaultData: T;\n\n /**\n * Per-data-source instances for direct and custom transports, keyed by\n * data-source key (e.g. `\"analytics\"`). Server-mediated sources are not\n * listed here — they fall through to `defaultData`.\n */\n sources: Record<string, T>;\n\n /**\n * Resolve the data-source key for a given collection slug or path.\n * Typically backed by the collection registry + `resolveDataSource`\n * (`resolveDataSource(registry.getCollection(path), defs).key`).\n *\n * Return `undefined` (or a key absent from `sources`) to route to the\n * default data source.\n */\n resolveKey: (slugOrPath: string) => string | undefined;\n}\n\n/**\n * Build a {@link RebaseData} that routes each collection to the right\n * backend based on its resolved data source.\n *\n * `.collection(path)` (and dynamic `data.products`-style access) resolves the\n * collection's data-source key via `resolveKey` and delegates to the matching\n * entry in `sources`, falling back to `defaultData` when there is no match.\n * Because routing keys off the *path being accessed*, a reference widget\n * inside a Firestore form that points at a Postgres collection is still\n * served by Postgres — routing follows the target, not the ancestor.\n *\n * When `sources` is empty this returns `defaultData` untouched, so the\n * single-driver setup keeps identical behaviour and identity (important for\n * effect dependencies that key off the data instance).\n *\n * @example\n * const data = buildRoutedRebaseData({\n * defaultData: client.data,\n * sources: { analytics: buildRebaseData(firestoreDriver) },\n * resolveKey: (path) => resolveDataSource(registry.getCollection(path), defs).key\n * });\n * await data.products.find(); // → default (server / Postgres)\n * await data.events.find(); // → Firestore, if `events.dataSource === \"analytics\"`\n */\nexport function buildRoutedRebaseData<T extends RoutableData = RebaseData>({\n defaultData,\n sources,\n resolveKey\n}: RoutedRebaseDataParams<T>): T {\n\n // Fast path: nothing to route → return the default untouched (preserves\n // referential identity for effect dependencies).\n if (!sources || Object.keys(sources).length === 0) {\n return defaultData;\n }\n\n function resolve(slugOrPath: string): T {\n const key = resolveKey(slugOrPath);\n if (key && sources[key]) return sources[key];\n return defaultData;\n }\n\n function getAccessor(slugOrPath: string) {\n return (resolve(slugOrPath) as RoutableData).collection(slugOrPath);\n }\n\n const target = {\n collection: getAccessor\n } as unknown as T;\n\n return new Proxy(target as object, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n // Ignore Symbol properties (e.g. Symbol.toPrimitive, Symbol.iterator)\n if (typeof prop === \"symbol\") return undefined;\n // Ignore internal JS properties\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n\n // Convert camelCase property names to snake_case slugs, mirroring\n // buildRebaseData so dynamic access routes consistently.\n return getAccessor(toSnakeCase(prop));\n }\n }) as T;\n}\n","import type { OrderByTuple } from \"@rebasepro/types\";\n\n/**\n * Sort-order wire codec.\n *\n * This is the ONLY module that knows about the colon-delimited wire format\n * (`\"field:direction\"`) used in HTTP query parameters.\n * Everything else speaks {@link OrderByTuple} exclusively.\n *\n * Mirrors the filter architecture in `filter-dialect.ts`.\n *\n * @module\n */\n\n/**\n * Serialize an {@link OrderByTuple} to the wire format `\"field:direction\"`.\n *\n * **Runtime tolerance:** if the input is already a well-formed wire string\n * (from an untyped JS caller), it is returned unchanged.\n * This is undocumented tolerance, not public API — don't rely on it.\n *\n * @param orderBy - A canonical `[field, direction]` tuple, or at runtime\n * possibly a pre-serialized string (undocumented tolerance).\n * @returns The wire-format string, or `undefined` if the input is falsy.\n *\n * @remarks\n * Field names containing `:` are representable in the tuple form but\n * **not** on the wire — this is an inherent limitation of the colon-delimited\n * encoding and is not resolved here.\n */\nexport function serializeOrderBy(orderBy?: OrderByTuple | string): string | undefined {\n if (!orderBy) return undefined;\n // Runtime tolerance: pass through a pre-serialized wire string unchanged.\n if (typeof orderBy === \"string\") return orderBy;\n return `${orderBy[0]}:${orderBy[1]}`;\n}\n\n/**\n * Deserialize a wire-format `\"field:direction\"` string into an {@link OrderByTuple}.\n *\n * Lenient parsing (matches existing server behaviour):\n * - Bare field name (no colon): `\"name\"` → `[\"name\", \"asc\"]`\n * - Unknown direction: `\"name:foo\"` → `[\"name\", \"asc\"]`\n * - Empty / falsy input: → `undefined`\n *\n * @param raw - The wire-format string from an HTTP query parameter.\n * @returns The canonical tuple, or `undefined` if the input is empty/falsy.\n */\nexport function deserializeOrderBy(raw?: string): OrderByTuple | undefined {\n if (!raw) return undefined;\n const idx = raw.indexOf(\":\");\n if (idx === -1) return [raw, \"asc\"];\n const field = raw.slice(0, idx);\n const dir = raw.slice(idx + 1);\n return [field, dir === \"desc\" ? \"desc\" : \"asc\"];\n}\n","import { CollectionRegistry } from \"@rebasepro/common\";\nimport { CollectionRegistryInterface } from \"../db/interfaces\";\nimport { CollectionConfig } from \"@rebasepro/types\";\n\n/**\n * Backend-agnostic collection registry.\n * Satisfies CollectionRegistryInterface through inheritance from CollectionRegistry.\n */\nexport class BackendCollectionRegistry extends CollectionRegistry implements CollectionRegistryInterface {\n\n /**\n * Get the available relation keys for a given collection path.\n * Maps from the collection's relation property names to the relation names.\n */\n getRelationKeysForCollection(collectionPath: string): string[] {\n const collection = this.getCollectionByPath(collectionPath) as (CollectionConfig & { relations?: { relationName?: string, localKey?: string }[] }) | undefined;\n if (!collection?.relations) return [];\n return collection.relations.map(r => (r.relationName || r.localKey || \"\") as string).filter(Boolean);\n }\n}\n","import { CollectionConfig } from \"@rebasepro/types\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Asynchronously load collection files from a directory for backend initialization\n */\nexport async function loadCollectionsFromDirectory(directory: string): Promise<CollectionConfig[]> {\n const collections: CollectionConfig[] = [];\n try {\n if (!fs.existsSync(directory)) {\n logger.warn(`[loadCollectionsFromDirectory] Collections directory not found: ${directory}`);\n return collections;\n }\n\n const files = fs.readdirSync(directory);\n for (const file of files) {\n // Only load .ts and .js files, ignore test files and declaration files\n if ((file.endsWith(\".ts\") || file.endsWith(\".js\")) &&\n !file.includes(\".test.\") &&\n !file.endsWith(\".d.ts\") &&\n file !== \"index.ts\" && file !== \"index.js\") {\n\n const filePath = path.join(directory, file);\n try {\n const fileUrl = pathToFileURL(filePath).href;\n\n // Use standard import() so that tsx/loader hooks can\n // resolve .ts files and workspace bare-specifiers.\n const module = await import(fileUrl);\n\n // Expect the collection to be the default export\n if (module && module.default) {\n collections.push(module.default);\n } else {\n logger.warn(`[loadCollectionsFromDirectory] File ${file} does not have a default export. Skipping.`);\n }\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n logger.error(`[loadCollectionsFromDirectory] Failed to load collection from ${file}: ${message}`);\n }\n }\n }\n } catch (err) {\n logger.error(`[loadCollectionsFromDirectory] Error reading collections directory: ${err}`);\n }\n return collections;\n}\n","/**\n * Driver Registry\n *\n * Manages multiple driver delegates for Rebase backend.\n * Allows different databases for different collections.\n *\n * Usage:\n * - Single DB: Pass a single DataDriver → maps to \"(default)\"\n * - Multiple DBs: Pass a map of { dbId: DataDriver }\n * - Collections use `databaseId` property to specify which driver to use\n * - Collections without `databaseId` fallback to \"(default)\"\n */\n\nimport { DataDriver } from \"@rebasepro/types\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The default driver identifier used when:\n * - A single driver is provided (not a map)\n * - A collection doesn't specify a databaseId\n */\nexport const DEFAULT_DRIVER_ID = \"(default)\";\n\n/**\n * Registry for managing multiple driver delegates\n */\nexport interface DriverRegistry {\n /**\n * Register a driver delegate with an ID\n * @param id - Unique identifier for this driver (e.g., \"analytics\", \"users\")\n * @param delegate - The DataDriver instance\n */\n register(id: string, delegate: DataDriver): void;\n\n /**\n * Get the default driver delegate (id = \"(default)\")\n * @throws Error if no default driver is registered\n */\n getDefault(): DataDriver;\n\n /**\n * Get a driver delegate by ID\n * @param id - Driver identifier, or undefined/null for default\n * @returns The DataDriver, or undefined if not found\n */\n get(id: string | undefined | null): DataDriver | undefined;\n\n /**\n * Get a driver delegate by ID, with fallback to default\n * @param id - Driver identifier, or undefined/null for default\n * @returns The DataDriver (falls back to default if id not found)\n * @throws Error if neither the specified nor default driver exists\n */\n getOrDefault(id: string | undefined | null): DataDriver;\n\n /**\n * Check if a driver with the given ID exists\n */\n has(id: string): boolean;\n\n /**\n * List all registered driver IDs\n */\n list(): string[];\n\n /**\n * Get the number of registered drivers\n */\n size(): number;\n}\n\n/**\n * Default implementation of DriverRegistry\n */\nexport class DefaultDriverRegistry implements DriverRegistry {\n private delegates = new Map<string, DataDriver>();\n\n /**\n * Create a DriverRegistry from either a single delegate or a map\n * @param input - Single DataDriver (maps to \"(default)\") or Record<string, DataDriver>\n */\n static create(\n input: DataDriver | Record<string, DataDriver>\n ): DefaultDriverRegistry {\n const registry = new DefaultDriverRegistry();\n\n if (isDataDriverDelegate(input)) {\n // Single delegate → register as \"(default)\"\n registry.register(DEFAULT_DRIVER_ID, input);\n } else {\n // Map of delegates → register each\n for (const [id, delegate] of Object.entries(input)) {\n registry.register(id, delegate);\n }\n // Ensure there's a default if not explicitly provided\n if (!registry.has(DEFAULT_DRIVER_ID) && registry.size() > 0) {\n // If no explicit \"(default)\", use the first one as default\n const firstId = Object.keys(input)[0];\n logger.warn(\n `[DriverRegistry] No \"${DEFAULT_DRIVER_ID}\" driver provided. ` +\n `Using \"${firstId}\" as the default.`\n );\n registry.register(DEFAULT_DRIVER_ID, input[firstId]);\n }\n }\n\n return registry;\n }\n\n register(id: string, delegate: DataDriver): void {\n if (this.delegates.has(id)) {\n logger.warn(`[DriverRegistry] Overwriting driver with id \"${id}\"`);\n }\n this.delegates.set(id, delegate);\n }\n\n getDefault(): DataDriver {\n const delegate = this.delegates.get(DEFAULT_DRIVER_ID);\n if (!delegate) {\n throw new Error(\n \"[DriverRegistry] No default driver registered. \" +\n `Register one with id \"${DEFAULT_DRIVER_ID}\" or pass a single DataDriver.`\n );\n }\n return delegate;\n }\n\n get(id: string | undefined | null): DataDriver | undefined {\n if (id === undefined || id === null) {\n return this.delegates.get(DEFAULT_DRIVER_ID);\n }\n return this.delegates.get(id);\n }\n\n getOrDefault(id: string | undefined | null): DataDriver {\n // If no ID specified, return default\n if (id === undefined || id === null) {\n return this.getDefault();\n }\n\n // Try to get by ID\n const delegate = this.delegates.get(id);\n if (delegate) {\n return delegate;\n }\n\n // Fallback to default with warning\n logger.warn(\n `[DriverRegistry] Driver \"${id}\" not found, falling back to \"${DEFAULT_DRIVER_ID}\"`\n );\n return this.getDefault();\n }\n\n has(id: string): boolean {\n return this.delegates.has(id);\n }\n\n list(): string[] {\n return Array.from(this.delegates.keys());\n }\n\n size(): number {\n return this.delegates.size;\n }\n}\n\n/**\n * Type guard to check if an object is a DataDriver\n */\nfunction isDataDriverDelegate(obj: unknown): obj is DataDriver {\n if (typeof obj !== \"object\" || obj === null) {\n return false;\n }\n const delegate = obj as DataDriver;\n // Check for required DataDriver properties\n return (\n typeof delegate.key === \"string\" &&\n typeof delegate.fetchCollection === \"function\" &&\n typeof delegate.fetchOne === \"function\" &&\n typeof delegate.save === \"function\" &&\n typeof delegate.delete === \"function\"\n );\n}\n","import { RealtimeProvider } from \"@rebasepro/types\";\n\n/**\n * A realtime client message as forwarded by the WebSocket server.\n */\ninterface ClientMessage {\n type: string;\n payload?: Record<string, unknown>;\n subscriptionId?: string;\n}\n\n/**\n * The concrete realtime service surface the WebSocket server drives — the\n * typed {@link RealtimeProvider} plus the client-connection methods that\n * every engine's realtime service implements.\n */\nexport interface WsRealtimeService extends RealtimeProvider {\n addClient(clientId: string, ws: unknown): void;\n handleClientMessage(clientId: string, message: ClientMessage, authContext?: unknown): Promise<void> | void;\n}\n\n/** Channel/presence/broadcast messages are engine-agnostic pub/sub. */\nconst CHANNEL_MESSAGE_TYPES = new Set([\n \"join_channel\", \"leave_channel\", \"broadcast\",\n \"presence_track\", \"presence_untrack\", \"presence_state\"\n]);\n\nexport interface RoutedRealtimeOptions {\n /** Per-engine realtime providers, keyed by data-source key. */\n providers: Record<string, RealtimeProvider>;\n /** Key of the default provider (handles channels/presence/broadcast). */\n defaultKey: string;\n /** Resolve a collection path to its data-source key. */\n resolveKey: (collectionPath: string) => string;\n}\n\n/**\n * Compose multiple per-engine {@link RealtimeProvider}s into one that routes\n * each subscription to the provider owning the subscribed collection — the\n * realtime counterpart of `buildRoutedRebaseData`.\n *\n * The WebSocket server stays single and engine-agnostic; this composite is\n * passed in its place. Routing rules:\n * - `subscribe_collection` / `subscribe_entity` → the provider for the\n * collection's data source (by `payload.path`).\n * - `unsubscribe` → forwarded to all providers (a no-op on non-owners).\n * - channel / presence / broadcast → the default provider (these are global\n * pub/sub, not bound to an engine).\n * - `addClient` and lifecycle (`onServerReady`/`destroy`/`stopListening`) →\n * all providers (each registers its own ws close handler for cleanup).\n */\nexport function createRoutedRealtimeService(opts: RoutedRealtimeOptions): WsRealtimeService {\n const { providers, defaultKey, resolveKey } = opts;\n\n const asWs = (p: RealtimeProvider): WsRealtimeService => p as unknown as WsRealtimeService;\n const all = (): WsRealtimeService[] => Object.values(providers).map(asWs);\n const fallback = (): WsRealtimeService => asWs(providers[defaultKey] ?? Object.values(providers)[0]);\n const forPath = (path?: string): WsRealtimeService => {\n if (!path) return fallback();\n const key = resolveKey(path);\n return asWs(providers[key] ?? providers[defaultKey] ?? Object.values(providers)[0]);\n };\n\n return {\n addClient(clientId, ws) {\n for (const p of all()) p.addClient?.(clientId, ws);\n },\n\n async handleClientMessage(clientId, message, authContext) {\n const { type } = message;\n if (type === \"subscribe_collection\" || type === \"subscribe_one\") {\n await forPath(message.payload?.path as string | undefined)\n .handleClientMessage(clientId, message, authContext);\n return;\n }\n if (type === \"unsubscribe\") {\n // The owning provider acts; others no-op on an unknown id.\n await Promise.all(all().map((p) => p.handleClientMessage(clientId, message, authContext)));\n return;\n }\n // Channels/presence/broadcast (and anything else) → default provider.\n await fallback().handleClientMessage(clientId, message, authContext);\n },\n\n subscribeToCollection(subscriptionId, config, callback) {\n forPath((config as { path?: string }).path).subscribeToCollection(subscriptionId, config, callback);\n },\n\n subscribeToOne(subscriptionId, config, callback) {\n forPath((config as { path?: string }).path).subscribeToOne(subscriptionId, config, callback);\n },\n\n unsubscribe(subscriptionId) {\n for (const p of all()) p.unsubscribe(subscriptionId);\n },\n\n async notifyUpdate(path: string, id: string, row: Record<string, unknown> | null, databaseId?: string) {\n await forPath(path).notifyUpdate(path, id, row, databaseId);\n },\n\n onServerReady(serverInfo) {\n for (const p of all()) p.onServerReady?.(serverInfo);\n },\n\n async destroy() {\n await Promise.all(all().map((p) => p.destroy?.()));\n },\n\n async stopListening() {\n await Promise.all(all().map((p) => p.stopListening?.()));\n }\n };\n}\n","import type { ErrorHandler } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport type { HonoEnv } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\n/** Tracks whether we've already shown the doctor hint (once per process). */\nlet _schemaDriftHinted = false;\n\n/** Shape of Postgres / network errors with diagnostic codes */\ninterface PgLikeError {\n code?: string;\n address?: string;\n port?: number;\n message?: string;\n table?: string;\n column?: string;\n schema?: string;\n}\n\n/**\n * Extract the missing table or column name from a PG error.\n * PG 42P01 messages look like: 'relation \"my_table\" does not exist'\n * PG 42703 messages look like: 'column \"my_col\" does not exist' or 'column my_table.my_col does not exist'\n */\nfunction extractMissingIdentifier(pgMessage?: string): string | null {\n if (!pgMessage) return null;\n // Match quoted identifier: relation \"xxx\" / column \"xxx\"\n const quoted = pgMessage.match(/(?:relation|column|table)\\s+\"([^\"]+)\"/i);\n if (quoted) return quoted[1];\n // Match unquoted: column table.col does not exist\n const unquoted = pgMessage.match(/(?:relation|column|table)\\s+([\\w.]+)\\s+does not exist/i);\n if (unquoted) return unquoted[1];\n return null;\n}\n\n/**\n * Standardized API error class.\n * Throw this from any route handler — the errorHandler middleware\n * will format it into `{ error: { message, code, details? } }`.\n */\nexport class ApiError extends Error {\n public readonly statusCode: number;\n public readonly code: string;\n public readonly details?: unknown;\n\n constructor(statusCode: number, code: string, message: string, details?: unknown) {\n super(message);\n this.name = \"ApiError\";\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n\n // ── Factory methods ──────────────────────────────────────────────\n\n static badRequest(message: string, code = \"BAD_REQUEST\", details?: unknown): ApiError {\n return new ApiError(400, code, message, details);\n }\n\n static unauthorized(message: string, code = \"UNAUTHORIZED\"): ApiError {\n return new ApiError(401, code, message);\n }\n\n static forbidden(message: string, code = \"FORBIDDEN\"): ApiError {\n return new ApiError(403, code, message);\n }\n\n static notFound(message: string, code = \"NOT_FOUND\"): ApiError {\n return new ApiError(404, code, message);\n }\n\n static conflict(message: string, code = \"CONFLICT\"): ApiError {\n return new ApiError(409, code, message);\n }\n\n static internal(message: string, code = \"INTERNAL_ERROR\"): ApiError {\n return new ApiError(500, code, message);\n }\n\n static serviceUnavailable(message: string, code = \"SERVICE_UNAVAILABLE\"): ApiError {\n return new ApiError(503, code, message);\n }\n}\n\n/**\n * Canonical error response shape:\n * `{ error: { message: string, code: string, details?: unknown } }`\n */\nexport interface ErrorResponse {\n error: {\n message: string;\n code: string;\n details?: unknown;\n /** Request correlation ID for tracing (echoes X-Request-ID). */\n requestId?: string;\n };\n}\n\n/**\n * General shape of errors that flow through the API error handler.\n * Extends Error with optional HTTP status, error code, and details.\n */\nexport interface RebaseApiError extends Error {\n statusCode?: number;\n code?: string;\n details?: unknown;\n}\n\n/**\n * Type guard for errors that carry optional API metadata (statusCode, code, details).\n * Returns true for any Error instance — the optional properties are then\n * checked via normal property access.\n */\nexport function isRebaseApiError(error: unknown): error is RebaseApiError {\n return error instanceof Error;\n}\n\n/**\n * Hono error-handling middleware (`app.onError`).\n * Converts any error into the canonical `{ error: { message, code } }` shape.\n */\nexport const errorHandler: ErrorHandler<HonoEnv> = (err, c) => {\n // Typecast custom error properties\n const error: RebaseApiError = err;\n const reqId = typeof c.get === \"function\" ? c.get(\"requestId\") : undefined;\n\n if (error instanceof ApiError || error.name === \"ApiError\") {\n // Operational errors — log at warn level\n logger.warn(\n `⚠️ [API] ${c.req.method} ${c.req.path} → ${error.statusCode} ${error.code}: ${error.message}` +\n (reqId ? ` [${reqId}]` : \"\")\n );\n return c.json({\n error: {\n message: error.message,\n code: error.code || \"INTERNAL_ERROR\",\n ...(error.details !== undefined && { details: error.details }),\n ...(reqId && { requestId: reqId })\n }\n } satisfies ErrorResponse, (error.statusCode || 500) as ContentfulStatusCode);\n }\n\n const statusCode = error.statusCode || codeToStatus(error.code) || 500;\n let code = error.code || \"INTERNAL_ERROR\";\n\n // Handle DB connection and specific system errors for better logging\n let logMessage = error.message;\n\n // Resolve the actual cause — Node's net module wraps dual-stack failures\n // in an AggregateError whose inner errors carry the real address/port.\n let resolvedCause: PgLikeError | undefined;\n if (error.cause && typeof error.cause === \"object\" && error.cause !== null && \"code\" in error.cause) {\n const cause = error.cause as PgLikeError & { errors?: PgLikeError[] };\n if (cause.code === \"ECONNREFUSED\" && !cause.address && Array.isArray(cause.errors)) {\n // AggregateError — pick the first inner error that has address info\n resolvedCause = cause.errors.find(e => e.address) || cause;\n } else {\n resolvedCause = cause;\n }\n }\n\n if (resolvedCause) {\n const cause = resolvedCause;\n if (cause.code === \"ENETUNREACH\") {\n logMessage = `Network unreachable. Cannot connect to database at ${cause.address}:${cause.port}.`;\n } else if (cause.code === \"ECONNREFUSED\") {\n logMessage = `Connection refused to database at ${cause.address}:${cause.port}. Is PostgreSQL running?`;\n } else if (cause.code === \"42703\" || cause.code === \"42P01\") {\n code = \"SCHEMA_DRIFT\";\n const issue = cause.code === \"42703\" ? \"column\" : \"table\";\n const identifier = cause.table || cause.column || extractMissingIdentifier(cause.message) || \"unknown\";\n logMessage = `Schema drift: ${issue} \"${identifier}\" does not exist in the database. Run \\`pnpm db:push\\` to sync your schema, or \\`pnpm db:migrate\\` to apply pending migrations.`;\n }\n } else if (\"code\" in error && error.code === \"ENETUNREACH\") {\n const netErr = error as PgLikeError;\n logMessage = `Network unreachable. Cannot connect to service at ${netErr.address}:${netErr.port}.`;\n } else if (\"code\" in error && (error.code === \"42703\" || error.code === \"42P01\")) {\n code = \"SCHEMA_DRIFT\";\n const issue = error.code === \"42703\" ? \"column\" : \"table\";\n const pgErr = error as PgLikeError;\n const identifier = pgErr.table || pgErr.column || extractMissingIdentifier(error.message) || \"unknown\";\n logMessage = `Schema drift: ${issue} \"${identifier}\" does not exist in the database. Run \\`pnpm db:push\\` to sync your schema, or \\`pnpm db:migrate\\` to apply pending migrations.`;\n }\n\n const causePg = (error.cause && typeof error.cause === \"object\") ? (error.cause as PgLikeError) : undefined;\n const pgErrorCode = causePg?.code || error.code;\n const isDbSchemaMismatch = code === \"SCHEMA_DRIFT\" || pgErrorCode === \"42703\" || pgErrorCode === \"42P01\";\n\n if (isDbSchemaMismatch) {\n // Database schema mismatch is logged as a warning instead of a fatal error\n logger.warn(\n `⚠️ [API] ${c.req.method} ${c.req.path} → ${statusCode} ${code}: ${logMessage}` +\n (reqId ? ` [${reqId}]` : \"\")\n );\n // In dev mode, show a one-time hint to run `rebase doctor`\n if (!_schemaDriftHinted && process.env.NODE_ENV !== \"production\") {\n _schemaDriftHinted = true;\n logger.warn([\n \"\",\n \"┌──────────────────────────────────────────────────────────────┐\",\n \"│ 💡 TIP: Run `rebase doctor` for full schema diagnostics │\",\n \"│ │\",\n \"│ Quick fixes: │\",\n \"│ pnpm db:push sync schema to database (dev) │\",\n \"│ pnpm db:migrate generate + apply migration (prod) │\",\n \"│ rebase doctor full 3-way drift report │\",\n \"└──────────────────────────────────────────────────────────────┘\",\n \"\"\n ].join(\"\\n\"));\n }\n } else {\n // Unexpected errors — log at error level\n logger.error(\n `❌ [API] ${c.req.method} ${c.req.path} → ${statusCode} ${code}: ${logMessage}` +\n (reqId ? ` [${reqId}]` : \"\")\n );\n }\n\n // Suppress the huge stack trace for known DB errors (it's noisy and leaks SQL)\n const suppressStack = isDbSchemaMismatch || (statusCode < 500 && code === \"BAD_REQUEST\");\n if (!suppressStack) {\n logger.error(String(error.stack || error));\n }\n\n // Sanitize the message for the client to prevent leaking sensitive details\n // like SQL queries or internal IP addresses.\n let clientMessage = \"An unexpected error occurred\";\n if (statusCode < 500 && error.message) {\n // If it's a 4xx error (e.g. from validation), it's generally safe to send the message\n clientMessage = error.message;\n } else if (error instanceof ApiError || error.name === \"ApiError\") {\n // We already handled ApiError above, but just in case\n clientMessage = error.message;\n } else if (code === \"SCHEMA_DRIFT\") {\n const pgErr = causePg || (error as PgLikeError);\n const issue = (pgErr.code === \"42703\" || pgErrorCode === \"42703\") ? \"column\" : \"table\";\n const identifier = pgErr.table || pgErr.column || extractMissingIdentifier(pgErr.message || error.message) || \"unknown\";\n clientMessage = `Schema drift: ${issue} \"${identifier}\" does not exist. Run \\`pnpm db:push\\` to sync your schema.`;\n } else if (code === \"INTERNAL_ERROR\") {\n clientMessage = \"Internal Server Error\";\n }\n\n return c.json({\n error: {\n message: clientMessage,\n code,\n ...(error.details !== undefined && { details: error.details }),\n ...(reqId && { requestId: reqId })\n }\n } satisfies ErrorResponse, statusCode as ContentfulStatusCode);\n};\n\n/**\n * Map known error codes to HTTP status codes.\n */\nfunction codeToStatus(code?: string): number | undefined {\n if (!code) return undefined;\n const map: Record<string, number> = {\n BAD_REQUEST: 400,\n INVALID_INPUT: 400,\n WEAK_PASSWORD: 400,\n UNAUTHORIZED: 401,\n INVALID_CREDENTIALS: 401,\n INVALID_TOKEN: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n CONFLICT: 409,\n EMAIL_EXISTS: 409,\n ROLE_EXISTS: 409,\n SCHEMA_DRIFT: 500,\n INTERNAL_ERROR: 500,\n NOT_CONFIGURED: 503,\n SERVICE_UNAVAILABLE: 503\n };\n return map[code];\n}\n\n\n","import type { LogicalCondition, VectorSearchParams } from \"@rebasepro/types\";\nimport { toCanonicalOp } from \"@rebasepro/types\";\nimport { deserializeOrderBy, deserializeFilter, deserializeLogicalCondition } from \"@rebasepro/common\";\nimport { QueryOptions } from \"../types\";\n\nexport const mapOperator = (op: string) => toCanonicalOp(op) ?? null;\n\nfunction getLastValue(val: unknown): unknown {\n if (Array.isArray(val)) {\n return val[val.length - 1];\n }\n return val;\n}\n\n/**\n * Parse an `or(...)` / `and(...)` logical group from its wire form.\n *\n * The wire carries the inner conditions wrapped in parens (e.g.\n * `(status.eq.active,age.gte.18)`); we re-attach the `or`/`and` prefix and\n * delegate to the canonical filter dialect (`@rebasepro/common`). Values are\n * preserved as strings — type coercion is the schema-aware driver's job, so\n * this path stays byte-for-byte consistent with the SDK/admin path (which\n * also parses via the shared dialect).\n */\nfunction parseLogicalGroup(type: \"or\" | \"and\", raw: unknown): LogicalCondition | undefined {\n let inner = String(raw).trim();\n if (inner.startsWith(\"(\") && inner.endsWith(\")\")) {\n inner = inner.slice(1, -1);\n }\n inner = inner.trim();\n if (!inner) return undefined;\n const parsed = deserializeLogicalCondition(`${type}(${inner})`);\n return \"type\" in parsed ? parsed : undefined;\n}\n\n/**\n * Parse query parameters into QueryOptions\n */\nexport function parseQueryOptions(query: Record<string, unknown>): QueryOptions {\n const options: QueryOptions = {};\n\n // Pagination\n const limitVal = getLastValue(query.limit);\n if (limitVal) options.limit = parseInt(String(limitVal));\n\n const offsetVal = getLastValue(query.offset);\n if (offsetVal) options.offset = parseInt(String(offsetVal));\n\n const pageVal = getLastValue(query.page);\n if (pageVal) {\n const page = parseInt(String(pageVal));\n const limit = options.limit || 20;\n options.offset = (page - 1) * limit;\n }\n\n // ── Logical conditions (or / and) ──────────────────────────────────\n const orVal = getLastValue(query.or);\n const andVal = getLastValue(query.and);\n if (orVal) {\n const logical = parseLogicalGroup(\"or\", orVal);\n if (logical) options.logical = logical;\n } else if (andVal) {\n const logical = parseLogicalGroup(\"and\", andVal);\n if (logical) options.logical = logical;\n }\n\n // ── PostgREST-style field filters: ?field=op.value ─────────────────\n // Delegate to the canonical filter dialect (the single source of truth\n // for the wire grammar: operator codes, list/escape handling, implicit\n // eq). Values stay strings; the schema-aware driver coerces them to\n // column types. This keeps the REST path byte-for-byte consistent with\n // the SDK/admin path, which parses through the same `deserializeFilter`.\n const reservedQueryKeys = [\"limit\", \"offset\", \"page\", \"orderBy\", \"include\", \"fields\", \"searchString\", \"vector_search\", \"vector\", \"vector_distance\", \"vector_threshold\", \"or\", \"and\"];\n const filterDict: Record<string, unknown> = {};\n for (const [key, rawValue] of Object.entries(query)) {\n if (reservedQueryKeys.includes(key)) continue;\n filterDict[key] = rawValue;\n }\n const where = deserializeFilter(filterDict);\n if (Object.keys(where).length > 0) {\n options.where = where;\n }\n\n // Sorting\n const orderByVal = getLastValue(query.orderBy);\n if (orderByVal) {\n try {\n options.orderBy = typeof orderByVal === \"string\"\n ? JSON.parse(orderByVal)\n : orderByVal;\n } catch {\n // Try simple format: \"field:direction\"\n if (typeof orderByVal === \"string\") {\n const parsed = deserializeOrderBy(orderByVal);\n if (parsed) {\n options.orderBy = [\n {\n field: parsed[0],\n direction: parsed[1]\n }\n ];\n }\n }\n }\n }\n\n // Relation includes\n const includeVal = getLastValue(query.include);\n if (includeVal) {\n const includeStr = String(includeVal).trim();\n if (includeStr === \"*\") {\n options.include = [\"*\"];\n } else {\n options.include = includeStr.split(\",\").map(s => s.trim()).filter(Boolean);\n }\n }\n\n // Field selection\n const fieldsVal = getLastValue(query.fields);\n if (fieldsVal) {\n const fieldsStr = String(fieldsVal).trim();\n options.fields = fieldsStr.split(\",\").map(s => s.trim()).filter(Boolean);\n }\n\n // Vector similarity search\n const vectorSearchVal = getLastValue(query.vector_search);\n const vectorVal = getLastValue(query.vector);\n if (vectorSearchVal && vectorVal) {\n const vectorStr = String(vectorVal);\n let queryVector: number[];\n try {\n queryVector = JSON.parse(vectorStr) as number[];\n if (!Array.isArray(queryVector) || !queryVector.every(v => typeof v === \"number\")) {\n throw new Error(\"Expected array of numbers\");\n }\n } catch {\n throw new Error(\"Invalid vector format. Expected JSON array of numbers, e.g. [0.1,0.2,0.3]\");\n }\n\n const distanceParamVal = getLastValue(query.vector_distance);\n const distanceParam = distanceParamVal ? String(distanceParamVal) : \"cosine\";\n if (distanceParam !== \"cosine\" && distanceParam !== \"l2\" && distanceParam !== \"inner_product\") {\n throw new Error(`Invalid vector_distance: ${distanceParam}. Expected: cosine, l2, or inner_product`);\n }\n\n const vectorSearch: VectorSearchParams = {\n property: String(vectorSearchVal),\n vector: queryVector,\n distance: distanceParam\n };\n\n const thresholdVal = getLastValue(query.vector_threshold);\n if (thresholdVal) {\n const threshold = parseFloat(String(thresholdVal));\n if (isNaN(threshold)) {\n throw new Error(\"Invalid vector_threshold. Expected a number.\");\n }\n vectorSearch.threshold = threshold;\n }\n\n options.vectorSearch = vectorSearch;\n }\n\n return options;\n}\n","/**\n * Permission guard for Service API Keys.\n *\n * Checks whether an API key's permission set allows a specific operation\n * on a specific collection. Used by the REST API generator middleware to\n * enforce fine-grained access control.\n *\n * @module\n */\n\nimport type { ApiKeyPermission } from \"./api-key-types\";\n\n/** Operations that map to HTTP methods. */\nexport type ApiKeyOperation = \"read\" | \"write\" | \"delete\";\n\n/**\n * Map an HTTP method string to an `ApiKeyOperation`.\n *\n * - `GET`, `HEAD`, `OPTIONS` → `\"read\"`\n * - `POST`, `PUT`, `PATCH` → `\"write\"`\n * - `DELETE` → `\"delete\"`\n */\nexport function httpMethodToOperation(method: string): ApiKeyOperation {\n const upper = method.toUpperCase();\n switch (upper) {\n case \"GET\":\n case \"HEAD\":\n case \"OPTIONS\":\n return \"read\";\n case \"POST\":\n case \"PUT\":\n case \"PATCH\":\n return \"write\";\n case \"DELETE\":\n return \"delete\";\n default:\n return \"read\";\n }\n}\n\n/**\n * Check whether the given permissions array allows `operation` on `collection`.\n *\n * Supports the `\"*\"` wildcard for the collection field, which matches any\n * collection. Returns `true` if at least one permission entry grants access.\n *\n * @param permissions - The API key's permission entries.\n * @param collection - The target collection slug.\n * @param operation - The requested operation.\n * @returns `true` if the operation is permitted.\n */\nexport function isOperationAllowed(\n permissions: ApiKeyPermission[],\n collection: string,\n operation: ApiKeyOperation\n): boolean {\n for (const perm of permissions) {\n const collectionMatch = perm.collection === \"*\" || perm.collection === collection;\n if (collectionMatch && perm.operations.includes(operation)) {\n return true;\n }\n }\n return false;\n}\n","import { Hono, type Context } from \"hono\";\nimport { AuthAdapter, DataDriver, CollectionConfig, getCollectionDataPath } from \"@rebasepro/types\";\nimport { QueryOptions, HonoEnv } from \"../types\";\nimport { ApiError, isRebaseApiError } from \"../errors\";\nimport { parseQueryOptions } from \"./query-parser\";\nimport { httpMethodToOperation, isOperationAllowed } from \"../../auth/api-keys/api-key-permission-guard\";\nimport type { ApiKeyMasked } from \"../../auth/api-keys/api-key-types\";\n\n/**\n * Parse a JSON request body for a create/update. An empty body yields `{}`\n * (a valid \"no explicit fields\" write), but a **malformed** body throws a 400\n * rather than being silently swallowed to `{}` — which would turn bad input\n * into an unintended empty write.\n */\nasync function parseJsonBody(c: Context<HonoEnv>): Promise<Record<string, unknown>> {\n const raw = await c.req.text();\n if (!raw || raw.trim() === \"\") return {};\n try {\n return JSON.parse(raw) as Record<string, unknown>;\n } catch {\n throw ApiError.badRequest(\"Invalid JSON body\");\n }\n}\n\n\n\n/**\n * Lightweight REST API generator that leverages existing Rebase DataDriver.\n * Supports `include` query parameter for eager-loading relations via Drizzle.\n */\nexport class RestApiGenerator {\n private collections: CollectionConfig[];\n private router: Hono<HonoEnv>;\n private driver: DataDriver;\n\n private authAdapter?: AuthAdapter;\n\n constructor(\n collections: CollectionConfig[],\n driver: DataDriver,\n authAdapter?: AuthAdapter\n ) {\n this.collections = collections;\n this.driver = driver;\n this.authAdapter = authAdapter;\n this.router = new Hono<HonoEnv>();\n }\n\n\n\n /**\n * Generate REST routes using existing DataDriver\n */\n generateRoutes(): Hono<HonoEnv> {\n this.collections.forEach(collection => {\n this.createCollectionRoutes(collection);\n });\n\n // Catch-all routes for subcollection paths like\n // /authors/111094/posts and /authors/111094/posts/43\n // The DataDriver already knows how to resolve nested relation paths.\n this.createSubcollectionRoutes();\n\n return this.router;\n }\n\n /**\n * Check API key permissions for a collection operation.\n * Throws 403 if the key doesn't have the required permission.\n * No-ops if the request is not authenticated via an API key.\n */\n private enforceApiKeyPermission(\n c: { get: (key: string) => unknown; req: { method: string } },\n collectionSlug: string\n ): void {\n const apiKey = c.get(\"apiKey\") as ApiKeyMasked | undefined;\n if (!apiKey) return; // Not an API key request — skip\n\n const operation = httpMethodToOperation(c.req.method);\n if (!isOperationAllowed(apiKey.permissions, collectionSlug, operation)) {\n throw ApiError.forbidden(\n `API key does not have \"${operation}\" permission for collection \"${collectionSlug}\"`,\n \"API_KEY_FORBIDDEN\"\n );\n }\n }\n\n /**\n * Get the request-scoped driver. Throws if none is set — never falls\n * back to the unscoped `this.driver` to avoid bypassing RLS/auth.\n */\n private getScopedDriver(c: { get: (key: string) => unknown }): DataDriver {\n const driver = c.get(\"driver\") as DataDriver | undefined;\n if (!driver) throw ApiError.internal(\"Scoped driver not available\");\n return driver;\n }\n\n\n\n /**\n * Create REST routes for a collection using existing Rebase patterns\n */\n private createCollectionRoutes(collection: CollectionConfig): void {\n const basePath = `/${collection.slug}`;\n const resolvedCollection = collection;\n\n // GET /collection/count - Count entities (with optional filters)\n this.router.get(`${basePath}/count`, async (c) => {\n this.enforceApiKeyPermission(c, collection.slug);\n const queryDict = c.req.queries();\n const queryOptions = parseQueryOptions(queryDict);\n const searchString = Array.isArray(queryDict.searchString) ? queryDict.searchString[queryDict.searchString.length - 1] : undefined;\n const driver = this.getScopedDriver(c);\n\n const total = await this.countRawEntities(driver, resolvedCollection, queryOptions, searchString);\n return c.json({ count: total });\n });\n\n // GET /collection - List entities\n this.router.get(basePath, async (c) => {\n this.enforceApiKeyPermission(c, collection.slug);\n const queryDict = c.req.queries();\n const queryOptions = parseQueryOptions(queryDict);\n const searchString = Array.isArray(queryDict.searchString) ? queryDict.searchString[queryDict.searchString.length - 1] : undefined;\n\n const driver = this.getScopedDriver(c);\n const fetchService = driver.restFetchService;\n\n // Use include-aware path when available\n const entities = fetchService\n ? await fetchService.fetchCollectionForRest(\n collection.slug,\n {\n filter: queryOptions.where,\n limit: queryOptions.limit,\n offset: queryOptions.offset,\n orderBy: queryOptions.orderBy?.[0]?.field,\n order: queryOptions.orderBy?.[0]?.direction === \"desc\" ? \"desc\" : \"asc\",\n searchString,\n vectorSearch: queryOptions.vectorSearch\n },\n queryOptions.include\n )\n : await this.fetchRawCollection(driver, resolvedCollection, queryOptions, searchString);\n\n const total = await this.countRawEntities(driver, resolvedCollection, queryOptions, searchString);\n\n return c.json({\n data: entities,\n meta: {\n total,\n limit: queryOptions.limit,\n offset: queryOptions.offset,\n hasMore: (queryOptions.offset || 0) + entities.length < total\n }\n });\n });\n\n // GET /collection/:id - Get single entity\n this.router.get(`${basePath}/:id`, async (c) => {\n this.enforceApiKeyPermission(c, collection.slug);\n const id = c.req.param(\"id\");\n const queryDict = c.req.queries();\n const queryOptions = parseQueryOptions(queryDict);\n const driver = this.getScopedDriver(c);\n const fetchService = driver.restFetchService;\n\n // Use include-aware path when available\n const entity = fetchService\n ? await fetchService.fetchOneForRest(collection.slug, String(id), queryOptions.include)\n : await this.fetchRawEntity(driver, resolvedCollection, String(id));\n\n if (!entity) {\n throw ApiError.notFound(\"Entity not found\");\n }\n\n return c.json(entity);\n });\n\n // POST /collection - Create entity\n this.router.post(basePath, async (c) => {\n try {\n this.enforceApiKeyPermission(c, collection.slug);\n const driver = this.getScopedDriver(c);\n const path = collection.slug;\n\n\n const body = await parseJsonBody(c);\n\n\n\n const isAuth = collection.auth;\n const isAuthCollection = isAuth === true || (isAuth && typeof isAuth === \"object\" && isAuth.enabled === true);\n\n if (isAuthCollection && this.authAdapter?.prepareUserCreation) {\n const collectionAuthConfig = typeof isAuth === \"object\" ? isAuth : undefined;\n const prepared = await this.authAdapter.prepareUserCreation(body, collectionAuthConfig);\n\n const entity = await driver.save({\n path,\n values: prepared.values,\n collection: resolvedCollection,\n status: \"new\"\n });\n\n const result = prepared.hookHandledEmail\n ? { temporaryPassword: prepared.clearPassword,\ninvitationSent: prepared.invitationSent }\n : this.authAdapter.finalizeUserCreation\n ? await this.authAdapter.finalizeUserCreation(\n { id: entity.id as string,\nvalues: entity.values as Record<string, unknown> },\n prepared.clearPassword\n )\n : { invitationSent: false };\n\n const response = this.formatResponse(entity) as Record<string, unknown>;\n\n\n\n return c.json({\n ...response,\n invitationSent: result.invitationSent,\n ...(result.temporaryPassword ? { temporaryPassword: result.temporaryPassword } : {})\n }, 201);\n }\n\n const entity = await driver.save({\n path,\n values: body,\n collection: resolvedCollection,\n status: \"new\"\n });\n\n const response = this.formatResponse(entity);\n\n\n\n return c.json(response, 201);\n } catch (error) {\n if (isRebaseApiError(error) && !error.code) {\n // Only classify as BAD_REQUEST if it's an operational error\n // (e.g. validation, DB constraints). Runtime bugs like TypeError,\n // RangeError etc. should remain as 500 INTERNAL_ERROR.\n const isRuntimeBug = error instanceof TypeError\n || error instanceof RangeError\n || error instanceof SyntaxError\n || error instanceof ReferenceError;\n if (!isRuntimeBug) {\n error.code = \"BAD_REQUEST\";\n }\n }\n throw error;\n }\n });\n\n // PUT /collection/:id - Update entity\n this.router.put(`${basePath}/:id`, async (c) => {\n try {\n this.enforceApiKeyPermission(c, collection.slug);\n const id = c.req.param(\"id\");\n const driver = this.getScopedDriver(c);\n\n\n const existingEntity = await driver.fetchOne({\n path: getCollectionDataPath(collection),\n id: String(id),\n collection: resolvedCollection\n });\n\n if (!existingEntity) {\n throw ApiError.notFound(\"Entity not found\");\n }\n\n const body = await parseJsonBody(c);\n\n\n\n const entity = await driver.save({\n path: getCollectionDataPath(collection),\n id: String(id),\n values: body,\n collection: resolvedCollection,\n status: \"existing\"\n });\n\n const response = this.formatResponse(entity);\n\n\n\n return c.json(response);\n } catch (error) {\n if (isRebaseApiError(error) && !error.code) {\n // Only classify as BAD_REQUEST if it's an operational error.\n // Runtime bugs (TypeError, RangeError, etc.) stay as 500.\n const isRuntimeBug = error instanceof TypeError\n || error instanceof RangeError\n || error instanceof SyntaxError\n || error instanceof ReferenceError;\n if (!isRuntimeBug) {\n error.code = \"BAD_REQUEST\";\n }\n }\n throw error;\n }\n });\n\n // DELETE /collection/:id - Delete entity\n this.router.delete(`${basePath}/:id`, async (c) => {\n this.enforceApiKeyPermission(c, collection.slug);\n const id = c.req.param(\"id\");\n const driver = this.getScopedDriver(c);\n\n\n const existingEntity = await driver.fetchOne({\n path: getCollectionDataPath(collection),\n id: String(id),\n collection: resolvedCollection\n });\n\n if (!existingEntity) {\n throw ApiError.notFound(\"Entity not found\");\n }\n\n\n\n await driver.delete({\n row: {\n id: existingEntity.id as string | number,\n path: getCollectionDataPath(collection),\n values: existingEntity\n },\n collection: resolvedCollection\n });\n\n\n\n return new Response(null, { status: 204 });\n });\n }\n\n /**\n * Catch-all routes for subcollection paths.\n *\n * Matches URL patterns like:\n * GET /authors/111094/posts → list child collection\n * GET /authors/111094/posts/43 → get child entity\n * POST /authors/111094/posts → create child entity\n * PUT /authors/111094/posts/43 → update child entity\n * DELETE /authors/111094/posts/43 → delete child entity\n *\n * The `:rest{.+}` regex param captures the full remainder of the URL\n * path (Hono v4 `*` wildcard does not populate `c.req.param(\"*\")`).\n * We split it into segments and reconstruct the `collectionPath`\n * (e.g. \"authors/111094/posts\") and optional `id` (e.g. \"43\").\n *\n * The DataDriver.save / fetchCollection / etc. already know how to\n * resolve multi-segment relation paths, so we just forward to them.\n */\n private createSubcollectionRoutes(): void {\n // Reserved path segments that should NOT be treated as relation names.\n // These are handled by dedicated route handlers (e.g., history routes)\n // mounted on the same data router.\n const RESERVED_SEGMENTS = new Set([\"history\"]);\n\n // Helper: parse a path like \"authors/111094/posts/43\" into\n // { collectionPath: \"authors/111094/posts\", id: \"43\" }\n // or \"authors/111094/posts\" into\n // { collectionPath: \"authors/111094/posts\", id: undefined }\n const parseSubPath = (rawPath: string): { collectionPath: string; id?: string } | null => {\n const segments = rawPath.split(\"/\").filter(s => s && s !== \"undefined\");\n // Need at least 3 segments for a subcollection path (parent/id/child)\n if (segments.length < 3) return null;\n\n // If any segment is a reserved path (e.g. \"history\"), this is not a\n // subcollection route — let it fall through to other handlers.\n if (segments.some(s => RESERVED_SEGMENTS.has(s))) return null;\n\n // Odd segment count → collection path (parent/id/child or parent/id/child/id2/grandchild)\n // Even segment count → entity path (parent/id/child/id)\n if (segments.length % 2 === 1) {\n return { collectionPath: segments.join(\"/\") };\n } else {\n const id = segments.pop()!;\n return { collectionPath: segments.join(\"/\"),\nid };\n }\n };\n\n // GET /<subcollection-path> — list or get single entity\n // Use :rest{.+} instead of * because Hono v4's wildcard doesn't\n // capture into c.req.param(\"*\") — it always returns undefined.\n this.router.get(\"/:parent/:parentId/:rest{.+}\", async (c, next) => {\n const rest = c.req.param(\"rest\");\n if (!rest || rest === \"undefined\") return next();\n const rawPath = `${c.req.param(\"parent\")}/${c.req.param(\"parentId\")}/${rest}`;\n const parsed = parseSubPath(rawPath);\n if (!parsed) return next();\n\n const driver = this.getScopedDriver(c);\n\n this.enforceApiKeyPermission(c, c.req.param(\"parent\"));\n\n\n\n if (parsed.id === \"count\") {\n // GET /parent/:parentId/child/count — count child entities\n const queryDict = c.req.queries();\n const queryOptions = parseQueryOptions(queryDict);\n const searchString = Array.isArray(queryDict.searchString) ? queryDict.searchString[queryDict.searchString.length - 1] : undefined;\n\n const total = driver.count ? await driver.count({\n path: parsed.collectionPath,\n filter: queryOptions.where,\n searchString\n }) : 0;\n\n return c.json({ count: total });\n } else if (parsed.id) {\n // GET /parent/:parentId/child/:id — single entity\n const entity = await driver.fetchOne({\n path: parsed.collectionPath,\n id: parsed.id\n });\n if (!entity) throw ApiError.notFound(\"Entity not found\");\n\n return c.json(entity);\n } else {\n // GET /parent/:parentId/child — list entities\n const queryDict = c.req.queries();\n const queryOptions = parseQueryOptions(queryDict);\n const searchString = Array.isArray(queryDict.searchString) ? queryDict.searchString[queryDict.searchString.length - 1] : undefined;\n const entities = await driver.fetchCollection({\n path: parsed.collectionPath,\n filter: queryOptions.where,\n limit: queryOptions.limit,\n orderBy: queryOptions.orderBy?.[0]?.field,\n order: queryOptions.orderBy?.[0]?.direction === \"desc\" ? \"desc\" : \"asc\",\n searchString\n });\n\n const total = driver.count ? await driver.count({\n path: parsed.collectionPath,\n filter: queryOptions.where,\n searchString\n }) : entities.length;\n\n return c.json({\n data: entities,\n meta: {\n total,\n limit: queryOptions.limit,\n offset: queryOptions.offset,\n hasMore: (queryOptions.offset || 0) + entities.length < total\n }\n });\n }\n });\n\n // POST /<subcollection-path> — create entity\n this.router.post(\"/:parent/:parentId/:rest{.+}\", async (c, next) => {\n const rest = c.req.param(\"rest\");\n if (!rest || rest === \"undefined\") return next();\n const rawPath = `${c.req.param(\"parent\")}/${c.req.param(\"parentId\")}/${rest}`;\n const parsed = parseSubPath(rawPath);\n if (!parsed || parsed.id) return next();\n\n const driver = this.getScopedDriver(c);\n\n\n this.enforceApiKeyPermission(c, c.req.param(\"parent\"));\n const body = await parseJsonBody(c);\n\n\n\n const entity = await driver.save({\n path: parsed.collectionPath,\n values: body,\n status: \"new\"\n });\n\n const response = this.formatResponse(entity);\n\n\n\n return c.json(response, 201);\n });\n\n // PUT /<subcollection-path>/:id — update entity\n this.router.put(\"/:parent/:parentId/:rest{.+}\", async (c, next) => {\n const rest = c.req.param(\"rest\");\n if (!rest || rest === \"undefined\") return next();\n const rawPath = `${c.req.param(\"parent\")}/${c.req.param(\"parentId\")}/${rest}`;\n const parsed = parseSubPath(rawPath);\n if (!parsed || !parsed.id) return next();\n\n const driver = this.getScopedDriver(c);\n\n\n this.enforceApiKeyPermission(c, c.req.param(\"parent\"));\n\n const body = await parseJsonBody(c);\n\n\n\n const entity = await driver.save({\n path: parsed.collectionPath,\n id: parsed.id,\n values: body,\n status: \"existing\"\n });\n\n const response = this.formatResponse(entity);\n\n\n\n return c.json(response);\n });\n\n // DELETE /<subcollection-path>/:id — delete entity\n this.router.delete(\"/:parent/:parentId/:rest{.+}\", async (c, next) => {\n const rest = c.req.param(\"rest\");\n if (!rest || rest === \"undefined\") return next();\n const rawPath = `${c.req.param(\"parent\")}/${c.req.param(\"parentId\")}/${rest}`;\n const parsed = parseSubPath(rawPath);\n if (!parsed || !parsed.id) return next();\n\n const driver = this.getScopedDriver(c);\n\n\n this.enforceApiKeyPermission(c, c.req.param(\"parent\"));\n\n const existingEntity = await driver.fetchOne({\n path: parsed.collectionPath,\n id: parsed.id\n });\n\n if (!existingEntity) throw ApiError.notFound(\"Entity not found\");\n\n\n\n await driver.delete({\n row: {\n id: existingEntity.id as string | number,\n path: parsed.collectionPath,\n values: existingEntity\n }\n });\n\n\n\n return new Response(null, { status: 204 });\n });\n }\n\n /**\n * Format successful API response\n */\n private formatResponse<T>(data: T, meta?: Record<string, unknown>): unknown {\n if (meta) {\n return {\n data,\n meta\n };\n }\n return data;\n }\n\n\n\n /**\n * Fetch raw collection data without Entity wrapper (fallback for non-Postgres)\n */\n private async fetchRawCollection(driver: DataDriver, collection: CollectionConfig, queryOptions: QueryOptions, searchString?: string) {\n const entities = await driver.fetchCollection({\n path: getCollectionDataPath(collection),\n collection,\n filter: queryOptions.where,\n limit: queryOptions.limit,\n orderBy: queryOptions.orderBy?.[0]?.field,\n order: queryOptions.orderBy?.[0]?.direction === \"desc\" ? \"desc\" : \"asc\",\n startAfter: queryOptions.offset ? String(queryOptions.offset) : undefined,\n searchString,\n vectorSearch: queryOptions.vectorSearch\n });\n\n return entities;\n }\n\n /**\n * Count raw entities for a collection\n */\n private async countRawEntities(driver: DataDriver, collection: CollectionConfig, queryOptions: QueryOptions, searchString?: string): Promise<number> {\n return driver.count ? await driver.count({\n path: getCollectionDataPath(collection),\n collection,\n filter: queryOptions.where,\n searchString\n }) : 0;\n }\n\n /**\n * Fetch single entity raw data without Entity wrapper (fallback)\n */\n private async fetchRawEntity(driver: DataDriver, collection: CollectionConfig, id: string) {\n const entity = await driver.fetchOne({\n path: getCollectionDataPath(collection),\n id,\n collection\n });\n\n return entity ?? null;\n }\n\n\n}\n","/**\n * Shared RLS (Row-Level Security) scoping helper.\n *\n * DataDrivers may implement a `withAuth()` method that returns a scoped\n * clone of the driver with RLS policies applied for the given user.\n * This is database-specific (e.g. Postgres SET LOCAL ROLE) and is not\n * part of the core DataDriver interface.\n *\n * This module provides the shared duck-typing logic used by the\n * adapter-aware middleware.\n *\n * @module\n */\n\nimport type { DataDriver } from \"@rebasepro/types\";\n\n/**\n * A DataDriver that supports RLS scoping via `withAuth()`.\n *\n * This is not part of the public DataDriver interface because not all\n * database implementations support RLS. Drivers that do (e.g. Postgres)\n * extend DataDriver with this method.\n */\ninterface RLSScopedDriver extends DataDriver {\n withAuth(user: { uid: string; roles?: string[] }): Promise<DataDriver>;\n}\n\n/**\n * Returns true if the driver supports RLS scoping via `withAuth()`.\n */\nfunction isRLSScopedDriver(driver: DataDriver): driver is RLSScopedDriver {\n return \"withAuth\" in driver && typeof (driver as Record<string, unknown>).withAuth === \"function\";\n}\n\n/**\n * Scope a DataDriver via `withAuth()` for RLS.\n *\n * SECURITY: If `withAuth()` is available but fails, the error is re-thrown\n * so the request is **denied** rather than proceeding with unscoped access\n * (fail-closed behavior).\n *\n * If the driver does not support RLS, the original driver is returned.\n *\n * @param driver - The DataDriver to scope.\n * @param user - The authenticated user identity for RLS.\n * @returns The RLS-scoped DataDriver (or the original if RLS is unsupported).\n */\nexport async function scopeDataDriver(\n driver: DataDriver,\n user: { uid: string; roles?: string[] }\n): Promise<DataDriver> {\n if (isRLSScopedDriver(driver)) {\n // Fail closed — do NOT catch and swallow errors here.\n // If RLS scoping fails the request must be rejected.\n return await driver.withAuth(user);\n }\n return driver;\n}\n","/**\n * Cryptographic utility functions for auth.\n *\n * @module\n */\n\nimport { timingSafeEqual } from \"crypto\";\n\n/**\n * Constant-time string comparison to prevent timing attacks.\n *\n * Used for comparing service keys, tokens, and other secrets where\n * timing side-channels could leak information about the expected value.\n *\n * @param a - First string to compare.\n * @param b - Second string to compare.\n * @returns `true` if the strings are identical, `false` otherwise.\n */\nexport function safeCompare(a: string, b: string): boolean {\n const maxLen = Math.max(a.length, b.length);\n const bufA = Buffer.alloc(maxLen);\n const bufB = Buffer.alloc(maxLen);\n bufA.write(a);\n bufB.write(b);\n try {\n const isEqual = timingSafeEqual(bufA, bufB);\n return isEqual && a.length === b.length;\n } catch {\n return false;\n }\n}\n","/**\n * Hono middleware for authenticating requests via Service API Keys.\n *\n * This middleware is integrated into `createAuthMiddleware()` and\n * activates only when the bearer token starts with `rk_`. It:\n *\n * 1. Hashes the token with SHA-256\n * 2. Looks up the hash in the `rebase.api_keys` table\n * 3. Validates the key is not revoked and not expired\n * 4. Sets `c.set(\"user\", ...)` and `c.set(\"apiKey\", ...)` for downstream use\n * 5. Scopes the DataDriver via `withAuth()` using the API key's service identity\n *\n * @module\n */\n\nimport { createHash } from \"crypto\";\nimport type { Context } from \"hono\";\nimport type { DataDriver } from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../../api/types\";\nimport type { ApiKeyStore } from \"./api-key-store\";\nimport type { ApiKeyMasked } from \"./api-key-types\";\nimport { scopeDataDriver } from \"../rls-scope\";\nimport { logger } from \"../../utils/logger\";\n\n/**\n * Check whether a token looks like a Rebase API key.\n */\nexport function isApiKeyToken(token: string): boolean {\n return token.startsWith(\"rk_\");\n}\n\n/**\n * Hash a plaintext API key token for database lookup.\n */\nfunction hashToken(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n/**\n * Options for the API key authentication handler.\n */\nexport interface ApiKeyAuthOptions {\n store: ApiKeyStore;\n driver: DataDriver;\n}\n\n/**\n * Validate an API key token and populate the Hono context.\n *\n * Returns `true` if the key is valid and context has been populated,\n * or returns an error Response if the key is invalid.\n *\n * This is NOT a standalone middleware — it's called from within\n * `createAuthMiddleware()` when a `rk_` prefixed token is detected.\n */\nexport async function validateApiKey(\n c: Context<HonoEnv>,\n token: string,\n options: ApiKeyAuthOptions\n): Promise<Response | true> {\n const { store, driver } = options;\n\n const hash = hashToken(token);\n const apiKey = await store.findByKeyHash(hash);\n\n if (!apiKey) {\n return c.json({\n error: { message: \"Invalid API key\",\ncode: \"UNAUTHORIZED\" }\n }, 401);\n }\n\n // Check revocation\n if (apiKey.revoked_at) {\n return c.json({\n error: { message: \"API key has been revoked\",\ncode: \"UNAUTHORIZED\" }\n }, 401);\n }\n\n // Check expiration\n if (apiKey.expires_at && new Date(apiKey.expires_at) < new Date()) {\n return c.json({\n error: { message: \"API key has expired\",\ncode: \"UNAUTHORIZED\" }\n }, 401);\n }\n\n // Set user identity — API keys represent service accounts\n const userId = `api-key:${apiKey.id}`;\n const roles: string[] = apiKey.admin ? [\"admin\", \"service\"] : [\"service\"];\n c.set(\"user\", { userId, roles });\n\n // Expose masked key metadata for downstream permission checks\n const masked: ApiKeyMasked = {\n id: apiKey.id,\n name: apiKey.name,\n key_prefix: apiKey.key_prefix,\n permissions: apiKey.permissions,\n admin: apiKey.admin,\n rate_limit: apiKey.rate_limit,\n created_by: apiKey.created_by,\n created_at: apiKey.created_at,\n updated_at: apiKey.updated_at,\n last_used_at: apiKey.last_used_at,\n expires_at: apiKey.expires_at,\n revoked_at: apiKey.revoked_at\n };\n // Store apiKey in the context for permission checking in api-generator\n c.set(\"apiKey\", masked);\n\n // Scope the DataDriver — API keys bypass RLS (service identity)\n try {\n const scopedDriver = await scopeDataDriver(driver, {\n uid: userId,\n roles\n });\n c.set(\"driver\", scopedDriver);\n } catch (error) {\n logger.error(\"[AUTH] RLS scoping failed for API key\", { error: error });\n return c.json({\n error: { message: \"Internal authentication error\",\ncode: \"INTERNAL_ERROR\" }\n }, 500);\n }\n\n // Touch last_used_at in the background (non-blocking)\n store.updateLastUsed(apiKey.id).catch(() => {\n // Swallowed intentionally — logged inside the store\n });\n\n return true;\n}\n","import { MiddlewareHandler, Context } from \"hono\";\nimport { DataDriver, isPublicStoragePath } from \"@rebasepro/types\";\nimport { verifyAccessToken, AccessTokenPayload, verifyDownloadToken } from \"./jwt\";\nimport { HonoEnv } from \"../api/types\";\nimport { scopeDataDriver } from \"./rls-scope\";\nimport { safeCompare } from \"./crypto-utils\";\nimport { isApiKeyToken, validateApiKey } from \"./api-keys/api-key-middleware\";\nimport type { ApiKeyStore } from \"./api-keys/api-key-store\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Result from a custom auth validator.\n * - `false`/`null`/`undefined` = not authenticated\n * - `true` = authenticated as default user\n * - object with `userId` or `uid` = authenticated with user info\n */\nexport type AuthResult = boolean | null | undefined | { userId?: string; uid?: string; roles?: string[]; [key: string]: unknown };\n\n/**\n * Options for creating an auth middleware via createAuthMiddleware()\n */\nexport interface AuthMiddlewareOptions {\n /** DataDriver to scope via withAuth() for RLS */\n driver: DataDriver;\n /**\n * Optional per-request driver resolver for multi-data-source backends.\n * Given the request context, returns the unscoped delegate to use (e.g.\n * Postgres vs Mongo, picked by the request's collection data source).\n * When omitted, `driver` is used for every request.\n */\n resolveDriver?: (c: Context<HonoEnv>) => DataDriver;\n /**\n * If true, return 401 when no valid token is present.\n *\n * **Defaults to `true` (secure by default).** Set to `false` only for\n * intentionally public endpoints where access control is fully delegated\n * to Postgres Row-Level Security policies.\n */\n requireAuth?: boolean;\n /** Optional custom validator (for non-JWT auth, e.g. external auth providers) */\n validator?: (c: Context<HonoEnv>) => Promise<AuthResult>;\n /**\n * A static secret key for server-to-server / script authentication.\n *\n * When a request sends `Authorization: Bearer <key>` and the key matches\n * this value, the request is granted admin-level access (uid: `service`,\n * roles: `[\"admin\"]`) **without** JWT verification. The driver is scoped\n * via `withAuth()` with the service identity.\n *\n * This is the Rebase equivalent of a Service Account key.\n * Set via `REBASE_SERVICE_KEY` in `.env` and pass through the backend config.\n *\n * **Security:** The comparison uses constant-time equality to prevent\n * timing attacks. The key must be at least 32 characters.\n */\n serviceKey?: string;\n /**\n * API key store for authenticating `rk_` prefixed tokens.\n * When set, tokens starting with `rk_` are validated against the\n * database instead of being treated as JWTs.\n */\n apiKeyStore?: ApiKeyStore;\n}\n\n/**\n * Hono middleware that requires a valid JWT token via Authorization header.\n * Returns 401 if token is missing or invalid.\n *\n * **Security:** Tokens are only accepted via the `Authorization: Bearer`\n * header. Query-string tokens (`?token=`) are intentionally NOT accepted\n * here because URLs leak into access logs, proxies, Referer headers, and\n * browser history. Use {@link queryTokenAuth} on routes that legitimately\n * need query-string tokens (e.g. storage file serving for `<img src>`).\n */\nexport const requireAuth: MiddlewareHandler<HonoEnv> = async (\n c,\n next\n) => {\n const authHeader = c.req.header(\"authorization\");\n const hasBearer = authHeader && authHeader.startsWith(\"Bearer \");\n\n if (!hasBearer) {\n // Skip 401 if a prior middleware (e.g. queryTokenAuth) already set the user.\n if (c.get(\"user\")) return next();\n return c.json({\n error: {\n message: \"Authorization header missing or invalid\",\n code: \"UNAUTHORIZED\"\n }\n }, 401);\n }\n\n const token = authHeader!.substring(7);\n const payload = verifyAccessToken(token);\n\n if (!payload) {\n return c.json({\n error: {\n message: \"Invalid or expired token\",\n code: \"UNAUTHORIZED\"\n }\n }, 401);\n }\n\n c.set(\"user\", payload);\n return next();\n};\n\n/**\n * Factory that creates a requireAuth middleware with optional service key support.\n *\n * When `serviceKey` is provided, the middleware will check if the Bearer token\n * matches the service key using constant-time comparison. If it matches, the\n * request is authenticated as a service user with admin privileges.\n *\n * This allows admin routes (which use standalone requireAuth + requireAdmin)\n * to be accessed via service keys for scripts and server-to-server calls.\n */\nexport function createRequireAuth(options?: { serviceKey?: string }): MiddlewareHandler<HonoEnv> {\n if (!options?.serviceKey) return requireAuth;\n\n const key = options.serviceKey;\n return async (c, next) => {\n const authHeader = c.req.header(\"authorization\");\n const hasBearer = authHeader && authHeader.startsWith(\"Bearer \");\n\n if (!hasBearer) {\n // Skip 401 if a prior middleware already set the user.\n if (c.get(\"user\")) return next();\n return c.json({\n error: {\n message: \"Authorization header missing or invalid\",\n code: \"UNAUTHORIZED\"\n }\n }, 401);\n }\n\n const token = authHeader!.substring(7);\n\n // Check service key first (constant-time comparison)\n if (safeCompare(token, key)) {\n c.set(\"user\", { userId: \"service\",\nroles: [\"admin\"] } as AccessTokenPayload);\n return next();\n }\n\n // Fall back to JWT verification\n const payload = verifyAccessToken(token);\n\n if (!payload) {\n return c.json({\n error: {\n message: \"Invalid or expired token\",\n code: \"UNAUTHORIZED\"\n }\n }, 401);\n }\n\n c.set(\"user\", payload);\n return next();\n };\n}\n\n/**\n * Middleware that requires the user to have an admin or schema-admin role.\n * Must be used AFTER requireAuth or on a route where user is guaranteed.\n */\nexport const requireAdmin: MiddlewareHandler<HonoEnv> = async (\n c,\n next\n) => {\n const user = c.get(\"user\");\n if (!user) {\n return c.json({\n error: {\n message: \"User not authenticated. requireAuth middleware is missing?\",\n code: \"UNAUTHORIZED\"\n }\n }, 401);\n }\n\n const roles = (typeof user === \"object\" && user !== null && \"roles\" in user) ? (user.roles || []) : [];\n const isAdmin = roles.some((role: string) => {\n return role === \"admin\" || role === \"schema-admin\";\n });\n\n if (!isAdmin) {\n return c.json({\n error: {\n message: \"Admin privileges required for this operation\",\n code: \"FORBIDDEN\"\n }\n }, 403);\n }\n\n return next();\n};\n\n\n/**\n * Middleware that optionally extracts user from JWT via Authorization header.\n * Does not return 401 if token is missing — allows anonymous access.\n *\n * Query-string tokens are NOT accepted here. Use {@link queryTokenAuth}\n * on routes that need them.\n */\nexport const optionalAuth: MiddlewareHandler<HonoEnv> = async (\n c,\n next\n) => {\n // Skip if a prior middleware (e.g. queryTokenAuth) already set the user.\n if (c.get(\"user\")) return next();\n\n const authHeader = c.req.header(\"authorization\");\n const hasBearer = authHeader && authHeader.startsWith(\"Bearer \");\n\n if (hasBearer) {\n const token = authHeader!.substring(7);\n const payload = verifyAccessToken(token);\n if (payload) {\n c.set(\"user\", payload);\n }\n }\n\n return next();\n};\n\n/**\n * Extract user from token - for WebSocket authentication\n */\nexport function extractUserFromToken(token: string): AccessTokenPayload | null {\n return verifyAccessToken(token);\n}\n\n/**\n * Create a configurable auth middleware that handles:\n * 1. Token extraction (via custom validator or JWT Bearer token)\n * 2. RLS-scoped DataDriver via withAuth()\n * 3. Enforcement (401 when requireAuth is true and no user)\n *\n * **Secure by default:** `requireAuth` defaults to `true`. Anonymous\n * access is only allowed when the developer explicitly opts out by\n * setting `requireAuth: false`, indicating that Postgres RLS policies\n * fully control access.\n *\n * **Fail-closed:** The raw unscoped driver is never placed in the\n * request context. Every code path either scopes via `withAuth()` or\n * rejects the request. This prevents silent RLS bypass.\n *\n * This is the single source of truth for HTTP auth in Rebase.\n * Use this instead of manually parsing tokens in route handlers.\n */\n\nexport function createAuthMiddleware(options: AuthMiddlewareOptions): MiddlewareHandler<HonoEnv> {\n const { driver: baseDriver, resolveDriver, requireAuth: enforceAuth = true, validator, serviceKey, apiKeyStore } = options;\n\n return async (c, next) => {\n // Pick the per-request delegate (multi-data-source) before scoping.\n const driver = resolveDriver ? resolveDriver(c) : baseDriver;\n if (validator) {\n // Custom validator path (e.g., API keys, external auth)\n try {\n const authResult = await validator(c);\n if (authResult && typeof authResult === \"object\") {\n const id = (\"userId\" in authResult ? authResult.userId : undefined)\n || (\"uid\" in authResult ? authResult.uid : undefined);\n if (id) {\n const roles = authResult.roles || [];\n c.set(\"user\", { userId: id,\nroles });\n const user = { uid: id,\nroles,\n...authResult };\n c.set(\"driver\", await scopeDataDriver(driver, user));\n } else {\n // Validator returned an object but without an ID — scope as anon\n c.set(\"driver\", await scopeDataDriver(driver, { uid: \"anon\",\nroles: [\"anon\"] }));\n }\n } else if (authResult === true) {\n c.set(\"user\", { userId: \"default\",\nroles: [] });\n c.set(\"driver\", await scopeDataDriver(driver, { uid: \"default\",\nroles: [] }));\n } else {\n // Not authenticated — scope as anon so RLS can evaluate.\n // Fail closed: if anon scoping fails, reject instead of\n // falling back to the raw driver.\n c.set(\"driver\", await scopeDataDriver(driver, { uid: \"anon\",\nroles: [\"anon\"] }));\n }\n } catch (error) {\n return c.json({ error: { message: \"Unauthorized\",\ncode: \"UNAUTHORIZED\" } }, 401);\n }\n } else {\n // Default JWT path (with optional service key support)\n const authHeader = c.req.header(\"authorization\");\n const hasBearer = authHeader && authHeader.startsWith(\"Bearer \");\n\n if (hasBearer) {\n const token = authHeader!.substring(7);\n\n // ── Service Key check ──────────────────────────────────\n // Check BEFORE JWT verification. Service keys are static\n // secrets (like Service Account keys) that grant admin access\n // for scripts, cron jobs, and server-to-server calls.\n if (serviceKey && safeCompare(token, serviceKey)) {\n const serviceUser: AccessTokenPayload = {\n userId: \"service\",\n roles: [\"admin\"]\n };\n c.set(\"user\", serviceUser);\n try {\n c.set(\"driver\", await scopeDataDriver(driver, {\n uid: \"service\",\n roles: [\"admin\"]\n }));\n } catch (error) {\n logger.error(\"[AUTH] RLS scoping failed for service key\", { error: error });\n return c.json({ error: { message: \"Internal authentication error\",\ncode: \"INTERNAL_ERROR\" } }, 500);\n }\n } else if (apiKeyStore && isApiKeyToken(token)) {\n // ── API Key verification ──────────────────────────────\n // Tokens starting with `rk_` are validated against the\n // api_keys table instead of JWT verification.\n const result = await validateApiKey(c, token, {\n store: apiKeyStore,\n driver\n });\n if (result !== true) {\n return result;\n }\n } else {\n // ── JWT verification ───────────────────────────────────\n const payload = extractUserFromToken(token);\n\n if (payload) {\n c.set(\"user\", payload);\n try {\n const user = { uid: payload.userId,\nroles: payload.roles };\n c.set(\"driver\", await scopeDataDriver(driver, user));\n } catch (error) {\n // withAuth() failed for a valid token — reject (fail closed)\n logger.error(\"[AUTH] RLS scoping failed for authenticated user\", { error: error });\n return c.json({ error: { message: \"Internal authentication error\",\ncode: \"INTERNAL_ERROR\" } }, 500);\n }\n } else {\n // Token present but invalid — always reject.\n // Providing a malformed token should never grant access,\n // regardless of requireAuth setting.\n return c.json({ error: { message: \"Invalid or expired token\",\ncode: \"UNAUTHORIZED\" } }, 401);\n }\n }\n } else {\n // No token provided — scope as anon for RLS evaluation.\n // Fail closed: if anon scoping fails, return 500 rather\n // than silently proceeding with an unscoped driver.\n try {\n c.set(\"driver\", await scopeDataDriver(driver, { uid: \"anon\",\nroles: [\"anon\"] }));\n } catch (error) {\n logger.error(\"[AUTH] Failed to create anon-scoped driver\", { error: error });\n return c.json({ error: { message: \"Server configuration error\",\ncode: \"INTERNAL_ERROR\" } }, 500);\n }\n }\n }\n\n if (enforceAuth && !c.get(\"user\")) {\n return c.json({ error: { message: \"Unauthorized: Authentication required\",\ncode: \"UNAUTHORIZED\" } }, 401);\n }\n\n return next();\n };\n}\n\n/**\n * Middleware that authenticates via a `?token=` query parameter.\n *\n * **Use sparingly.** Tokens in URLs leak into access logs, proxy logs,\n * Referer headers, and browser history. This middleware exists solely for\n * routes where the consumer cannot set HTTP headers — e.g. `<img src>`,\n * `<a href>` for file downloads, or similar browser-native requests.\n *\n * Apply it **before** `requireAuth` or `optionalAuth` on the specific\n * route that needs it. Those middlewares will see the user context this\n * middleware sets and skip their own 401 check.\n *\n * @example\n * ```ts\n * router.get(\"/file/*\", queryTokenAuth, readAuthMiddleware, handler);\n * ```\n */\nexport const queryTokenAuth: MiddlewareHandler<HonoEnv> = async (c, next) => {\n // Only activate when no Authorization header is present and a query token exists.\n const authHeader = c.req.header(\"authorization\");\n if (authHeader && authHeader.startsWith(\"Bearer \")) {\n // Authorization header takes precedence — let downstream middleware handle it.\n return next();\n }\n\n const queryToken = c.req.query(\"token\");\n if (queryToken) {\n const payload = verifyAccessToken(queryToken);\n if (payload) {\n c.set(\"user\", payload);\n }\n // If the token is invalid, we don't reject here — let the downstream\n // requireAuth / optionalAuth middleware decide the enforcement policy.\n }\n\n return next();\n};\n\n/**\n * Authorizes anonymous access to **public** storage objects (those under the\n * public prefix), which are served token-less via stable, permanent URLs.\n *\n * Runs on the storage `/file/*` and `/metadata/*` routes, *after* the token\n * middleware and *before* the read-auth gate. If the request is already\n * authenticated (Bearer or scoped token), it does nothing. Otherwise, when the\n * requested object path is public, it sets a minimal \"public\" principal so the\n * downstream `requireAuth` gate lets the read through. Private paths are left\n * untouched, so they still require a valid token.\n */\nexport const publicObjectAuth: MiddlewareHandler<HonoEnv> = async (c, next) => {\n // Already authenticated (Bearer / scoped token) — nothing to authorize.\n if (c.get(\"user\")) return next();\n\n const routePath = c.req.routePath; // e.g. \"/api/storage/file/*\"\n const prefix = routePath.replace(\"/*\", \"\");\n const fullPath = c.req.path;\n const idx = fullPath.indexOf(prefix);\n const rawPath = idx < 0 ? \"\" : fullPath.substring(idx + prefix.length + 1);\n\n if (rawPath && isPublicStoragePath(decodeURIComponent(rawPath))) {\n c.set(\"user\", { userId: \"public\", roles: [\"public\"] });\n }\n\n return next();\n};\n\n/**\n * Helper to match paths for scoped file tokens.\n * Matches exact paths or prefixes (exact folder prefixes or ending with /).\n */\nfunction isPathMatch(requested: string, allowed: string): boolean {\n if (requested === allowed) return true;\n if (allowed.endsWith(\"/\")) {\n return requested.startsWith(allowed);\n }\n return requested.startsWith(allowed + \"/\");\n}\n\n/**\n * Middleware that authenticates file-serving routes using scoped download tokens.\n * It enforces that only scoped \"file-read\" tokens can access \"/file/*\" and \"?token=\" query params.\n * Full access JWTs are explicitly rejected on \"/file/*\" routes, and in the \"?token=\" query param.\n */\nexport const fileTokenAuth: MiddlewareHandler<HonoEnv> = async (c, next) => {\n const path = c.req.path;\n const isFileRoute = path.includes(\"/storage/file/\");\n const authHeader = c.req.header(\"authorization\");\n const queryToken = c.req.query(\"token\");\n\n // Local copy of helper to avoid circular imports with routes.ts\n const extractWildcard = (ctx: import(\"hono\").Context): string => {\n const routePath = ctx.req.routePath;\n const prefix = routePath.replace(\"/*\", \"\");\n const fullPath = ctx.req.path;\n const idx = fullPath.indexOf(prefix);\n if (idx < 0) return \"\";\n return fullPath.substring(idx + prefix.length + 1);\n };\n\n const parseBucketPath = (filePath: string): { bucket: string; resolvedPath: string } => {\n const parts = filePath.split(\"/\");\n if (parts.length > 1 && parts[0].toLowerCase() === \"default\") {\n return {\n bucket: \"default\",\n resolvedPath: parts.slice(1).join(\"/\")\n };\n }\n return {\n bucket: \"default\",\n resolvedPath: filePath\n };\n };\n\n // 1. Authorization: Bearer <token>\n if (authHeader && authHeader.startsWith(\"Bearer \")) {\n const token = authHeader.substring(7);\n const payload = verifyDownloadToken(token);\n\n if (payload) {\n const rawPath = extractWildcard(c);\n if (rawPath) {\n const filePath = decodeURIComponent(rawPath);\n const { bucket, resolvedPath } = parseBucketPath(filePath);\n const requestedFullPath = `${bucket}/${resolvedPath}`;\n\n if (isPathMatch(requestedFullPath, payload.path)) {\n c.set(\"user\", { userId: \"download-token\", roles: [\"reader\"] });\n return next();\n } else {\n return c.json({ error: { message: \"Forbidden: Scoped token path mismatch\", code: \"FORBIDDEN\" } }, 403);\n }\n }\n }\n\n // If it's a file serving route, explicitly reject full access JWTs\n if (isFileRoute) {\n return c.json({ error: { message: \"Unauthorized: Access JWT not allowed on file routes\", code: \"UNAUTHORIZED\" } }, 401);\n }\n\n // Otherwise (e.g. /metadata/*) let it pass to downstream requireAuth\n return next();\n }\n\n // 2. Query param: ?token=<token>\n if (queryToken) {\n const payload = verifyDownloadToken(queryToken);\n\n if (payload) {\n const rawPath = extractWildcard(c);\n if (rawPath) {\n const filePath = decodeURIComponent(rawPath);\n const { bucket, resolvedPath } = parseBucketPath(filePath);\n const requestedFullPath = `${bucket}/${resolvedPath}`;\n\n if (isPathMatch(requestedFullPath, payload.path)) {\n c.set(\"user\", { userId: \"download-token\", roles: [\"reader\"] });\n return next();\n } else {\n return c.json({ error: { message: \"Forbidden: Scoped token path mismatch\", code: \"FORBIDDEN\" } }, 403);\n }\n }\n }\n\n // Explicitly reject query-token if it is not a valid scoped download token (e.g. if it is a full access JWT)\n return c.json({ error: { message: \"Unauthorized: Invalid or unauthorized token\", code: \"UNAUTHORIZED\" } }, 401);\n }\n\n return next();\n};\n\n","/**\n * Adapter Auth Middleware\n *\n * Creates a Hono middleware that delegates authentication to an `AuthAdapter`\n * instead of hardcoded JWT verification. This is used when the user passes\n * an `AuthAdapter` to `initializeRebaseBackend()`.\n *\n * The middleware:\n * 1. Checks for API key tokens (`rk_` prefix) first — these are Rebase-level\n * 2. Falls back to `adapter.verifyRequest(request)` to resolve the user\n * 3. Scopes the DataDriver via `withAuth()` for RLS\n * 4. Enforces auth (401) when `requireAuth` is true and no user is found\n *\n * The behavior is identical to `createAuthMiddleware()` — only the\n * token verification strategy is pluggable.\n */\n\nimport type { MiddlewareHandler, Context } from \"hono\";\nimport type { DataDriver, AuthAdapter } from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../api/types\";\nimport type { ApiKeyStore } from \"./api-keys/api-key-store\";\nimport { scopeDataDriver } from \"./rls-scope\";\nimport { validateApiKey } from \"./api-keys/api-key-middleware\";\nimport { logger } from \"../utils/logger\";\n\nexport interface AdapterAuthMiddlewareOptions {\n /** The auth adapter to delegate verification to. */\n adapter: AuthAdapter;\n /** The DataDriver to scope via withAuth() for RLS. */\n driver: DataDriver;\n /**\n * Optional per-request driver resolver for multi-data-source backends.\n * Returns the unscoped delegate to use for this request (e.g. Postgres vs\n * Mongo). When omitted, `driver` is used for every request.\n */\n resolveDriver?: (c: Context<HonoEnv>) => DataDriver;\n /**\n * If true, return 401 when no valid user is resolved.\n * Defaults to `true` (secure by default).\n */\n requireAuth?: boolean;\n /** Optional API key store — when provided, `rk_` bearer tokens are accepted. */\n apiKeyStore?: ApiKeyStore;\n}\n\n/**\n * Create a Hono middleware that uses an `AuthAdapter` for request verification.\n */\nexport function createAdapterAuthMiddleware(options: AdapterAuthMiddlewareOptions): MiddlewareHandler<HonoEnv> {\n const { adapter, driver: baseDriver, resolveDriver, requireAuth: enforceAuth = true, apiKeyStore } = options;\n\n return async (c, next) => {\n // Pick the per-request delegate (multi-data-source) before scoping.\n const driver = resolveDriver ? resolveDriver(c) : baseDriver;\n // ── API Key check (Rebase-level, independent of auth adapter) ────\n if (apiKeyStore) {\n const authHeader = c.req.header(\"authorization\") || \"\";\n const token = authHeader.startsWith(\"Bearer \") ? authHeader.slice(7) : \"\";\n if (token.startsWith(\"rk_\")) {\n const result = await validateApiKey(c, token, { store: apiKeyStore,\ndriver });\n if (result === true) return next();\n return result;\n }\n }\n\n let authenticatedUser = null;\n\n try {\n authenticatedUser = await adapter.verifyRequest(c.req.raw);\n } catch (error) {\n // adapter.verifyRequest() threw — reject the request (fail closed)\n return c.json({ error: { message: \"Unauthorized\",\ncode: \"UNAUTHORIZED\" } }, 401);\n }\n\n if (authenticatedUser) {\n // Authenticated — set user context and scope driver\n c.set(\"user\", {\n userId: authenticatedUser.uid,\n email: authenticatedUser.email,\n roles: authenticatedUser.roles\n });\n try {\n c.set(\"driver\", await scopeDataDriver(driver, {\n uid: authenticatedUser.uid,\n roles: authenticatedUser.roles\n }));\n } catch (error) {\n logger.error(\"[AUTH-ADAPTER] RLS scoping failed for authenticated user\", { error: error });\n return c.json({ error: { message: \"Internal authentication error\",\ncode: \"INTERNAL_ERROR\" } }, 500);\n }\n } else {\n // Not authenticated — scope as anon for RLS evaluation\n try {\n c.set(\"driver\", await scopeDataDriver(driver, { uid: \"anon\",\nroles: [\"anon\"] }));\n } catch (error) {\n logger.error(\"[AUTH-ADAPTER] Failed to create anon-scoped driver\", { error: error });\n return c.json({ error: { message: \"Server configuration error\",\ncode: \"INTERNAL_ERROR\" } }, 500);\n }\n }\n\n // Enforce auth if required\n if (enforceAuth && !c.get(\"user\")) {\n return c.json({ error: { message: \"Unauthorized: Authentication required\",\ncode: \"UNAUTHORIZED\" } }, 401);\n }\n\n return next();\n };\n}\n","/**\n * Default email templates for authentication emails\n */\n\ninterface TemplateUser {\n email: string;\n displayName?: string | null;\n}\n\n/**\n * Get a greeting name for the user\n */\nfunction getGreeting(user: TemplateUser): string {\n return user.displayName || user.email.split(\"@\")[0];\n}\n\n/**\n * Common email styles\n */\nconst styles = {\n container: `\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n max-width: 600px;\n margin: 0 auto;\n padding: 40px 20px;\n background-color: #f8fafc;\n `,\n card: `\n background-color: #ffffff;\n border-radius: 12px;\n padding: 40px;\n box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);\n `,\n heading: `\n color: #1e293b;\n font-size: 24px;\n font-weight: 600;\n margin: 0 0 20px 0;\n `,\n paragraph: `\n color: #475569;\n font-size: 16px;\n line-height: 1.6;\n margin: 0 0 20px 0;\n `,\n button: `\n display: inline-block;\n background-color: #3b82f6;\n color: #ffffff;\n font-size: 16px;\n font-weight: 600;\n text-decoration: none;\n padding: 14px 28px;\n border-radius: 8px;\n margin: 20px 0;\n `,\n footer: `\n color: #94a3b8;\n font-size: 14px;\n margin-top: 30px;\n padding-top: 20px;\n border-top: 1px solid #e2e8f0;\n `,\n warning: `\n color: #64748b;\n font-size: 14px;\n background-color: #fef3c7;\n padding: 12px 16px;\n border-radius: 6px;\n margin-top: 20px;\n `\n};\n\n/**\n * Default password reset email template\n */\nexport function getPasswordResetTemplate(\n resetUrl: string,\n user: TemplateUser,\n appName = \"Rebase\"\n): { subject: string; html: string; text: string } {\n const greeting = getGreeting(user);\n\n const subject = `Reset your ${appName} password`;\n\n const html = `\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${subject}</title>\n</head>\n<body style=\"margin: 0; padding: 0; background-color: #f8fafc;\">\n <div style=\"${styles.container}\">\n <div style=\"${styles.card}\">\n <h1 style=\"${styles.heading}\">Reset Your Password</h1>\n \n <p style=\"${styles.paragraph}\">\n Hi ${greeting},\n </p>\n \n <p style=\"${styles.paragraph}\">\n We received a request to reset your password for your ${appName} account. \n Click the button below to create a new password:\n </p>\n \n <div style=\"text-align: center;\">\n <a href=\"${resetUrl}\" style=\"${styles.button}\">Reset Password</a>\n </div>\n \n <p style=\"${styles.paragraph}\">\n Or copy and paste this link into your browser:\n </p>\n <p style=\"color: #3b82f6; word-break: break-all; font-size: 14px;\">\n ${resetUrl}\n </p>\n \n <div style=\"${styles.warning}\">\n ⏰ This link will expire in 1 hour for security reasons.\n </div>\n \n <div style=\"${styles.footer}\">\n <p style=\"margin: 0;\">\n If you didn't request a password reset, you can safely ignore this email. \n Your password will remain unchanged.\n </p>\n </div>\n </div>\n </div>\n</body>\n</html>\n `.trim();\n\n const text = `\nReset Your Password\n\nHi ${greeting},\n\nWe received a request to reset your password for your ${appName} account.\n\nClick this link to create a new password:\n${resetUrl}\n\nThis link will expire in 1 hour for security reasons.\n\nIf you didn't request a password reset, you can safely ignore this email.\nYour password will remain unchanged.\n `.trim();\n\n return { subject,\nhtml,\ntext };\n}\n\n/**\n * Default email verification template\n */\nexport function getEmailVerificationTemplate(\n verifyUrl: string,\n user: TemplateUser,\n appName = \"Rebase\"\n): { subject: string; html: string; text: string } {\n const greeting = getGreeting(user);\n\n const subject = `Verify your ${appName} email address`;\n\n const html = `\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${subject}</title>\n</head>\n<body style=\"margin: 0; padding: 0; background-color: #f8fafc;\">\n <div style=\"${styles.container}\">\n <div style=\"${styles.card}\">\n <h1 style=\"${styles.heading}\">Verify Your Email</h1>\n \n <p style=\"${styles.paragraph}\">\n Hi ${greeting},\n </p>\n \n <p style=\"${styles.paragraph}\">\n Thanks for signing up for ${appName}! Please verify your email address \n by clicking the button below:\n </p>\n \n <div style=\"text-align: center;\">\n <a href=\"${verifyUrl}\" style=\"${styles.button}\">Verify Email Address</a>\n </div>\n \n <p style=\"${styles.paragraph}\">\n Or copy and paste this link into your browser:\n </p>\n <p style=\"color: #3b82f6; word-break: break-all; font-size: 14px;\">\n ${verifyUrl}\n </p>\n \n <div style=\"${styles.footer}\">\n <p style=\"margin: 0;\">\n If you didn't create an account with ${appName}, you can safely ignore this email.\n </p>\n </div>\n </div>\n </div>\n</body>\n</html>\n `.trim();\n\n const text = `\nVerify Your Email\n\nHi ${greeting},\n\nThanks for signing up for ${appName}! Please verify your email address by clicking this link:\n${verifyUrl}\n\nIf you didn't create an account with ${appName}, you can safely ignore this email.\n `.trim();\n\n return { subject,\nhtml,\ntext };\n}\n\n/**\n * Default user invitation email template\n * Sent when an admin creates a new user account\n */\nexport function getUserInvitationTemplate(\n setPasswordUrl: string,\n user: TemplateUser,\n appName = \"Rebase\"\n): { subject: string; html: string; text: string } {\n const greeting = getGreeting(user);\n\n const subject = `You've been invited to ${appName}`;\n\n const html = `\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${subject}</title>\n</head>\n<body style=\"margin: 0; padding: 0; background-color: #f8fafc;\">\n <div style=\"${styles.container}\">\n <div style=\"${styles.card}\">\n <h1 style=\"${styles.heading}\">Welcome to ${appName}!</h1>\n \n <p style=\"${styles.paragraph}\">\n Hi ${greeting},\n </p>\n \n <p style=\"${styles.paragraph}\">\n An account has been created for you on ${appName}. \n Click the button below to set your password and get started:\n </p>\n \n <div style=\"text-align: center;\">\n <a href=\"${setPasswordUrl}\" style=\"${styles.button}\">Set Your Password</a>\n </div>\n \n <p style=\"${styles.paragraph}\">\n Or copy and paste this link into your browser:\n </p>\n <p style=\"color: #3b82f6; word-break: break-all; font-size: 14px;\">\n ${setPasswordUrl}\n </p>\n \n <div style=\"${styles.warning}\">\n ⏰ This link will expire in 1 hour for security reasons.\n </div>\n \n <div style=\"${styles.footer}\">\n <p style=\"margin: 0;\">\n If you weren't expecting this invitation, you can safely ignore this email.\n </p>\n </div>\n </div>\n </div>\n</body>\n</html>\n `.trim();\n\n const text = `\nWelcome to ${appName}!\n\nHi ${greeting},\n\nAn account has been created for you on ${appName}.\n\nClick this link to set your password and get started:\n${setPasswordUrl}\n\nThis link will expire in 1 hour for security reasons.\n\nIf you weren't expecting this invitation, you can safely ignore this email.\n `.trim();\n\n return { subject,\nhtml,\ntext };\n}\n\n/**\n * Default welcome email template\n * Sent automatically when a new user registers\n */\nexport function getWelcomeEmailTemplate(\n user: TemplateUser,\n appName = \"Rebase\",\n loginUrl?: string\n): { subject: string; html: string; text: string } {\n const greeting = getGreeting(user);\n const url = loginUrl || \"\";\n\n const subject = `¡Bienvenido/a a ${appName}!`;\n\n const html = `\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${subject}</title>\n</head>\n<body style=\"margin: 0; padding: 0; background-color: #f8fafc;\">\n <div style=\"${styles.container}\">\n <div style=\"${styles.card}\">\n <h1 style=\"${styles.heading}\">¡Bienvenido/a a ${appName}!</h1>\n \n <p style=\"${styles.paragraph}\">\n Hola ${greeting},\n </p>\n \n <p style=\"${styles.paragraph}\">\n Tu cuenta en ${appName} ha sido creada exitosamente. \n Estamos encantados de tenerte con nosotros.\n </p>\n \n <p style=\"${styles.paragraph}\">\n Ya puedes acceder a tu panel y empezar a explorar todas las oportunidades \n que tenemos para ti.\n </p>\n\n ${url ? `\n <div style=\"text-align: center;\">\n <a href=\"${url}\" style=\"${styles.button}\">Ir a mi Panel</a>\n </div>\n ` : \"\"}\n \n <p style=\"${styles.paragraph}\">\n Si tienes alguna pregunta, no dudes en contactarnos respondiendo a este correo.\n </p>\n \n <div style=\"${styles.footer}\">\n <p style=\"margin: 0;\">\n Este correo fue enviado porque se creó una cuenta con esta dirección de email en ${appName}.\n </p>\n </div>\n </div>\n </div>\n</body>\n</html>\n `.trim();\n\n const text = `\n¡Bienvenido/a a ${appName}!\n\nHola ${greeting},\n\nTu cuenta en ${appName} ha sido creada exitosamente. Estamos encantados de tenerte con nosotros.\n\nYa puedes acceder a tu panel y empezar a explorar todas las oportunidades que tenemos para ti.\n\n${url ? `Ir a mi panel: ${url}` : \"\"}\n\nSi tienes alguna pregunta, no dudes en contactarnos respondiendo a este correo.\n `.trim();\n\n return { subject,\nhtml,\ntext };\n}\n\n/**\n * Default magic link email template\n */\nexport function getMagicLinkTemplate(\n magicLinkUrl: string,\n user: TemplateUser,\n appName = \"Rebase\"\n): { subject: string; html: string; text: string } {\n const greeting = getGreeting(user);\n\n const subject = `Sign in to ${appName}`;\n\n const html = `\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${subject}</title>\n</head>\n<body style=\"margin: 0; padding: 0; background-color: #f8fafc;\">\n <div style=\"${styles.container}\">\n <div style=\"${styles.card}\">\n <h1 style=\"${styles.heading}\">Sign In to ${appName}</h1>\n \n <p style=\"${styles.paragraph}\">\n Hi ${greeting},\n </p>\n \n <p style=\"${styles.paragraph}\">\n We received a request to sign in to your ${appName} account. \n Click the button below to log in:\n </p>\n \n <div style=\"text-align: center;\">\n <a href=\"${magicLinkUrl}\" style=\"${styles.button}\">Sign In</a>\n </div>\n \n <p style=\"${styles.paragraph}\">\n Or copy and paste this link into your browser:\n </p>\n <p style=\"color: #3b82f6; word-break: break-all; font-size: 14px;\">\n ${magicLinkUrl}\n </p>\n \n <div style=\"${styles.warning}\">\n ⏰ This link will expire in 15 minutes for security reasons and can only be used once.\n </div>\n \n <div style=\"${styles.footer}\">\n <p style=\"margin: 0;\">\n If you didn't request this sign-in link, you can safely ignore this email. \n No action is needed.\n </p>\n </div>\n </div>\n </div>\n</body>\n</html>\n `.trim();\n\n const text = `\nSign In to ${appName}\n\nHi ${greeting},\n\nWe received a request to sign in to your ${appName} account.\n\nClick this link to log in:\n${magicLinkUrl}\n\nThis link will expire in 15 minutes for security reasons and can only be used once.\n\nIf you didn't request this sign-in link, you can safely ignore this email.\nNo action is needed.\n `.trim();\n\n return { subject,\nhtml,\ntext };\n}\n","/**\n * Admin User Operations\n *\n * Shared utilities and orchestration for admin-initiated user management\n * (user creation via REST API, password reset via admin panel).\n *\n * Hook resolution order:\n * 1. Collection-level hook (`auth.onCreateUser` on the collection) — closest to the data\n * 2. Backend-level hook (`AuthHooks.onAdminCreateUser`) — global override\n * 3. Built-in default — framework fallback\n */\n\nimport { randomBytes, createHash, randomInt } from \"node:crypto\";\nimport type { AuthRepository } from \"./interfaces\";\nimport type { EmailService, EmailConfig } from \"../email\";\nimport type { ResolvedAuthHooks } from \"./auth-hooks\";\nimport type { AuthCollectionConfig, AuthCollectionContext } from \"@rebasepro/types\";\nimport { getPasswordResetTemplate } from \"../email/templates\";\nimport { logger } from \"../utils/logger\";\n\n// ─── Shared Crypto Utilities ────────────────────────────────────────────────\n\n/**\n * Generate a cryptographically secure random password that meets strength requirements.\n *\n * 16 characters, guaranteed at least one uppercase, one lowercase, one digit.\n * Ambiguous characters (0, O, 1, l, I) are excluded.\n */\nexport function generateSecurePassword(): string {\n const upper = \"ABCDEFGHJKLMNPQRSTUVWXYZ\";\n const lower = \"abcdefghjkmnpqrstuvwxyz\";\n const digits = \"23456789\";\n const all = upper + lower + digits;\n\n const pick = (chars: string) => chars[randomInt(chars.length)];\n const parts = [pick(upper), pick(lower), pick(digits)];\n\n for (let i = parts.length; i < 16; i++) {\n parts.push(pick(all));\n }\n\n // Shuffle\n for (let i = parts.length - 1; i > 0; i--) {\n const j = randomInt(i + 1);\n [parts[i], parts[j]] = [parts[j], parts[i]];\n }\n return parts.join(\"\");\n}\n\n/**\n * Generate a cryptographically secure random token (80 hex characters).\n */\nexport function generateSecureToken(): string {\n return randomBytes(40).toString(\"hex\");\n}\n\n/**\n * Hash a token for database storage using SHA-256.\n */\nexport function hashToken(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n// ─── Admin User Creation ────────────────────────────────────────────────────\n\n/**\n * Context needed by admin user creation / password reset operations.\n */\nexport interface AdminUserContext {\n authRepo: AuthRepository;\n emailService?: EmailService;\n emailConfig?: EmailConfig;\n resolvedHooks: ResolvedAuthHooks;\n /** The parsed auth config from the collection (if `auth` is an object, not just `true`). */\n collectionAuthConfig?: AuthCollectionConfig;\n}\n\n/**\n * Result of preparing user values for admin-initiated creation.\n */\nexport interface AdminUserPrepareResult {\n /** Values ready for `driver.save()`. */\n values: Record<string, unknown>;\n /** The cleartext password (for returning to admin or sending via email). */\n clearPassword?: string;\n /** Whether the hook already handled the invitation email. */\n hookHandledEmail: boolean;\n /** Whether an invitation was sent (only relevant when hookHandledEmail is true). */\n invitationSent: boolean;\n}\n\n/**\n * Build the `AuthCollectionContext` facade from server internals.\n *\n * This is the simplified context exposed to collection-level auth hooks,\n * keeping them decoupled from internal interfaces like `AuthRepository`.\n */\nfunction buildCollectionContext(ctx: AdminUserContext): AuthCollectionContext {\n const isEmailConfigured = !!(ctx.emailService && ctx.emailService.isConfigured());\n\n return {\n hashPassword: (password: string) => ctx.resolvedHooks.hashPassword(password),\n sendEmail: isEmailConfigured\n ? (options) => ctx.emailService!.send(options)\n : undefined,\n emailConfigured: isEmailConfigured,\n appName: ctx.emailConfig?.appName || \"Rebase\",\n resetPasswordUrl: ctx.emailConfig?.resetPasswordUrl || \"\"\n };\n}\n\n/**\n * Prepare user values for an admin-initiated user creation.\n *\n * Resolution order:\n * 1. Collection-level `auth.onCreateUser` — closest to the data\n * 2. Backend-level `AuthHooks.onAdminCreateUser` — global override\n * 3. Built-in default — generate password → hash → normalize email\n *\n * The caller is responsible for persisting (via `driver.save()`).\n */\nexport async function prepareAdminUserValues(\n body: Record<string, unknown>,\n ctx: AdminUserContext\n): Promise<AdminUserPrepareResult> {\n const { resolvedHooks, collectionAuthConfig } = ctx;\n\n // 1. Collection-level hook (closest to the data)\n if (collectionAuthConfig?.onCreateUser) {\n const collectionCtx = buildCollectionContext(ctx);\n const hookResult = await collectionAuthConfig.onCreateUser(body, collectionCtx);\n return {\n values: hookResult.values,\n clearPassword: hookResult.temporaryPassword,\n hookHandledEmail: true,\n invitationSent: hookResult.invitationSent ?? false\n };\n }\n\n // 2. Backend-level hook (global override)\n if (resolvedHooks.onAdminCreateUser) {\n const hookResult = await resolvedHooks.onAdminCreateUser(body, {\n authRepo: ctx.authRepo,\n emailService: ctx.emailService,\n emailConfig: ctx.emailConfig,\n hashPassword: (password: string) => resolvedHooks.hashPassword(password)\n });\n return {\n values: hookResult.values,\n clearPassword: hookResult.temporaryPassword,\n hookHandledEmail: true,\n invitationSent: hookResult.invitationSent ?? false\n };\n }\n\n // 3. Built-in default\n const password = body.password as string | undefined;\n const clearPassword = password || generateSecurePassword();\n const passwordHash = await resolvedHooks.hashPassword(clearPassword);\n\n const values = { ...body };\n values.passwordHash = passwordHash;\n if (values.email) {\n values.email = (values.email as string).toLowerCase();\n }\n values.emailVerified = true;\n delete values.password;\n\n return {\n values,\n clearPassword: password ? undefined : clearPassword,\n hookHandledEmail: false,\n invitationSent: false\n };\n}\n\n/**\n * Handle post-creation work for admin-created users.\n *\n * Sends an invitation email (password-reset link) if email is configured\n * and no explicit password was provided. Falls back to returning the\n * temporary password if email fails or is not configured.\n */\nexport async function finalizeAdminUserCreation(\n entity: { id: string; values: Record<string, unknown> },\n clearPassword: string | undefined,\n ctx: AdminUserContext\n): Promise<{\n temporaryPassword?: string;\n invitationSent: boolean;\n}> {\n // If an explicit password was provided (clearPassword is undefined), nothing to do\n if (!clearPassword) {\n return { invitationSent: false };\n }\n\n const isEmailConfigured = !!(ctx.emailService && ctx.emailService.isConfigured());\n\n if (isEmailConfigured) {\n try {\n const token = generateSecureToken();\n const tokenHash = hashToken(token);\n const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours\n\n await ctx.authRepo.createPasswordResetToken(entity.id, tokenHash, expiresAt);\n\n const baseUrl = ctx.emailConfig?.resetPasswordUrl || \"\";\n const setPasswordUrl = `${baseUrl}/reset-password?token=${token}`;\n\n const appName = ctx.emailConfig?.appName || \"Rebase\";\n const templateFn = ctx.emailConfig?.templates?.passwordReset;\n const emailContent = templateFn\n ? templateFn(setPasswordUrl, { email: entity.values.email as string,\ndisplayName: entity.values.displayName as string })\n : getPasswordResetTemplate(setPasswordUrl, { email: entity.values.email as string,\ndisplayName: entity.values.displayName as string }, appName);\n\n await ctx.emailService!.send({\n to: entity.values.email as string,\n subject: emailContent.subject,\n html: emailContent.html,\n text: emailContent.text\n });\n return { invitationSent: true };\n } catch (emailError: unknown) {\n logger.error(\"Failed to send reset email\", { error: emailError instanceof Error ? emailError.message : emailError });\n // Fall back to returning the temporary password\n return { temporaryPassword: clearPassword,\ninvitationSent: false };\n }\n }\n\n // No email service — return the temporary password\n return { temporaryPassword: clearPassword,\ninvitationSent: false };\n}\n","import { scrypt, randomBytes, timingSafeEqual } from \"crypto\";\nimport { promisify } from \"util\";\n\nconst scryptAsync = promisify(scrypt);\n\n// Scrypt parameters (recommended values for 2024+)\nconst SALT_LENGTH = 32;\nconst KEY_LENGTH = 64;\nconst SCRYPT_PARAMS = { N: 16384,\nr: 8,\np: 1 };\n\nexport interface PasswordValidationResult {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Password requirements:\n * - Minimum 8 characters\n * - At least 1 uppercase letter\n * - At least 1 lowercase letter\n * - At least 1 number\n */\nexport function validatePasswordStrength(password: string): PasswordValidationResult {\n const errors: string[] = [];\n\n if (password.length < 8) {\n errors.push(\"Password must be at least 8 characters long\");\n }\n\n if (!/[A-Z]/.test(password)) {\n errors.push(\"Password must contain at least one uppercase letter\");\n }\n\n if (!/[a-z]/.test(password)) {\n errors.push(\"Password must contain at least one lowercase letter\");\n }\n\n if (!/[0-9]/.test(password)) {\n errors.push(\"Password must contain at least one number\");\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n}\n\n/**\n * Hash a password using Node's built-in scrypt\n * Returns format: salt:hash (both hex encoded)\n */\nexport async function hashPassword(password: string): Promise<string> {\n const salt = randomBytes(SALT_LENGTH);\n const derivedKey = await scryptAsync(password, salt, KEY_LENGTH) as Buffer;\n return `${salt.toString(\"hex\")}:${derivedKey.toString(\"hex\")}`;\n}\n\n/**\n * Verify a password against a scrypt hash\n * Expects format: salt:hash (both hex encoded)\n */\nexport async function verifyPassword(password: string, storedHash: string): Promise<boolean> {\n const [saltHex, hashHex] = storedHash.split(\":\");\n if (!saltHex || !hashHex) {\n return false;\n }\n\n const salt = Buffer.from(saltHex, \"hex\");\n const storedKey = Buffer.from(hashHex, \"hex\");\n\n const derivedKey = await scryptAsync(password, salt, KEY_LENGTH) as Buffer;\n\n // Use timing-safe comparison to prevent timing attacks\n return timingSafeEqual(derivedKey, storedKey);\n}\n","/**\n * AuthHooks\n *\n * Customize specific behaviors of the built-in Rebase auth system.\n *\n * Each method replaces one piece of the default implementation.\n * Unset methods fall through to the built-in defaults (scrypt passwords,\n * standard validation rules, etc.).\n *\n * This interface is intentionally open for extension — new hooks\n * can be added as optional methods without breaking existing configurations.\n *\n * @example bcrypt password support\n * ```ts\n * import bcrypt from \"bcrypt\";\n *\n * const hooks: AuthHooks = {\n * hashPassword: (pw) => bcrypt.hash(pw, 12),\n * verifyPassword: (pw, hash) => bcrypt.compare(pw, hash),\n * validatePasswordStrength: (pw) => ({\n * valid: pw.length >= 6,\n * errors: pw.length < 6 ? [\"Password must be at least 6 characters\"] : []\n * })\n * };\n * ```\n *\n * @example Override the entire login credential check\n * ```ts\n * const hooks: AuthHooks = {\n * verifyCredentials: async (email, password, repo) => {\n * const user = await repo.getUserByEmail(email);\n * if (!user || !user.passwordHash) return null;\n * const valid = await myCustomVerify(password, user.passwordHash);\n * return valid ? user : null;\n * }\n * };\n * ```\n */\n\nimport {\n hashPassword as defaultHashPassword,\n verifyPassword as defaultVerifyPassword,\n validatePasswordStrength as defaultValidatePasswordStrength\n} from \"./password\";\nimport type { PasswordValidationResult } from \"./password\";\nimport type { AuthRepository, UserData, CreateUserData } from \"./interfaces\";\nimport type { EmailService, EmailConfig } from \"../email\";\nimport type { AuthResponsePayload, TransformAuthResponseContext } from \"@rebasepro/types\";\n\n/**\n * Authentication method identifier for lifecycle hooks.\n */\nexport type AuthMethod = \"login\" | \"register\" | \"oauth\" | \"refresh\" | \"password-reset\" | \"anonymous\" | \"magic-link\" | \"mfa\";\n\n/**\n * Hook specific parts of the built-in Rebase auth implementation.\n *\n * Every method is optional. The built-in defaults apply for any method\n * that is not provided.\n */\nexport interface AuthHooks {\n // ─── Password Operations ──────────────────────────────────────────────\n\n /**\n * Hash a cleartext password for storage.\n *\n * Default: scrypt (Node.js crypto, 64-byte key, random 32-byte salt).\n *\n * @param password - The cleartext password.\n * @returns The hashed password string (format is implementation-defined).\n */\n hashPassword?(password: string): Promise<string>;\n\n /**\n * Verify a cleartext password against a stored hash.\n *\n * Default: scrypt verification with timing-safe comparison.\n *\n * @param password - The cleartext password to check.\n * @param storedHash - The hash string retrieved from the database.\n * @returns `true` if the password matches the hash.\n */\n verifyPassword?(password: string, storedHash: string): Promise<boolean>;\n\n /**\n * Validate password strength before hashing.\n *\n * Default: minimum 8 characters, at least one uppercase, one lowercase, one digit.\n *\n * @param password - The cleartext password to validate.\n * @returns Validation result with `valid` flag and error messages.\n */\n validatePasswordStrength?(password: string): PasswordValidationResult;\n\n // ─── Credential Resolution ────────────────────────────────────────────\n\n /**\n * Override the complete credential verification during email/password login.\n *\n * When set, this replaces the default flow:\n * 1. Look up user by email\n * 2. Verify password hash\n *\n * The auth repository is provided for database access. Return the user\n * data if credentials are valid, or `null` to reject the login.\n *\n * Default: `getUserByEmail(email)` + `verifyPassword(password, user.passwordHash)`.\n */\n verifyCredentials?(email: string, password: string, repo: AuthRepository): Promise<UserData | null>;\n\n // ─── Lifecycle Hooks ──────────────────────────────────────────────────\n\n /**\n * Called after any successful authentication event (login, register,\n * OAuth, token refresh, password reset).\n *\n * Use for audit logging, syncing external state, updating\n * last-login timestamps, etc.\n *\n * This is fire-and-forget — errors are logged but do not fail the request.\n */\n onAuthenticated?(user: UserData, method: AuthMethod): Promise<void>;\n\n /**\n * Called before a new user is created (registration or admin creation).\n *\n * Return modified data to alter what gets stored, or throw an error\n * to reject the creation entirely.\n *\n * Default: passthrough (returns data unchanged).\n */\n beforeUserCreate?(data: CreateUserData): Promise<CreateUserData>;\n\n /**\n * Called after a new user is created.\n *\n * Use for provisioning external resources, sending notifications\n * to third-party systems, etc.\n *\n * This is fire-and-forget — errors are logged but do not fail the request.\n */\n afterUserCreate?(user: UserData): Promise<void>;\n\n // ─── Extended Lifecycle Hooks ─────────────────────────────────────────\n\n /**\n * Pre-login validation. Called before credential verification.\n *\n * Throw an error to reject the login attempt (e.g. for account lockout,\n * IP-based restrictions, etc.).\n */\n beforeLogin?(email: string, method: AuthMethod): Promise<void>;\n\n /**\n * Post-logout cleanup.\n *\n * Called after a user's session has been invalidated.\n * Use for audit logging, cleanup of temporary resources, etc.\n *\n * This is fire-and-forget — errors are logged but do not fail the request.\n */\n afterLogout?(userId: string): Promise<void>;\n\n /**\n * Called after successful MFA verification.\n *\n * Use for audit logging, notifying external systems, etc.\n *\n * This is fire-and-forget — errors are logged but do not fail the request.\n */\n onMfaVerified?(userId: string, factorId: string): Promise<void>;\n\n /**\n * Customize JWT access token claims before signing.\n *\n * Return the modified claims object. The returned claims are merged\n * into the JWT payload alongside standard claims (userId, roles).\n *\n * @param claims - The default claims that would be included.\n * @param user - The authenticated user data.\n * @returns Modified claims to include in the JWT.\n */\n customizeAccessToken?(claims: Record<string, unknown>, user: UserData): Promise<Record<string, unknown>>;\n\n /**\n * Transform the auth response before sending it to the client.\n *\n * Called after successful login, register, refresh, OAuth, anonymous,\n * magic-link, and MFA flows. The hook receives the fully-formed\n * response and returns a (potentially enriched) response.\n *\n * Use cases:\n * - Inject tokens from external auth systems (custom provider tokens, etc.)\n * - Add project-specific metadata to the response\n * - Enrich the user object with data from external sources\n *\n * The hook runs in the request path — keep it fast.\n * Heavy work should be offloaded to `onAuthenticated` (fire-and-forget).\n */\n transformAuthResponse?(\n response: AuthResponsePayload,\n context: TransformAuthResponseContext\n ): Promise<AuthResponsePayload>;\n\n /**\n * Called after a successful password reset.\n *\n * Use for audit logging, sending confirmation notifications, etc.\n *\n * This is fire-and-forget — errors are logged but do not fail the request.\n */\n onPasswordReset?(userId: string): Promise<void>;\n\n /**\n * Called before a user is deleted.\n *\n * Throw an error to prevent deletion (e.g. for users with active\n * subscriptions, pending transactions, etc.).\n */\n beforeUserDelete?(userId: string): Promise<void>;\n\n /**\n * Called after a user is deleted.\n *\n * Use for cleaning up external resources, audit logging, etc.\n *\n * This is fire-and-forget — errors are logged but do not fail the request.\n */\n afterUserDelete?(userId: string): Promise<void>;\n\n /**\n * Optional hook to customize or override the default user creation flow via the admin panel/REST API.\n * When provided, this replaces the built-in password generation, hashing, and invitation email logic.\n */\n onAdminCreateUser?(\n values: Record<string, unknown>,\n ctx: {\n authRepo: AuthRepository;\n emailService?: EmailService;\n emailConfig?: EmailConfig;\n hashPassword: (password: string) => Promise<string>;\n }\n ): Promise<{\n values: Record<string, unknown>;\n temporaryPassword?: string;\n invitationSent?: boolean;\n }>;\n\n /**\n * Optional hook to customize or override the default password reset flow via the admin panel.\n * When provided, this replaces the built-in password reset token generation, hashing, and email logic.\n */\n onAdminResetPassword?(\n userId: string,\n ctx: {\n authRepo: AuthRepository;\n emailService?: EmailService;\n emailConfig?: EmailConfig;\n }\n ): Promise<{\n temporaryPassword?: string;\n invitationSent?: boolean;\n }>;\n}\n\n/**\n * Resolved auth hooks — password operations are guaranteed to exist,\n * all other hooks are passed through as-is (optional).\n *\n * Created by `resolveAuthHooks()` which merges user hooks\n * with built-in defaults.\n *\n * Consumers should use the resolved object exclusively —\n * never access the raw `AuthHooks` directly.\n */\nexport type ResolvedAuthHooks =\n Required<Pick<AuthHooks, \"hashPassword\" | \"verifyPassword\" | \"validatePasswordStrength\">>\n & Omit<AuthHooks, \"hashPassword\" | \"verifyPassword\" | \"validatePasswordStrength\">;\n\n/**\n * Merge user-provided hooks with the built-in defaults to produce\n * a complete set of resolved hooks.\n *\n * This is the single point where defaults are applied — all consumers\n * call this once and use the resolved hooks throughout.\n */\nexport function resolveAuthHooks(hooks?: AuthHooks): ResolvedAuthHooks {\n return {\n ...hooks,\n\n hashPassword: hooks?.hashPassword\n ?? defaultHashPassword,\n\n verifyPassword: hooks?.verifyPassword\n ?? defaultVerifyPassword,\n\n validatePasswordStrength: hooks?.validatePasswordStrength\n ?? defaultValidatePasswordStrength\n };\n}\n","import { MiddlewareHandler } from \"hono\";\nimport { HonoEnv } from \"../api/types\";\n\n/**\n * In-memory sliding-window rate limiter for Hono.\n *\n * Suitable for single-instance and moderate-scale deployments.\n * For multi-instance setups, consider a shared store\n * (e.g. PostgreSQL-backed counters or an external rate-limit service).\n */\n\ninterface RateLimitEntry {\n timestamps: number[];\n}\n\ninterface RateLimiterOptions {\n /** Time window in milliseconds (default: 15 minutes) */\n windowMs?: number;\n /** Maximum requests per window (default: 100) */\n limit?: number;\n /** Key generator function. Defaults to IP-based keying. */\n keyGenerator?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => string;\n /** Custom message for rate limit responses */\n message?: string;\n}\n\n/**\n * Create a rate-limiting middleware.\n *\n * Uses a sliding window algorithm: only timestamps within the last\n * `windowMs` milliseconds are counted. Old entries are garbage-collected\n * every `windowMs` to prevent unbounded memory growth.\n */\nexport function createRateLimiter(options: RateLimiterOptions = {}): MiddlewareHandler<HonoEnv> {\n const {\n windowMs = 15 * 60 * 1000,\n limit = 100,\n keyGenerator = defaultKeyGenerator,\n message = \"Too many requests, please try again later.\"\n } = options;\n\n const store = new Map<string, RateLimitEntry>();\n\n // Periodic cleanup to prevent memory leak from expired entries\n const cleanupInterval = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of store.entries()) {\n entry.timestamps = entry.timestamps.filter(t => now - t < windowMs);\n if (entry.timestamps.length === 0) {\n store.delete(key);\n }\n }\n }, windowMs);\n\n // Allow the Node.js process to exit even if the interval is still running\n if (cleanupInterval.unref) {\n cleanupInterval.unref();\n }\n\n return async (c, next) => {\n const key = keyGenerator(c);\n const now = Date.now();\n\n let entry = store.get(key);\n if (!entry) {\n entry = { timestamps: [] };\n store.set(key, entry);\n }\n\n // Remove timestamps outside the current window\n entry.timestamps = entry.timestamps.filter(t => now - t < windowMs);\n\n if (entry.timestamps.length >= limit) {\n const retryAfterMs = entry.timestamps[0] + windowMs - now;\n const retryAfterSec = Math.ceil(retryAfterMs / 1000);\n\n c.header(\"Retry-After\", String(retryAfterSec));\n c.header(\"X-RateLimit-Limit\", String(limit));\n c.header(\"X-RateLimit-Remaining\", \"0\");\n c.header(\"X-RateLimit-Reset\", String(Math.ceil((now + retryAfterMs) / 1000)));\n\n return c.json({\n error: {\n message,\n code: \"RATE_LIMITED\"\n }\n }, 429);\n }\n\n entry.timestamps.push(now);\n\n // Set rate limit headers\n c.header(\"X-RateLimit-Limit\", String(limit));\n c.header(\"X-RateLimit-Remaining\", String(limit - entry.timestamps.length));\n\n return next();\n };\n}\n\n/**\n * Default key generator: extract client IP from standard headers.\n */\nfunction defaultKeyGenerator(c: Parameters<MiddlewareHandler<HonoEnv>>[0]): string {\n const forwardedFor = c.req.header(\"x-forwarded-for\");\n if (forwardedFor) {\n const ips = forwardedFor.split(\",\");\n // The leftmost IP can be easily spoofed by the client in the initial request.\n // Reverse proxies append to the right. We take the rightmost IP as the most\n // reliable indicator of the true client IP (the one closest to our server).\n return ips[ips.length - 1].trim();\n }\n return c.req.header(\"x-real-ip\") || \"unknown\";\n}\n\n/**\n * Pre-configured rate limiter for general auth endpoints (login, register).\n * 200 requests per 15 minutes per IP.\n */\nexport const defaultAuthLimiter = createRateLimiter({\n windowMs: 15 * 60 * 1000,\n limit: 200,\n message: \"Too many authentication attempts, please try again later.\"\n});\n\n/**\n * Pre-configured strict rate limiter for sensitive endpoints (password reset, verification).\n * 50 requests per 15 minutes per IP.\n */\nexport const strictAuthLimiter = createRateLimiter({\n windowMs: 15 * 60 * 1000,\n limit: 50,\n message: \"Too many requests to this sensitive endpoint, please try again later.\"\n});\n\n/**\n * Key generator for API-key-based rate limiting.\n *\n * Uses the API key ID (from `c.get(\"apiKey\")`) as the rate limit key.\n * Falls back to IP-based keying when the request is not authenticated\n * via an API key.\n */\nexport function apiKeyKeyGenerator(c: Parameters<MiddlewareHandler<HonoEnv>>[0]): string {\n const apiKey = c.get(\"apiKey\") as { id: string } | undefined;\n if (apiKey) {\n return `api-key:${apiKey.id}`;\n }\n return defaultKeyGenerator(c);\n}\n\n/**\n * Create a rate limiter specifically for API key requests.\n *\n * When a request is authenticated via an API key that has a `rate_limit`\n * configured, this limiter enforces per-key limits using the key's ID\n * as the rate limit bucket.\n *\n * @param defaultLimit - Fallback limit when the key has no `rate_limit` set.\n * @param windowMs - Time window in milliseconds (default: 15 minutes).\n */\nexport function createApiKeyRateLimiter(\n defaultLimit = 1000,\n windowMs = 15 * 60 * 1000\n): MiddlewareHandler<HonoEnv> {\n // We maintain a single shared store keyed by API key ID.\n // The actual limit is resolved per-request from the key's metadata.\n const store = new Map<string, { timestamps: number[] }>();\n\n const cleanupInterval = setInterval(() => {\n const now = Date.now();\n for (const [key, entry] of store.entries()) {\n entry.timestamps = entry.timestamps.filter(t => now - t < windowMs);\n if (entry.timestamps.length === 0) {\n store.delete(key);\n }\n }\n }, windowMs);\n\n if (cleanupInterval.unref) {\n cleanupInterval.unref();\n }\n\n return async (c, next) => {\n const apiKey = c.get(\"apiKey\") as { id: string; rate_limit: number | null } | undefined;\n if (!apiKey) {\n // Not an API key request — skip this limiter\n return next();\n }\n\n const limit = apiKey.rate_limit ?? defaultLimit;\n const key = `api-key:${apiKey.id}`;\n const now = Date.now();\n\n let entry = store.get(key);\n if (!entry) {\n entry = { timestamps: [] };\n store.set(key, entry);\n }\n\n entry.timestamps = entry.timestamps.filter(t => now - t < windowMs);\n\n if (entry.timestamps.length >= limit) {\n const retryAfterMs = entry.timestamps[0] + windowMs - now;\n const retryAfterSec = Math.ceil(retryAfterMs / 1000);\n\n c.header(\"Retry-After\", String(retryAfterSec));\n c.header(\"X-RateLimit-Limit\", String(limit));\n c.header(\"X-RateLimit-Remaining\", \"0\");\n c.header(\"X-RateLimit-Reset\", String(Math.ceil((now + retryAfterMs) / 1000)));\n\n return c.json({\n error: {\n message: \"API key rate limit exceeded, please try again later.\",\n code: \"RATE_LIMITED\"\n }\n }, 429);\n }\n\n entry.timestamps.push(now);\n\n c.header(\"X-RateLimit-Limit\", String(limit));\n c.header(\"X-RateLimit-Remaining\", String(limit - entry.timestamps.length));\n\n return next();\n };\n}\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n // from the output body where it would otherwise leak. The id is preserved\n // implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n const proto = Object.getPrototypeOf(inst);\n let installed = _installedGroups.get(proto);\n if (!installed) {\n installed = new Set();\n _installedGroups.set(proto, installed);\n }\n if (installed.has(group))\n return;\n installed.add(group);\n for (const key in methods) {\n const fn = methods[key];\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const bound = fn.bind(this);\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: bound,\n });\n return bound;\n },\n set(v) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: v,\n });\n },\n });\n }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // Parse-family is intentionally kept as per-instance closures: these are\n // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n // ~12 closure allocations per schema but get monomorphic call sites and\n // detached usage that \"just works\".\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // All builder methods are placed on the internal prototype as lazy-bind\n // getters. On first access per-instance, a bound thunk is allocated and\n // cached as an own property; subsequent accesses skip the getter. This\n // means: no per-instance allocation for unused methods, full\n // detachability preserved (`const m = schema.optional; m()` works), and\n // shared underlying function references across all instances.\n _installLazyMethods(inst, \"ZodType\", {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data)\n // returns a clone with `data` registered. The mapped type picks\n // up the second overload, so we accept variadic any-args and\n // return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn) {\n return fn(this);\n },\n });\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n _installLazyMethods(inst, \"_ZodString\", {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n _installLazyMethods(inst, \"ZodNumber\", {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n });\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n _installLazyMethods(inst, \"ZodArray\", {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n });\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n _installLazyMethods(inst, \"ZodObject\", {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n return this.clone({ ...this._zod.def, catchall: catchall });\n },\n passthrough() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n loose() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n strict() {\n return this.clone({ ...this._zod.def, catchall: never() });\n },\n strip() {\n return this.clone({ ...this._zod.def, catchall: undefined });\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n });\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n payload.value = output;\n payload.fallback = true;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n","/**\n * TOTP (Time-based One-Time Password) implementation.\n *\n * Pure Node.js crypto implementation — no external dependencies required.\n * Implements RFC 6238 (TOTP) and RFC 4226 (HOTP).\n */\n\nimport { createHmac, randomBytes, createHash } from \"crypto\";\n\n// ─── Base32 Encoding/Decoding ────────────────────────────────────────────────\n\nconst BASE32_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n\n/**\n * Encode a Buffer to Base32 string (RFC 4648)\n */\nexport function base32Encode(buffer: Buffer): string {\n let bits = 0;\n let value = 0;\n let output = \"\";\n\n for (let i = 0; i < buffer.length; i++) {\n value = (value << 8) | buffer[i];\n bits += 8;\n\n while (bits >= 5) {\n output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];\n bits -= 5;\n }\n }\n\n if (bits > 0) {\n output += BASE32_ALPHABET[(value << (5 - bits)) & 31];\n }\n\n return output;\n}\n\n/**\n * Decode a Base32 string to Buffer\n */\nexport function base32Decode(encoded: string): Buffer {\n const cleanInput = encoded.replace(/=+$/, \"\").toUpperCase();\n const bytes: number[] = [];\n let bits = 0;\n let value = 0;\n\n for (let i = 0; i < cleanInput.length; i++) {\n const index = BASE32_ALPHABET.indexOf(cleanInput[i]);\n if (index === -1) continue;\n\n value = (value << 5) | index;\n bits += 5;\n\n if (bits >= 8) {\n bytes.push((value >>> (bits - 8)) & 255);\n bits -= 8;\n }\n }\n\n return Buffer.from(bytes);\n}\n\n// ─── HOTP/TOTP ───────────────────────────────────────────────────────────────\n\n/**\n * Generate an HOTP value per RFC 4226\n */\nfunction generateHotp(secret: Buffer, counter: bigint): string {\n const hmac = createHmac(\"sha1\", secret);\n const counterBuffer = Buffer.alloc(8);\n counterBuffer.writeBigInt64BE(counter);\n hmac.update(counterBuffer);\n const hash = hmac.digest();\n\n const offset = hash[hash.length - 1] & 0x0f;\n const code =\n (((hash[offset] & 0x7f) << 24) |\n (hash[offset + 1] << 16) |\n (hash[offset + 2] << 8) |\n hash[offset + 3]) %\n 1000000;\n\n return code.toString().padStart(6, \"0\");\n}\n\n/**\n * Generate a TOTP value for the current time step\n */\nexport function generateTotp(secret: Buffer, timeStep = 30): string {\n const counter = BigInt(Math.floor(Date.now() / 1000 / timeStep));\n return generateHotp(secret, counter);\n}\n\n/**\n * Verify a TOTP token with a configurable time window\n *\n * @param secret - The shared secret as a Buffer\n * @param token - The 6-digit TOTP code to verify\n * @param window - Number of time steps to check on each side (default: 1)\n * @returns true if the token is valid within the window\n */\nexport function verifyTotp(secret: Buffer, token: string, window = 1): boolean {\n const timeStep = 30;\n const counter = BigInt(Math.floor(Date.now() / 1000 / timeStep));\n for (let i = -window; i <= window; i++) {\n if (generateHotp(secret, counter + BigInt(i)) === token) {\n return true;\n }\n }\n return false;\n}\n\n// ─── Secret Generation ───────────────────────────────────────────────────────\n\n/**\n * Generate a new TOTP secret and return the setup information\n *\n * @param issuer - The issuer name (app name) for the QR code\n * @param accountName - The account identifier (usually email)\n * @returns Object with base32 secret and otpauth URI\n */\nexport function generateTotpSecret(issuer: string, accountName: string): {\n secret: string;\n uri: string;\n} {\n // Generate a 20-byte random secret (160 bits, recommended by RFC 4226)\n const secretBuffer = randomBytes(20);\n const secret = base32Encode(secretBuffer);\n\n // Build otpauth:// URI for QR code generation\n const encodedIssuer = encodeURIComponent(issuer);\n const encodedAccount = encodeURIComponent(accountName);\n const uri = `otpauth://totp/${encodedIssuer}:${encodedAccount}?secret=${secret}&issuer=${encodedIssuer}&algorithm=SHA1&digits=6&period=30`;\n\n return { secret,\nuri };\n}\n\n// ─── Recovery Codes ──────────────────────────────────────────────────────────\n\n/**\n * Generate a set of one-time recovery codes\n *\n * @param count - Number of recovery codes to generate (default: 10)\n * @returns Array of formatted recovery code strings (e.g. \"A1B2C-D3E4F\")\n */\nexport function generateRecoveryCodes(count = 10): string[] {\n return Array.from({ length: count }, () => {\n const raw = randomBytes(5).toString(\"hex\").toUpperCase();\n const parts = raw.match(/.{1,5}/g);\n return parts ? parts.join(\"-\") : raw;\n });\n}\n\n/**\n * Hash a recovery code for storage\n */\nexport function hashRecoveryCode(code: string): string {\n return createHash(\"sha256\").update(code.replace(/-/g, \"\").toUpperCase()).digest(\"hex\");\n}\n","/**\n * Envelope encryption for TOTP secrets using AES-256-GCM.\n *\n * - Derives a 32-byte key via SHA-256 from `MFA_ENCRYPTION_KEY` or `JWT_SECRET`.\n * - Generates a random 12-byte IV per encryption call.\n * - Returns ciphertexts in the format `iv_hex:authTag_hex:ciphertext_hex`.\n *\n * @module\n */\n\nimport { createCipheriv, createDecipheriv, createHash, randomBytes } from \"crypto\";\nimport { logger } from \"../utils/logger\";\n\nconst ALGORITHM = \"aes-256-gcm\";\nconst IV_BYTES = 12;\nconst AUTH_TAG_LENGTH = 16;\n\n/**\n * Resolve the raw key string from environment variables.\n *\n * Prefers `MFA_ENCRYPTION_KEY`; falls back to `JWT_SECRET` with a warning.\n * Throws if neither is set.\n */\nfunction resolveKeyString(): string {\n const explicit = process.env.MFA_ENCRYPTION_KEY;\n if (explicit) {\n return explicit;\n }\n\n const fallback = process.env.JWT_SECRET;\n if (fallback) {\n logger.warn(\n \"[MFA-Crypto] MFA_ENCRYPTION_KEY is not set — falling back to JWT_SECRET. \" +\n \"Set a dedicated MFA_ENCRYPTION_KEY for production.\"\n );\n return fallback;\n }\n\n throw new Error(\n \"Cannot encrypt TOTP secret: neither MFA_ENCRYPTION_KEY nor JWT_SECRET is configured.\"\n );\n}\n\n/**\n * Derive a deterministic 32-byte AES-256 key from the raw secret string.\n */\nfunction deriveKey(raw: string): Buffer {\n return createHash(\"sha256\").update(raw).digest();\n}\n\n/**\n * Encrypt a plaintext TOTP secret.\n *\n * @param plaintext - The Base32 TOTP secret to encrypt.\n * @returns A string in the format `iv_hex:authTag_hex:ciphertext_hex`.\n */\nexport function encryptTotpSecret(plaintext: string): string {\n const key = deriveKey(resolveKeyString());\n const iv = randomBytes(IV_BYTES);\n\n const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });\n const encrypted = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n const authTag = cipher.getAuthTag();\n\n return `${iv.toString(\"hex\")}:${authTag.toString(\"hex\")}:${encrypted.toString(\"hex\")}`;\n}\n\n/**\n * Decrypt a previously encrypted TOTP secret.\n *\n * @param ciphertext - A string in the format `iv_hex:authTag_hex:ciphertext_hex`.\n * @returns The original Base32 TOTP secret.\n */\nexport function decryptTotpSecret(ciphertext: string): string {\n const parts = ciphertext.split(\":\");\n if (parts.length !== 3) {\n throw new Error(\"Invalid encrypted TOTP secret format — expected iv:authTag:ciphertext\");\n }\n\n const [ivHex, authTagHex, encryptedHex] = parts;\n const key = deriveKey(resolveKeyString());\n const iv = Buffer.from(ivHex, \"hex\");\n const authTag = Buffer.from(authTagHex, \"hex\");\n const encrypted = Buffer.from(encryptedHex, \"hex\");\n\n const decipher = createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });\n decipher.setAuthTag(authTag);\n\n const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);\n return decrypted.toString(\"utf8\");\n}\n","import { Hono } from \"hono\";\nimport { z } from \"zod\";\nimport { ApiError } from \"../api/errors\";\nimport { HonoEnv } from \"../api/types\";\nimport { requireAuth } from \"./middleware\";\nimport { logger } from \"../utils/logger\";\nimport {\n generateTotpSecret,\n verifyTotp,\n base32Decode,\n generateRecoveryCodes,\n hashRecoveryCode\n} from \"./mfa\";\nimport { encryptTotpSecret, decryptTotpSecret } from \"./mfa-crypto\";\nimport {\n generateAccessToken,\n generateRefreshToken,\n hashRefreshToken,\n getRefreshTokenExpiry,\n getAccessTokenExpiry,\n type AccessTokenPayload\n} from \"./jwt\";\nimport type { AuthModuleConfig } from \"./routes\";\nimport { resolveAuthHooks } from \"./auth-hooks\";\nimport type { AuthResponsePayload, TransformAuthResponseContext } from \"@rebasepro/types\";\n\nexport function mountMfaRoutes(\n router: Hono<HonoEnv>,\n config: AuthModuleConfig,\n ops: ReturnType<typeof resolveAuthHooks>,\n parseBody: <T>(schema: z.ZodSchema<T>, body: unknown) => T,\n applyTransformHook?: (\n response: AuthResponsePayload,\n method: TransformAuthResponseContext[\"method\"],\n request: Request,\n userId: string\n ) => Promise<AuthResponsePayload>\n): void {\n const authRepo = config.authRepo;\n const emailConfig = config.emailConfig;\n\n /**\n * POST /auth/mfa/enroll\n * Start MFA enrollment: generate TOTP secret and recovery codes\n */\n router.post(\"/mfa/enroll\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const body = (await c.req.json().catch(() => ({}))) as Record<string, unknown>;\n const friendlyName = typeof body.friendlyName === \"string\" ? body.friendlyName : undefined;\n const issuer = typeof body.issuer === \"string\" ? body.issuer : emailConfig?.appName || \"Rebase\";\n\n // Get user for account name\n const user = await authRepo.getUserById(userCtx.userId);\n if (!user) {\n throw ApiError.notFound(\"User not found\");\n }\n\n // Generate TOTP secret\n const { secret, uri } = generateTotpSecret(issuer, user.email);\n\n // Encrypt the TOTP secret before storage (AES-256-GCM envelope encryption)\n const encryptedSecret = encryptTotpSecret(secret);\n const factor = await authRepo.createMfaFactor(\n user.id,\n \"totp\",\n encryptedSecret,\n friendlyName\n );\n\n // Generate recovery codes\n const codes = generateRecoveryCodes(10);\n const codeHashes = codes.map(hashRecoveryCode);\n await authRepo.createRecoveryCodes(user.id, codeHashes);\n\n return c.json(\n {\n factor: {\n id: factor.id,\n factorType: factor.factorType,\n friendlyName: factor.friendlyName\n },\n totp: {\n secret,\n uri,\n qrUri: uri\n },\n recoveryCodes: codes\n },\n 201\n );\n });\n\n /**\n * POST /auth/mfa/verify\n * Verify TOTP code to complete MFA enrollment\n */\n router.post(\"/mfa/verify\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const verifySchema = z.object({\n factorId: z.string().min(1, \"Factor ID is required\"),\n code: z.string().length(6, \"Code must be 6 digits\")\n });\n const { factorId, code } = parseBody(verifySchema, await c.req.json());\n\n // Get the factor\n const factor = await authRepo.getMfaFactorById(factorId);\n if (!factor || factor.userId !== userCtx.userId) {\n throw ApiError.notFound(\"MFA factor not found\");\n }\n\n if (factor.verified) {\n throw ApiError.badRequest(\"Factor is already verified\", \"ALREADY_VERIFIED\");\n }\n\n // Decrypt and verify the TOTP code\n const decryptedSecret = decryptTotpSecret(factor.secretEncrypted);\n const secretBuffer = base32Decode(decryptedSecret);\n const isValid = verifyTotp(secretBuffer, code);\n\n if (!isValid) {\n throw ApiError.unauthorized(\"Invalid TOTP code\", \"INVALID_CODE\");\n }\n\n // Mark factor as verified\n await authRepo.verifyMfaFactor(factorId);\n\n return c.json({\n success: true,\n message: \"MFA factor verified and enrolled\"\n });\n });\n\n /**\n * POST /auth/mfa/challenge\n * Create an MFA challenge during login (user has MFA enrolled)\n */\n router.post(\"/mfa/challenge\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const challengeSchema = z.object({\n factorId: z.string().min(1, \"Factor ID is required\")\n });\n const { factorId } = parseBody(challengeSchema, await c.req.json());\n\n // Verify the factor belongs to this user and is verified\n const factor = await authRepo.getMfaFactorById(factorId);\n if (!factor || factor.userId !== userCtx.userId) {\n throw ApiError.notFound(\"MFA factor not found\");\n }\n\n if (!factor.verified) {\n throw ApiError.badRequest(\"MFA factor is not yet verified\", \"FACTOR_NOT_VERIFIED\");\n }\n\n const ipAddress = c.req.header(\"x-forwarded-for\") || \"unknown\";\n const challenge = await authRepo.createMfaChallenge(factorId, ipAddress);\n\n return c.json({\n challengeId: challenge.id,\n factorId: challenge.factorId,\n expiresAt: new Date(Date.now() + 5 * 60 * 1000).toISOString()\n });\n });\n\n /**\n * POST /auth/mfa/challenge/verify\n * Verify a TOTP code for an active challenge, upgrade aal1 → aal2\n */\n router.post(\"/mfa/challenge/verify\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const challengeVerifySchema = z.object({\n challengeId: z.string().min(1, \"Challenge ID is required\"),\n code: z.string().min(1, \"Code is required\")\n });\n const { challengeId, code } = parseBody(challengeVerifySchema, await c.req.json());\n\n // Find the challenge\n const challenge = await authRepo.getMfaChallengeById(challengeId);\n if (!challenge) {\n throw ApiError.badRequest(\"Invalid or expired challenge\", \"INVALID_CHALLENGE\");\n }\n\n // Get the factor and verify ownership\n const factor = await authRepo.getMfaFactorById(challenge.factorId);\n if (!factor || factor.userId !== userCtx.userId) {\n throw ApiError.notFound(\"MFA factor not found\");\n }\n\n // Try TOTP verification first (standard 6-digit codes)\n const decryptedSecret = decryptTotpSecret(factor.secretEncrypted);\n const secretBuffer = base32Decode(decryptedSecret);\n let isValid = verifyTotp(secretBuffer, code);\n\n // Fall back to recovery code verification if TOTP didn't match\n if (!isValid) {\n const codeHash = hashRecoveryCode(code);\n isValid = await authRepo.useRecoveryCode(userCtx.userId, codeHash);\n }\n\n if (!isValid) {\n throw ApiError.unauthorized(\"Invalid verification code\", \"INVALID_CODE\");\n }\n\n // Mark challenge as verified\n await authRepo.verifyMfaChallenge(challengeId);\n\n // Generate new access token with aal2\n const roles = await authRepo.getUserRoles(userCtx.userId);\n const roleIds = roles.map((r) => r.id);\n const accessToken = generateAccessToken(userCtx.userId, roleIds, \"aal2\");\n const refreshToken = generateRefreshToken();\n\n // Create new refresh token\n await authRepo.createRefreshToken(\n userCtx.userId,\n hashRefreshToken(refreshToken),\n getRefreshTokenExpiry(),\n c.req.header(\"user-agent\") || \"unknown\",\n c.req.header(\"x-forwarded-for\") || \"unknown\"\n );\n\n // Fire onMfaVerified hook\n if (ops.onMfaVerified) {\n ops.onMfaVerified(userCtx.userId, factor.id).catch((err) => {\n logger.error(\"[AuthHooks] onMfaVerified error\", {\n error: err instanceof Error ? err.message : err\n });\n });\n }\n\n let mfaResponse: AuthResponsePayload = {\n tokens: {\n accessToken,\n refreshToken,\n accessTokenExpiresAt: getAccessTokenExpiry()\n }\n };\n if (applyTransformHook) {\n mfaResponse = await applyTransformHook(mfaResponse, \"mfa\", c.req.raw, userCtx.userId);\n }\n return c.json(mfaResponse);\n });\n\n /**\n * GET /auth/mfa/factors\n * List enrolled MFA factors for the current user\n */\n router.get(\"/mfa/factors\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const factors = await authRepo.getMfaFactors(userCtx.userId);\n return c.json({\n factors: factors.map((f) => ({\n id: f.id,\n factorType: f.factorType,\n friendlyName: f.friendlyName,\n verified: f.verified,\n createdAt: f.createdAt\n }))\n });\n });\n\n /**\n * DELETE /auth/mfa/unenroll\n * Remove an MFA factor\n */\n router.delete(\"/mfa/unenroll\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as AccessTokenPayload | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n // Require aal2 (MFA-verified session) to unenroll MFA factors\n if (userCtx.aal !== \"aal2\") {\n throw ApiError.forbidden(\n \"MFA verification required to unenroll. Please re-authenticate with your second factor.\",\n \"AAL2_REQUIRED\"\n );\n }\n\n const unenrollSchema = z.object({\n factorId: z.string().min(1, \"Factor ID is required\")\n });\n const { factorId } = parseBody(unenrollSchema, await c.req.json());\n\n // Verify ownership\n const factor = await authRepo.getMfaFactorById(factorId);\n if (!factor || factor.userId !== userCtx.userId) {\n throw ApiError.notFound(\"MFA factor not found\");\n }\n\n await authRepo.deleteMfaFactor(factorId, userCtx.userId);\n\n // If no more verified factors, clean up recovery codes\n const hasFactors = await authRepo.hasVerifiedMfaFactors(userCtx.userId);\n if (!hasFactors) {\n await authRepo.deleteAllRecoveryCodes(userCtx.userId);\n }\n\n return c.json({\n success: true,\n message: \"MFA factor removed\"\n });\n });\n}\n","import type { Context } from \"hono\";\nimport type { AuthResponsePayload } from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../api/types\";\nimport type { CookieAuthConfig } from \"./routes\";\n\n/**\n * Cookie auth helpers for httpOnly refresh tokens.\n */\nexport function getCookieSettings(config: CookieAuthConfig | undefined) {\n const COOKIE_NAME = config?.cookieName || \"__rb_refresh\";\n const COOKIE_PATH = config?.path || \"/\";\n const COOKIE_SAMESITE = config?.sameSite || \"Lax\";\n const COOKIE_DOMAIN = config?.domain;\n const COOKIE_SECURE = config?.secure;\n\n return {\n name: COOKIE_NAME,\n path: COOKIE_PATH,\n sameSite: COOKIE_SAMESITE,\n domain: COOKIE_DOMAIN,\n secure: COOKIE_SECURE\n };\n}\n\n/**\n * Set the refresh token as an httpOnly cookie on the response.\n */\nexport function setRefreshCookie(c: Context<HonoEnv>, refreshToken: string, config: CookieAuthConfig | undefined): void {\n if (!config) return;\n\n const settings = getCookieSettings(config);\n const isSecure = settings.secure ??\n (settings.sameSite === \"None\" ? true : c.req.url.startsWith(\"https\"));\n\n let cookie = `${settings.name}=${encodeURIComponent(refreshToken)}; Path=${settings.path}; HttpOnly; SameSite=${settings.sameSite}`;\n if (isSecure) cookie += \"; Secure\";\n if (settings.domain) cookie += `; Domain=${settings.domain}`;\n // Match the server's refresh token expiry (30 days default)\n cookie += `; Max-Age=${30 * 24 * 60 * 60}`;\n c.header(\"Set-Cookie\", cookie, { append: true });\n}\n\n/**\n * Clear the refresh token cookie.\n */\nexport function clearRefreshCookie(c: Context<HonoEnv>, config: CookieAuthConfig | undefined): void {\n if (!config) return;\n\n const settings = getCookieSettings(config);\n let cookie = `${settings.name}=; Path=${settings.path}; HttpOnly; SameSite=${settings.sameSite}; Max-Age=0`;\n if (settings.domain) cookie += `; Domain=${settings.domain}`;\n c.header(\"Set-Cookie\", cookie, { append: true });\n}\n\n/**\n * Read the refresh token from the request — cookie first, then body fallback.\n */\nexport function readRefreshToken(c: Context<HonoEnv>, body: { refreshToken?: string }, config: CookieAuthConfig | undefined): string | undefined {\n if (config) {\n const settings = getCookieSettings(config);\n const cookieHeader = c.req.header(\"cookie\") || \"\";\n const prefix = `${settings.name}=`;\n const cookies = cookieHeader.split(\";\");\n for (const part of cookies) {\n const trimmed = part.trim();\n if (trimmed.startsWith(prefix)) {\n return decodeURIComponent(trimmed.slice(prefix.length));\n }\n }\n }\n return body.refreshToken;\n}\n\n/**\n * Redact the refresh token from the response body when cookie mode is active.\n */\nexport function redactRefreshToken(\n response: AuthResponsePayload,\n c: Context<HonoEnv>,\n refreshToken: string,\n config: CookieAuthConfig | undefined\n): AuthResponsePayload {\n if (!config) return response;\n\n setRefreshCookie(c, refreshToken, config);\n return {\n ...response,\n tokens: {\n ...response.tokens,\n refreshToken: \"\" // Omit from JSON body — the cookie carries it\n }\n };\n}\n","import { Hono } from \"hono\";\nimport { z } from \"zod\";\nimport { randomBytes } from \"crypto\";\nimport { ApiError } from \"../api/errors\";\nimport { HonoEnv } from \"../api/types\";\nimport { requireAuth } from \"./middleware\";\nimport { logger } from \"../utils/logger\";\nimport { strictAuthLimiter, defaultAuthLimiter } from \"./rate-limiter\";\nimport { hashRefreshToken } from \"./jwt\";\nimport type { AuthModuleConfig } from \"./routes\";\nimport type { AuthResponsePayload, TransformAuthResponseContext } from \"@rebasepro/types\";\nimport { readRefreshToken, clearRefreshCookie } from \"./cookie-utils\";\nimport type { resolveAuthHooks } from \"./auth-hooks\";\nimport type { CreateUserData } from \"./interfaces\";\n\ninterface SessionRoutesConfig {\n router: Hono<HonoEnv>;\n config: AuthModuleConfig;\n ops: ReturnType<typeof resolveAuthHooks>;\n parseBody: <T>(schema: z.ZodSchema<T>, body: unknown) => T;\n buildAuthResponse: (\n user: { id: string; email: string; displayName?: string | null; photoUrl?: string | null; emailVerified?: boolean; isAnonymous?: boolean; metadata?: Record<string, unknown> | null },\n roleIds: string[],\n accessToken: string,\n refreshToken: string,\n providerId: string\n ) => unknown;\n createSessionAndTokens: (userId: string, userAgent: string, ipAddress: string) => Promise<{\n roleIds: string[];\n accessToken: string;\n refreshToken: string;\n }>;\n applyTransformHook: (\n response: AuthResponsePayload,\n method: TransformAuthResponseContext[\"method\"],\n request: Request,\n userId: string\n ) => Promise<AuthResponsePayload>;\n}\n\nexport function mountSessionRoutes(opts: SessionRoutesConfig): void {\n const { router, config, ops, parseBody, buildAuthResponse, createSessionAndTokens, applyTransformHook } = opts;\n const authRepo = config.authRepo;\n\n const logoutSchema = z.object({\n refreshToken: z.string().optional()\n });\n\n const linkSchema = z.object({\n email: z.string().email(\"Invalid email address\").max(255),\n password: z.string().min(1, \"Password is required\").max(128)\n });\n\n const updateProfileSchema = z.object({\n displayName: z.string().max(255).optional(),\n photoURL: z.string().url().max(2048).optional()\n });\n\n const findUserSchema = z.object({\n email: z.string().email(\"Invalid email address\").max(255)\n });\n\n const isEmailConfigured = () => !!(config.emailService && config.emailService.isConfigured());\n\n /**\n * POST /auth/logout\n */\n router.post(\"/logout\", async (c) => {\n const body = await c.req.json().catch(() => ({}));\n const parsed = parseBody(logoutSchema, body);\n const refreshToken = readRefreshToken(c, parsed, config.cookieAuth);\n\n if (refreshToken) {\n const tokenHash = hashRefreshToken(refreshToken);\n await authRepo.deleteRefreshToken(tokenHash);\n }\n\n // Always clear the cookie if in cookie mode\n clearRefreshCookie(c, config.cookieAuth);\n\n // Call afterLogout hook (fire-and-forget)\n // Extract userId from the access token if present\n const authHeader = c.req.header(\"authorization\");\n if (ops.afterLogout && authHeader?.startsWith(\"Bearer \")) {\n const { verifyAccessToken } = await import(\"./jwt\");\n const payload = verifyAccessToken(authHeader.substring(7));\n if (payload) {\n ops.afterLogout(payload.userId).catch((err: unknown) => {\n logger.error(\"[AuthHooks] afterLogout error\", {\n error: err instanceof Error ? err.message : err\n });\n });\n }\n }\n\n return c.json({ success: true });\n });\n\n /**\n * GET /auth/sessions\n * Get active refresh tokens (sessions) for the current user\n */\n router.get(\"/sessions\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const currentRefreshToken = c.req.header(\"x-refresh-token\") as string;\n const currentTokenHash = currentRefreshToken ? hashRefreshToken(currentRefreshToken) : null;\n\n const sessions = await authRepo.listRefreshTokensForUser(userCtx.userId);\n\n const mappedSessions = sessions.map((s) => ({\n id: s.id,\n userAgent: s.userAgent,\n ipAddress: s.ipAddress,\n createdAt: s.createdAt,\n isCurrentSession: currentTokenHash ? s.tokenHash === currentTokenHash : false\n }));\n\n return c.json({ sessions: mappedSessions });\n });\n\n /**\n * DELETE /auth/sessions\n * Delete all refresh tokens for the current user (remote logout every device)\n */\n router.delete(\"/sessions\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n await authRepo.deleteAllRefreshTokensForUser(userCtx.userId);\n return c.json({\n success: true,\n message: \"All sessions revoked successfully\"\n });\n });\n\n /**\n * DELETE /auth/sessions/:id\n * Delete a specific refresh token (remote logout)\n */\n router.delete(\"/sessions/:id\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const id = c.req.param(\"id\");\n if (!id) {\n throw ApiError.badRequest(\"Session ID is required\", \"INVALID_INPUT\");\n }\n\n await authRepo.deleteRefreshTokenById(id, userCtx.userId);\n return c.json({\n success: true,\n message: \"Session revoked successfully\"\n });\n });\n\n /**\n * GET /auth/me\n * Get current authenticated user\n */\n router.get(\"/me\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const result = await authRepo.getUserWithRoles(userCtx.userId);\n if (!result) {\n throw ApiError.notFound(\"User not found\");\n }\n\n return c.json({\n user: {\n uid: result.user.id,\n email: result.user.email,\n displayName: result.user.displayName,\n photoURL: result.user.photoUrl,\n providerId: \"password\",\n isAnonymous: result.user.isAnonymous ?? false,\n emailVerified: result.user.emailVerified,\n roles: result.roles.map((r) => r.id),\n metadata: result.user.metadata ?? {}\n }\n });\n });\n\n /**\n * POST /auth/find-user\n * Resolve an email to a MINIMAL public profile (uid, displayName, photoURL).\n * Opt-in (`auth.allowUserLookup`) and authenticated-only — powers\n * invite-by-email flows without exposing the users table or a custom admin\n * server function. Never returns the email, roles, metadata, or any other\n * field of the looked-up user.\n */\n if (config.allowUserLookup) {\n router.post(\"/find-user\", defaultAuthLimiter, requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n const { email } = parseBody(findUserSchema, await c.req.json());\n const user = await authRepo.getUserByEmail(email.toLowerCase());\n return c.json({\n user: user\n ? { uid: user.id, displayName: user.displayName ?? null, photoURL: user.photoUrl ?? null }\n : null\n });\n });\n }\n\n /**\n * PATCH /auth/me\n * Update current authenticated user profile\n */\n router.patch(\"/me\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const { displayName, photoURL } = parseBody(updateProfileSchema, await c.req.json());\n\n const updatedUser = await authRepo.updateUser(userCtx.userId, {\n displayName: displayName !== undefined ? displayName : undefined,\n photoUrl: photoURL !== undefined ? photoURL : undefined\n });\n\n if (!updatedUser) {\n throw ApiError.notFound(\"User not found\");\n }\n\n const result = await authRepo.getUserWithRoles(userCtx.userId);\n if (!result) {\n throw ApiError.notFound(\"User not found\");\n }\n\n return c.json({\n user: {\n uid: result.user.id,\n email: result.user.email,\n displayName: result.user.displayName,\n photoURL: result.user.photoUrl,\n providerId: \"password\",\n isAnonymous: result.user.isAnonymous ?? false,\n emailVerified: result.user.emailVerified,\n roles: result.roles.map((r) => r.id),\n metadata: result.user.metadata ?? {}\n }\n });\n });\n\n /**\n * GET /auth/config\n * Get public auth configuration\n */\n router.get(\"/config\", defaultAuthLimiter, async (c) => {\n let needsSetup: boolean;\n if (config.isBootstrapCompleted) {\n needsSetup = !(await config.isBootstrapCompleted());\n } else {\n const allUsers = await authRepo.listUsers();\n needsSetup = allUsers.length === 0;\n }\n\n const registrationAllowed = needsSetup || !!config.allowRegistration;\n const enabledProviders = (config.oauthProviders || []).map((p) => p.id);\n\n return c.json({\n needsSetup,\n registrationEnabled: registrationAllowed,\n emailServiceEnabled: isEmailConfigured(),\n magicLinkEnabled: !!config.enableMagicLink && isEmailConfigured(),\n enabledProviders\n });\n });\n\n /**\n * POST /auth/anonymous\n * Create an anonymous user with temporary credentials\n */\n router.post(\"/anonymous\", strictAuthLimiter, async (c) => {\n const anonId = randomBytes(16).toString(\"hex\");\n const anonEmail = `anon_${anonId.slice(0, 8)}@anonymous.local`;\n\n let createData: CreateUserData = {\n email: anonEmail,\n emailVerified: false,\n isAnonymous: true\n };\n\n if (ops.beforeUserCreate) {\n createData = await ops.beforeUserCreate(createData);\n }\n\n const user = await authRepo.createUser(createData);\n\n // Assign default role (follow register route pattern, but never auto-admin)\n if (config.defaultRole) {\n await authRepo.assignDefaultRole(user.id, config.defaultRole);\n }\n\n const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(\n user.id,\n c.req.header(\"user-agent\") || \"unknown\",\n c.req.header(\"x-forwarded-for\") || \"unknown\"\n );\n\n // Fire afterUserCreate hook\n if (ops.afterUserCreate) {\n ops.afterUserCreate(user).catch((err: unknown) => {\n logger.error(\"[AuthHooks] afterUserCreate error\", {\n error: err instanceof Error ? err.message : err\n });\n });\n }\n\n // Fire onAuthenticated hook\n if (ops.onAuthenticated) {\n ops.onAuthenticated(user, \"anonymous\").catch((err: unknown) => {\n logger.error(\"[AuthHooks] onAuthenticated error\", {\n error: err instanceof Error ? err.message : err\n });\n });\n }\n\n const authResponse = buildAuthResponse(user, roleIds, accessToken, refreshToken, \"anonymous\") as AuthResponsePayload;\n const finalResponse = await applyTransformHook(authResponse, \"anonymous\", c.req.raw, user.id);\n return c.json(finalResponse, 201);\n });\n\n /**\n * POST /auth/anonymous/link\n * Upgrade an anonymous user to a permanent account with email/password\n */\n router.post(\"/anonymous/link\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const user = await authRepo.getUserById(userCtx.userId);\n if (!user?.isAnonymous) {\n throw ApiError.badRequest(\"User is not anonymous\", \"NOT_ANONYMOUS\");\n }\n\n const { email, password } = parseBody(linkSchema, await c.req.json());\n\n // Validate password strength\n const passwordValidation = ops.validatePasswordStrength(password);\n if (!passwordValidation.valid) {\n throw ApiError.badRequest(passwordValidation.errors.join(\". \"), \"WEAK_PASSWORD\");\n }\n\n // Check if email is already taken\n const existingUser = await authRepo.getUserByEmail(email.toLowerCase());\n if (existingUser) {\n throw ApiError.conflict(\"Email already registered\", \"EMAIL_EXISTS\");\n }\n\n // Hash password\n const passwordHash = await ops.hashPassword(password);\n\n // Update user: set email, password, remove anonymous flag\n const updatedUser = await authRepo.updateUser(user.id, {\n email: email.toLowerCase(),\n passwordHash,\n isAnonymous: false\n });\n\n if (!updatedUser) {\n throw ApiError.notFound(\"User not found\");\n }\n\n // Generate new tokens with updated identity\n const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(\n user.id,\n c.req.header(\"user-agent\") || \"unknown\",\n c.req.header(\"x-forwarded-for\") || \"unknown\"\n );\n\n const authResponse = buildAuthResponse(updatedUser, roleIds, accessToken, refreshToken, \"password\") as AuthResponsePayload;\n const finalResponse = await applyTransformHook(authResponse, \"anonymous\", c.req.raw, user.id);\n return c.json(finalResponse);\n });\n}\n","import { Hono } from \"hono\";\nimport type { AuthModuleConfig } from \"./routes\";\nimport type { ResolvedAuthHooks } from \"./auth-hooks\";\nimport type { HonoEnv } from \"../api/types\";\nimport { ApiError } from \"../api/errors\";\nimport { generateSecureToken, hashToken } from \"./admin-user-ops\";\nimport { getMagicLinkTemplate } from \"../email/templates\";\nimport { strictAuthLimiter } from \"./rate-limiter\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\nimport type { AuthResponsePayload, TransformAuthResponseContext } from \"@rebasepro/types\";\n\n/**\n * Magic link token expiry (15 minutes from now)\n */\nfunction getMagicLinkExpiry(): Date {\n return new Date(Date.now() + 15 * 60 * 1000);\n}\n\n/**\n * Mount magic link routes onto the auth router.\n *\n * Follows the same delegation pattern as `mountMfaRoutes()` and `mountSessionRoutes()`.\n */\nexport function mountMagicLinkRoutes(deps: {\n router: Hono<HonoEnv>;\n config: AuthModuleConfig;\n ops: ResolvedAuthHooks;\n parseBody: <T>(schema: z.ZodSchema<T>, body: unknown) => T;\n buildAuthResponse: (\n user: { id: string; email: string; displayName?: string | null; photoUrl?: string | null; emailVerified?: boolean; isAnonymous?: boolean; metadata?: Record<string, unknown> | null },\n roleIds: string[],\n accessToken: string,\n refreshToken: string,\n providerId: string\n ) => unknown;\n createSessionAndTokens: (userId: string, userAgent: string, ipAddress: string) => Promise<{ roleIds: string[]; accessToken: string; refreshToken: string }>;\n applyTransformHook: (\n response: AuthResponsePayload,\n method: TransformAuthResponseContext[\"method\"],\n request: Request,\n userId: string\n ) => Promise<AuthResponsePayload>;\n}) {\n const { router, config, ops, parseBody, buildAuthResponse, createSessionAndTokens, applyTransformHook } = deps;\n const { authRepo, emailService, emailConfig } = config;\n\n const magicLinkSchema = z.object({\n email: z.string().email(\"Invalid email address\").max(255)\n });\n\n const verifyMagicLinkSchema = z.object({\n token: z.string().min(1, \"Token is required\")\n });\n\n function isEmailConfigured(): boolean {\n return !!(emailService && emailService.isConfigured());\n }\n\n /**\n * POST /auth/magic-link\n * Request a magic link email\n */\n router.post(\"/magic-link\", strictAuthLimiter, async (c) => {\n const { email } = parseBody(magicLinkSchema, await c.req.json());\n\n // Require email service\n if (!isEmailConfigured()) {\n throw ApiError.serviceUnavailable(\"Email service not configured. Magic link login is not available.\", \"EMAIL_NOT_CONFIGURED\");\n }\n\n // Always return success (security: don't reveal if email exists)\n const user = await authRepo.getUserByEmail(email);\n\n if (user) {\n // Call beforeLogin hook if provided (throw to reject)\n if (ops.beforeLogin) {\n await ops.beforeLogin(email, \"magic-link\");\n }\n\n // Generate magic link token\n const token = generateSecureToken();\n const tokenHash = hashToken(token);\n const expiresAt = getMagicLinkExpiry();\n\n await authRepo.createMagicLinkToken(user.id, tokenHash, expiresAt);\n\n // Build magic link URL\n const baseUrl = emailConfig?.magicLinkUrl || emailConfig?.resetPasswordUrl || \"\";\n const magicLinkUrl = `${baseUrl}/auth/magic-link?token=${token}`;\n\n // Get email template\n const appName = emailConfig?.appName || \"Rebase\";\n const templateFn = emailConfig?.templates?.magicLink;\n const emailContent = templateFn\n ? templateFn(magicLinkUrl, { email: user.email, displayName: user.displayName })\n : getMagicLinkTemplate(magicLinkUrl, { email: user.email, displayName: user.displayName }, appName);\n\n // Send email\n try {\n await emailService!.send({\n to: user.email,\n subject: emailContent.subject,\n html: emailContent.html,\n text: emailContent.text\n });\n } catch (emailError: unknown) {\n logger.error(\"Failed to send magic link email\", { error: emailError instanceof Error ? emailError.message : emailError });\n // Don't reveal email sending failure to client\n }\n }\n\n // Always return success\n return c.json({\n success: true,\n message: \"If an account with that email exists, a magic link has been sent.\"\n });\n });\n\n /**\n * POST /auth/magic-link/verify\n * Verify magic link token and create session\n */\n router.post(\"/magic-link/verify\", strictAuthLimiter, async (c) => {\n const { token } = parseBody(verifyMagicLinkSchema, await c.req.json());\n\n // Find valid token\n const tokenHash = hashToken(token);\n const storedToken = await authRepo.findValidMagicLinkToken(tokenHash);\n\n if (!storedToken) {\n throw ApiError.badRequest(\"Invalid or expired magic link\", \"INVALID_TOKEN\");\n }\n\n // Mark token as used (one-time use)\n await authRepo.markMagicLinkTokenUsed(tokenHash);\n\n // Get user\n const user = await authRepo.getUserById(storedToken.userId);\n if (!user) {\n throw ApiError.badRequest(\"Invalid or expired magic link\", \"INVALID_TOKEN\");\n }\n\n // Clicking a magic link proves email ownership — auto-verify\n if (!user.emailVerified) {\n await authRepo.setEmailVerified(user.id, true);\n user.emailVerified = true;\n }\n\n // Create session\n const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(\n user.id,\n c.req.header(\"user-agent\") || \"unknown\",\n c.req.header(\"x-forwarded-for\") || \"unknown\"\n );\n\n // Fire onAuthenticated hook (fire-and-forget)\n if (ops.onAuthenticated) {\n ops.onAuthenticated(user, \"magic-link\").catch(err => {\n logger.error(\"[AuthHooks] onAuthenticated error\", { error: err instanceof Error ? err.message : err });\n });\n }\n\n const authResponse = buildAuthResponse(user, roleIds, accessToken, refreshToken, \"magic-link\") as AuthResponsePayload;\n const finalResponse = await applyTransformHook(authResponse, \"magic-link\", c.req.raw, user.id);\n return c.json(finalResponse);\n });\n}\n","import { Hono } from \"hono\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { randomBytes } from \"crypto\";\nimport { generateSecureToken, hashToken } from \"./admin-user-ops\";\nimport type { AuthRepository, OAuthProvider, CreateUserData } from \"./interfaces\";\nimport { generateAccessToken, generateRefreshToken, hashRefreshToken, getRefreshTokenExpiry, getAccessTokenExpiry } from \"./jwt\";\nimport type { AuthHooks } from \"./auth-hooks\";\nimport { resolveAuthHooks } from \"./auth-hooks\";\nimport { requireAuth } from \"./middleware\";\nimport { EmailService, EmailConfig } from \"../email\";\nimport { getPasswordResetTemplate, getEmailVerificationTemplate, getWelcomeEmailTemplate } from \"../email/templates\";\nimport { HonoEnv } from \"../api/types\";\nimport { defaultAuthLimiter, strictAuthLimiter } from \"./rate-limiter\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\nimport { mountMfaRoutes } from \"./mfa-routes\";\nimport { mountSessionRoutes } from \"./session-routes\";\nimport { mountMagicLinkRoutes } from \"./magic-link-routes\";\nimport type { AuthResponsePayload, TransformAuthResponseContext } from \"@rebasepro/types\";\nimport type { Context } from \"hono\";\nimport { readRefreshToken, redactRefreshToken, clearRefreshCookie } from \"./cookie-utils\";\n\n/**\n * Shared configuration for auth and admin route factories.\n */\nexport interface AuthModuleConfig {\n authRepo: AuthRepository;\n emailService?: EmailService;\n emailConfig?: EmailConfig;\n /** Allow new user registration (default: false). */\n allowRegistration?: boolean;\n /** Expose the authenticated email→minimal-profile lookup route (default: false). */\n allowUserLookup?: boolean;\n /** Default role ID to assign to new users (default: none). Must NOT be \"admin\". */\n defaultRole?: string;\n /** Optional array of OAuth providers */\n oauthProviders?: OAuthProvider<unknown>[];\n /** When true, blocks all self-registration regardless of `allowRegistration`. */\n disableSelfRegistration?: boolean;\n /**\n * Auth hooks for customizing password hashing, credential\n * verification, lifecycle hooks, etc.\n */\n authHooks?: AuthHooks;\n /**\n * Callback that checks if bootstrap has already been completed.\n * Used by GET /auth/config to report `needsSetup` status.\n * When not provided, falls back to checking if any users exist.\n */\n isBootstrapCompleted?: () => Promise<boolean>;\n /** Enable magic link (passwordless email) login. Requires email service. */\n enableMagicLink?: boolean;\n /**\n * Opt-in httpOnly cookie mode for refresh tokens.\n *\n * When set, the refresh token is delivered as an `httpOnly`, `Secure`,\n * `SameSite` cookie instead of in the JSON response body. This\n * prevents XSS from stealing the long-lived refresh token.\n *\n * The access token remains in the JSON body so the client can use it\n * in `Authorization: Bearer` headers for API calls.\n *\n * **Requires** `credentials: \"include\"` on client-side fetch calls to\n * auth endpoints, and CORS must allow credentials (no `origin: \"*\"`).\n */\n cookieAuth?: CookieAuthConfig;\n}\n\n/**\n * Configuration for httpOnly refresh-token cookies.\n */\nexport interface CookieAuthConfig {\n /** Cookie name (default: \"__rb_refresh\"). */\n cookieName?: string;\n /** Cookie domain. Omit to use the current domain. */\n domain?: string;\n /** Cookie path (default: \"/\"). */\n path?: string;\n /** SameSite attribute (default: \"Lax\"). */\n sameSite?: \"Strict\" | \"Lax\" | \"None\";\n /** Force the Secure flag. Defaults to `true` when SameSite is \"None\", otherwise auto-detected from the request protocol. */\n secure?: boolean;\n}\n\n/**\n * Helper to build standard auth response output\n */\nfunction buildAuthResponse(\n user: { id: string; email: string; displayName?: string | null; photoUrl?: string | null; emailVerified?: boolean; isAnonymous?: boolean; metadata?: Record<string, unknown> | null },\n roleIds: string[],\n accessToken: string,\n refreshToken: string,\n providerId: string\n): AuthResponsePayload {\n return {\n user: {\n uid: user.id,\n email: user.email,\n displayName: user.displayName ?? null,\n photoURL: user.photoUrl ?? null,\n providerId,\n isAnonymous: user.isAnonymous ?? false,\n emailVerified: user.emailVerified ?? false,\n roles: roleIds,\n metadata: user.metadata ?? {}\n },\n tokens: {\n accessToken,\n refreshToken,\n accessTokenExpiresAt: getAccessTokenExpiry()\n }\n };\n}\n\n\n/**\n * Get password reset token expiry (1 hour from now)\n */\nfunction getPasswordResetExpiry(): Date {\n return new Date(Date.now() + 60 * 60 * 1000); // 1 hour\n}\n\nexport function createAuthRoutes(config: AuthModuleConfig): Hono<HonoEnv> {\n if (config.defaultRole === \"admin\") {\n throw new Error(\"CRITICAL SECURITY ERROR: defaultRole cannot be 'admin'. Administrative privilege escalation via registration is strictly forbidden. Use the POST /admin/bootstrap endpoint to promote the initial administrator.\");\n }\n\n const router = new Hono<HonoEnv>();\n\n // Attach Rebase error handler to ensure ApiError exceptions are correctly\n // formatted instead of caught by Hono's default error handler.\n // Hono's onError does NOT propagate from parent to child routers.\n router.onError(errorHandler);\n\n const authRepo = config.authRepo;\n const { emailService, emailConfig, allowRegistration = false } = config;\n const ops = resolveAuthHooks(config.authHooks);\n\n /**\n * Apply the `transformAuthResponse` hook if provided.\n *\n * Errors are caught and logged — the untransformed response is returned\n * as a graceful fallback so auth never breaks due to a hook failure.\n */\n async function applyTransformHook(\n response: AuthResponsePayload,\n method: TransformAuthResponseContext[\"method\"],\n request: Request,\n userId: string\n ): Promise<AuthResponsePayload> {\n if (!ops.transformAuthResponse) return response;\n try {\n return await ops.transformAuthResponse(response, { userId, method, request });\n } catch (err) {\n logger.error(\"[AuthHooks] transformAuthResponse error\", {\n error: err instanceof Error ? err.message : err\n });\n return response;\n }\n }\n\n // ── Zod input schemas ──────────────────────────────────────────────\n const registerSchema = z.object({\n email: z.string().email(\"Invalid email address\").max(255),\n password: z.string().min(1, \"Password is required\").max(128),\n displayName: z.string().max(255).optional()\n });\n const loginSchema = z.object({\n email: z.string().email(\"Invalid email address\").max(255),\n password: z.string().min(1, \"Password is required\").max(128)\n });\n const forgotPasswordSchema = z.object({\n email: z.string().email(\"Invalid email address\").max(255)\n });\n const resetPasswordSchema = z.object({\n token: z.string().min(1, \"Token is required\"),\n password: z.string().min(1, \"Password is required\").max(128)\n });\n const changePasswordSchema = z.object({\n oldPassword: z.string().min(1, \"Old password is required\").max(128),\n newPassword: z.string().min(1, \"New password is required\").max(128)\n });\n const refreshSchema = z.object({\n // When cookieAuth is enabled the refresh token arrives via cookie, so\n // the body field becomes optional.\n refreshToken: config.cookieAuth\n ? z.string().optional()\n : z.string().min(1, \"Refresh token is required\")\n });\n const logoutSchema = z.object({\n refreshToken: z.string().optional()\n });\n const updateProfileSchema = z.object({\n displayName: z.string().max(255).optional(),\n photoURL: z.string().url().max(2048).optional()\n });\n\n /** Parse a Zod schema against the request body, throwing ApiError on failure */\n function parseBody<T>(schema: z.ZodSchema<T>, body: unknown): T {\n const result = schema.safeParse(body);\n if (!result.success) {\n const messages = result.error.issues.map(e => `${e.path.join(\".\")}: ${e.message}`).join(\". \");\n throw ApiError.badRequest(messages, \"INVALID_INPUT\");\n }\n return result.data;\n }\n\n /**\n * Check if email service is configured\n */\n function isEmailConfigured(): boolean {\n return !!(emailService && emailService.isConfigured());\n }\n\n /**\n * Check if registration is allowed.\n * Registration is only allowed when explicitly enabled via `allowRegistration`.\n * First-user bootstrap must use POST /admin/bootstrap instead.\n */\n function isRegistrationAllowed(): boolean {\n if (config.disableSelfRegistration) return false;\n return !!allowRegistration;\n }\n\n /**\n * Send welcome email to a newly registered user (fire-and-forget).\n */\n function sendWelcomeEmail(user: { email: string; displayName?: string | null }) {\n if (!isEmailConfigured()) return;\n const appName = emailConfig?.appName || \"Rebase\";\n const loginUrl = emailConfig?.resetPasswordUrl || \"\"; // reuse base URL → the login / app page\n const templateFn = emailConfig?.templates?.welcomeEmail;\n const emailContent = templateFn\n ? templateFn(user, appName)\n : getWelcomeEmailTemplate(user, appName, loginUrl ? `${loginUrl}/app` : undefined);\n\n emailService!.send({\n to: user.email,\n subject: emailContent.subject,\n html: emailContent.html,\n text: emailContent.text\n }).catch(err => {\n logger.error(\"Failed to send welcome email\", { error: err instanceof Error ? err.message : err });\n });\n }\n\n /**\n * Helper to generate and store session tokens\n */\n async function createSessionAndTokens(userId: string, userAgent: string, ipAddress: string) {\n const roles = await authRepo.getUserRoles(userId);\n const roleIds = roles.map(r => r.id);\n\n // Allow customization of access token claims via hook\n let customClaims: Record<string, unknown> | undefined;\n if (ops.customizeAccessToken) {\n const user = await authRepo.getUserById(userId);\n if (user) {\n const defaultClaims: Record<string, unknown> = { userId,\nroles: roleIds,\naal: \"aal1\" };\n customClaims = await ops.customizeAccessToken(defaultClaims, user);\n }\n }\n\n const accessToken = generateAccessToken(userId, roleIds, \"aal1\", customClaims);\n const refreshToken = generateRefreshToken();\n\n await authRepo.createRefreshToken(\n userId,\n hashRefreshToken(refreshToken),\n getRefreshTokenExpiry(),\n userAgent,\n ipAddress\n );\n\n return { roleIds,\naccessToken,\nrefreshToken };\n }\n\n /**\n * POST /auth/register\n * Create a new account with email/password\n */\n router.post(\"/register\", defaultAuthLimiter, async (c) => {\n const { email, password, displayName } = parseBody(registerSchema, await c.req.json());\n\n // Hard kill switch — blocks registration regardless of allowRegistration\n if (config.disableSelfRegistration) {\n throw ApiError.forbidden(\"Registration is disabled\", \"REGISTRATION_DISABLED\");\n }\n\n // Check if registration is allowed (no bypass for empty databases)\n if (!isRegistrationAllowed()) {\n throw ApiError.forbidden(\"Registration is disabled\", \"REGISTRATION_DISABLED\");\n }\n\n // Validate password strength\n const passwordValidation = ops.validatePasswordStrength(password);\n if (!passwordValidation.valid) {\n throw ApiError.badRequest(passwordValidation.errors.join(\". \"), \"WEAK_PASSWORD\");\n }\n\n // Check if email already exists\n const existingUser = await authRepo.getUserByEmail(email);\n if (existingUser) {\n throw ApiError.conflict(\"Email already registered\", \"EMAIL_EXISTS\");\n }\n\n // Create user\n const passwordHash = await ops.hashPassword(password);\n let createData: import(\"./interfaces\").CreateUserData = {\n email: email.toLowerCase(),\n passwordHash,\n displayName: displayName || undefined\n };\n if (ops.beforeUserCreate) {\n createData = await ops.beforeUserCreate(createData);\n }\n const user = await authRepo.createUser(createData);\n\n // Auto-bootstrap: if this is the very first user in the system, promote to admin.\n // This avoids the chicken-and-egg problem where the first user has no permissions\n // and no way to access the bootstrap endpoint from the UI.\n const existingUsers = await authRepo.listUsers();\n const isFirstUser = existingUsers.length === 1 && existingUsers[0].id === user.id;\n\n if (isFirstUser) {\n await authRepo.setUserRoles(user.id, [\"admin\"]);\n } else if (config.defaultRole) {\n // Assign configured default role (never auto-assign admin via registration)\n await authRepo.assignDefaultRole(user.id, config.defaultRole);\n }\n\n const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(\n user.id,\n c.req.header(\"user-agent\") || \"unknown\",\n c.req.header(\"x-forwarded-for\") || \"unknown\"\n );\n\n // Send welcome email (fire-and-forget, don't block registration)\n sendWelcomeEmail({ email: user.email,\ndisplayName: user.displayName });\n\n // Fire afterUserCreate hook\n if (ops.afterUserCreate) {\n try {\n await ops.afterUserCreate(user);\n } catch (err) {\n logger.error(\"[AuthHooks] afterUserCreate error\", { error: err instanceof Error ? err.message : err });\n }\n }\n\n // Fire onAuthenticated hook (fire-and-forget)\n if (ops.onAuthenticated) {\n ops.onAuthenticated(user, \"register\").catch(err => {\n logger.error(\"[AuthHooks] onAuthenticated error\", { error: err instanceof Error ? err.message : err });\n });\n }\n\n const authResponse = buildAuthResponse(user, roleIds, accessToken, refreshToken, \"password\");\n const transformedResponse = await applyTransformHook(authResponse, \"register\", c.req.raw, user.id);\n const finalResponse = redactRefreshToken(transformedResponse, c, refreshToken, config.cookieAuth);\n return c.json(finalResponse, 201);\n });\n\n /**\n * POST /auth/login\n * Login with email/password\n */\n router.post(\"/login\", defaultAuthLimiter, async (c) => {\n const { email, password } = parseBody(loginSchema, await c.req.json());\n\n // Call beforeLogin hook if provided (throw to reject)\n if (ops.beforeLogin) {\n await ops.beforeLogin(email, \"login\");\n }\n\n let user;\n\n if (ops.verifyCredentials) {\n // Full credential verification override\n user = await ops.verifyCredentials(email, password, authRepo);\n if (!user) {\n throw ApiError.unauthorized(\"Invalid email or password\", \"INVALID_CREDENTIALS\");\n }\n } else {\n // Default: email lookup + password hash verification\n user = await authRepo.getUserByEmail(email);\n if (!user) {\n throw ApiError.unauthorized(\"Invalid email or password\", \"INVALID_CREDENTIALS\");\n }\n\n if (!user.passwordHash) {\n throw ApiError.unauthorized(\"Invalid email or password\", \"INVALID_CREDENTIALS\");\n }\n\n const isValidPassword = await ops.verifyPassword(password, user.passwordHash);\n if (!isValidPassword) {\n logger.warn(\"[Security Audit] Auth login failure\", {\n eventType: \"auth.login.failure\",\n email,\n userId: user.id\n });\n throw ApiError.unauthorized(\"Invalid email or password\", \"INVALID_CREDENTIALS\");\n }\n }\n\n const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(\n user.id,\n c.req.header(\"user-agent\") || \"unknown\",\n c.req.header(\"x-forwarded-for\") || \"unknown\"\n );\n\n // Fire onAuthenticated hook (fire-and-forget)\n if (ops.onAuthenticated) {\n ops.onAuthenticated(user, \"login\").catch(err => {\n logger.error(\"[AuthHooks] onAuthenticated error\", { error: err instanceof Error ? err.message : err });\n });\n }\n\n logger.info(\"[Security Audit] Auth login success\", {\n eventType: \"auth.login.success\",\n userId: user.id,\n email\n });\n\n const authResponse = buildAuthResponse(user, roleIds, accessToken, refreshToken, \"password\");\n const transformedResponse = await applyTransformHook(authResponse, \"login\", c.req.raw, user.id);\n const finalResponse = redactRefreshToken(transformedResponse, c, refreshToken, config.cookieAuth);\n return c.json(finalResponse);\n });\n\n /**\n * Dynamically mount OAuth provider routes\n */\n if (config.oauthProviders && config.oauthProviders.length > 0) {\n for (const provider of config.oauthProviders) {\n router.post(`/${provider.id}`, defaultAuthLimiter, async (c) => {\n const payload = parseBody(provider.schema, await c.req.json());\n\n let externalUser;\n try {\n externalUser = await provider.verify(payload);\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n throw ApiError.unauthorized(`${provider.id} login failed: ${msg}`, \"OAUTH_ERROR\");\n }\n if (!externalUser) {\n throw ApiError.unauthorized(`Invalid ${provider.id} credentials`, \"INVALID_TOKEN\");\n }\n\n // Find or create user\n let user = await authRepo.getUserByIdentity(provider.id, externalUser.providerId);\n\n if (!user) {\n // Check if email exists (link accounts)\n user = await authRepo.getUserByEmail(externalUser.email);\n\n if (user) {\n // Only auto-link if the OAuth provider confirmed the email is verified\n if (!externalUser.emailVerified) {\n throw ApiError.forbidden(\n \"Cannot auto-link account: email not verified by the OAuth provider. Please log in with your password first and link the provider from your profile.\",\n \"EMAIL_NOT_VERIFIED\"\n );\n }\n // Link Provider to existing account\n await authRepo.linkUserIdentity(user.id, provider.id, externalUser.providerId, { email: externalUser.email });\n\n // Optional: Update profile info from external provider if empty\n await authRepo.updateUser(user.id, {\n displayName: user.displayName || externalUser.displayName || undefined,\n photoUrl: user.photoUrl || externalUser.photoUrl || undefined\n });\n } else {\n // Create new user\n user = await authRepo.createUser({\n email: externalUser.email.toLowerCase(),\n displayName: externalUser.displayName || undefined,\n photoUrl: externalUser.photoUrl || undefined\n });\n\n await authRepo.linkUserIdentity(user.id, provider.id, externalUser.providerId, { email: externalUser.email });\n\n // Fire afterUserCreate hook\n if (ops.afterUserCreate) {\n try {\n await ops.afterUserCreate(user);\n } catch (err) {\n logger.error(\"[AuthHooks] afterUserCreate error\", { error: err instanceof Error ? err.message : err });\n }\n }\n\n // Auto-bootstrap: first user in the system gets admin\n const allUsers = await authRepo.listUsers();\n const isFirstUser = allUsers.length === 1 && allUsers[0].id === user.id;\n\n if (isFirstUser) {\n await authRepo.setUserRoles(user.id, [\"admin\"]);\n } else if (config.defaultRole) {\n // Assign configured default role (never auto-assign admin via registration)\n await authRepo.assignDefaultRole(user.id, config.defaultRole);\n }\n\n // Send welcome email for new OAuth users (fire-and-forget)\n sendWelcomeEmail({ email: user.email,\ndisplayName: user.displayName });\n }\n } else {\n // Update profile info from external provider\n await authRepo.updateUser(user.id, {\n displayName: externalUser.displayName || user.displayName || undefined,\n photoUrl: externalUser.photoUrl || user.photoUrl || undefined\n });\n }\n\n const { roleIds, accessToken, refreshToken } = await createSessionAndTokens(\n user.id,\n c.req.header(\"user-agent\") || \"unknown\",\n c.req.header(\"x-forwarded-for\") || \"unknown\"\n );\n\n const authResponse = buildAuthResponse(user, roleIds, accessToken, refreshToken, provider.id);\n const transformedResponse = await applyTransformHook(authResponse, \"oauth\", c.req.raw, user.id);\n const finalResponse = redactRefreshToken(transformedResponse, c, refreshToken, config.cookieAuth);\n return c.json(finalResponse);\n });\n }\n }\n\n /**\n * POST /auth/forgot-password\n * Request password reset email\n */\n router.post(\"/forgot-password\", strictAuthLimiter, async (c) => {\n const { email } = parseBody(forgotPasswordSchema, await c.req.json());\n\n // Check if email service is configured\n if (!isEmailConfigured()) {\n throw ApiError.serviceUnavailable(\"Email service not configured. Password reset is not available.\", \"EMAIL_NOT_CONFIGURED\");\n }\n\n // Always return success (security: don't reveal if email exists)\n // But only send email if user exists\n const user = await authRepo.getUserByEmail(email);\n\n if (user) {\n // Generate reset token\n const token = generateSecureToken();\n const tokenHash = hashToken(token);\n const expiresAt = getPasswordResetExpiry();\n\n await authRepo.createPasswordResetToken(user.id, tokenHash, expiresAt);\n\n // Build reset URL\n const baseUrl = emailConfig?.resetPasswordUrl || \"\";\n const resetUrl = `${baseUrl}/reset-password?token=${token}`;\n\n // Get email template\n const appName = emailConfig?.appName || \"Rebase\";\n const templateFn = emailConfig?.templates?.passwordReset;\n const emailContent = templateFn\n ? templateFn(resetUrl, { email: user.email,\ndisplayName: user.displayName })\n : getPasswordResetTemplate(resetUrl, { email: user.email,\ndisplayName: user.displayName }, appName);\n\n // Send email\n try {\n await emailService!.send({\n to: user.email,\n subject: emailContent.subject,\n html: emailContent.html,\n text: emailContent.text\n });\n } catch (emailError: unknown) {\n logger.error(\"Failed to send password reset email\", { error: emailError instanceof Error ? emailError.message : emailError });\n // Don't reveal email sending failure to client\n }\n }\n\n // Always return success\n return c.json({\n success: true,\n message: \"If an account with that email exists, a password reset link has been sent.\"\n });\n });\n\n /**\n * POST /auth/reset-password\n * Reset password using token\n */\n router.post(\"/reset-password\", strictAuthLimiter, async (c) => {\n const { token, password } = parseBody(resetPasswordSchema, await c.req.json());\n\n // Validate password strength\n const passwordValidation = ops.validatePasswordStrength(password);\n if (!passwordValidation.valid) {\n throw ApiError.badRequest(passwordValidation.errors.join(\". \"), \"WEAK_PASSWORD\");\n }\n\n // Find valid token\n const tokenHash = hashToken(token);\n const storedToken = await authRepo.findValidPasswordResetToken(tokenHash);\n\n if (!storedToken) {\n throw ApiError.badRequest(\"Invalid or expired reset token\", \"INVALID_TOKEN\");\n }\n\n // Update password\n const passwordHash = await ops.hashPassword(password);\n await authRepo.updatePassword(storedToken.userId, passwordHash);\n\n // Mark token as used\n await authRepo.markPasswordResetTokenUsed(tokenHash);\n\n // Invalidate all refresh tokens (security: log out all sessions)\n await authRepo.deleteAllRefreshTokensForUser(storedToken.userId);\n\n // Fire onPasswordReset hook (fire-and-forget)\n if (ops.onPasswordReset) {\n ops.onPasswordReset(storedToken.userId).catch(err => {\n logger.error(\"[AuthHooks] onPasswordReset error\", { error: err instanceof Error ? err.message : err });\n });\n }\n\n return c.json({ success: true,\nmessage: \"Password has been reset successfully\" });\n });\n\n /**\n * POST /auth/change-password\n * Change password for authenticated user\n */\n router.post(\"/change-password\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n const { oldPassword, newPassword } = parseBody(changePasswordSchema, await c.req.json());\n\n // Get user\n const user = await authRepo.getUserById(userCtx.userId);\n if (!user || !user.passwordHash) {\n throw ApiError.badRequest(\"Cannot change password for this account\", \"INVALID_ACCOUNT\");\n }\n\n // Verify old password\n const isValidOldPassword = await ops.verifyPassword(oldPassword, user.passwordHash);\n if (!isValidOldPassword) {\n throw ApiError.unauthorized(\"Current password is incorrect\", \"INVALID_CREDENTIALS\");\n }\n\n // Validate new password strength\n const passwordValidation = ops.validatePasswordStrength(newPassword);\n if (!passwordValidation.valid) {\n throw ApiError.badRequest(passwordValidation.errors.join(\". \"), \"WEAK_PASSWORD\");\n }\n\n // Update password\n const passwordHash = await ops.hashPassword(newPassword);\n await authRepo.updatePassword(user.id, passwordHash);\n\n // Invalidate all refresh tokens (security: log out all sessions)\n await authRepo.deleteAllRefreshTokensForUser(user.id);\n\n return c.json({ success: true,\nmessage: \"Password has been changed successfully\" });\n });\n\n /**\n * POST /auth/send-verification\n * Send email verification link (authenticated)\n */\n router.post(\"/send-verification\", requireAuth, async (c) => {\n const userCtx = c.get(\"user\") as { userId: string; roles?: string[] } | undefined;\n if (!userCtx) {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n // Check if email service is configured\n if (!isEmailConfigured()) {\n throw ApiError.serviceUnavailable(\"Email service not configured. Email verification is not available.\", \"EMAIL_NOT_CONFIGURED\");\n }\n\n const user = await authRepo.getUserById(userCtx.userId);\n if (!user) {\n throw ApiError.notFound(\"User not found\");\n }\n\n if (user.emailVerified) {\n throw ApiError.badRequest(\"Email is already verified\", \"ALREADY_VERIFIED\");\n }\n\n // Generate verification token\n const token = generateSecureToken();\n\n // Store hashed token in user record (raw token goes in the email URL)\n await authRepo.setVerificationToken(user.id, hashToken(token));\n\n // Build verification URL\n const baseUrl = emailConfig?.verifyEmailUrl || \"\";\n const verifyUrl = `${baseUrl}/verify-email?token=${token}`;\n\n // Get email template\n const appName = emailConfig?.appName || \"Rebase\";\n const templateFn = emailConfig?.templates?.emailVerification;\n const emailContent = templateFn\n ? templateFn(verifyUrl, { email: user.email,\ndisplayName: user.displayName })\n : getEmailVerificationTemplate(verifyUrl, { email: user.email,\ndisplayName: user.displayName }, appName);\n\n // Send email\n await emailService!.send({\n to: user.email,\n subject: emailContent.subject,\n html: emailContent.html,\n text: emailContent.text\n });\n\n return c.json({ success: true,\nmessage: \"Verification email sent\" });\n });\n\n /**\n * GET /auth/verify-email\n * Verify email address using token\n */\n router.get(\"/verify-email\", async (c) => {\n const token = c.req.query(\"token\");\n\n if (!token) {\n throw ApiError.badRequest(\"Verification token is required\", \"INVALID_INPUT\");\n }\n\n // Find user by hashed verification token\n const user = await authRepo.getUserByVerificationToken(hashToken(token));\n if (!user) {\n throw ApiError.badRequest(\"Invalid or expired verification token\", \"INVALID_TOKEN\");\n }\n\n // Mark email as verified\n await authRepo.setEmailVerified(user.id, true);\n\n return c.json({ success: true,\nmessage: \"Email verified successfully\" });\n });\n\n /**\n * POST /auth/refresh\n * Refresh access token using refresh token\n */\n router.post(\"/refresh\", async (c) => {\n const body = await c.req.json();\n const parsed = parseBody(refreshSchema, body);\n const refreshToken = readRefreshToken(c, parsed, config.cookieAuth);\n\n if (!refreshToken) {\n throw ApiError.badRequest(\"Refresh token is required\", \"INVALID_INPUT\");\n }\n\n const tokenHash = hashRefreshToken(refreshToken);\n const storedToken = await authRepo.findRefreshTokenByHash(tokenHash);\n\n if (!storedToken) {\n // When cookie mode is active, clear the stale cookie\n clearRefreshCookie(c, config.cookieAuth);\n throw ApiError.unauthorized(\"Invalid refresh token\", \"INVALID_TOKEN\");\n }\n\n if (new Date() > storedToken.expiresAt) {\n await authRepo.deleteRefreshToken(tokenHash);\n clearRefreshCookie(c, config.cookieAuth);\n throw ApiError.unauthorized(\"Refresh token expired\", \"TOKEN_EXPIRED\");\n }\n\n // Generate new tokens\n const roles = await authRepo.getUserRoles(storedToken.userId);\n const roleIds = roles.map(r => r.id);\n\n // Best-effort: load the user so we can return it in the response, which\n // lets the client restore a session from an httpOnly cookie alone (cold\n // start in cookie mode). This enrichment must NEVER break refresh — on\n // any failure we fall back to a tokens-only response (the pre-existing\n // behavior), and the client restores the user via GET /me.\n const user = await authRepo.getUserById(storedToken.userId).catch((err: unknown) => {\n logger.warn(\"[Auth] Could not load user during token refresh; returning tokens only\", {\n userId: storedToken.userId,\n error: err instanceof Error ? err.message : String(err)\n });\n return null;\n });\n\n // Allow customization of access token claims via hook\n let customClaims: Record<string, unknown> | undefined;\n if (ops.customizeAccessToken && user) {\n const defaultClaims: Record<string, unknown> = { userId: storedToken.userId,\nroles: roleIds,\naal: \"aal1\" };\n customClaims = await ops.customizeAccessToken(defaultClaims, user);\n }\n\n const newAccessToken = generateAccessToken(storedToken.userId, roleIds, \"aal1\", customClaims);\n const newRefreshToken = generateRefreshToken();\n\n // Rotate refresh token (delete old, create new)\n const userAgent = c.req.header(\"user-agent\") || \"unknown\";\n const ipAddress = c.req.header(\"x-forwarded-for\") || \"unknown\";\n\n await authRepo.deleteRefreshToken(tokenHash);\n await authRepo.createRefreshToken(\n storedToken.userId,\n hashRefreshToken(newRefreshToken),\n getRefreshTokenExpiry(),\n userAgent,\n ipAddress\n );\n\n const tokensOnlyResponse: AuthResponsePayload = {\n tokens: {\n accessToken: newAccessToken,\n refreshToken: newRefreshToken,\n accessTokenExpiresAt: getAccessTokenExpiry()\n }\n };\n let refreshResponse: AuthResponsePayload = tokensOnlyResponse;\n if (user) {\n try {\n refreshResponse = buildAuthResponse(user, roleIds, newAccessToken, newRefreshToken, \"password\");\n } catch (err: unknown) {\n logger.warn(\"[Auth] Could not build enriched refresh response; returning tokens only\", {\n error: err instanceof Error ? err.message : String(err)\n });\n refreshResponse = tokensOnlyResponse;\n }\n }\n const transformedResponse = await applyTransformHook(refreshResponse, \"refresh\", c.req.raw, storedToken.userId);\n const finalResponse = redactRefreshToken(transformedResponse, c, newRefreshToken, config.cookieAuth);\n return c.json(finalResponse);\n });\n\n mountSessionRoutes({\n router,\n config,\n ops,\n parseBody,\n buildAuthResponse,\n createSessionAndTokens,\n applyTransformHook\n });\n\n // ═══════════════════════════════════════════════════════════════════════\n // MFA / TOTP\n // ═══════════════════════════════════════════════════════════════════════\n mountMfaRoutes(router, config, ops, parseBody, applyTransformHook);\n\n // ═══════════════════════════════════════════════════════════════════════\n // Magic Link (passwordless email login)\n // ═══════════════════════════════════════════════════════════════════════\n if (config.enableMagicLink) {\n mountMagicLinkRoutes({\n router,\n config,\n ops,\n parseBody,\n buildAuthResponse,\n createSessionAndTokens,\n applyTransformHook\n });\n }\n\n return router;\n}\n","/**\n * Standalone admin endpoint for resetting a user's password.\n *\n * Hook resolution order:\n * 1. Collection-level hook (`auth.onResetPassword` on the collection)\n * 2. Backend-level hook (`AuthHooks.onAdminResetPassword`)\n * 3. Built-in default (send reset email, or generate temp password)\n */\n\nimport { Hono } from \"hono\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport type { AuthRepository } from \"./interfaces\";\nimport { createRequireAuth, requireAdmin } from \"./middleware\";\nimport type { AuthHooks } from \"./auth-hooks\";\nimport { resolveAuthHooks } from \"./auth-hooks\";\nimport { generateSecurePassword, generateSecureToken, hashToken } from \"./admin-user-ops\";\nimport { getPasswordResetTemplate } from \"../email/templates\";\nimport type { EmailService, EmailConfig } from \"../email\";\nimport type { HonoEnv } from \"../api/types\";\nimport type { AuthCollectionConfig } from \"@rebasepro/types\";\nimport { logger } from \"../utils/logger\";\n\nexport interface ResetPasswordRouteConfig {\n authRepo: AuthRepository;\n emailService?: EmailService;\n emailConfig?: EmailConfig;\n serviceKey?: string;\n authHooks?: AuthHooks;\n /** The parsed auth config from the collection, if available. */\n collectionAuthConfig?: AuthCollectionConfig;\n}\n\n/**\n * Create a standalone admin route for resetting user passwords.\n *\n * Mounts: POST /users/:userId/reset-password\n */\nexport function createResetPasswordRoute(config: ResetPasswordRouteConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n const authRepo = config.authRepo;\n const { emailService, emailConfig, collectionAuthConfig } = config;\n const ops = resolveAuthHooks(config.authHooks);\n\n router.onError(errorHandler);\n router.use(\"/*\", createRequireAuth({ serviceKey: config.serviceKey }));\n\n router.post(\"/users/:userId/reset-password\", requireAdmin, async (c) => {\n const userId = c.req.param(\"userId\");\n const existing = await authRepo.getUserById(userId);\n if (!existing) {\n throw ApiError.notFound(\"User not found\");\n }\n\n let invitationSent = false;\n let temporaryPassword: string | undefined;\n\n // Parse optional body — if a password is provided, set it directly\n const body = await c.req.json().catch(() => ({}));\n\n if (body.password) {\n const password = body.password as string;\n const validation = ops.validatePasswordStrength(password);\n if (!validation.valid) {\n throw ApiError.badRequest(\n `Password too weak: ${validation.errors.join(\", \")}`\n );\n }\n const passwordHash = await ops.hashPassword(password);\n await authRepo.updatePassword(existing.id, passwordHash);\n temporaryPassword = undefined;\n invitationSent = false;\n }\n // 1. Collection-level hook (closest to the data)\n else if (collectionAuthConfig?.onResetPassword) {\n const isEmailConfigured = !!(emailService && emailService.isConfigured());\n const hookResult = await collectionAuthConfig.onResetPassword(existing.id, {\n hashPassword: (password: string) => ops.hashPassword(password),\n sendEmail: isEmailConfigured\n ? (options) => emailService!.send(options)\n : undefined,\n emailConfigured: isEmailConfigured,\n appName: emailConfig?.appName || \"Rebase\",\n resetPasswordUrl: emailConfig?.resetPasswordUrl || \"\"\n });\n temporaryPassword = hookResult.temporaryPassword;\n invitationSent = hookResult.invitationSent ?? false;\n }\n // 2. Backend-level hook (global override)\n else if (ops.onAdminResetPassword) {\n const hookResult = await ops.onAdminResetPassword(existing.id, {\n authRepo,\n emailService,\n emailConfig\n });\n temporaryPassword = hookResult.temporaryPassword;\n invitationSent = hookResult.invitationSent ?? false;\n }\n // 3. Built-in default\n else {\n const isEmailConfigured = !!(emailService && emailService.isConfigured());\n\n if (isEmailConfigured) {\n try {\n const token = generateSecureToken();\n const tokenHash = hashToken(token);\n const expiresAt = new Date(Date.now() + 60 * 60 * 1000); // 1 hour\n\n await authRepo.createPasswordResetToken(existing.id, tokenHash, expiresAt);\n\n const baseUrl = emailConfig?.resetPasswordUrl || \"\";\n const setPasswordUrl = `${baseUrl}/reset-password?token=${token}`;\n\n const appName = emailConfig?.appName || \"Rebase\";\n const templateFn = emailConfig?.templates?.passwordReset;\n const emailContent = templateFn\n ? templateFn(setPasswordUrl, { email: existing.email,\ndisplayName: existing.displayName })\n : getPasswordResetTemplate(setPasswordUrl, { email: existing.email,\ndisplayName: existing.displayName }, appName);\n\n await emailService!.send({\n to: existing.email,\n subject: emailContent.subject,\n html: emailContent.html,\n text: emailContent.text\n });\n invitationSent = true;\n } catch (emailError: unknown) {\n logger.error(\"Failed to send reset email\", { error: emailError instanceof Error ? emailError.message : emailError });\n // Fall back to returning the temporary password\n const clearPassword = generateSecurePassword();\n const passwordHash = await ops.hashPassword(clearPassword);\n await authRepo.updatePassword(existing.id, passwordHash);\n temporaryPassword = clearPassword;\n }\n } else {\n // No email service — generate password, set it, and return one-time\n const clearPassword = generateSecurePassword();\n const passwordHash = await ops.hashPassword(clearPassword);\n await authRepo.updatePassword(existing.id, passwordHash);\n temporaryPassword = clearPassword;\n }\n }\n\n const userRoles = await authRepo.getUserRoleIds(existing.id);\n\n return c.json({\n user: {\n uid: existing.id,\n email: existing.email,\n displayName: existing.displayName,\n roles: userRoles\n },\n invitationSent,\n ...(temporaryPassword ? { temporaryPassword } : {})\n }, 200);\n });\n\n return router;\n}\n","/**\n * Admin endpoint for listing all roles.\n *\n * Mounts: GET /roles\n */\n\nimport { Hono } from \"hono\";\nimport { errorHandler } from \"../api/errors\";\nimport type { AuthRepository } from \"./interfaces\";\nimport { createRequireAuth, requireAdmin } from \"./middleware\";\nimport type { HonoEnv } from \"../api/types\";\n\nexport interface AdminRolesRouteConfig {\n authRepo: AuthRepository;\n serviceKey?: string;\n}\n\n/**\n * Create a standalone admin route for listing roles.\n *\n * Mounts: GET /roles\n */\nexport function createAdminRolesRoute(config: AdminRolesRouteConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n const authRepo = config.authRepo;\n\n router.onError(errorHandler);\n router.use(\"/*\", createRequireAuth({ serviceKey: config.serviceKey }));\n\n router.get(\"/roles\", requireAdmin, async (c) => {\n const roles = await authRepo.listRoles();\n return c.json({ roles });\n });\n\n return router;\n}\n","/**\n * Standalone admin endpoint for user management.\n *\n * Mounts:\n * GET /users\n * GET /users/:userId\n * POST /users\n * PUT /users/:userId\n * DELETE /users/:userId\n * POST /bootstrap\n */\n\nimport { Hono } from \"hono\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport type { AuthRepository } from \"./interfaces\";\nimport { createRequireAuth, requireAdmin } from \"./middleware\";\nimport type { AuthHooks } from \"./auth-hooks\";\nimport { resolveAuthHooks } from \"./auth-hooks\";\nimport { prepareAdminUserValues, finalizeAdminUserCreation } from \"./admin-user-ops\";\nimport type { EmailService, EmailConfig } from \"../email\";\nimport type { HonoEnv } from \"../api/types\";\nimport type { AdminUser, AuthCollectionConfig } from \"@rebasepro/types\";\nimport { logger } from \"../utils/logger\";\n\nexport interface AdminUsersRouteConfig {\n authRepo: AuthRepository;\n emailService?: EmailService;\n emailConfig?: EmailConfig;\n serviceKey?: string;\n authHooks?: AuthHooks;\n collectionAuthConfig?: AuthCollectionConfig;\n isBootstrapCompleted?: () => Promise<boolean>;\n setBootstrapCompleted?: () => Promise<void>;\n}\n\nexport function createAdminUsersRoute(config: AdminUsersRouteConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n const authRepo = config.authRepo;\n const { emailService, emailConfig, collectionAuthConfig } = config;\n const ops = resolveAuthHooks(config.authHooks);\n\n function toAdminUser(\n u: {\n id: string;\n email: string;\n displayName?: string | null;\n photoUrl?: string | null;\n createdAt?: Date | string;\n updatedAt?: Date | string;\n },\n roles: string[]\n ): AdminUser {\n return {\n uid: u.id,\n email: u.email,\n displayName: u.displayName ?? null,\n photoURL: u.photoUrl ?? null,\n providerId: \"custom\",\n roles,\n createdAt: u.createdAt instanceof Date ? u.createdAt.toISOString() : (u.createdAt ?? new Date().toISOString()),\n updatedAt: u.updatedAt instanceof Date ? u.updatedAt.toISOString() : (u.updatedAt ?? new Date().toISOString())\n };\n }\n\n router.onError(errorHandler);\n router.use(\"/*\", createRequireAuth({ serviceKey: config.serviceKey }));\n\n router.post(\"/bootstrap\", async (c) => {\n const user = c.get(\"user\");\n if (!user || typeof user !== \"object\") {\n throw ApiError.unauthorized(\"Not authenticated\");\n }\n\n if (config.isBootstrapCompleted) {\n const alreadyDone = await config.isBootstrapCompleted();\n if (alreadyDone) {\n throw ApiError.forbidden(\"Bootstrap has already been completed.\", \"BOOTSTRAP_COMPLETED\");\n }\n }\n\n const users = await authRepo.listUsers();\n let hasAdmin = false;\n\n for (const u of users) {\n const roles = await authRepo.getUserRoleIds(u.id);\n if (roles.includes(\"admin\")) {\n hasAdmin = true;\n break;\n }\n }\n\n if (hasAdmin) {\n throw ApiError.forbidden(\"Admin users already exist. Bootstrap not allowed.\", \"BOOTSTRAP_COMPLETED\");\n }\n\n const userId = \"userId\" in user ? (user as { userId: string }).userId : (\"uid\" in user ? (user as { uid: string }).uid : undefined);\n if (!userId) {\n throw ApiError.unauthorized(\"User ID not found in auth context\");\n }\n const caller = await authRepo.getUserById(userId);\n if (!caller) {\n throw ApiError.notFound(\"Authenticated user does not exist in the database.\", \"USER_NOT_FOUND\");\n }\n await authRepo.setUserRoles(userId, [\"admin\"]);\n\n if (config.setBootstrapCompleted) {\n await config.setBootstrapCompleted();\n }\n\n return c.json({\n success: true,\n message: \"You are now an admin\",\n user: {\n uid: userId,\n roles: [\"admin\"]\n }\n });\n });\n\n router.get(\"/users\", requireAdmin, async (c) => {\n const limitParam = c.req.query(\"limit\");\n const offsetParam = c.req.query(\"offset\");\n const search = c.req.query(\"search\");\n const orderBy = c.req.query(\"orderBy\");\n const orderDir = c.req.query(\"orderDir\") as \"asc\" | \"desc\" | undefined;\n\n const limit = limitParam ? parseInt(limitParam, 10) : 25;\n const offset = offsetParam ? parseInt(offsetParam, 10) : 0;\n\n const result = await authRepo.listUsersPaginated({\n limit,\n offset,\n search: search || undefined,\n orderBy: orderBy || undefined,\n orderDir: orderDir || undefined,\n roleId: c.req.query(\"role\") || undefined\n });\n\n const usersWithRoles = await Promise.all(\n result.users.map(async (u) => {\n const roles = await authRepo.getUserRoleIds(u.id);\n return toAdminUser(u, roles);\n })\n );\n\n return c.json({\n users: usersWithRoles,\n total: result.total,\n limit: result.limit,\n offset: result.offset\n });\n });\n\n router.get(\"/users/:userId\", requireAdmin, async (c) => {\n const userId = c.req.param(\"userId\");\n const result = await authRepo.getUserWithRoles(userId);\n\n if (!result) {\n throw ApiError.notFound(\"User not found\");\n }\n\n const adminUser = toAdminUser(result.user, result.roles.map((r) => r.id));\n return c.json({ user: adminUser });\n });\n\n router.post(\"/users\", requireAdmin, async (c) => {\n const body = await c.req.json();\n const { email, roles } = body;\n if (!email) {\n throw ApiError.badRequest(\"Email is required\");\n }\n\n const existing = await authRepo.getUserByEmail(email.toLowerCase());\n if (existing) {\n throw ApiError.conflict(\"A user with this email already exists\");\n }\n\n const prepResult = await prepareAdminUserValues(body, {\n authRepo,\n emailService,\n emailConfig,\n resolvedHooks: ops,\n collectionAuthConfig\n });\n\n const user = await authRepo.createUser({\n email: prepResult.values.email as string,\n passwordHash: prepResult.values.passwordHash as string | undefined,\n displayName: prepResult.values.displayName as string | undefined,\n photoUrl: prepResult.values.photoUrl as string | undefined,\n metadata: prepResult.values.metadata as Record<string, unknown> | undefined\n });\n\n if (roles && Array.isArray(roles)) {\n await authRepo.setUserRoles(user.id, roles);\n }\n\n const finalizeResult = await finalizeAdminUserCreation(\n { id: user.id, values: prepResult.values },\n prepResult.clearPassword,\n {\n authRepo,\n emailService,\n emailConfig,\n resolvedHooks: ops,\n collectionAuthConfig\n }\n );\n\n const userRoles = await authRepo.getUserRoleIds(user.id);\n const adminUser = toAdminUser(user, userRoles);\n\n return c.json(\n {\n user: adminUser,\n invitationSent: finalizeResult.invitationSent,\n ...(finalizeResult.temporaryPassword ? { temporaryPassword: finalizeResult.temporaryPassword } : {})\n },\n 201\n );\n });\n\n router.put(\"/users/:userId\", requireAdmin, async (c) => {\n const userId = c.req.param(\"userId\");\n const body = await c.req.json();\n const { password, email, displayName, roles } = body;\n\n const existing = await authRepo.getUserById(userId);\n if (!existing) {\n throw ApiError.notFound(\"User not found\");\n }\n\n const updates: Record<string, unknown> = {};\n if (email !== undefined) updates.email = email.toLowerCase();\n if (displayName !== undefined) updates.displayName = displayName;\n\n if (password) {\n const validation = ops.validatePasswordStrength(password);\n if (!validation.valid) {\n throw ApiError.badRequest(`Password too weak: ${validation.errors.join(\". \")}`);\n }\n updates.passwordHash = await ops.hashPassword(password);\n }\n\n if (Object.keys(updates).length > 0) {\n await authRepo.updateUser(userId, updates);\n }\n\n if (roles !== undefined && Array.isArray(roles)) {\n const currentRoles = await authRepo.getUserRoleIds(userId);\n const wasAdmin = currentRoles.includes(\"admin\");\n const willBeAdmin = roles.includes(\"admin\");\n\n if (wasAdmin && !willBeAdmin) {\n const adminUsers = await authRepo.listUsersPaginated({\n roleId: \"admin\",\n limit: 1\n });\n if (adminUsers.total <= 1) {\n throw ApiError.forbidden(\"Cannot demote the last administrator\", \"LAST_ADMIN\");\n }\n }\n await authRepo.setUserRoles(userId, roles);\n }\n\n const result = await authRepo.getUserWithRoles(userId);\n const adminUser = toAdminUser(result!.user, result!.roles.map((r) => r.id));\n\n return c.json({ user: adminUser });\n });\n\n router.delete(\"/users/:userId\", requireAdmin, async (c) => {\n const userId = c.req.param(\"userId\");\n const authUser = c.get(\"user\") as { uid?: string; userId?: string } | undefined;\n const currentUserId = authUser?.uid || authUser?.userId;\n\n if (currentUserId === userId) {\n throw ApiError.badRequest(\"Cannot delete your own account\", \"SELF_DELETE\");\n }\n\n const existing = await authRepo.getUserById(userId);\n if (!existing) {\n throw ApiError.notFound(\"User not found\");\n }\n\n const roles = await authRepo.getUserRoleIds(userId);\n if (roles.includes(\"admin\")) {\n const adminUsers = await authRepo.listUsersPaginated({\n roleId: \"admin\",\n limit: 1\n });\n if (adminUsers.total <= 1) {\n throw ApiError.forbidden(\"Cannot delete the last administrator\", \"LAST_ADMIN\");\n }\n }\n\n await authRepo.deleteUser(userId);\n return c.json({ success: true });\n });\n\n return router;\n}\n","/**\n * RebaseBuiltinAuthAdapter\n *\n * Wraps Rebase's existing built-in JWT auth system (routes, middleware, user/role\n * management) into the `AuthAdapter` interface. This is the default adapter used\n * when the user passes a plain `RebaseAuthConfig` object.\n *\n * This is NOT a rewrite — it delegates to the existing `createAuthRoutes()`,\n * `createResetPasswordRoute()`, and `verifyAccessToken()` functions. The goal is to\n * present the same functionality through the pluggable `AuthAdapter` contract.\n */\n\nimport type {\n AuthAdapter,\n AuthenticatedUser,\n AuthAdapterCapabilities,\n UserManagementAdapter,\n AuthUserListOptions,\n AuthUserListResult,\n AuthUserData,\n AuthCreateUserData,\n BootstrappedAuth\n} from \"@rebasepro/types\";\n\nimport { Hono } from \"hono\";\nimport { verifyAccessToken } from \"./jwt\";\nimport type { AccessTokenPayload } from \"./jwt\";\nimport { createAuthRoutes } from \"./routes\";\nimport { createResetPasswordRoute } from \"./reset-password-admin\";\nimport { createAdminRolesRoute } from \"./admin-roles-route\";\nimport { createAdminUsersRoute } from \"./admin-users-route\";\nimport { prepareAdminUserValues, finalizeAdminUserCreation } from \"./admin-user-ops\";\nimport type { AuthRepository, OAuthProvider } from \"./interfaces\";\nimport type { AuthHooks, ResolvedAuthHooks } from \"./auth-hooks\";\nimport { resolveAuthHooks } from \"./auth-hooks\";\nimport type { EmailService, EmailConfig } from \"../email\";\nimport type { HonoEnv } from \"../api/types\";\nimport { safeCompare } from \"./crypto-utils\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Configuration for the built-in Rebase auth adapter.\n *\n * This mirrors the existing `RebaseAuthConfig` — users pass this and\n * server-core auto-wraps it in a `RebaseBuiltinAuthAdapter`.\n */\nexport interface BuiltinAuthAdapterConfig {\n /** The bootstrapper-provided auth repository (users, roles, tokens). */\n authRepository: AuthRepository;\n /** Email service for password resets, verification, etc. */\n emailService?: EmailService;\n /** Email configuration. */\n emailConfig?: EmailConfig;\n /** Whether to allow new user registration. */\n allowRegistration?: boolean;\n /** Whether to expose the authenticated email→minimal-profile lookup route. */\n allowUserLookup?: boolean;\n /** Default role to assign to new users. */\n defaultRole?: string;\n /** OAuth providers to register. */\n oauthProviders?: OAuthProvider<unknown>[];\n /** Static service key for server-to-server auth. */\n serviceKey?: string;\n /** Auth hooks for customizing password, credentials, lifecycle, etc. */\n authHooks?: AuthHooks;\n /** The parsed auth config from the collection (if `auth` is an object, not just `true`). */\n collectionAuthConfig?: import(\"@rebasepro/types\").AuthCollectionConfig;\n /** Enable magic link (passwordless email) login. Requires email service. */\n enableMagicLink?: boolean;\n /** Opt-in httpOnly cookie mode for refresh tokens. */\n cookieAuth?: import(\"./routes\").CookieAuthConfig;\n}\n\n/**\n * Create the built-in Rebase auth adapter.\n *\n * This wraps the existing auth infrastructure (JWT, OAuth, user/role management)\n * into the `AuthAdapter` interface. It's used internally by `initializeRebaseBackend()`\n * when the user passes a plain `RebaseAuthConfig` object.\n */\nexport function createBuiltinAuthAdapter(config: BuiltinAuthAdapterConfig): AuthAdapter {\n const {\n authRepository,\n emailService,\n emailConfig,\n allowRegistration = false,\n allowUserLookup = false,\n defaultRole,\n oauthProviders = [],\n serviceKey,\n authHooks,\n collectionAuthConfig,\n enableMagicLink = false,\n cookieAuth\n } = config;\n\n const resolvedOps = resolveAuthHooks(authHooks);\n\n const adapter: AuthAdapter = {\n id: \"rebase-builtin\",\n\n serviceKey,\n\n async verifyRequest(request: Request): Promise<AuthenticatedUser | null> {\n const authHeader = request.headers.get(\"authorization\");\n const url = new URL(request.url, \"http://localhost\");\n const queryToken = url.searchParams.get(\"token\");\n const hasBearer = authHeader?.startsWith(\"Bearer \");\n\n if (!hasBearer && !queryToken) {\n return null;\n }\n\n const token = hasBearer ? authHeader!.substring(7) : queryToken!;\n\n // Check service key first (constant-time)\n if (serviceKey && safeCompare(token, serviceKey)) {\n return {\n uid: \"service\",\n email: \"service@rebase.internal\",\n roles: [\"admin\"],\n isAdmin: true,\n rawToken: token\n };\n }\n\n // JWT verification\n const payload = verifyAccessToken(token);\n if (!payload) {\n return null;\n }\n\n // Resolve roles from the repository\n let roles: string[] = payload.roles || [];\n try {\n roles = await authRepository.getUserRoleIds(payload.userId);\n } catch (err: unknown) {\n logger.warn(\"Role lookup from repository failed, using token roles as fallback\", { userId: payload.userId, error: err });\n }\n\n const isAdmin = roles.some((r) => r === \"admin\" || r === \"schema-admin\");\n\n return {\n uid: payload.userId,\n email: payload.email ?? \"\",\n displayName: payload.displayName ?? null,\n roles,\n isAdmin,\n rawToken: token\n };\n },\n\n async verifyToken(token: string): Promise<AuthenticatedUser | null> {\n // Service key check (constant-time)\n if (serviceKey && safeCompare(token, serviceKey)) {\n return {\n uid: \"service\",\n email: \"service@rebase.internal\",\n roles: [\"admin\"],\n isAdmin: true,\n rawToken: token\n };\n }\n\n // JWT verification\n const payload = verifyAccessToken(token);\n if (!payload) {\n return null;\n }\n\n let roles: string[] = payload.roles || [];\n try {\n roles = await authRepository.getUserRoleIds(payload.userId);\n } catch (err: unknown) {\n logger.warn(\"Role lookup from repository failed, using token roles as fallback\", { userId: payload.userId, error: err });\n }\n\n const isAdmin = roles.some((r) => r === \"admin\" || r === \"schema-admin\");\n\n return {\n uid: payload.userId,\n email: payload.email ?? \"\",\n displayName: payload.displayName ?? null,\n roles,\n isAdmin,\n rawToken: token\n };\n },\n\n userManagement: createUserManagementFromRepo(authRepository, resolvedOps),\n\n\n createAuthRoutes(): Hono<HonoEnv> | undefined {\n return createAuthRoutes({\n authRepo: authRepository,\n emailService,\n emailConfig,\n allowRegistration,\n allowUserLookup,\n defaultRole,\n oauthProviders,\n authHooks,\n enableMagicLink,\n cookieAuth\n });\n },\n\n createAdminRoutes(): Hono<HonoEnv> | undefined {\n const router = new Hono<HonoEnv>();\n const resetPasswordRoute = createResetPasswordRoute({\n authRepo: authRepository,\n emailService,\n emailConfig,\n serviceKey,\n authHooks,\n collectionAuthConfig\n });\n const rolesRoute = createAdminRolesRoute({\n authRepo: authRepository,\n serviceKey\n });\n const adminUsersRoute = createAdminUsersRoute({\n authRepo: authRepository,\n emailService,\n emailConfig,\n serviceKey,\n authHooks,\n collectionAuthConfig\n });\n router.route(\"/\", resetPasswordRoute);\n router.route(\"/\", rolesRoute);\n router.route(\"/\", adminUsersRoute);\n return router;\n },\n\n async prepareUserCreation(values, collectionAuth) {\n const parsedCollectionAuth = collectionAuth as import(\"@rebasepro/types\").AuthCollectionConfig | undefined;\n return prepareAdminUserValues(values, {\n authRepo: authRepository,\n emailService,\n emailConfig,\n resolvedHooks: resolvedOps,\n collectionAuthConfig: parsedCollectionAuth ?? collectionAuthConfig\n });\n },\n\n async finalizeUserCreation(entity, clearPassword) {\n return finalizeAdminUserCreation(entity, clearPassword, {\n authRepo: authRepository,\n emailService,\n emailConfig,\n resolvedHooks: resolvedOps,\n collectionAuthConfig\n });\n },\n\n async getCapabilities(): Promise<AuthAdapterCapabilities> {\n // Detect bootstrap mode: are there any users?\n let needsSetup = false;\n try {\n const result = await authRepository.listUsersPaginated({ limit: 1 });\n needsSetup = result.total === 0;\n } catch {\n // If the check fails, assume not in setup mode\n }\n\n const enabledProviders = oauthProviders.map((p) => p.id);\n\n return {\n hasBuiltInAuthRoutes: true,\n emailPasswordLogin: true,\n registration: allowRegistration || needsSetup,\n registrationEnabled: allowRegistration || needsSetup,\n passwordReset: !!emailService?.isConfigured(),\n sessionManagement: true,\n profileUpdate: true,\n emailVerification: !!emailService?.isConfigured(),\n magicLink: enableMagicLink && !!emailService?.isConfigured(),\n enabledProviders,\n needsSetup\n };\n }\n };\n\n return adapter;\n}\n\n// ─── Internal Helpers ────────────────────────────────────────────────────────\n\nfunction createUserManagementFromRepo(repo: AuthRepository, resolvedOps: ResolvedAuthHooks): UserManagementAdapter {\n return {\n async listUsers(options?: AuthUserListOptions): Promise<AuthUserListResult> {\n const result = await repo.listUsersPaginated({\n limit: options?.limit,\n offset: options?.offset,\n search: options?.search,\n orderBy: options?.orderBy,\n orderDir: options?.orderDir,\n roleId: options?.roleId\n });\n return {\n users: result.users.map(toAuthUserData),\n total: result.total,\n limit: result.limit,\n offset: result.offset\n };\n },\n\n async getUserById(id: string): Promise<AuthUserData | null> {\n const user = await repo.getUserById(id);\n return user ? toAuthUserData(user) : null;\n },\n\n async createUser(data: AuthCreateUserData): Promise<AuthUserData> {\n const passwordHash = data.password ? await resolvedOps.hashPassword(data.password) : undefined;\n let createData: import(\"./interfaces\").CreateUserData = {\n email: data.email,\n passwordHash,\n displayName: data.displayName,\n photoUrl: data.photoUrl,\n metadata: data.metadata\n };\n if (resolvedOps.beforeUserCreate) {\n createData = await resolvedOps.beforeUserCreate(createData);\n }\n const user = await repo.createUser(createData);\n if (resolvedOps.afterUserCreate) {\n try {\n await resolvedOps.afterUserCreate(user);\n } catch (err) {\n logger.error(\"[AuthHooks] afterUserCreate error\", { error: err instanceof Error ? err.message : err });\n }\n }\n return toAuthUserData(user);\n },\n\n async updateUser(id: string, data: Partial<AuthCreateUserData>): Promise<AuthUserData | null> {\n const updateData: Record<string, unknown> = {};\n if (data.email !== undefined) updateData.email = data.email;\n if (data.displayName !== undefined) updateData.displayName = data.displayName;\n if (data.photoUrl !== undefined) updateData.photoUrl = data.photoUrl;\n if (data.metadata !== undefined) updateData.metadata = data.metadata;\n if (data.password) {\n updateData.passwordHash = await resolvedOps.hashPassword(data.password);\n }\n const user = await repo.updateUser(id, updateData);\n return user ? toAuthUserData(user) : null;\n },\n\n async deleteUser(id: string): Promise<void> {\n // Call beforeUserDelete hook (throw to prevent deletion)\n if (resolvedOps.beforeUserDelete) {\n await resolvedOps.beforeUserDelete(id);\n }\n\n await repo.deleteUser(id);\n\n // Fire afterUserDelete hook (fire-and-forget)\n if (resolvedOps.afterUserDelete) {\n resolvedOps.afterUserDelete(id).catch(err => {\n logger.error(\"[AuthHooks] afterUserDelete error\", { error: err instanceof Error ? err.message : err });\n });\n }\n },\n\n async getUserRoles(userId: string): Promise<string[]> {\n return repo.getUserRoleIds(userId);\n },\n\n async setUserRoles(userId: string, roleIds: string[]): Promise<void> {\n await repo.setUserRoles(userId, roleIds);\n }\n };\n}\n\nfunction toAuthUserData(user: { id: string; email: string; displayName?: string | null; photoUrl?: string | null; emailVerified?: boolean; metadata?: Record<string, unknown>; createdAt?: Date; updatedAt?: Date }): AuthUserData {\n return {\n id: user.id,\n email: user.email,\n displayName: user.displayName,\n photoUrl: user.photoUrl,\n emailVerified: user.emailVerified,\n metadata: user.metadata,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt\n };\n}\n","/**\n * Configure console log levels based on environment variable\n * Call this early in your application to set up proper logging levels\n */\nexport function configureLogLevel(logLevel?: string) {\n const LOG_LEVEL = logLevel || process.env.LOG_LEVEL || \"info\";\n const logLevels = { error: 0,\nwarn: 1,\ninfo: 2,\ndebug: 3 };\n const currentLevel = logLevels[LOG_LEVEL as keyof typeof logLevels] ?? 2;\n\n if (currentLevel < 3) console.debug = () => { };\n if (currentLevel < 2) console.log = () => { };\n if (currentLevel < 1) console.warn = () => { };\n if (currentLevel < 0) console.error = () => { };\n}\n\n/** Module-scoped backup of the original console methods. */\nlet originalConsole: Pick<Console, \"log\" | \"warn\" | \"error\" | \"debug\"> | undefined;\n\n/**\n * Reset console methods to their original state\n */\nexport function resetConsole() {\n // Store original methods if not already stored\n if (!originalConsole) {\n originalConsole = {\n log: console.log,\n warn: console.warn,\n error: console.error,\n debug: console.debug\n };\n }\n\n console.log = originalConsole.log;\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n console.debug = originalConsole.debug;\n}\n","/**\n * X-Request-ID Middleware for Hono.\n *\n * Generates a unique request identifier (UUID v4) for every inbound\n * request, or propagates an existing `X-Request-ID` header from the\n * caller. The ID is:\n *\n * 1. Stored in the Hono context (`c.get(\"requestId\")`)\n * 2. Echoed back on the response as `X-Request-ID`\n *\n * Downstream middleware and handlers (request logger, error handler,\n * etc.) read the ID from context to include it in log entries and\n * error responses, enabling end-to-end request tracing across services.\n *\n * @example\n * ```ts\n * import { requestId } from \"@rebasepro/server-core\";\n * app.use(\"/*\", requestId());\n * ```\n */\nimport { randomUUID } from \"node:crypto\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { HonoEnv } from \"../api/types\";\n\nexport const REQUEST_ID_HEADER = \"X-Request-ID\";\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport function requestId(): MiddlewareHandler<HonoEnv> {\n return async (c, next) => {\n const incoming = c.req.header(REQUEST_ID_HEADER);\n const id = incoming && UUID_RE.test(incoming) ? incoming : randomUUID();\n\n c.set(\"requestId\", id);\n\n await next();\n\n c.header(REQUEST_ID_HEADER, id);\n };\n}\n","/**\n * Structured HTTP request logging middleware for Hono.\n *\n * Logs every request with method, path, status code, latency, and\n * content-length. In production, outputs JSON for Cloud Logging; in\n * development, emits a coloured one-liner.\n *\n * @example\n * ```ts\n * import { requestLogger } from \"@rebasepro/server-core\";\n * app.use(\"/*\", requestLogger());\n * ```\n */\nimport type { MiddlewareHandler } from \"hono\";\nimport { logger as log } from \"./logger\";\n\nexport interface RequestLoggerOptions {\n /** Paths to skip logging (e.g. \"/health\"). Supports exact match. */\n skip?: string[];\n}\n\nexport function requestLogger(options?: RequestLoggerOptions): MiddlewareHandler {\n const skipPaths = new Set(options?.skip ?? [\"/health\", \"/favicon.ico\"]);\n\n return async (c, next) => {\n const start = performance.now();\n const method = c.req.method;\n const path = c.req.path;\n\n // Skip noisy endpoints\n if (skipPaths.has(path)) {\n return next();\n }\n\n await next();\n\n const latencyMs = Math.round(performance.now() - start);\n const status = c.res.status;\n const contentLength = c.res.headers.get(\"content-length\");\n\n const data: Record<string, unknown> = {\n method,\n path,\n status,\n latencyMs\n };\n\n // Include request correlation ID if available\n const reqId = c.get(\"requestId\");\n if (reqId) {\n data.requestId = reqId;\n }\n\n if (contentLength) {\n data.contentLength = parseInt(contentLength, 10);\n }\n\n // Extract user ID from context if auth middleware ran\n const userId = c.get(\"userId\" as never) as string | undefined;\n if (userId) {\n data.userId = userId;\n }\n\n if (status >= 500) {\n log.error(\"request\", data);\n } else if (status >= 400) {\n log.warn(\"request\", data);\n } else {\n log.info(\"request\", data);\n }\n };\n}\n","import { Hono } from \"hono\";\nimport { bodyLimit } from \"hono/body-limit\";\nimport { csrf } from \"hono/csrf\";\nimport { HonoEnv } from \"../api/types\";\nimport { requestId } from \"../utils/request-id\";\nimport { requestLogger } from \"../utils/request-logger\";\nimport { logger } from \"../utils/logger\";\n\ninterface MiddlewareConfig {\n maxBodySize?: number;\n csrf?: {\n origin: string | string[] | ((origin: string) => boolean);\n };\n}\n\nexport function configureMiddlewares(\n app: Hono<HonoEnv>,\n basePath: string,\n isProduction: boolean,\n config: MiddlewareConfig\n): void {\n // Request ID (correlation)\n app.use(`${basePath}/*`, requestId());\n\n // Request Body Size Limit\n const maxBodySize = config.maxBodySize ?? 10 * 1024 * 1024; // 10MB default\n if (maxBodySize > 0) {\n app.use(`${basePath}/*`, bodyLimit({\n maxSize: maxBodySize,\n onError: (c) => {\n return c.json({\n error: {\n message: `Request body too large. Maximum size is ${Math.round(maxBodySize / 1024 / 1024)}MB.`,\n code: \"PAYLOAD_TOO_LARGE\"\n }\n }, 413);\n }\n }));\n logger.info(\"Request body limit configured\", { maxSizeMB: Math.round(maxBodySize / 1024 / 1024) });\n }\n\n // CSRF Protection (opt-in)\n if (config.csrf?.origin) {\n app.use(`${basePath}/*`, csrf({\n origin: config.csrf.origin\n }));\n logger.info(\"CSRF protection enabled\");\n }\n\n // CORS Warning\n if (!isProduction && !process.env.CORS_ORIGINS && !process.env.FRONTEND_URL) {\n logger.warn(\n \"No CORS configuration detected (CORS_ORIGINS / FRONTEND_URL not set). \" +\n \"The API will accept requests from any origin. \" +\n \"Set CORS_ORIGINS in your .env file to restrict access.\"\n );\n }\n\n // Request Logging\n app.use(`${basePath}/*`, requestLogger());\n}\n","/**\n * Storage configuration and types for Rebase backend\n */\n\nimport { StorageSource, UploadFileProps, UploadFileResult, DownloadConfig, StorageListResult, StorageReference } from \"@rebasepro/types\";\n\n/**\n * Local filesystem storage configuration\n */\nexport interface LocalStorageConfig {\n type: \"local\";\n /** Base directory for file storage (e.g., './uploads') */\n basePath: string;\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types (if not set, all types allowed) */\n allowedMimeTypes?: string[];\n /** Base URL for generating download URLs (default: auto-detected from request) */\n baseUrl?: string;\n}\n\n/**\n * S3-compatible storage configuration (works with AWS S3 and MinIO)\n */\nexport interface S3StorageConfig {\n type: \"s3\";\n /** S3 bucket name */\n bucket: string;\n /** AWS region (e.g., 'us-east-1') */\n region?: string;\n /** Custom endpoint URL (required for MinIO, Cloudflare R2, Hetzner Object Storage) */\n endpoint?: string;\n /** AWS access key ID */\n accessKeyId: string;\n /** AWS secret access key */\n secretAccessKey: string;\n /** Use path-style URLs (required for MinIO) */\n forcePathStyle?: boolean;\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types (if not set, all types allowed) */\n allowedMimeTypes?: string[];\n /** URL expiration time in seconds for signed URLs (default: 3600) */\n signedUrlExpiration?: number;\n}\n\n/**\n * Google Cloud Storage configuration (works with GCS and Firebase Storage)\n */\nexport interface GCSStorageConfig {\n type: \"gcs\";\n /** GCS bucket name (e.g. \"my-project.appspot.com\" for Firebase Storage) */\n bucket: string;\n /** GCP project ID (optional, auto-detected from credentials) */\n projectId?: string;\n /** Path to service account JSON key file */\n keyFilename?: string;\n /** Service account credentials object (alternative to keyFilename) */\n credentials?: { client_email: string; private_key: string; project_id?: string };\n /** Maximum file size in bytes (default: 50MB) */\n maxFileSize?: number;\n /** Allowed MIME types */\n allowedMimeTypes?: string[];\n /** Signed URL expiration in seconds (default: 3600) */\n signedUrlExpiration?: number;\n}\n\n/**\n * Storage configuration — local filesystem, S3-compatible, or Google Cloud Storage.\n *\n * **Built-in providers:**\n * - `local` — Zero-config filesystem storage. Great for dev and single-server deployments (Hetzner, bare metal).\n * - `s3` — Any S3-compatible provider. AWS S3, Cloudflare R2, MinIO, Hetzner Object Storage,\n * Backblaze B2, DigitalOcean Spaces, and even GCS (via its S3-compatible interoperability API).\n * - `gcs` — Native Google Cloud Storage / Firebase Storage via `@google-cloud/storage`.\n *\n * **Custom providers:**\n * For other cloud storage (Azure Blob, etc.), implement the `StorageController`\n * interface and pass the instance directly to the `storage` config.\n */\nexport type BackendStorageConfig = LocalStorageConfig | S3StorageConfig | GCSStorageConfig;\n\n/**\n * Storage controller interface for backend implementations\n */\nexport interface StorageController {\n /**\n * Upload an object\n */\n putObject(props: UploadFileProps): Promise<UploadFileResult>;\n\n /**\n * Get a download URL (signed URL equivalent) for an object\n */\n getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig>;\n\n /**\n * Get object as a File\n */\n getObject(key: string, bucket?: string): Promise<File | null>;\n\n /**\n * Delete an object\n */\n deleteObject(key: string, bucket?: string): Promise<void>;\n\n /**\n * List objects in a prefix\n */\n listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult>;\n\n /**\n * Get the storage provider identifier.\n *\n * Built-in values are `'local'` and `'s3'`. Custom implementations\n * should return their own identifier (e.g. `'gcs'`, `'azure'`).\n */\n getType(): string;\n}\n\n/**\n * Default maximum file size (50MB)\n */\nexport const DEFAULT_MAX_FILE_SIZE = 50 * 1024 * 1024;\n\n/**\n * Common image MIME types\n */\nexport const IMAGE_MIME_TYPES = [\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n \"image/svg+xml\",\n \"image/bmp\",\n \"image/tiff\"\n];\n\n/**\n * Common document MIME types\n */\nexport const DOCUMENT_MIME_TYPES = [\n \"application/pdf\",\n \"application/msword\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \"application/vnd.ms-excel\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n \"application/vnd.ms-powerpoint\",\n \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n \"text/plain\",\n \"text/csv\"\n];\n","/**\n * Local filesystem storage controller\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { promisify } from \"util\";\nimport {\n StorageController,\n LocalStorageConfig,\n DEFAULT_MAX_FILE_SIZE\n} from \"./types\";\nimport {\n UploadFileProps,\n UploadFileResult,\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference\n} from \"@rebasepro/types\";\n\nconst mkdir = promisify(fs.mkdir);\nconst writeFile = promisify(fs.writeFile);\nconst readFile = promisify(fs.readFile);\nconst unlink = promisify(fs.unlink);\nconst readdir = promisify(fs.readdir);\nconst stat = promisify(fs.stat);\nconst access = promisify(fs.access);\n\n/**\n * Remove initial and trailing slashes from a path.\n * Handles paths like \"/images/\", \"images/\", \"/images\" → \"images\"\n */\nfunction normalizeStoragePath(s: string): string {\n let result = s;\n while (result.startsWith(\"/\")) {\n result = result.slice(1);\n }\n while (result.endsWith(\"/\")) {\n result = result.slice(0, -1);\n }\n return result;\n}\n\n/**\n * Local filesystem storage implementation\n * Stores files in a directory structure: {basePath}/{bucket}/{path}\n */\nexport class LocalStorageController implements StorageController {\n private config: LocalStorageConfig;\n private basePath: string;\n\n constructor(config: LocalStorageConfig) {\n this.config = config;\n this.basePath = path.resolve(config.basePath);\n }\n\n getType(): \"local\" {\n return \"local\";\n }\n\n /**\n * Ensure directory exists, creating it if necessary\n */\n private async ensureDir(dirPath: string): Promise<void> {\n try {\n await mkdir(dirPath, { recursive: true });\n } catch (error: unknown) {\n if (error instanceof Error && (error as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw error;\n }\n }\n }\n\n /**\n * Get the full filesystem path for a storage path.\n * Includes a path traversal guard to prevent escaping the base directory.\n */\n private getFullPath(storagePath: string, bucket?: string): string {\n const bucketPath = bucket ? path.join(this.basePath, bucket) : this.basePath;\n const resolved = path.resolve(path.join(bucketPath, storagePath));\n if (!resolved.startsWith(bucketPath + path.sep) && resolved !== bucketPath) {\n throw new Error(\"Path traversal detected: resolved storage path is outside the bucket directory.\");\n }\n return resolved;\n }\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n // Always use a bucket (default to 'default')\n const usedBucket = bucket ?? \"default\";\n const fullStoragePath = key;\n const fullPath = this.getFullPath(fullStoragePath, usedBucket);\n\n // Ensure parent directory exists\n await this.ensureDir(path.dirname(fullPath));\n\n // Convert File to Buffer and write\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n await writeFile(fullPath, buffer);\n\n // Always save metadata file with at least contentType (required for preview)\n const metadataPath = `${fullPath}.metadata.json`;\n await writeFile(metadataPath, JSON.stringify({\n ...(metadata || {}),\n contentType: file.type,\n size: file.size,\n uploadedAt: new Date().toISOString()\n }, null, 2));\n\n return {\n key: fullStoragePath,\n bucket: usedBucket,\n storageUrl: `local://${usedBucket}/${fullStoragePath}`\n };\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle local:// URLs\n let resolvedPath = key;\n let resolvedBucket = bucket;\n\n if (key.startsWith(\"local://\")) {\n const withoutProtocol = key.substring(\"local://\".length);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n // Normalize path to handle leading/trailing slashes\n resolvedPath = normalizeStoragePath(resolvedPath);\n const fullPath = this.getFullPath(resolvedPath, resolvedBucket);\n\n try {\n await access(fullPath, fs.constants.R_OK);\n } catch {\n return {\n url: null,\n fileNotFound: true\n };\n }\n\n // Read metadata if available\n let metadata: DownloadMetadata | undefined;\n const metadataPath = `${fullPath}.metadata.json`;\n try {\n const metadataContent = await readFile(metadataPath, \"utf-8\");\n const savedMetadata = JSON.parse(metadataContent);\n const fileStat = await stat(fullPath);\n\n metadata = {\n bucket: resolvedBucket ?? \"default\",\n fullPath: resolvedPath,\n name: path.basename(resolvedPath),\n size: fileStat.size,\n contentType: savedMetadata.contentType || \"application/octet-stream\",\n customMetadata: savedMetadata\n };\n } catch {\n // No metadata file, create basic metadata from stat\n try {\n const fileStat = await stat(fullPath);\n metadata = {\n bucket: resolvedBucket ?? \"default\",\n fullPath: resolvedPath,\n name: path.basename(resolvedPath),\n size: fileStat.size,\n contentType: \"application/octet-stream\",\n customMetadata: {}\n };\n } catch {\n // Stat failed\n }\n }\n\n // Return a relative URL that will be served by the storage routes\n const bucketPath = resolvedBucket ? `${resolvedBucket}/` : \"\";\n const url = `/api/storage/file/${bucketPath}${resolvedPath}`;\n\n return {\n url,\n metadata\n };\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle local:// URLs\n let resolvedPath = key;\n let resolvedBucket = bucket;\n\n if (key.startsWith(\"local://\")) {\n const withoutProtocol = key.substring(\"local://\".length);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n // Normalize path to handle leading/trailing slashes\n resolvedPath = normalizeStoragePath(resolvedPath);\n const fullPath = this.getFullPath(resolvedPath, resolvedBucket);\n\n try {\n await access(fullPath, fs.constants.R_OK);\n const buffer = await readFile(fullPath);\n\n // Try to get content type from metadata\n let contentType = \"application/octet-stream\";\n try {\n const metadataPath = `${fullPath}.metadata.json`;\n const metadataContent = await readFile(metadataPath, \"utf-8\");\n const metadata = JSON.parse(metadataContent);\n contentType = metadata.contentType || contentType;\n } catch {\n // No metadata, use default content type\n }\n\n const blob = new Blob([buffer], { type: contentType });\n return new File([blob], path.basename(resolvedPath), { type: contentType });\n } catch {\n return null;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle local:// URLs\n let resolvedPath = key;\n let resolvedBucket = bucket;\n\n if (key.startsWith(\"local://\")) {\n const withoutProtocol = key.substring(\"local://\".length);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n // Normalize path to handle leading/trailing slashes\n resolvedPath = normalizeStoragePath(resolvedPath);\n\n if (!resolvedPath) {\n // Safety: never delete the bucket root\n return;\n }\n\n const fullPath = this.getFullPath(resolvedPath, resolvedBucket);\n\n // Check if path exists before attempting to delete\n try {\n await access(fullPath, fs.constants.F_OK);\n } catch {\n // File doesn't exist — nothing to delete\n return;\n }\n\n try {\n const stats = await stat(fullPath);\n if (stats.isDirectory()) {\n // Only remove if empty — client must delete contents first\n await fs.promises.rmdir(fullPath);\n } else {\n await unlink(fullPath);\n // Also delete metadata file if exists\n try {\n await unlink(`${fullPath}.metadata.json`);\n } catch {\n // Metadata file might not exist\n }\n }\n } catch (error: unknown) {\n if (error instanceof Error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\" || code === \"ENOTEMPTY\") {\n // File doesn't exist or directory not empty — ignore\n return;\n }\n }\n throw error;\n }\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n // Normalize path to handle leading/trailing slashes\n const normalizedPath = normalizeStoragePath(prefix);\n const fullPath = this.getFullPath(normalizedPath, options?.bucket);\n const items: StorageReference[] = [];\n const prefixes: StorageReference[] = [];\n\n try {\n await access(fullPath, fs.constants.R_OK);\n const entries = await readdir(fullPath, { withFileTypes: true });\n\n let count = 0;\n const maxResults = options?.maxResults ?? 1000;\n const startIndex = options?.pageToken ? parseInt(options.pageToken, 10) : 0;\n\n for (let i = startIndex; i < entries.length && count < maxResults; i++) {\n const entry = entries[i];\n\n // Skip metadata files\n if (entry.name.endsWith(\".metadata.json\")) {\n continue;\n }\n\n const entryPath = prefix ? `${prefix}/${entry.name}` : entry.name;\n const bucket = options?.bucket ?? \"default\";\n\n const ref: StorageReference = {\n bucket,\n fullPath: entryPath,\n name: entry.name,\n parent: null as never, // Simplified - not fully implementing parent chain\n root: null as never,\n toString: () => `local://${bucket}/${entryPath}`\n };\n\n if (entry.isDirectory()) {\n prefixes.push(ref);\n } else {\n items.push(ref);\n }\n count++;\n }\n\n const nextPageToken = startIndex + count < entries.length\n ? String(startIndex + count)\n : undefined;\n\n return {\n items,\n prefixes,\n nextPageToken\n };\n } catch (error: unknown) {\n const code = (error as NodeJS.ErrnoException)?.code;\n if (code === \"ENOENT\" || code === \"ENOTDIR\") {\n return { items: [],\nprefixes: [] };\n }\n throw error;\n }\n }\n\n /**\n * Get the absolute filesystem path for serving files\n * Used by the storage routes to serve files directly\n */\n getAbsolutePath(key: string, bucket?: string): string {\n return this.getFullPath(key, bucket);\n }\n\n /**\n * Get the base path for the storage\n */\n getBasePath(): string {\n return this.basePath;\n }\n}\n","/**\n * S3-compatible storage controller (works with AWS S3 and MinIO)\n */\n\nimport type { S3Client as S3ClientType, } from \"@aws-sdk/client-s3\";\nimport { DEFAULT_MAX_FILE_SIZE, S3StorageConfig, StorageController } from \"./types\";\nimport {\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference,\n UploadFileProps,\n UploadFileResult\n} from \"@rebasepro/types\";\n\nlet _s3Module: typeof import(\"@aws-sdk/client-s3\") | undefined;\nlet _presignerModule: typeof import(\"@aws-sdk/s3-request-presigner\") | undefined;\n\nasync function loadS3() {\n if (!_s3Module) {\n try {\n _s3Module = await import(\"@aws-sdk/client-s3\");\n } catch {\n throw new Error(\n \"@aws-sdk/client-s3 is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _s3Module;\n}\n\nasync function loadPresigner() {\n if (!_presignerModule) {\n try {\n _presignerModule = await import(\"@aws-sdk/s3-request-presigner\");\n } catch {\n throw new Error(\n \"@aws-sdk/s3-request-presigner is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _presignerModule;\n}\n\n/**\n * S3-compatible storage implementation\n * Works with AWS S3 and MinIO (with forcePathStyle option)\n */\nexport class S3StorageController implements StorageController {\n private config: S3StorageConfig;\n private _client: S3ClientType | undefined;\n\n constructor(config: S3StorageConfig) {\n this.config = config;\n }\n\n /**\n * Lazily create and cache the S3 client on first use\n */\n private async getClient(): Promise<S3ClientType> {\n if (!this._client) {\n const s3 = await loadS3();\n this._client = new s3.S3Client({\n region: this.config.region || \"us-east-1\",\n endpoint: this.config.endpoint,\n forcePathStyle: this.config.forcePathStyle ?? !!this.config.endpoint, // Auto-enable for custom endpoints (MinIO)\n credentials: {\n accessKeyId: this.config.accessKeyId,\n secretAccessKey: this.config.secretAccessKey\n }\n });\n }\n return this._client;\n }\n\n getType(): \"s3\" {\n return \"s3\";\n }\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name - either from parameter or config\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for S3 it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.PutObjectCommand({\n Bucket: usedBucket,\n Key: key,\n Body: buffer,\n ContentType: file.type,\n Metadata: metadata ? this.flattenMetadata(metadata) : undefined\n });\n\n await client.send(command);\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `s3://${usedBucket}/${key}`\n };\n }\n\n /**\n * Flatten nested metadata to string values (S3 requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle s3:// and gs:// URLs for backward compatibility\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const presigner = await loadPresigner();\n const client = await this.getClient();\n\n // First check if the object exists and get metadata\n const headCommand = new s3.HeadObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const headResult = await client.send(headCommand);\n\n // Generate a signed URL\n const getCommand = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const url = await presigner.getSignedUrl(client, getCommand, { expiresIn });\n\n const metadata: DownloadMetadata = {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: headResult.ContentLength || 0,\n contentType: headResult.ContentType || \"application/octet-stream\",\n customMetadata: headResult.Metadata || {}\n };\n\n return {\n url,\n metadata\n };\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NotFound\" || s3Error.$metadata?.httpStatusCode === 404) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw error;\n }\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const response = await client.send(command);\n\n if (!response.Body) {\n return null;\n }\n\n // Convert stream to buffer\n const chunks: Uint8Array[] = [];\n for await (const chunk of response.Body as AsyncIterable<Uint8Array>) {\n chunks.push(chunk);\n }\n const buffer = Buffer.concat(chunks);\n\n const contentType = response.ContentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([buffer], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.DeleteObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n await client.send(command);\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.ListObjectsV2Command({\n Bucket: resolvedBucket,\n Prefix: prefix || undefined,\n MaxKeys: options?.maxResults ?? 1000,\n ContinuationToken: options?.pageToken,\n Delimiter: \"/\" // This gives us folder-like behavior\n });\n\n const response = await client.send(command);\n\n const items: StorageReference[] = (response.Contents || []).map(obj => ({\n bucket: resolvedBucket,\n fullPath: obj.Key || \"\",\n name: (obj.Key || \"\").split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${obj.Key}`\n }));\n\n const prefixes: StorageReference[] = (response.CommonPrefixes || []).map(prefix => ({\n bucket: resolvedBucket,\n fullPath: prefix.Prefix || \"\",\n name: (prefix.Prefix || \"\").replace(/\\/$/, \"\").split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${prefix.Prefix}`\n }));\n\n return {\n items,\n prefixes,\n nextPageToken: response.NextContinuationToken\n };\n }\n}\n","/**\n * Google Cloud Storage controller (works with GCS and Firebase Storage)\n *\n * The `@google-cloud/storage` package is loaded lazily so it remains an\n * optional peer dependency — users who don't need GCS never pay for the\n * import cost or need it installed.\n */\n\nimport {\n StorageController,\n GCSStorageConfig,\n DEFAULT_MAX_FILE_SIZE\n} from \"./types\";\nimport {\n UploadFileProps,\n UploadFileResult,\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference\n} from \"@rebasepro/types\";\n\n// ---------------------------------------------------------------------------\n// Lazy import of @google-cloud/storage\n// ---------------------------------------------------------------------------\n\nlet gcsModule: typeof import(\"@google-cloud/storage\") | null = null;\n\nasync function loadGCS(): Promise<typeof import(\"@google-cloud/storage\")> {\n if (gcsModule) return gcsModule;\n try {\n gcsModule = await import(\"@google-cloud/storage\");\n return gcsModule;\n } catch {\n throw new Error(\n \"Google Cloud Storage is required for the GCS storage controller. \" +\n \"Install it with: pnpm add @google-cloud/storage\"\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// GCSStorageController\n// ---------------------------------------------------------------------------\n\n/**\n * Google Cloud Storage implementation of `StorageController`.\n *\n * Works with standard GCS buckets **and** Firebase Storage buckets\n * (e.g. `\"my-project.appspot.com\"`).\n */\nexport class GCSStorageController implements StorageController {\n private config: GCSStorageConfig;\n private client: InstanceType<typeof import(\"@google-cloud/storage\").Storage> | null = null;\n\n constructor(config: GCSStorageConfig) {\n this.config = config;\n }\n\n // ------------------------------------------------------------------\n // Lazy client initialisation\n // ------------------------------------------------------------------\n\n private async getClient(): Promise<InstanceType<typeof import(\"@google-cloud/storage\").Storage>> {\n if (this.client) return this.client;\n const { Storage } = await loadGCS();\n this.client = new Storage({\n projectId: this.config.projectId,\n keyFilename: this.config.keyFilename,\n credentials: this.config.credentials\n });\n return this.client;\n }\n\n // ------------------------------------------------------------------\n // StorageController interface\n // ------------------------------------------------------------------\n\n getType(): \"gcs\" {\n return \"gcs\";\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n const client = await this.getClient();\n const gcsFile = client.bucket(usedBucket).file(key);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n await gcsFile.save(buffer, {\n contentType: file.type,\n metadata: metadata ? { metadata: this.flattenMetadata(metadata) } : undefined\n });\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `gs://${usedBucket}/${key}`\n };\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n // Get metadata first to check existence and populate response\n const [fileMetadata] = await gcsFile.getMetadata();\n\n // Generate a signed URL\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const [url] = await gcsFile.getSignedUrl({\n action: \"read\",\n expires: Date.now() + expiresIn * 1000\n });\n\n const metadata: DownloadMetadata = {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: Number(fileMetadata.size) || 0,\n contentType: fileMetadata.contentType || \"application/octet-stream\",\n customMetadata: (fileMetadata.metadata as Record<string, string> | undefined) || {}\n };\n\n return {\n url,\n metadata\n };\n } catch (error: unknown) {\n if (isNotFoundError(error)) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw error;\n }\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n const [contents] = await gcsFile.download();\n\n // Get content type from metadata\n const [fileMetadata] = await gcsFile.getMetadata();\n const contentType = fileMetadata.contentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([new Uint8Array(contents)], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n await gcsFile.delete({ ignoreNotFound: true });\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n const client = await this.getClient();\n const gcsBucket = client.bucket(resolvedBucket);\n\n // Fetch files (objects) matching the prefix\n const [files, , filesApiResponse] = await gcsBucket.getFiles({\n prefix: prefix || undefined,\n delimiter: \"/\",\n maxResults: options?.maxResults ?? 1000,\n pageToken: options?.pageToken,\n autoPaginate: false\n });\n\n const items: StorageReference[] = files.map(file => ({\n bucket: resolvedBucket,\n fullPath: file.name,\n name: file.name.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `gs://${resolvedBucket}/${file.name}`\n }));\n\n // Common prefixes (folder-like entries) come from the API response\n const apiPrefixes: string[] =\n (filesApiResponse as Record<string, unknown> | undefined)?.prefixes as string[] ?? [];\n\n const prefixes: StorageReference[] = apiPrefixes.map(p => ({\n bucket: resolvedBucket,\n fullPath: p,\n name: p.replace(/\\/$/, \"\").split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `gs://${resolvedBucket}/${p}`\n }));\n\n // The next page token is returned on the query object (second element)\n const nextPageToken =\n (filesApiResponse as Record<string, unknown> | undefined)?.nextPageToken as string | undefined;\n\n return {\n items,\n prefixes,\n nextPageToken\n };\n }\n\n // ------------------------------------------------------------------\n // Private helpers\n // ------------------------------------------------------------------\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name — either from parameter or config.\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for GCS it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n /**\n * Flatten nested metadata to string values (GCS custom metadata requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Error helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether an error represents a 404 / Not Found from the GCS client.\n */\nfunction isNotFoundError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const err = error as Record<string, unknown>;\n if (err[\"code\"] === 404) return true;\n if (typeof err[\"message\"] === \"string\" && /not found/i.test(err[\"message\"])) return true;\n return false;\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\nlet _googleAuth: typeof import(\"google-auth-library/build/src/index.js\") | undefined;\n\nasync function loadGoogleAuth() {\n if (!_googleAuth) {\n try {\n _googleAuth = await import(\"google-auth-library/build/src/index.js\");\n } catch {\n throw new Error(\n \"google-auth-library is required for Google OAuth. \" +\n \"Install it: pnpm add google-auth-library\"\n );\n }\n }\n return _googleAuth;\n}\n\nexport interface GoogleUserInfo {\n googleId: string;\n email: string;\n displayName: string | null;\n photoUrl: string | null;\n emailVerified: boolean;\n}\n\nexport interface GoogleProviderConfig {\n clientId: string;\n /**\n * The OAuth 2.0 client secret from Google Cloud Console.\n *\n * Required for the **authorization code flow** (Path 3), where the\n * frontend sends an authorization `code` and the backend exchanges it\n * server-side for tokens. This is the most secure flow because tokens\n * never touch the browser.\n *\n * When omitted, only ID-token and access-token verification are available\n * (Paths 1 & 2), which rely on the frontend obtaining tokens directly.\n */\n clientSecret?: string;\n}\n\n/**\n * Creates a Google OAuth Provider integration.\n *\n * Supports three verification paths:\n *\n * **Path 1 – ID Token** (One Tap / Sign In With Google button):\n * Frontend sends `idToken`. Backend verifies cryptographically using\n * Google's public keys. No secret required.\n *\n * **Path 2 – Access Token** (popup via `initTokenClient`):\n * Frontend sends `accessToken`. Backend validates by calling Google's\n * userinfo endpoint. No secret required.\n *\n * **Path 3 – Authorization Code** (most secure, requires `clientSecret`):\n * Frontend sends `code` + `redirectUri`. Backend exchanges the code\n * server-side for an ID token using `clientId` + `clientSecret`, then\n * verifies the ID token. Tokens never touch the browser.\n */\nexport function createGoogleProvider(config: GoogleProviderConfig | string): OAuthProvider<{\n idToken?: string;\n accessToken?: string;\n code?: string;\n redirectUri?: string;\n}> {\n const clientId = typeof config === \"string\" ? config : config.clientId;\n const clientSecret = typeof config === \"string\" ? undefined : config.clientSecret;\n let googleClient: InstanceType<typeof import(\"google-auth-library/build/src/index.js\").OAuth2Client> | undefined;\n\n async function getClient() {\n if (!googleClient) {\n const { OAuth2Client } = await loadGoogleAuth();\n googleClient = new OAuth2Client(clientId, clientSecret);\n }\n return googleClient;\n }\n\n return {\n id: \"google\",\n schema: z.object({\n idToken: z.string().min(1).optional(),\n accessToken: z.string().min(1).optional(),\n code: z.string().min(1).optional(),\n redirectUri: z.string().min(1).optional()\n }).refine(\n (data) => data.idToken || data.accessToken || (data.code && data.redirectUri),\n { message: \"One of idToken, accessToken, or code+redirectUri is required\" }\n ),\n verify: async (payload: {\n idToken?: string;\n accessToken?: string;\n code?: string;\n redirectUri?: string;\n }): Promise<OAuthProviderProfile | null> => {\n try {\n // Path 1: verify an ID token (One Tap / renderButton)\n if (payload.idToken) {\n const client = await getClient();\n const ticket = await client.verifyIdToken({\n idToken: payload.idToken,\n audience: clientId\n });\n\n const content = ticket.getPayload();\n if (!content) {\n throw new Error(\"Google ID token payload was empty\");\n }\n\n return {\n providerId: content.sub,\n email: content.email || \"\",\n displayName: content.name || null,\n photoUrl: content.picture || null,\n emailVerified: true\n };\n }\n\n // Path 2: verify an access token via Google's userinfo endpoint\n if (payload.accessToken) {\n const res = await fetch(\n \"https://www.googleapis.com/oauth2/v3/userinfo\",\n { headers: { Authorization: `Bearer ${payload.accessToken}` } }\n );\n if (!res.ok) {\n throw new Error(`Google userinfo request failed with status ${res.status}`);\n }\n const info = await res.json() as {\n sub: string;\n email?: string;\n name?: string;\n picture?: string;\n };\n if (!info.sub || !info.email) {\n throw new Error(\"Google userinfo response missing sub or email\");\n }\n return {\n providerId: info.sub,\n email: info.email,\n displayName: info.name || null,\n photoUrl: info.picture || null,\n emailVerified: true\n };\n }\n\n // Path 3: authorization code exchange (most secure)\n // The frontend obtained a one-time authorization code via the\n // Google OAuth consent screen. We exchange it server-side for\n // tokens, so the access/id tokens never touch the browser.\n if (payload.code && payload.redirectUri) {\n if (!clientSecret) {\n throw new Error(\n \"Google authorization code flow requires clientSecret. \" +\n \"Configure GOOGLE_CLIENT_SECRET in your environment.\"\n );\n }\n\n // Exchange the authorization code for tokens\n const tokenResponse = await fetch(\"https://oauth2.googleapis.com/token\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n code: payload.code,\n client_id: clientId,\n client_secret: clientSecret,\n redirect_uri: payload.redirectUri,\n grant_type: \"authorization_code\"\n })\n });\n\n if (!tokenResponse.ok) {\n const errorBody = await tokenResponse.text();\n throw new Error(`Google token exchange failed (${tokenResponse.status}): ${errorBody}`);\n }\n\n const tokenData = await tokenResponse.json() as {\n id_token?: string;\n access_token?: string;\n error?: string;\n error_description?: string;\n };\n\n if (tokenData.error) {\n throw new Error(`Google token exchange error: ${tokenData.error} – ${tokenData.error_description || \"no details\"}`);\n }\n\n // Prefer verifying the ID token (cryptographic verification)\n if (tokenData.id_token) {\n const client = await getClient();\n const ticket = await client.verifyIdToken({\n idToken: tokenData.id_token,\n audience: clientId\n });\n\n const content = ticket.getPayload();\n if (!content) {\n throw new Error(\"Google ID token payload was empty after code exchange\");\n }\n\n return {\n providerId: content.sub,\n email: content.email || \"\",\n displayName: content.name || null,\n photoUrl: content.picture || null,\n emailVerified: true\n };\n }\n\n // Fallback: use the access token to fetch userinfo\n if (tokenData.access_token) {\n const userInfoRes = await fetch(\n \"https://www.googleapis.com/oauth2/v3/userinfo\",\n { headers: { Authorization: `Bearer ${tokenData.access_token}` } }\n );\n if (!userInfoRes.ok) {\n throw new Error(`Google userinfo request failed after code exchange (${userInfoRes.status})`);\n }\n const info = await userInfoRes.json() as {\n sub: string;\n email?: string;\n name?: string;\n picture?: string;\n };\n if (!info.sub || !info.email) {\n return null;\n }\n return {\n providerId: info.sub,\n email: info.email,\n displayName: info.name || null,\n photoUrl: info.picture || null,\n emailVerified: true\n };\n }\n\n throw new Error(\"Google token exchange returned neither id_token nor access_token\");\n }\n\n throw new Error(\"No valid Google credential provided (expected idToken, accessToken, or code+redirectUri)\");\n } catch (error) {\n logger.error(\"Google OAuth verification failed\", { error: error });\n throw error;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\nexport interface LinkedinUserInfo {\n linkedinId: string;\n email: string;\n displayName: string | null;\n photoUrl: string | null;\n emailVerified: boolean;\n}\n\n/**\n * Creates a LinkedIn OAuth Provider integration\n */\nexport function createLinkedinProvider(config: { clientId: string, clientSecret: string }): OAuthProvider<{ code: string; redirectUri: string }> {\n return {\n id: \"linkedin\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n // Exchange code for access token\n const tokenResponse = await fetch(\"https://www.linkedin.com/oauth/v2/accessToken\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n body: new URLSearchParams({\n grant_type: \"authorization_code\",\n code: payload.code,\n redirect_uri: payload.redirectUri,\n client_id: config.clientId,\n client_secret: config.clientSecret\n })\n });\n\n if (!tokenResponse.ok) {\n const errBody = await tokenResponse.text();\n logger.error(\"Failed to get LinkedIn access token\", { detail: errBody });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token: string; id_token?: string };\n const accessToken = tokenData.access_token;\n\n // Fetch User Info using OIDC userinfo endpoint\n const profileResponse = await fetch(\"https://api.linkedin.com/v2/userinfo\", {\n headers: {\n \"Authorization\": `Bearer ${accessToken}`\n }\n });\n\n if (!profileResponse.ok) {\n const errBody = await profileResponse.text();\n logger.error(\"Failed to get LinkedIn user info\", { detail: errBody });\n return null;\n }\n\n const profileData = await profileResponse.json() as {\n sub: string;\n email: string;\n name?: string;\n picture?: string;\n email_verified?: boolean;\n };\n\n return {\n providerId: profileData.sub,\n email: profileData.email,\n displayName: profileData.name || null,\n photoUrl: profileData.picture || null,\n emailVerified: profileData.email_verified === true\n };\n } catch (error) {\n logger.error(\"LinkedIn OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a GitHub OAuth Provider integration.\n *\n * Flow: Frontend receives an authorization `code` via the GitHub OAuth redirect.\n * This provider exchanges the code for an access token, then fetches the user's\n * profile and primary email from the GitHub API.\n */\nexport function createGitHubProvider(config: { clientId: string; clientSecret: string }): OAuthProvider<{ code: string; redirectUri: string }> {\n return {\n id: \"github\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n // Exchange code for access token\n const tokenResponse = await fetch(\"https://github.com/login/oauth/access_token\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify({\n client_id: config.clientId,\n client_secret: config.clientSecret,\n code: payload.code,\n redirect_uri: payload.redirectUri\n })\n });\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get GitHub access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token?: string; error?: string };\n if (tokenData.error || !tokenData.access_token) {\n logger.error(\"GitHub token exchange error\", { detail: tokenData.error });\n return null;\n }\n\n const accessToken = tokenData.access_token;\n\n // Fetch user profile\n const profileResponse = await fetch(\"https://api.github.com/user\", {\n headers: {\n \"Authorization\": `Bearer ${accessToken}`,\n \"Accept\": \"application/vnd.github+json\",\n \"User-Agent\": \"Rebase-Auth\"\n }\n });\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get GitHub user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const profileData = await profileResponse.json() as {\n id: number;\n login: string;\n name?: string | null;\n avatar_url?: string | null;\n email?: string | null;\n };\n\n // GitHub may not return email in profile if it's private.\n // Fetch from /user/emails endpoint instead.\n let email = profileData.email;\n if (!email) {\n const emailsResponse = await fetch(\"https://api.github.com/user/emails\", {\n headers: {\n \"Authorization\": `Bearer ${accessToken}`,\n \"Accept\": \"application/vnd.github+json\",\n \"User-Agent\": \"Rebase-Auth\"\n }\n });\n\n if (emailsResponse.ok) {\n const emails = await emailsResponse.json() as Array<{\n email: string;\n primary: boolean;\n verified: boolean;\n }>;\n const primary = emails.find(e => e.primary && e.verified) || emails.find(e => e.verified);\n email = primary?.email || null;\n }\n }\n\n if (!email) {\n logger.error(\"GitHub user has no verified email\");\n return null;\n }\n\n return {\n providerId: String(profileData.id),\n email,\n displayName: profileData.name || profileData.login || null,\n photoUrl: profileData.avatar_url || null,\n emailVerified: true\n };\n } catch (error) {\n logger.error(\"GitHub OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a Microsoft / Entra ID (Azure AD) OAuth Provider integration.\n *\n * Supports both personal Microsoft accounts and work/school (Azure AD) accounts\n * via the \"common\" tenant endpoint. Uses the authorization code flow.\n */\nexport function createMicrosoftProvider(config: {\n clientId: string;\n clientSecret: string;\n /** Tenant ID. Defaults to \"common\" which allows both personal and organizational accounts. */\n tenantId?: string;\n}): OAuthProvider<{ code: string; redirectUri: string }> {\n const tenantId = config.tenantId || \"common\";\n\n return {\n id: \"microsoft\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n // Exchange code for access token\n const tokenResponse = await fetch(\n `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: config.clientId,\n client_secret: config.clientSecret,\n code: payload.code,\n redirect_uri: payload.redirectUri,\n grant_type: \"authorization_code\",\n scope: \"openid profile email User.Read\"\n })\n }\n );\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get Microsoft access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token: string };\n const accessToken = tokenData.access_token;\n\n // Fetch user profile from Microsoft Graph\n const profileResponse = await fetch(\"https://graph.microsoft.com/v1.0/me\", {\n headers: { \"Authorization\": `Bearer ${accessToken}` }\n });\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get Microsoft user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const profileData = await profileResponse.json() as {\n id: string;\n displayName?: string | null;\n mail?: string | null;\n userPrincipalName?: string | null;\n };\n\n const email = profileData.mail || profileData.userPrincipalName;\n if (!email) {\n logger.error(\"Microsoft user has no email\");\n return null;\n }\n\n // Attempt to fetch profile photo URL (Graph returns binary, not a URL).\n // We skip this and let the frontend use the Microsoft Graph photo endpoint.\n return {\n providerId: profileData.id,\n email,\n displayName: profileData.displayName || null,\n photoUrl: null,\n emailVerified: true\n };\n } catch (error) {\n logger.error(\"Microsoft OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport jwt from \"jsonwebtoken\";\nimport { logger } from \"../utils/logger\";\n/**\n * Creates an Apple Sign In OAuth Provider integration.\n *\n * Apple requires a client secret that is a signed JWT, regenerated on each\n * token exchange (valid up to 6 months). This provider handles that automatically.\n *\n * Required Apple Developer configuration:\n * - Services ID (clientId)\n * - Key ID from the private key registered with Apple\n * - Team ID from Apple Developer account\n * - Private key (.p8 file contents) downloaded from Apple Developer portal\n */\nexport function createAppleProvider(config: {\n clientId: string;\n teamId: string;\n keyId: string;\n /** The raw PEM contents of the .p8 private key file */\n privateKey: string;\n}): OAuthProvider<{\n code: string;\n redirectUri: string;\n user?: { name?: { firstName?: string; lastName?: string }; email?: string };\n }> {\n /**\n * Generate a client_secret JWT signed with the Apple private key.\n * Apple requires this instead of a static client_secret.\n */\n async function generateClientSecret(): Promise<string> {\n return jwt.sign({}, config.privateKey, {\n algorithm: \"ES256\",\n keyid: config.keyId,\n issuer: config.teamId,\n expiresIn: \"180d\",\n audience: \"https://appleid.apple.com\",\n subject: config.clientId\n });\n }\n\n return {\n id: \"apple\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\"),\n /** Apple sends user info only on first authorization; the frontend must forward it. */\n user: z.object({\n name: z.object({\n firstName: z.string().optional(),\n lastName: z.string().optional()\n }).optional(),\n email: z.string().email().optional()\n }).optional()\n }),\n verify: async (payload: {\n code: string;\n redirectUri: string;\n user?: { name?: { firstName?: string; lastName?: string }; email?: string };\n }): Promise<OAuthProviderProfile | null> => {\n try {\n const clientSecret = await generateClientSecret();\n\n // Exchange code for tokens\n const tokenResponse = await fetch(\"https://appleid.apple.com/auth/token\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: config.clientId,\n client_secret: clientSecret,\n code: payload.code,\n grant_type: \"authorization_code\",\n redirect_uri: payload.redirectUri\n })\n });\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get Apple access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { id_token: string };\n\n // Decode the id_token (JWT) to get user info.\n // Apple's id_token is a standard JWT — we only need the payload.\n const [, payloadB64] = tokenData.id_token.split(\".\");\n const decoded = JSON.parse(Buffer.from(payloadB64, \"base64url\").toString(\"utf8\")) as {\n sub: string;\n email?: string;\n email_verified?: string | boolean;\n };\n\n // Apple only sends the user's name on the FIRST authorization.\n // Subsequent logins only have the id_token. The frontend should pass\n // the user object from the first auth for us to capture the name.\n const email = decoded.email || payload.user?.email;\n if (!email) {\n logger.error(\"Apple user has no email\");\n return null;\n }\n\n let displayName: string | null = null;\n if (payload.user?.name) {\n const parts = [payload.user.name.firstName, payload.user.name.lastName].filter(Boolean);\n displayName = parts.length > 0 ? parts.join(\" \") : null;\n }\n\n return {\n providerId: decoded.sub,\n email,\n displayName,\n photoUrl: null, // Apple does not provide a profile photo\n emailVerified: decoded.email_verified === true || decoded.email_verified === \"true\"\n };\n } catch (error) {\n logger.error(\"Apple OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a Facebook / Meta OAuth Provider integration.\n *\n * Uses the authorization code flow to exchange a code for an access token,\n * then fetches user profile from the Facebook Graph API.\n */\nexport function createFacebookProvider(config: { clientId: string; clientSecret: string }): OAuthProvider<{ code: string; redirectUri: string }> {\n return {\n id: \"facebook\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n // Exchange code for access token\n const tokenUrl = new URL(\"https://graph.facebook.com/v19.0/oauth/access_token\");\n tokenUrl.searchParams.set(\"client_id\", config.clientId);\n tokenUrl.searchParams.set(\"client_secret\", config.clientSecret);\n tokenUrl.searchParams.set(\"redirect_uri\", payload.redirectUri);\n tokenUrl.searchParams.set(\"code\", payload.code);\n\n const tokenResponse = await fetch(tokenUrl.toString());\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get Facebook access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token: string };\n const accessToken = tokenData.access_token;\n\n // Fetch user profile with email and profile picture\n const profileUrl = new URL(\"https://graph.facebook.com/v19.0/me\");\n profileUrl.searchParams.set(\"fields\", \"id,name,email,picture.type(large)\");\n profileUrl.searchParams.set(\"access_token\", accessToken);\n\n const profileResponse = await fetch(profileUrl.toString());\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get Facebook user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const profileData = await profileResponse.json() as {\n id: string;\n name?: string;\n email?: string;\n picture?: { data?: { url?: string } };\n };\n\n if (!profileData.email) {\n logger.error(\"Facebook user has no email (email permission may not have been granted)\");\n return null;\n }\n\n return {\n providerId: profileData.id,\n email: profileData.email,\n displayName: profileData.name || null,\n photoUrl: profileData.picture?.data?.url || null,\n emailVerified: true\n };\n } catch (error) {\n logger.error(\"Facebook OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a Twitter/X OAuth 2.0 Provider integration.\n *\n * Uses OAuth 2.0 with PKCE (authorization code flow). The frontend must include\n * the PKCE `code_verifier` when sending the authorization code.\n *\n * Twitter API v2 requires the \"tweet.read\" and \"users.read\" scopes at minimum,\n * plus \"offline.access\" if refresh tokens are needed on Twitter's side.\n */\nexport function createTwitterProvider(config: { clientId: string; clientSecret: string }): OAuthProvider<{\n code: string;\n redirectUri: string;\n codeVerifier: string;\n }> {\n return {\n id: \"twitter\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\"),\n codeVerifier: z.string().min(1, \"PKCE code verifier is required\")\n }),\n verify: async (payload: {\n code: string;\n redirectUri: string;\n codeVerifier: string;\n }): Promise<OAuthProviderProfile | null> => {\n try {\n // Twitter OAuth 2.0 uses Basic auth for the token endpoint\n const basicAuth = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString(\"base64\");\n\n // Exchange code for access token\n const tokenResponse = await fetch(\"https://api.twitter.com/2/oauth2/token\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Authorization\": `Basic ${basicAuth}`\n },\n body: new URLSearchParams({\n code: payload.code,\n grant_type: \"authorization_code\",\n redirect_uri: payload.redirectUri,\n code_verifier: payload.codeVerifier\n })\n });\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get Twitter access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token: string };\n const accessToken = tokenData.access_token;\n\n // Fetch user profile from Twitter API v2\n const profileResponse = await fetch(\n \"https://api.twitter.com/2/users/me?user.fields=id,name,username,profile_image_url\",\n {\n headers: { \"Authorization\": `Bearer ${accessToken}` }\n }\n );\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get Twitter user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const profileResult = await profileResponse.json() as {\n data: {\n id: string;\n name: string;\n username: string;\n profile_image_url?: string;\n };\n };\n\n const profileData = profileResult.data;\n\n // Twitter does NOT expose email via API v2 by default.\n // It requires elevated access. If we can't get an email, we\n // generate a placeholder email — the user can update it later.\n // For apps with elevated access, fetch from v1.1 endpoint.\n let email: string | null = null;\n let emailVerified = false;\n try {\n const emailResponse = await fetch(\n \"https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true\",\n {\n headers: { \"Authorization\": `Bearer ${accessToken}` }\n }\n );\n if (emailResponse.ok) {\n const emailData = await emailResponse.json() as { email?: string };\n email = emailData.email || null;\n if (email) {\n emailVerified = true;\n }\n }\n } catch {\n // Elevated access not available — fall through\n }\n\n if (!email) {\n // Construct a deterministic placeholder email from the Twitter user ID.\n // This allows the account to be created and linked; the user should\n // update their email through the profile settings.\n email = `${profileData.id}@twitter.placeholder.rebase`;\n // Placeholder emails are NOT verified — prevents auto-linking to existing accounts\n emailVerified = false;\n }\n\n return {\n providerId: profileData.id,\n email,\n displayName: profileData.name || profileData.username || null,\n photoUrl: profileData.profile_image_url?.replace(\"_normal\", \"_400x400\") || null,\n emailVerified\n };\n } catch (error) {\n logger.error(\"Twitter OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a Discord OAuth2 Provider integration.\n *\n * Uses the authorization code flow. Requires the \"identify\" and \"email\"\n * scopes to retrieve the user's email and profile information.\n */\nexport function createDiscordProvider(config: { clientId: string; clientSecret: string }): OAuthProvider<{ code: string; redirectUri: string }> {\n return {\n id: \"discord\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n // Exchange code for access token\n const tokenResponse = await fetch(\"https://discord.com/api/v10/oauth2/token\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: config.clientId,\n client_secret: config.clientSecret,\n grant_type: \"authorization_code\",\n code: payload.code,\n redirect_uri: payload.redirectUri\n })\n });\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get Discord access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token: string };\n const accessToken = tokenData.access_token;\n\n // Fetch user profile\n const profileResponse = await fetch(\"https://discord.com/api/v10/users/@me\", {\n headers: { \"Authorization\": `Bearer ${accessToken}` }\n });\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get Discord user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const profileData = await profileResponse.json() as {\n id: string;\n username: string;\n global_name?: string | null;\n avatar?: string | null;\n email?: string | null;\n verified?: boolean;\n };\n\n if (!profileData.email) {\n logger.error(\"Discord user has no email (email scope may not have been granted)\");\n return null;\n }\n\n // Build avatar URL\n let photoUrl: string | null = null;\n if (profileData.avatar) {\n const ext = profileData.avatar.startsWith(\"a_\") ? \"gif\" : \"png\";\n photoUrl = `https://cdn.discordapp.com/avatars/${profileData.id}/${profileData.avatar}.${ext}?size=256`;\n }\n\n return {\n providerId: profileData.id,\n email: profileData.email,\n displayName: profileData.global_name || profileData.username || null,\n photoUrl,\n emailVerified: profileData.verified === true\n };\n } catch (error) {\n logger.error(\"Discord OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a GitLab OAuth Provider integration.\n * Works with both GitLab.com and self-hosted instances.\n */\nexport function createGitLabProvider(config: {\n clientId: string;\n clientSecret: string;\n baseUrl?: string;\n}): OAuthProvider<{ code: string; redirectUri: string }> {\n const gitlabUrl = (config.baseUrl || \"https://gitlab.com\").replace(/\\/$/, \"\");\n\n return {\n id: \"gitlab\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n const tokenResponse = await fetch(`${gitlabUrl}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n client_id: config.clientId,\n client_secret: config.clientSecret,\n code: payload.code,\n grant_type: \"authorization_code\",\n redirect_uri: payload.redirectUri\n })\n });\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get GitLab access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token: string };\n\n const profileResponse = await fetch(`${gitlabUrl}/api/v4/user`, {\n headers: { \"Authorization\": `Bearer ${tokenData.access_token}` }\n });\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get GitLab user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const p = await profileResponse.json() as {\n id: number; username: string; name?: string;\n email: string; avatar_url?: string | null;\n };\n\n if (!p.email) { logger.error(\"GitLab user has no email\"); return null; }\n\n return {\n providerId: String(p.id),\n email: p.email,\n displayName: p.name || p.username || null,\n photoUrl: p.avatar_url || null,\n emailVerified: true\n };\n } catch (error) {\n logger.error(\"GitLab OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a Bitbucket OAuth Provider integration (OAuth 2.0 consumer).\n */\nexport function createBitbucketProvider(config: { clientId: string; clientSecret: string }): OAuthProvider<{ code: string; redirectUri: string }> {\n return {\n id: \"bitbucket\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n const basicAuth = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString(\"base64\");\n\n const tokenResponse = await fetch(\"https://bitbucket.org/site/oauth2/access_token\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Authorization\": `Basic ${basicAuth}`\n },\n body: new URLSearchParams({\n grant_type: \"authorization_code\",\n code: payload.code,\n redirect_uri: payload.redirectUri\n })\n });\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get Bitbucket access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token: string };\n const accessToken = tokenData.access_token;\n\n const profileResponse = await fetch(\"https://api.bitbucket.org/2.0/user\", {\n headers: { \"Authorization\": `Bearer ${accessToken}` }\n });\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get Bitbucket user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const p = await profileResponse.json() as {\n uuid: string; display_name?: string; username?: string;\n links?: { avatar?: { href?: string } };\n };\n\n // Bitbucket doesn't return email in user profile — fetch from /emails endpoint\n const emailsResponse = await fetch(\"https://api.bitbucket.org/2.0/user/emails\", {\n headers: { \"Authorization\": `Bearer ${accessToken}` }\n });\n\n let email: string | null = null;\n if (emailsResponse.ok) {\n const emailData = await emailsResponse.json() as {\n values: Array<{ email: string; is_primary: boolean; is_confirmed: boolean }>;\n };\n const primary = emailData.values.find(e => e.is_primary && e.is_confirmed)\n || emailData.values.find(e => e.is_confirmed);\n email = primary?.email || null;\n }\n\n if (!email) { logger.error(\"Bitbucket user has no verified email\"); return null; }\n\n return {\n providerId: p.uuid,\n email,\n displayName: p.display_name || p.username || null,\n photoUrl: p.links?.avatar?.href || null,\n emailVerified: true\n };\n } catch (error) {\n logger.error(\"Bitbucket OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a Slack OAuth Provider integration (OAuth 2.0 / \"Sign in with Slack\").\n * Uses the OpenID Connect flow with the \"openid,email,profile\" scopes.\n */\nexport function createSlackProvider(config: { clientId: string; clientSecret: string }): OAuthProvider<{ code: string; redirectUri: string }> {\n return {\n id: \"slack\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n const tokenResponse = await fetch(\"https://slack.com/api/openid.connect.token\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: config.clientId,\n client_secret: config.clientSecret,\n code: payload.code,\n redirect_uri: payload.redirectUri,\n grant_type: \"authorization_code\"\n })\n });\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get Slack access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { ok: boolean; access_token?: string; error?: string };\n if (!tokenData.ok || !tokenData.access_token) {\n logger.error(\"Slack token exchange failed\", { detail: tokenData.error });\n return null;\n }\n\n const profileResponse = await fetch(\"https://slack.com/api/openid.connect.userInfo\", {\n headers: { \"Authorization\": `Bearer ${tokenData.access_token}` }\n });\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get Slack user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const p = await profileResponse.json() as {\n ok: boolean; sub: string; name?: string;\n email?: string; picture?: string; email_verified?: boolean;\n };\n\n if (!p.ok || !p.email) {\n logger.error(\"Slack user has no email\");\n return null;\n }\n\n return {\n providerId: p.sub,\n email: p.email,\n displayName: p.name || null,\n photoUrl: p.picture || null,\n emailVerified: p.email_verified === true\n };\n } catch (error) {\n logger.error(\"Slack OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","import type { OAuthProvider, OAuthProviderProfile } from \"./interfaces\";\nimport { z } from \"zod\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * Creates a Spotify OAuth Provider integration.\n * Uses the authorization code flow with the \"user-read-email\" scope.\n */\nexport function createSpotifyProvider(config: { clientId: string; clientSecret: string }): OAuthProvider<{ code: string; redirectUri: string }> {\n return {\n id: \"spotify\",\n schema: z.object({\n code: z.string().min(1, \"Auth code is required\"),\n redirectUri: z.string().url(\"Valid redirect URI is required\")\n }),\n verify: async (payload: { code: string; redirectUri: string }): Promise<OAuthProviderProfile | null> => {\n try {\n const basicAuth = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString(\"base64\");\n\n const tokenResponse = await fetch(\"https://accounts.spotify.com/api/token\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Authorization\": `Basic ${basicAuth}`\n },\n body: new URLSearchParams({\n grant_type: \"authorization_code\",\n code: payload.code,\n redirect_uri: payload.redirectUri\n })\n });\n\n if (!tokenResponse.ok) {\n logger.error(\"Failed to get Spotify access token\", { detail: await tokenResponse.text() });\n return null;\n }\n\n const tokenData = await tokenResponse.json() as { access_token: string };\n\n const profileResponse = await fetch(\"https://api.spotify.com/v1/me\", {\n headers: { \"Authorization\": `Bearer ${tokenData.access_token}` }\n });\n\n if (!profileResponse.ok) {\n logger.error(\"Failed to get Spotify user info\", { detail: await profileResponse.text() });\n return null;\n }\n\n const p = await profileResponse.json() as {\n id: string; display_name?: string | null;\n email?: string; images?: Array<{ url: string }>;\n };\n\n if (!p.email) { logger.error(\"Spotify user has no email\"); return null; }\n\n return {\n providerId: p.id,\n email: p.email,\n displayName: p.display_name || null,\n photoUrl: p.images?.[0]?.url || null,\n emailVerified: true\n };\n } catch (error) {\n logger.error(\"Spotify OAuth error\", { error: error });\n return null;\n }\n }\n };\n}\n","/**\n * Database operations for Service API Keys.\n *\n * Uses the DataDriver's `admin.executeSql` capability (same pattern as\n * the cron-store and ensure-tables modules). All data lives in the\n * `rebase.api_keys` table.\n *\n * @module\n */\n\nimport { randomBytes, createHash } from \"crypto\";\nimport type { DataDriver } from \"@rebasepro/types\";\nimport { isSQLAdmin } from \"@rebasepro/types\";\nimport { logger } from \"../../utils/logger\";\nimport type {\n ApiKey,\n ApiKeyMasked,\n ApiKeyPermission,\n ApiKeyWithSecret,\n CreateApiKeyRequest,\n UpdateApiKeyRequest\n} from \"./api-key-types\";\n\nconst TABLE = \"rebase.api_keys\";\n\n/** Characters used to generate the random portion of an API key. */\nconst HEX_CHARS = \"abcdef0123456789\";\n\n/**\n * Generate a plaintext API key with the `rk_live_` prefix.\n *\n * Format: `rk_live_` + 32 random hex characters.\n */\nfunction generateApiKey(): string {\n const random = randomBytes(16).toString(\"hex\"); // 32 hex chars\n return `rk_live_${random}`;\n}\n\n/**\n * SHA-256 hash a plaintext API key for database storage.\n */\nfunction hashKey(plaintext: string): string {\n return createHash(\"sha256\").update(plaintext).digest(\"hex\");\n}\n\n/**\n * Extract the display prefix from a plaintext key (first 12 chars).\n */\nfunction keyPrefix(plaintext: string): string {\n return plaintext.substring(0, 12);\n}\n\n/**\n * Strip the `key_hash` field and return a safe-to-expose masked key.\n */\nfunction toMasked(row: ApiKey): ApiKeyMasked {\n return {\n id: row.id,\n name: row.name,\n key_prefix: row.key_prefix,\n permissions: row.permissions,\n admin: row.admin,\n rate_limit: row.rate_limit,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n last_used_at: row.last_used_at,\n expires_at: row.expires_at,\n revoked_at: row.revoked_at\n };\n}\n\n/**\n * Parse a raw DB row into the typed `ApiKey` shape.\n */\nfunction rowToApiKey(row: Record<string, unknown>): ApiKey {\n let permissions = (row.permissions ?? []) as ApiKeyPermission[];\n if (typeof row.permissions === \"string\") {\n try {\n permissions = JSON.parse(row.permissions) as ApiKeyPermission[];\n } catch {\n permissions = [];\n }\n }\n\n return {\n id: row.id as string,\n name: row.name as string,\n key_prefix: row.key_prefix as string,\n key_hash: row.key_hash as string,\n permissions,\n admin: Boolean(row.admin),\n rate_limit: row.rate_limit !== null && row.rate_limit !== undefined\n ? Number(row.rate_limit)\n : null,\n created_by: row.created_by as string,\n created_at: new Date(row.created_at as string).toISOString(),\n updated_at: new Date(row.updated_at as string).toISOString(),\n last_used_at: row.last_used_at ? new Date(row.last_used_at as string).toISOString() : null,\n expires_at: row.expires_at ? new Date(row.expires_at as string).toISOString() : null,\n revoked_at: row.revoked_at ? new Date(row.revoked_at as string).toISOString() : null\n };\n}\n\n// ─── Public API ──────────────────────────────────────────────────────\n\nexport interface ApiKeyStore {\n /** Ensure the `rebase.api_keys` table exists. Called once on startup. */\n ensureTable(): Promise<void>;\n\n /** Create a new API key. Returns the full plaintext key exactly once. */\n createApiKey(request: CreateApiKeyRequest, createdBy: string): Promise<ApiKeyWithSecret>;\n\n /** Look up an API key by its SHA-256 hash. Returns `null` if not found. */\n findByKeyHash(hash: string): Promise<ApiKey | null>;\n\n /** List all API keys (masked, never includes hash). */\n listApiKeys(): Promise<ApiKeyMasked[]>;\n\n /** Get a single API key by ID (masked). */\n getApiKeyById(id: string): Promise<ApiKeyMasked | null>;\n\n /** Update name, permissions, rate_limit, or expires_at. */\n updateApiKey(id: string, updates: UpdateApiKeyRequest): Promise<ApiKeyMasked | null>;\n\n /** Soft-delete: set `revoked_at` to now. */\n revokeApiKey(id: string): Promise<boolean>;\n\n /** Touch `last_used_at` to the current timestamp. */\n updateLastUsed(id: string): Promise<void>;\n}\n\n/**\n * Create an `ApiKeyStore` backed by the driver's SQL admin capability.\n *\n * Returns `undefined` if the driver does not support `executeSql`.\n */\nexport function createApiKeyStore(driver: DataDriver): ApiKeyStore | undefined {\n const admin = driver.admin;\n if (!isSQLAdmin(admin)) {\n logger.warn(\"⚠️ [api-key-store] DataDriver does not support SQL admin — API keys will not be available.\");\n return undefined;\n }\n\n const exec = (sqlText: string, options?: { params?: unknown[] }) =>\n admin.executeSql(sqlText, options?.params ? { params: options.params } : undefined);\n\n return {\n // ── Schema bootstrap ────────────────────────────────────────\n async ensureTable(): Promise<void> {\n try {\n await exec(\"CREATE SCHEMA IF NOT EXISTS rebase\");\n await exec(`\n CREATE TABLE IF NOT EXISTS ${TABLE} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n name TEXT NOT NULL,\n key_prefix TEXT NOT NULL,\n key_hash TEXT NOT NULL UNIQUE,\n permissions JSONB NOT NULL DEFAULT '[]'::jsonb,\n admin BOOLEAN NOT NULL DEFAULT FALSE,\n rate_limit INTEGER,\n created_by TEXT NOT NULL,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n last_used_at TIMESTAMPTZ,\n expires_at TIMESTAMPTZ,\n revoked_at TIMESTAMPTZ\n )\n `);\n\n await exec(`\n CREATE INDEX IF NOT EXISTS idx_api_keys_hash\n ON ${TABLE}(key_hash)\n `);\n\n await exec(`\n CREATE INDEX IF NOT EXISTS idx_api_keys_prefix\n ON ${TABLE}(key_prefix)\n `);\n\n // Migration: add admin column to existing tables\n await exec(`\n ALTER TABLE ${TABLE}\n ADD COLUMN IF NOT EXISTS admin BOOLEAN NOT NULL DEFAULT FALSE\n `);\n\n logger.info(\"✅ API keys table ready\");\n } catch (err) {\n logger.error(\"❌ Failed to create API keys table\", { error: err });\n logger.warn(\"⚠️ Continuing without API keys support.\");\n }\n },\n\n // ── Create ──────────────────────────────────────────────────\n async createApiKey(request: CreateApiKeyRequest, createdBy: string): Promise<ApiKeyWithSecret> {\n const plaintext = generateApiKey();\n const hash = hashKey(plaintext);\n const prefix = keyPrefix(plaintext);\n const permissionsJson = JSON.stringify(request.permissions);\n\n const rows = await exec(\n `INSERT INTO ${TABLE} (name, key_prefix, key_hash, permissions, admin, rate_limit, created_by, expires_at)\n VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8)\n RETURNING *`,\n { params: [\n request.name,\n prefix,\n hash,\n permissionsJson,\n request.admin ?? false,\n request.rate_limit ?? null,\n createdBy,\n request.expires_at ?? null\n ]}\n );\n\n const apiKey = rowToApiKey(rows[0]);\n return {\n ...toMasked(apiKey),\n key: plaintext\n };\n },\n\n // ── Lookup by hash ──────────────────────────────────────────\n async findByKeyHash(hash: string): Promise<ApiKey | null> {\n const rows = await exec(\n `SELECT * FROM ${TABLE}\n WHERE key_hash = $1\n LIMIT 1`,\n { params: [hash] }\n );\n if (rows.length === 0) return null;\n return rowToApiKey(rows[0]);\n },\n\n // ── List all (masked) ───────────────────────────────────────\n async listApiKeys(): Promise<ApiKeyMasked[]> {\n const rows = await exec(`\n SELECT * FROM ${TABLE}\n ORDER BY created_at DESC\n `);\n return rows.map(r => toMasked(rowToApiKey(r)));\n },\n\n // ── Get by ID (masked) ──────────────────────────────────────\n async getApiKeyById(id: string): Promise<ApiKeyMasked | null> {\n const rows = await exec(\n `SELECT * FROM ${TABLE}\n WHERE id = $1\n LIMIT 1`,\n { params: [id] }\n );\n if (rows.length === 0) return null;\n return toMasked(rowToApiKey(rows[0]));\n },\n\n // ── Update ──────────────────────────────────────────────────\n async updateApiKey(id: string, updates: UpdateApiKeyRequest): Promise<ApiKeyMasked | null> {\n const setClauses: string[] = [];\n const params: unknown[] = [];\n let paramIdx = 1;\n\n if (updates.name !== undefined) {\n setClauses.push(`name = $${paramIdx++}`);\n params.push(updates.name);\n }\n if (updates.permissions !== undefined) {\n setClauses.push(`permissions = $${paramIdx++}::jsonb`);\n params.push(JSON.stringify(updates.permissions));\n }\n if (updates.admin !== undefined) {\n setClauses.push(`admin = $${paramIdx++}`);\n params.push(updates.admin);\n }\n if (updates.rate_limit !== undefined) {\n if (updates.rate_limit !== null) {\n setClauses.push(`rate_limit = $${paramIdx++}`);\n params.push(updates.rate_limit);\n } else {\n setClauses.push(\"rate_limit = NULL\");\n }\n }\n if (updates.expires_at !== undefined) {\n if (updates.expires_at !== null) {\n setClauses.push(`expires_at = $${paramIdx++}`);\n params.push(updates.expires_at);\n } else {\n setClauses.push(\"expires_at = NULL\");\n }\n }\n\n if (setClauses.length === 0) {\n return this.getApiKeyById(id);\n }\n\n setClauses.push(\"updated_at = NOW()\");\n\n // The WHERE id = $N uses the next available param index\n params.push(id);\n\n const rows = await exec(\n `UPDATE ${TABLE}\n SET ${setClauses.join(\", \")}\n WHERE id = $${paramIdx}\n RETURNING *`,\n { params }\n );\n\n if (rows.length === 0) return null;\n return toMasked(rowToApiKey(rows[0]));\n },\n\n // ── Revoke (soft-delete) ────────────────────────────────────\n async revokeApiKey(id: string): Promise<boolean> {\n const rows = await exec(\n `UPDATE ${TABLE}\n SET revoked_at = NOW(), updated_at = NOW()\n WHERE id = $1 AND revoked_at IS NULL\n RETURNING id`,\n { params: [id] }\n );\n return rows.length > 0;\n },\n\n // ── Touch last_used_at ──────────────────────────────────────\n async updateLastUsed(id: string): Promise<void> {\n try {\n await exec(\n `UPDATE ${TABLE}\n SET last_used_at = NOW()\n WHERE id = $1`,\n { params: [id] }\n );\n } catch (err) {\n // Non-blocking — don't fail requests because of a usage timestamp update\n logger.error(\"[api-key-store] Failed to update last_used_at\", { error: err });\n }\n }\n };\n}\n","/**\n * Admin routes for managing Service API Keys.\n *\n * Mounted under `/api/admin/api-keys` with `requireAuth` + `requireAdmin`.\n * All routes return masked keys (never the hash). The full plaintext key\n * is returned exactly once in the POST response.\n *\n * @module\n */\n\nimport { Hono } from \"hono\";\nimport { ApiError, errorHandler } from \"../../api/errors\";\nimport { createRequireAuth, requireAdmin } from \"../middleware\";\nimport type { HonoEnv } from \"../../api/types\";\nimport type { ApiKeyStore } from \"./api-key-store\";\nimport type { CreateApiKeyRequest, UpdateApiKeyRequest, ApiKeyPermission } from \"./api-key-types\";\n\nexport interface ApiKeyRouteOptions {\n store: ApiKeyStore;\n serviceKey?: string;\n}\n\n/**\n * Validate that a permissions array is well-formed.\n */\nfunction validatePermissions(permissions: unknown): permissions is ApiKeyPermission[] {\n if (!Array.isArray(permissions)) return false;\n for (const perm of permissions) {\n if (typeof perm !== \"object\" || perm === null) return false;\n if (typeof perm.collection !== \"string\" || perm.collection.length === 0) return false;\n if (!Array.isArray(perm.operations) || perm.operations.length === 0) return false;\n const validOps = new Set([\"read\", \"write\", \"delete\"]);\n for (const op of perm.operations) {\n if (!validOps.has(op)) return false;\n }\n }\n return true;\n}\n\n/**\n * Create admin routes for API key management.\n */\nexport function createApiKeyRoutes(options: ApiKeyRouteOptions): Hono<HonoEnv> {\n const { store, serviceKey } = options;\n const router = new Hono<HonoEnv>();\n\n router.onError(errorHandler);\n\n // Apply auth middleware (service-key-aware)\n router.use(\"/*\", createRequireAuth({ serviceKey }));\n router.use(\"/*\", requireAdmin);\n\n // GET / — List all API keys (masked)\n router.get(\"/\", async (c) => {\n const keys = await store.listApiKeys();\n return c.json({ keys });\n });\n\n // POST / — Create a new API key\n router.post(\"/\", async (c) => {\n const body = await c.req.json() as Record<string, unknown>;\n const { name, permissions, admin, rate_limit, expires_at } = body;\n\n if (!name || typeof name !== \"string\" || name.trim().length === 0) {\n throw ApiError.badRequest(\"Name is required\", \"INVALID_INPUT\");\n }\n\n if (!validatePermissions(permissions)) {\n throw ApiError.badRequest(\n \"Permissions must be an array of { collection: string, operations: ('read' | 'write' | 'delete')[] }\",\n \"INVALID_INPUT\"\n );\n }\n\n if (admin !== undefined && typeof admin !== \"boolean\") {\n throw ApiError.badRequest(\"admin must be a boolean\", \"INVALID_INPUT\");\n }\n\n if (rate_limit !== undefined && rate_limit !== null) {\n if (typeof rate_limit !== \"number\" || rate_limit < 1 || !Number.isInteger(rate_limit)) {\n throw ApiError.badRequest(\"rate_limit must be a positive integer or null\", \"INVALID_INPUT\");\n }\n }\n\n if (expires_at !== undefined && expires_at !== null) {\n const parsed = new Date(expires_at as string);\n if (isNaN(parsed.getTime())) {\n throw ApiError.badRequest(\"expires_at must be a valid ISO-8601 date\", \"INVALID_INPUT\");\n }\n if (parsed <= new Date()) {\n throw ApiError.badRequest(\"expires_at must be in the future\", \"INVALID_INPUT\");\n }\n }\n\n const user = c.get(\"user\");\n const createdBy = (user && typeof user === \"object\" && \"userId\" in user)\n ? (user.userId as string)\n : \"unknown\";\n\n const request: CreateApiKeyRequest = {\n name: name.trim(),\n permissions: permissions as ApiKeyPermission[],\n admin: (admin as boolean) ?? false,\n rate_limit: (rate_limit as number | null) ?? null,\n expires_at: (expires_at as string | null) ?? null\n };\n\n const keyWithSecret = await store.createApiKey(request, createdBy);\n\n return c.json({ key: keyWithSecret }, 201);\n });\n\n // GET /:id — Get API key details (masked)\n router.get(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const key = await store.getApiKeyById(id);\n\n if (!key) {\n throw ApiError.notFound(\"API key not found\");\n }\n\n return c.json({ key });\n });\n\n // PUT /:id — Update API key\n router.put(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const body = await c.req.json() as Record<string, unknown>;\n const { name, permissions, admin, rate_limit, expires_at } = body;\n\n // Validate fields if provided\n if (name !== undefined) {\n if (typeof name !== \"string\" || name.trim().length === 0) {\n throw ApiError.badRequest(\"Name must be a non-empty string\", \"INVALID_INPUT\");\n }\n }\n\n if (permissions !== undefined) {\n if (!validatePermissions(permissions)) {\n throw ApiError.badRequest(\n \"Permissions must be an array of { collection: string, operations: ('read' | 'write' | 'delete')[] }\",\n \"INVALID_INPUT\"\n );\n }\n }\n\n if (admin !== undefined && typeof admin !== \"boolean\") {\n throw ApiError.badRequest(\"admin must be a boolean\", \"INVALID_INPUT\");\n }\n\n if (rate_limit !== undefined && rate_limit !== null) {\n if (typeof rate_limit !== \"number\" || rate_limit < 1 || !Number.isInteger(rate_limit)) {\n throw ApiError.badRequest(\"rate_limit must be a positive integer or null\", \"INVALID_INPUT\");\n }\n }\n\n if (expires_at !== undefined && expires_at !== null) {\n const parsed = new Date(expires_at as string);\n if (isNaN(parsed.getTime())) {\n throw ApiError.badRequest(\"expires_at must be a valid ISO-8601 date\", \"INVALID_INPUT\");\n }\n }\n\n const updates: UpdateApiKeyRequest = {};\n if (name !== undefined) updates.name = (name as string).trim();\n if (permissions !== undefined) updates.permissions = permissions as ApiKeyPermission[];\n if (admin !== undefined) updates.admin = admin as boolean;\n if (rate_limit !== undefined) updates.rate_limit = rate_limit as number | null;\n if (expires_at !== undefined) updates.expires_at = expires_at as string | null;\n\n const key = await store.updateApiKey(id, updates);\n\n if (!key) {\n throw ApiError.notFound(\"API key not found\");\n }\n\n return c.json({ key });\n });\n\n // DELETE /:id — Revoke (soft-delete)\n router.delete(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const revoked = await store.revokeApiKey(id);\n\n if (!revoked) {\n throw ApiError.notFound(\"API key not found or already revoked\");\n }\n\n return c.json({ success: true });\n });\n\n return router;\n}\n","/**\n * Custom Auth Adapter Factory\n *\n * Provides a minimal-config way for users with existing auth systems\n * to plug into Rebase. Only `verifyRequest` is required — everything\n * else is optional.\n *\n * @example\n * ```ts\n * import { createCustomAuthAdapter } from \"@rebasepro/server-core\";\n *\n * const auth = createCustomAuthAdapter({\n * verifyRequest: async (request) => {\n * const token = request.headers.get(\"Authorization\")?.replace(\"Bearer \", \"\");\n * if (!token) return null;\n * const decoded = jwt.verify(token, MY_SECRET);\n * return {\n * uid: decoded.sub,\n * email: decoded.email,\n * displayName: decoded.name,\n * roles: decoded.roles || [],\n * isAdmin: decoded.roles?.includes(\"admin\") ?? false,\n * };\n * },\n * });\n * ```\n */\n\nimport type {\n AuthAdapter,\n AuthAdapterCapabilities,\n CustomAuthAdapterOptions\n} from \"@rebasepro/types\";\n\n/**\n * Create a custom auth adapter from minimal options.\n *\n * This is the recommended entry point for users who already have their own\n * auth system and just need to tell Rebase how to extract the user from\n * incoming requests.\n *\n * @param options - Configuration options. Only `verifyRequest` is required.\n * @returns A fully-formed `AuthAdapter` ready for `initializeRebaseBackend()`.\n */\nexport function createCustomAuthAdapter(options: CustomAuthAdapterOptions): AuthAdapter {\n const defaultCapabilities: AuthAdapterCapabilities = {\n hasBuiltInAuthRoutes: false,\n emailPasswordLogin: false,\n registration: false,\n passwordReset: false,\n sessionManagement: false,\n profileUpdate: false,\n emailVerification: false,\n magicLink: false,\n enabledProviders: [],\n ...options.capabilities\n };\n\n const resolvedVerifyToken = options.verifyToken\n ?? (async (token: string) => {\n // Synthesize a minimal Request so adapters that only implement\n // verifyRequest still work for WebSocket token verification.\n const syntheticRequest = new Request(\"http://localhost/_ws_auth\", {\n headers: { Authorization: `Bearer ${token}` }\n });\n return options.verifyRequest(syntheticRequest);\n });\n\n return {\n id: \"custom\",\n\n serviceKey: options.serviceKey,\n\n verifyRequest: options.verifyRequest,\n\n verifyToken: resolvedVerifyToken,\n\n userManagement: options.userManagement,\n\n transformAuthResponse: options.transformAuthResponse,\n\n getCapabilities() {\n return defaultCapabilities;\n }\n };\n}\n","// Auth module exports\nexport * from \"./interfaces\";\n\nexport { configureJwt, generateAccessToken, verifyAccessToken, generateRefreshToken, hashRefreshToken, getRefreshTokenExpiry, getAccessTokenExpiry, generateDownloadToken, verifyDownloadToken } from \"./jwt\";\nexport type { JwtConfig, AccessTokenPayload, DownloadTokenPayload } from \"./jwt\";\n\nexport { hashPassword, verifyPassword, validatePasswordStrength } from \"./password\";\nexport type { PasswordValidationResult } from \"./password\";\n\nexport type { AuthHooks, AuthMethod, ResolvedAuthHooks } from \"./auth-hooks\";\nexport { resolveAuthHooks } from \"./auth-hooks\";\n\nexport { generateSecurePassword, generateSecureToken, hashToken, prepareAdminUserValues, finalizeAdminUserCreation } from \"./admin-user-ops\";\nexport type { AdminUserContext, AdminUserPrepareResult } from \"./admin-user-ops\";\n\n// OAuth Providers\nexport { createGoogleProvider } from \"./google-oauth\";\nexport type { GoogleProviderConfig } from \"./google-oauth\";\nexport { createLinkedinProvider } from \"./linkedin-oauth\";\nexport { createGitHubProvider } from \"./github-oauth\";\nexport { createMicrosoftProvider } from \"./microsoft-oauth\";\nexport { createAppleProvider } from \"./apple-oauth\";\nexport { createFacebookProvider } from \"./facebook-oauth\";\nexport { createTwitterProvider } from \"./twitter-oauth\";\nexport { createDiscordProvider } from \"./discord-oauth\";\nexport { createGitLabProvider } from \"./gitlab-oauth\";\nexport { createBitbucketProvider } from \"./bitbucket-oauth\";\nexport { createSlackProvider } from \"./slack-oauth\";\nexport { createSpotifyProvider } from \"./spotify-oauth\";\n\nexport { requireAuth, requireAdmin, optionalAuth, extractUserFromToken, createAuthMiddleware, queryTokenAuth, fileTokenAuth } from \"./middleware\";\nexport type { AuthMiddlewareOptions, AuthResult } from \"./middleware\";\n\n\nexport { createAuthRoutes } from \"./routes\";\nexport type { AuthModuleConfig, CookieAuthConfig } from \"./routes\";\n\nexport { mountMagicLinkRoutes } from \"./magic-link-routes\";\n\nexport { createResetPasswordRoute } from \"./reset-password-admin\";\nexport type { ResetPasswordRouteConfig } from \"./reset-password-admin\";\n\n\nexport { createRateLimiter, defaultAuthLimiter, strictAuthLimiter, createApiKeyRateLimiter, apiKeyKeyGenerator } from \"./rate-limiter\";\n\n// API Keys\nexport { createApiKeyStore, createApiKeyRoutes, isApiKeyToken, validateApiKey, httpMethodToOperation, isOperationAllowed } from \"./api-keys\";\nexport type { ApiKey, ApiKeyMasked, ApiKeyPermission, ApiKeyWithSecret, CreateApiKeyRequest, UpdateApiKeyRequest, ApiKeyStore, ApiKeyOperation } from \"./api-keys\";\n\n// Auth Adapters\nexport { createBuiltinAuthAdapter } from \"./builtin-auth-adapter\";\nexport type { BuiltinAuthAdapterConfig } from \"./builtin-auth-adapter\";\nexport { createCustomAuthAdapter } from \"./custom-auth-adapter\";\nexport { createAdapterAuthMiddleware } from \"./adapter-middleware\";\nexport type { AdapterAuthMiddlewareOptions } from \"./adapter-middleware\";\n","/**\n * Image Transformation Service\n *\n * Provides on-the-fly image resize, crop, format conversion, and quality\n * adjustment using the `sharp` library. Results are cached in an LRU\n * in-memory cache to avoid redundant processing.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet sharpFactory: ((input: Buffer | Uint8Array) => any) | undefined;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function getSharp(): Promise<(input: Buffer | Uint8Array) => any> {\n if (!sharpFactory) {\n try {\n const mod = await import(\"sharp\");\n sharpFactory = mod.default;\n } catch (err) {\n throw new Error(\"Failed to load optional 'sharp' dependency for image transformation.\");\n }\n }\n if (!sharpFactory) {\n throw new Error(\"Failed to load optional 'sharp' dependency for image transformation.\");\n }\n return sharpFactory;\n}\n\n/** Options that can be specified via query parameters. */\nexport interface ImageTransformOptions {\n width?: number;\n height?: number;\n quality?: number;\n format?: \"webp\" | \"avif\" | \"jpeg\" | \"png\";\n fit?: \"cover\" | \"contain\" | \"fill\" | \"inside\" | \"outside\";\n}\n\n/** Maximum dimension allowed (prevents abuse). */\nconst MAX_DIMENSION = 4096;\n/** Maximum quality value. */\nconst MAX_QUALITY = 100;\n/** Minimum quality value. */\nconst MIN_QUALITY = 1;\n\nconst VALID_FORMATS = new Set([\"webp\", \"avif\", \"jpeg\", \"png\"]);\nconst VALID_FITS = new Set([\"cover\", \"contain\", \"fill\", \"inside\", \"outside\"]);\n\n/**\n * Parse transform options from URL query parameters.\n * Returns `null` when no transformation is requested.\n */\nexport function parseTransformOptions(query: Record<string, string>): ImageTransformOptions | null {\n const opts: ImageTransformOptions = {};\n let hasTransform = false;\n\n if (query.width) {\n const w = parseInt(query.width, 10);\n if (!Number.isNaN(w) && w > 0) {\n opts.width = Math.min(w, MAX_DIMENSION);\n hasTransform = true;\n }\n }\n\n if (query.height) {\n const h = parseInt(query.height, 10);\n if (!Number.isNaN(h) && h > 0) {\n opts.height = Math.min(h, MAX_DIMENSION);\n hasTransform = true;\n }\n }\n\n if (query.quality) {\n const q = parseInt(query.quality, 10);\n if (!Number.isNaN(q)) {\n opts.quality = Math.min(Math.max(q, MIN_QUALITY), MAX_QUALITY);\n hasTransform = true;\n }\n }\n\n if (query.format && VALID_FORMATS.has(query.format)) {\n opts.format = query.format as ImageTransformOptions[\"format\"];\n hasTransform = true;\n }\n\n if (query.fit && VALID_FITS.has(query.fit)) {\n opts.fit = query.fit as ImageTransformOptions[\"fit\"];\n hasTransform = true;\n }\n\n return hasTransform ? opts : null;\n}\n\n/** MIME types that can be used as a Content-Type header. */\nconst FORMAT_CONTENT_TYPES: Record<string, string> = {\n webp: \"image/webp\",\n avif: \"image/avif\",\n jpeg: \"image/jpeg\",\n png: \"image/png\"\n};\n\n/** Check whether a content type is a transformable image. */\nexport function isTransformableImage(contentType: string): boolean {\n return (\n contentType.startsWith(\"image/\") &&\n !contentType.includes(\"svg\") &&\n !contentType.includes(\"gif\")\n );\n}\n\n/**\n * Apply image transformations and return the result buffer + content type.\n */\nexport async function transformImage(\n buffer: Buffer | Uint8Array,\n options: ImageTransformOptions\n): Promise<{ data: Buffer; contentType: string }> {\n const sharp = await getSharp();\n let pipeline = sharp(buffer);\n\n if (options.width || options.height) {\n pipeline = pipeline.resize({\n width: options.width,\n height: options.height,\n fit: options.fit || \"cover\",\n withoutEnlargement: true\n });\n }\n\n const format = options.format || \"webp\";\n const quality = options.quality || 80;\n\n switch (format) {\n case \"webp\":\n pipeline = pipeline.webp({ quality });\n break;\n case \"avif\":\n pipeline = pipeline.avif({ quality });\n break;\n case \"jpeg\":\n pipeline = pipeline.jpeg({ quality });\n break;\n case \"png\":\n pipeline = pipeline.png({ quality });\n break;\n }\n\n const data = await pipeline.toBuffer();\n return { data,\ncontentType: FORMAT_CONTENT_TYPES[format] };\n}\n\n// ---------------------------------------------------------------------------\n// LRU Transform Cache\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry {\n data: Buffer;\n contentType: string;\n timestamp: number;\n}\n\n/**\n * Simple LRU cache for transformed images.\n *\n * Entries expire after `maxAgeMs` (default: 1 hour) and the cache\n * evicts the oldest entry when `maxEntries` is exceeded.\n */\nexport class TransformCache {\n private cache = new Map<string, CacheEntry>();\n private readonly maxEntries: number;\n private readonly maxAgeMs: number;\n private readonly maxTotalBytes: number;\n private totalBytes = 0;\n\n constructor(maxEntries = 500, maxAgeMs = 3_600_000, maxTotalBytes = 256 * 1024 * 1024) {\n this.maxEntries = maxEntries;\n this.maxAgeMs = maxAgeMs;\n this.maxTotalBytes = maxTotalBytes;\n }\n\n /** Build a deterministic cache key from file key + transform options. */\n buildKey(fileKey: string, options: ImageTransformOptions): string {\n return `${fileKey}::${JSON.stringify(options)}`;\n }\n\n get(cacheKey: string): { data: Buffer; contentType: string } | null {\n const entry = this.cache.get(cacheKey);\n if (!entry) return null;\n if (Date.now() - entry.timestamp > this.maxAgeMs) {\n this.totalBytes -= entry.data.length;\n this.cache.delete(cacheKey);\n return null;\n }\n // Move to end (most recently used)\n this.cache.delete(cacheKey);\n this.cache.set(cacheKey, entry);\n return { data: entry.data,\ncontentType: entry.contentType };\n }\n\n set(cacheKey: string, data: Buffer, contentType: string): void {\n // Evict oldest entries while over capacity (entry count or total bytes)\n while (\n (this.cache.size >= this.maxEntries || this.totalBytes + data.length > this.maxTotalBytes)\n && this.cache.size > 0\n ) {\n const oldest = this.cache.keys().next().value;\n if (oldest !== undefined) {\n const evicted = this.cache.get(oldest);\n if (evicted) this.totalBytes -= evicted.data.length;\n this.cache.delete(oldest);\n }\n }\n this.totalBytes += data.length;\n this.cache.set(cacheKey, { data,\ncontentType,\ntimestamp: Date.now() });\n }\n}\n","/**\n * TUS Protocol Handler\n *\n * Implements the TUS v1.0.0 resumable upload protocol with the\n * Creation and Termination extensions. Uploads are stored in a\n * temporary directory and moved to final storage on completion.\n *\n * @see https://tus.io/protocols/resumable-upload\n */\n\nimport { randomUUID } from \"crypto\";\nimport { writeFile, unlink, stat, mkdir, open } from \"fs/promises\";\nimport { existsSync } from \"fs\";\nimport { join } from \"path\";\nimport type { Context } from \"hono\";\nimport type { StorageController } from \"./types\";\nimport type { StorageRegistry } from \"./storage-registry\";\nimport { logger } from \"../utils/logger.js\";\nimport { ApiError } from \"../api/errors\";\n\n/** Metadata for an in-progress resumable upload. */\ninterface TusUpload {\n id: string;\n /** Total declared size in bytes. */\n size: number;\n /** Bytes received so far. */\n offset: number;\n /** TUS metadata parsed from the creation request. */\n metadata: Record<string, string>;\n /** Timestamp of creation (epoch ms). */\n createdAt: number;\n /** Absolute path to the temp file on disk. */\n filePath: string;\n /** Target bucket (from metadata). */\n bucket?: string;\n /** Target key / filename (from metadata). */\n key?: string;\n /** Whether the upload has been fully received and finalized. */\n completed: boolean;\n}\n\n/** Maximum upload size: 5 GB. */\nconst MAX_UPLOAD_SIZE = 5 * 1024 * 1024 * 1024;\n\n/** Stale upload expiry: 24 hours. */\nconst UPLOAD_EXPIRY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * TUS resumable upload handler.\n *\n * Each instance manages uploads for a single storage root. The\n * `storageController` is used to finalize completed uploads by\n * calling `putObject`.\n */\nexport class TusHandler {\n private uploads = new Map<string, TusUpload>();\n private tusDir: string;\n private cleanupTimer?: ReturnType<typeof setInterval>;\n\n constructor(\n storageBaseDir: string,\n private storageController?: StorageController,\n private storageRegistry?: StorageRegistry\n ) {\n this.tusDir = join(storageBaseDir, \".tus-uploads\");\n }\n\n /** Ensure the temp directory exists. */\n private async ensureDir(): Promise<void> {\n if (!existsSync(this.tusDir)) {\n await mkdir(this.tusDir, { recursive: true });\n }\n }\n\n /** Start periodic cleanup of stale uploads. */\n startCleanup(): void {\n if (this.cleanupTimer) return;\n this.cleanupTimer = setInterval(() => {\n void this.cleanupStale();\n }, 60_000); // every minute\n }\n\n /** Remove uploads that have been idle for longer than UPLOAD_EXPIRY_MS. */\n private async cleanupStale(): Promise<void> {\n const now = Date.now();\n for (const [id, upload] of this.uploads) {\n if (now - upload.createdAt > UPLOAD_EXPIRY_MS && !upload.completed) {\n try { await unlink(upload.filePath); } catch { /* ok */ }\n this.uploads.delete(id);\n }\n }\n }\n\n // -----------------------------------------------------------------------\n // TUS Metadata Parsing\n // -----------------------------------------------------------------------\n\n /**\n * Parse the `Upload-Metadata` header.\n *\n * Format: `key base64value,key2 base64value2`\n */\n private parseMetadata(header: string): Record<string, string> {\n const metadata: Record<string, string> = {};\n if (!header) return metadata;\n for (const pair of header.split(\",\")) {\n const trimmed = pair.trim();\n const spaceIdx = trimmed.indexOf(\" \");\n if (spaceIdx === -1) {\n metadata[trimmed] = \"\";\n } else {\n const key = trimmed.substring(0, spaceIdx);\n const value = Buffer.from(trimmed.substring(spaceIdx + 1), \"base64\").toString(\"utf-8\");\n metadata[key] = value;\n }\n }\n return metadata;\n }\n\n // -----------------------------------------------------------------------\n // Protocol Endpoints\n // -----------------------------------------------------------------------\n\n /** `OPTIONS /tus` — TUS capability discovery. */\n options(): Response {\n return new Response(null, {\n status: 204,\n headers: {\n \"Tus-Resumable\": \"1.0.0\",\n \"Tus-Version\": \"1.0.0\",\n \"Tus-Extension\": \"creation,termination\",\n \"Tus-Max-Size\": String(MAX_UPLOAD_SIZE)\n }\n });\n }\n\n /** `POST /tus` — Create a new upload. */\n async create(c: Context): Promise<Response> {\n await this.ensureDir();\n\n const uploadLengthHeader = c.req.header(\"Upload-Length\");\n if (!uploadLengthHeader) {\n throw ApiError.badRequest(\"Upload-Length header is required\");\n }\n\n const uploadLength = parseInt(uploadLengthHeader, 10);\n if (Number.isNaN(uploadLength) || uploadLength <= 0) {\n throw ApiError.badRequest(\"Invalid Upload-Length\");\n }\n if (uploadLength > MAX_UPLOAD_SIZE) {\n throw new ApiError(413, \"PAYLOAD_TOO_LARGE\", `Upload-Length exceeds maximum of ${MAX_UPLOAD_SIZE} bytes`);\n }\n\n const metadata = this.parseMetadata(c.req.header(\"Upload-Metadata\") || \"\");\n const id = randomUUID();\n const filePath = join(this.tusDir, id);\n\n // Create empty temp file\n await writeFile(filePath, Buffer.alloc(0));\n\n const upload: TusUpload = {\n id,\n size: uploadLength,\n offset: 0,\n metadata,\n createdAt: Date.now(),\n filePath,\n bucket: metadata.bucket || undefined,\n key: metadata.key || metadata.filename || undefined,\n completed: false\n };\n this.uploads.set(id, upload);\n\n // Build absolute Location\n const reqUrl = new URL(c.req.url);\n const location = `${reqUrl.origin}${reqUrl.pathname}/${id}`;\n\n return new Response(null, {\n status: 201,\n headers: {\n Location: location,\n \"Tus-Resumable\": \"1.0.0\",\n \"Upload-Offset\": \"0\"\n }\n });\n }\n\n /** `HEAD /tus/:id` — Query upload progress. */\n head(c: Context, id: string): Response {\n const upload = this.uploads.get(id);\n if (!upload) {\n throw ApiError.notFound(\"Upload not found\");\n }\n\n return new Response(null, {\n status: 200,\n headers: {\n \"Tus-Resumable\": \"1.0.0\",\n \"Upload-Offset\": String(upload.offset),\n \"Upload-Length\": String(upload.size),\n \"Cache-Control\": \"no-store\"\n }\n });\n }\n\n /** `PATCH /tus/:id` — Append data to an upload. */\n async patch(c: Context, id: string): Promise<Response> {\n const upload = this.uploads.get(id);\n if (!upload) {\n throw ApiError.notFound(\"Upload not found\");\n }\n if (upload.completed) {\n throw ApiError.badRequest(\"Upload already completed\");\n }\n\n // Validate offset\n const offsetHeader = c.req.header(\"Upload-Offset\");\n if (!offsetHeader) {\n throw ApiError.badRequest(\"Upload-Offset header is required\");\n }\n const offset = parseInt(offsetHeader, 10);\n if (offset !== upload.offset) {\n throw ApiError.conflict(\"Offset mismatch\");\n }\n\n // Validate content type\n const contentType = c.req.header(\"Content-Type\");\n if (contentType !== \"application/offset+octet-stream\") {\n throw new ApiError(415, \"UNSUPPORTED_MEDIA_TYPE\", \"Content-Type must be application/offset+octet-stream\");\n }\n\n // Read chunk and append to temp file\n const body = await c.req.arrayBuffer();\n const chunk = Buffer.from(body);\n\n // Prevent overrun\n if (upload.offset + chunk.length > upload.size) {\n throw new ApiError(413, \"PAYLOAD_TOO_LARGE\", \"Chunk exceeds declared Upload-Length\");\n }\n\n const fh = await open(upload.filePath, \"a\");\n try {\n await fh.write(chunk);\n } finally {\n await fh.close();\n }\n upload.offset += chunk.length;\n\n // Finalize if complete\n if (upload.offset >= upload.size) {\n await this.finalize(upload);\n }\n\n return new Response(null, {\n status: 204,\n headers: {\n \"Tus-Resumable\": \"1.0.0\",\n \"Upload-Offset\": String(upload.offset)\n }\n });\n }\n\n /** `DELETE /tus/:id` — Cancel and remove an upload. */\n async delete(c: Context, id: string): Promise<Response> {\n const upload = this.uploads.get(id);\n if (!upload) {\n throw ApiError.notFound(\"Upload not found\");\n }\n\n try { await unlink(upload.filePath); } catch { /* ok */ }\n this.uploads.delete(id);\n\n return new Response(null, {\n status: 204,\n headers: { \"Tus-Resumable\": \"1.0.0\" }\n });\n }\n\n // -----------------------------------------------------------------------\n // Finalization\n // -----------------------------------------------------------------------\n\n /**\n * Move a completed upload into the storage controller.\n */\n private async finalize(upload: TusUpload): Promise<void> {\n upload.completed = true;\n\n // Resolve the target controller: prefer storageId from TUS metadata,\n // then fall back to the registry default, then the single controller.\n const storageId = upload.metadata.storageId;\n let targetController = this.storageController;\n if (this.storageRegistry) {\n targetController = storageId\n ? this.storageRegistry.getOrDefault(storageId)\n : this.storageRegistry.getDefault();\n }\n\n if (!targetController) {\n // No controller — leave temp file in place\n logger.warn(\"[TUS] Upload completed but no StorageController configured. Temp file remains:\", { filePath: upload.filePath });\n return;\n }\n\n try {\n const { readFile } = await import(\"fs/promises\");\n const data = await readFile(upload.filePath);\n const fileName = upload.key || upload.metadata.filename || upload.id;\n const mimeType = upload.metadata.contentType || upload.metadata.filetype || \"application/octet-stream\";\n\n const file = new File([data], fileName, { type: mimeType });\n\n await targetController.putObject({\n file,\n key: fileName,\n bucket: upload.bucket\n });\n\n // Clean up temp file\n try { await unlink(upload.filePath); } catch { /* ok */ }\n this.uploads.delete(upload.id);\n\n logger.info(`[TUS] Upload ${upload.id} finalized → ${fileName}`, storageId ? { storageId } : {});\n } catch (err) {\n logger.error(`[TUS] Failed to finalize upload ${upload.id}`, { error: err });\n }\n }\n}\n","/**\n * Storage REST API routes using Hono\n *\n * Supports multi-backend routing via `StorageRegistry`. Each endpoint\n * accepts an optional `storageId` parameter (query string or form field)\n * to target a named storage backend. When omitted, the default backend\n * is used.\n */\n\nimport { Hono, type MiddlewareHandler } from \"hono\";\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport { StorageController } from \"./types\";\nimport { LocalStorageController } from \"./LocalStorageController\";\nimport type { StorageRegistry } from \"./storage-registry\";\nimport { DEFAULT_STORAGE_SOURCE_KEY, isPublicStoragePath, type StorageSourceDefinition, type AuthAdapter } from \"@rebasepro/types\";\nimport { requireAuth as jwtRequireAuth, optionalAuth as jwtOptionalAuth, queryTokenAuth, fileTokenAuth, publicObjectAuth } from \"../auth/middleware\";\nimport { generateDownloadToken } from \"../auth\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { HonoEnv } from \"../api/types\";\nimport { parseTransformOptions, transformImage, isTransformableImage, TransformCache } from \"./image-transform\";\nimport { TusHandler } from \"./tus-handler\";\n\n/** Shared image transform cache (LRU, 500 entries, 1 hour TTL). */\nconst transformCache = new TransformCache();\n\nexport interface StorageRoutesConfig {\n /**\n * Single storage controller (backward-compatible).\n * Used as fallback when no `registry` is provided.\n */\n controller?: StorageController;\n /**\n * Full storage registry for multi-backend routing.\n * When provided, endpoints resolve the controller from `storageId`\n * parameter. Takes precedence over `controller`.\n */\n registry?: StorageRegistry;\n /**\n * Declared storage sources, surfaced by `GET /sources` so the client can\n * bootstrap its registry. Carries the frontend `transport` (server vs\n * direct) and human-readable labels. Server-transport sources are also\n * derived from the registry; `direct` sources (e.g. Firebase Storage) only\n * exist here since the backend does not proxy them.\n */\n sources?: StorageSourceDefinition[];\n /** Base path for storage routes (default: '/api/storage') */\n basePath?: string;\n /** Require authentication for write operations (default: true) */\n requireAuth?: boolean;\n /** Allow unauthenticated read access to stored files (default: false).\n * When false and requireAuth is true, reads also require authentication. */\n publicRead?: boolean;\n /**\n * When provided, storage routes delegate auth to this adapter instead\n * of the built-in JWT module. This mirrors how data routes use\n * `createAdapterAuthMiddleware()` and avoids the \"JWT secret not\n * configured\" crash when `configureJwt()` was never called.\n */\n authAdapter?: AuthAdapter;\n}\n\n/**\n * Extract the wildcard portion of a route path from the full request path.\n *\n * Hono's `c.req.param('*')` does not work reliably in sub-routers mounted\n * via `app.route(prefix, subRouter)`. Instead we derive the wildcard value\n * from the fully-resolved `c.req.path` and `c.req.routePath`.\n *\n * For a route `/metadata/*` mounted at `/api/storage`, a request to\n * `/api/storage/metadata/default/file.jpg` yields routePath\n * `/api/storage/metadata/*`. We strip the prefix (everything before `/*`)\n * plus one character for the trailing `/` to obtain `default/file.jpg`.\n */\nexport function extractWildcardPath(c: { req: { path: string; routePath: string } }): string {\n const routePath = c.req.routePath; // e.g. \"/api/storage/metadata/*\"\n const prefix = routePath.replace(\"/*\", \"\"); // e.g. \"/api/storage/metadata\"\n const fullPath = c.req.path; // e.g. \"/api/storage/metadata/default/file.jpg\"\n const idx = fullPath.indexOf(prefix);\n if (idx < 0) return \"\";\n // +1 to skip the '/' after the prefix\n return fullPath.substring(idx + prefix.length + 1);\n}\n\n/**\n * Sanitize a user-supplied storage key to prevent path traversal and other attacks.\n * Removes null bytes, ../ sequences, leading slashes, and limits length.\n */\nfunction sanitizeStorageKey(key: string): string {\n let sanitized = key;\n // Remove null bytes\n sanitized = sanitized.replace(/\\0/g, \"\");\n // Remove ../ sequences (and ..\\ on Windows)\n sanitized = sanitized.replace(/\\.\\.\\/|\\.\\.\\\\/g, \"\");\n // Remove leading slashes\n sanitized = sanitized.replace(/^\\/+/, \"\");\n // Limit length\n sanitized = sanitized.slice(0, 1024);\n return sanitized;\n}\n\n/**\n * Build adapter-aware auth middleware for storage routes.\n *\n * When an `AuthAdapter` is provided, token verification is delegated to the\n * adapter instead of the built-in JWT module. This mirrors how data routes\n * use `createAdapterAuthMiddleware()`, but without RLS driver scoping (storage\n * routes don't interact with the DataDriver).\n *\n * Returns both a \"write\" middleware (enforces auth when `requireAuth` is true)\n * and a \"read\" middleware (enforces auth unless `publicRead` is set).\n */\nfunction buildAdapterAuthMiddleware(\n adapter: AuthAdapter,\n requireAuth: boolean,\n publicRead: boolean\n): { writeAuthMiddleware: MiddlewareHandler<HonoEnv>; readAuthMiddleware: MiddlewareHandler<HonoEnv> } {\n /**\n * Core middleware: verifies the request via the adapter. When `enforce`\n * is true, returns 401 if no authenticated user is resolved.\n */\n const createMiddleware = (enforce: boolean): MiddlewareHandler<HonoEnv> => {\n return async (c, next) => {\n let authenticatedUser = null;\n try {\n authenticatedUser = await adapter.verifyRequest(c.req.raw);\n } catch {\n return c.json({ error: { message: \"Unauthorized\", code: \"UNAUTHORIZED\" } }, 401);\n }\n\n if (authenticatedUser) {\n c.set(\"user\", {\n userId: authenticatedUser.uid,\n email: authenticatedUser.email,\n roles: authenticatedUser.roles\n });\n }\n\n if (enforce && !authenticatedUser) {\n return c.json({ error: { message: \"Unauthorized: Authentication required\", code: \"UNAUTHORIZED\" } }, 401);\n }\n\n return next();\n };\n };\n\n return {\n writeAuthMiddleware: createMiddleware(requireAuth),\n readAuthMiddleware: createMiddleware(!publicRead && requireAuth)\n };\n}\n\n/**\n * Create storage REST API routes\n */\nexport function createStorageRoutes(config: StorageRoutesConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n const { controller, registry, sources: declaredSources, requireAuth = true, publicRead = false, authAdapter } = config;\n\n /**\n * Resolve the storage controller for a request.\n * Looks up by `storageId` in the registry, falls back to the single\n * controller, and finally to the registry default.\n */\n const resolveController = (storageId?: string | null): StorageController => {\n if (registry) {\n return registry.getOrDefault(storageId);\n }\n if (controller) {\n return controller;\n }\n throw new Error(\"No storage controller or registry available\");\n };\n\n /** Get the default controller (used for TUS and base-path derivation). */\n const getDefaultController = (): StorageController => {\n if (registry) return registry.getDefault();\n if (controller) return controller;\n throw new Error(\"No storage controller or registry available\");\n };\n\n // ── Auth middleware selection ────────────────────────────────────────\n // When an AuthAdapter is available, delegate token verification to it\n // (mirroring the data-routes pattern). This avoids calling the JWT\n // module which may not have been configured (e.g. custom auth).\n // When no adapter is present, fall back to the built-in JWT middleware.\n const { writeAuthMiddleware, readAuthMiddleware } = authAdapter\n ? buildAdapterAuthMiddleware(authAdapter, requireAuth, publicRead)\n : {\n writeAuthMiddleware: requireAuth ? jwtRequireAuth : jwtOptionalAuth,\n readAuthMiddleware: (publicRead || !requireAuth) ? jwtOptionalAuth : jwtRequireAuth\n };\n\n /**\n * Parse bucket and path from a combined file path.\n */\n const parseBucketAndPath = (filePath: string): { bucket: string; resolvedPath: string } => {\n const parts = filePath.split(\"/\");\n\n // Only recognize 'default' as an explicit bucket prefix\n if (parts.length > 1 && parts[0].toLowerCase() === \"default\") {\n return {\n bucket: \"default\",\n resolvedPath: parts.slice(1).join(\"/\")\n };\n }\n\n // All other paths use 'default' bucket with the full path\n return {\n bucket: \"default\",\n resolvedPath: filePath\n };\n };\n\n /**\n * POST /upload - Upload a file\n * Body: multipart/form-data with 'file' field\n * Request body can also contain metadata keys 'metadata_*'\n */\n router.post(\"/upload\", writeAuthMiddleware, async (c) => {\n const body = await c.req.parseBody();\n const uploadedFile = body[\"file\"];\n\n if (!uploadedFile || typeof uploadedFile === \"string\") {\n throw ApiError.badRequest(\"No file provided\");\n }\n\n const key = typeof body[\"key\"] === \"string\" ? body[\"key\"] : \"\";\n const bucket = typeof body[\"bucket\"] === \"string\" ? body[\"bucket\"] : undefined;\n const storageId = typeof body[\"storageId\"] === \"string\" ? body[\"storageId\"] : c.req.query(\"storageId\");\n\n const finalKey = sanitizeStorageKey(key || uploadedFile.name || \"unnamed\");\n\n // Extract custom metadata from request body\n const metadata: Record<string, unknown> = {};\n for (const [k, value] of Object.entries(body)) {\n if (k.startsWith(\"metadata_\")) {\n metadata[k.replace(\"metadata_\", \"\")] = value;\n }\n }\n\n const resolved = resolveController(storageId);\n const result = await resolved.putObject({\n file: uploadedFile,\n key: finalKey,\n metadata: Object.keys(metadata).length > 0 ? metadata : undefined,\n bucket\n });\n\n return c.json({\n success: true,\n data: result\n }, 201);\n });\n\n /**\n * GET /file/* - Download/serve a file\n * Path: /file/{bucket}/{path} or /file/{path}\n */\n router.get(\"/file/*\", fileTokenAuth, publicObjectAuth, readAuthMiddleware, async (c) => {\n // Allow cross-origin loading so admin frontends on different\n // ports (dev) or domains (CDN) can render images via <img>.\n c.header(\"Cross-Origin-Resource-Policy\", \"cross-origin\");\n\n const rawPath = extractWildcardPath(c);\n if (!rawPath) {\n throw ApiError.notFound(\"File not found\");\n }\n\n const filePath = decodeURIComponent(rawPath);\n const storageId = c.req.query(\"storageId\");\n const resolved = resolveController(storageId);\n\n // Parse image transform query params (e.g. ?width=300&format=webp)\n const transformOpts = parseTransformOptions(c.req.query() as Record<string, string>);\n\n // For local storage, serve the file directly from disk\n if (resolved.getType() === \"local\") {\n const localController = resolved as LocalStorageController;\n const { bucket, resolvedPath } = parseBucketAndPath(filePath);\n\n const absolutePath = localController.getAbsolutePath(resolvedPath, bucket);\n\n // Check if file exists\n try {\n await fsp.access(absolutePath);\n } catch {\n throw ApiError.notFound(\"File not found\");\n }\n\n // Get content type from metadata or infer from extension\n let contentType = \"application/octet-stream\";\n const metadataPath = `${absolutePath}.metadata.json`;\n try {\n const metadataRaw = await fsp.readFile(metadataPath, \"utf-8\");\n const metadata = JSON.parse(metadataRaw);\n contentType = metadata.contentType || contentType;\n } catch {\n // Ignore metadata errors (file may not exist)\n }\n\n const fileContent = await fsp.readFile(absolutePath);\n\n // Apply image transforms if requested and the file is a transformable image\n if (transformOpts && isTransformableImage(contentType)) {\n const cacheKey = transformCache.buildKey(filePath, transformOpts);\n let cached = transformCache.get(cacheKey);\n if (!cached) {\n cached = await transformImage(Buffer.from(fileContent), transformOpts);\n transformCache.set(cacheKey, cached.data, cached.contentType);\n }\n c.header(\"Content-Type\", cached.contentType);\n c.header(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n return c.body(new Uint8Array(cached.data));\n }\n\n c.header(\"Content-Type\", contentType);\n return c.body(new Uint8Array(fileContent));\n }\n\n // For remote storage (S3, GCS, etc.), proxy the file through the backend.\n // We avoid redirecting to signed URLs because:\n // 1. Mixed-content (HTTPS page → HTTP MinIO) is blocked by browsers\n // 2. Internal IPs / VPC endpoints are unreachable from the browser\n const { bucket: parsedBucket, resolvedPath: parsedPath } = parseBucketAndPath(filePath);\n const fileObject = await resolved.getObject(parsedPath, parsedBucket);\n if (!fileObject) {\n throw ApiError.notFound(\"File not found\");\n }\n\n const remoteContentType = fileObject.type || \"application/octet-stream\";\n\n // Apply image transforms for remote storage too\n if (transformOpts && isTransformableImage(remoteContentType)) {\n const cacheKey = transformCache.buildKey(filePath, transformOpts);\n let cached = transformCache.get(cacheKey);\n if (!cached) {\n const buf = Buffer.from(await fileObject.arrayBuffer());\n cached = await transformImage(buf, transformOpts);\n transformCache.set(cacheKey, cached.data, cached.contentType);\n }\n c.header(\"Content-Type\", cached.contentType);\n c.header(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n return c.body(new Uint8Array(cached.data));\n }\n\n c.header(\"Content-Type\", remoteContentType);\n c.header(\"Cache-Control\", \"public, max-age=3600, immutable\");\n const buf = await fileObject.arrayBuffer();\n return c.body(new Uint8Array(buf));\n });\n\n /**\n * GET /metadata/* - Get file metadata\n */\n router.get(\"/metadata/*\", fileTokenAuth, publicObjectAuth, readAuthMiddleware, async (c) => {\n const rawPath = extractWildcardPath(c);\n if (!rawPath) {\n return c.json({\n success: true,\n data: null,\n fileNotFound: true\n }, 404);\n }\n\n const filePath = decodeURIComponent(rawPath);\n const storageId = c.req.query(\"storageId\");\n const resolved = resolveController(storageId);\n const { bucket, resolvedPath } = parseBucketAndPath(filePath);\n\n const downloadConfig = await resolved.getSignedUrl(resolvedPath, bucket);\n\n if (downloadConfig.fileNotFound) {\n throw ApiError.notFound(\"File not found\");\n }\n\n if (downloadConfig.metadata) {\n const scopedPath = `${bucket}/${resolvedPath}`;\n if (isPublicStoragePath(scopedPath)) {\n // Public object: served token-less via a permanent URL.\n downloadConfig.metadata.public = true;\n } else {\n // Private object: mint a short-lived, path-scoped download token.\n downloadConfig.metadata.token = generateDownloadToken(scopedPath, 300);\n downloadConfig.metadata.tokenExpiresIn = 300;\n }\n }\n\n return c.json({\n success: true,\n data: downloadConfig.metadata\n });\n });\n\n /**\n * DELETE /file/* - Delete a file\n */\n router.delete(\"/file/*\", writeAuthMiddleware, async (c) => {\n const rawPath = extractWildcardPath(c);\n if (!rawPath) {\n return c.json({ success: true,\nmessage: \"No file to delete\" });\n }\n\n const filePath = decodeURIComponent(rawPath);\n const storageId = c.req.query(\"storageId\");\n const resolved = resolveController(storageId);\n const { bucket, resolvedPath } = parseBucketAndPath(filePath);\n\n await resolved.deleteObject(resolvedPath, bucket);\n\n return c.json({\n success: true,\n message: \"File deleted\"\n });\n });\n\n /**\n * GET /list - List files in a path\n */\n router.get(\"/list\", writeAuthMiddleware, async (c) => {\n // Fallback to path for backward compatibility\n const storagePrefix = c.req.query(\"prefix\") || c.req.query(\"path\") || \"\";\n const bucket = c.req.query(\"bucket\");\n const maxResults = c.req.query(\"maxResults\");\n const pageToken = c.req.query(\"pageToken\");\n const storageId = c.req.query(\"storageId\");\n const resolved = resolveController(storageId);\n\n const result = await resolved.listObjects(\n storagePrefix,\n {\n bucket: bucket ?? (resolved.getType() === \"local\" ? \"default\" : undefined),\n maxResults: maxResults ? parseInt(maxResults, 10) : undefined,\n pageToken\n }\n );\n\n return c.json({\n success: true,\n data: result\n });\n });\n\n /**\n * POST /folder - Create a new folder\n * Body: { path: string, bucket?: string }\n */\n router.post(\"/folder\", writeAuthMiddleware, async (c) => {\n const body = await c.req.json();\n const folderPath = body.path;\n const storageId = typeof body.storageId === \"string\" ? body.storageId : c.req.query(\"storageId\");\n\n if (!folderPath || typeof folderPath !== \"string\") {\n throw ApiError.badRequest(\"Folder path is required\");\n }\n\n const resolved = resolveController(storageId);\n const { bucket, resolvedPath } = parseBucketAndPath(folderPath);\n\n if (!resolvedPath || resolvedPath.trim() === \"\") {\n throw ApiError.badRequest(\"Invalid folder path\");\n }\n\n if (resolved.getType() === \"local\") {\n // For local storage, create the directory\n const localController = resolved as LocalStorageController;\n const absolutePath = localController.getAbsolutePath(resolvedPath, bucket);\n fs.mkdirSync(absolutePath, { recursive: true });\n } else {\n // For S3/GCS-compatible storage, create a zero-byte marker object with trailing slash\n const key = resolvedPath.endsWith(\"/\") ? resolvedPath : resolvedPath + \"/\";\n const emptyFile = new File([], key, { type: \"application/x-directory\" });\n await resolved.putObject({\n file: emptyFile,\n key\n });\n }\n\n return c.json({\n success: true,\n message: \"Folder created\"\n }, 201);\n });\n\n // -----------------------------------------------------------------------\n // TUS Resumable Uploads\n // -----------------------------------------------------------------------\n\n const defaultCtrl = getDefaultController();\n const tusBaseDir = defaultCtrl.getType() === \"local\"\n ? (defaultCtrl as LocalStorageController).getBasePath()\n : (process.env.STORAGE_PATH || \"./uploads\");\n const tusHandler = new TusHandler(tusBaseDir, defaultCtrl, registry);\n tusHandler.startCleanup();\n\n router.options(\"/tus\", (_c) => tusHandler.options());\n router.post(\"/tus\", writeAuthMiddleware, async (c) => tusHandler.create(c));\n router.get(\"/tus/:id\", readAuthMiddleware, (c) => tusHandler.head(c, c.req.param(\"id\")));\n router.patch(\"/tus/:id\", writeAuthMiddleware, async (c) => tusHandler.patch(c, c.req.param(\"id\")));\n router.delete(\"/tus/:id\", writeAuthMiddleware, async (c) => tusHandler.delete(c, c.req.param(\"id\")));\n\n // -----------------------------------------------------------------------\n // Storage Sources Discovery\n // -----------------------------------------------------------------------\n\n /**\n * GET /sources — list all registered storage backends.\n * The client can bootstrap its StorageSourceRegistry from this endpoint.\n */\n router.get(\"/sources\", (c) => {\n const byKey = new Map<string, { key: string; engine: string; transport: \"server\" | \"direct\"; label?: string }>();\n\n // 1. Server-backed sources derived from the registry (source of truth\n // for the actual engine type), or the single controller.\n if (registry) {\n for (const key of registry.list()) {\n byKey.set(key, {\n key,\n engine: registry.get(key)?.getType() ?? \"unknown\",\n transport: \"server\",\n });\n }\n } else {\n byKey.set(DEFAULT_STORAGE_SOURCE_KEY, {\n key: DEFAULT_STORAGE_SOURCE_KEY,\n engine: defaultCtrl.getType(),\n transport: \"server\",\n });\n }\n\n // 2. Overlay declared definitions: adds `direct` sources the backend\n // does not proxy, plus labels and explicit transport/engine.\n for (const def of declaredSources ?? []) {\n const existing = byKey.get(def.key);\n byKey.set(def.key, {\n key: def.key,\n engine: def.engine ?? existing?.engine ?? \"unknown\",\n transport: def.transport ?? existing?.transport ?? \"server\",\n label: def.label ?? existing?.label,\n });\n }\n\n return c.json({ success: true, data: Array.from(byKey.values()) });\n });\n\n return router;\n}\n","/**\n * Storage Registry\n *\n * Manages multiple storage controllers for Rebase backend.\n * Allows different storage backends for different use cases.\n *\n * Usage:\n * - Single storage: Pass a single StorageController → maps to \"(default)\"\n * - Multiple storages: Pass a map of { storageId: StorageController }\n * - String properties use `storageId` in their config to specify which storage to use\n * - Properties without `storageId` fallback to \"(default)\"\n */\n\nimport { StorageController } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The default storage identifier used when:\n * - A single storage controller is provided (not a map)\n * - A property doesn't specify a storageId\n */\nexport const DEFAULT_STORAGE_ID = \"(default)\";\n\n/**\n * Registry for managing multiple storage controllers\n */\nexport interface StorageRegistry {\n /**\n * Register a storage controller with an ID\n * @param id - Unique identifier for this storage (e.g., \"media\", \"backups\")\n * @param controller - The StorageController instance\n */\n register(id: string, controller: StorageController): void;\n\n /**\n * Get the default storage controller (id = \"(default)\")\n * @throws Error if no default storage is registered\n */\n getDefault(): StorageController;\n\n /**\n * Get a storage controller by ID\n * @param id - Storage identifier, or undefined/null for default\n * @returns The StorageController, or undefined if not found\n */\n get(id: string | undefined | null): StorageController | undefined;\n\n /**\n * Get a storage controller by ID, with fallback to default\n * @param id - Storage identifier, or undefined/null for default\n * @returns The StorageController (falls back to default if id not found)\n * @throws Error if neither the specified nor default storage exists\n */\n getOrDefault(id: string | undefined | null): StorageController;\n\n /**\n * Check if a storage with the given ID exists\n */\n has(id: string): boolean;\n\n /**\n * List all registered storage IDs\n */\n list(): string[];\n\n /**\n * Get the number of registered storage controllers\n */\n size(): number;\n}\n\n/**\n * Default implementation of StorageRegistry\n */\nexport class DefaultStorageRegistry implements StorageRegistry {\n private controllers = new Map<string, StorageController>();\n\n /**\n * Create a StorageRegistry from either a single controller or a map\n * @param input - Single StorageController (maps to \"(default)\") or Record<string, StorageController>\n */\n static create(\n input: StorageController | Record<string, StorageController>\n ): DefaultStorageRegistry {\n const registry = new DefaultStorageRegistry();\n\n if (isStorageController(input)) {\n // Single controller → register as \"(default)\"\n registry.register(DEFAULT_STORAGE_ID, input);\n } else {\n // Map of controllers → register each\n for (const [id, controller] of Object.entries(input)) {\n if (isStorageController(controller)) {\n registry.register(id, controller);\n }\n }\n // Ensure there's a default if not explicitly provided\n if (!registry.has(DEFAULT_STORAGE_ID) && registry.size() > 0) {\n // If no explicit \"(default)\", use the first one as default\n const firstId = Object.keys(input).find(k => isStorageController(input[k]));\n if (firstId) {\n logger.warn(\n `[StorageRegistry] No \"${DEFAULT_STORAGE_ID}\" storage provided. ` +\n `Using \"${firstId}\" as the default.`\n );\n registry.register(DEFAULT_STORAGE_ID, input[firstId]);\n }\n }\n }\n\n return registry;\n }\n\n register(id: string, controller: StorageController): void {\n if (this.controllers.has(id)) {\n logger.warn(`[StorageRegistry] Overwriting storage with id \"${id}\"`);\n }\n this.controllers.set(id, controller);\n }\n\n getDefault(): StorageController {\n const controller = this.controllers.get(DEFAULT_STORAGE_ID);\n if (!controller) {\n throw new Error(\n \"[StorageRegistry] No default storage registered. \" +\n `Register one with id \"${DEFAULT_STORAGE_ID}\" or pass a single StorageController.`\n );\n }\n return controller;\n }\n\n get(id: string | undefined | null): StorageController | undefined {\n if (id === undefined || id === null) {\n return this.controllers.get(DEFAULT_STORAGE_ID);\n }\n return this.controllers.get(id);\n }\n\n getOrDefault(id: string | undefined | null): StorageController {\n // If no ID specified, return default\n if (id === undefined || id === null) {\n return this.getDefault();\n }\n\n // Try to get by ID\n const controller = this.controllers.get(id);\n if (controller) {\n return controller;\n }\n\n // Fallback to default with warning\n logger.warn(\n `[StorageRegistry] Storage \"${id}\" not found, falling back to \"${DEFAULT_STORAGE_ID}\"`\n );\n return this.getDefault();\n }\n\n has(id: string): boolean {\n return this.controllers.has(id);\n }\n\n list(): string[] {\n return Array.from(this.controllers.keys());\n }\n\n size(): number {\n return this.controllers.size;\n }\n}\n\n/**\n * Type guard to check if an object is a StorageController\n * vs a Record<string, StorageController> (multiple storages)\n */\nfunction isStorageController(obj: unknown): obj is StorageController {\n if (typeof obj !== \"object\" || obj === null) {\n return false;\n }\n const controller = obj as StorageController;\n // Check for required StorageController properties\n return (\n typeof controller.putObject === \"function\" &&\n typeof controller.getSignedUrl === \"function\" &&\n typeof controller.deleteObject === \"function\" &&\n typeof controller.listObjects === \"function\" &&\n typeof controller.getType === \"function\"\n );\n}\n","/**\n * Storage module for Rebase backend\n *\n * Provides pluggable file storage with three built-in providers:\n * - **Local filesystem** — zero config, great for dev and single-server deployments.\n * - **S3-compatible** — works with AWS S3, Cloudflare R2, MinIO, Hetzner Object Storage,\n * Backblaze B2, DigitalOcean Spaces, and GCS (via S3 interop).\n * - **Google Cloud Storage / Firebase Storage** — native GCS support via `@google-cloud/storage`\n * (optional peer dependency, lazily loaded).\n *\n * For other providers (Azure Blob, etc.), implement the\n * `StorageController` interface and pass the instance directly to the `storage` config.\n */\n\nexport * from \"./types\";\nexport { LocalStorageController } from \"./LocalStorageController\";\nexport { S3StorageController } from \"./S3StorageController\";\nexport { GCSStorageController } from \"./GCSStorageController\";\nexport { createStorageRoutes } from \"./routes\";\nexport type { StorageRoutesConfig } from \"./routes\";\nexport * from \"./storage-registry\";\nexport { parseTransformOptions, transformImage, isTransformableImage, TransformCache } from \"./image-transform\";\nexport type { ImageTransformOptions } from \"./image-transform\";\nexport { TusHandler } from \"./tus-handler\";\n\nimport { BackendStorageConfig, StorageController } from \"./types\";\nimport { LocalStorageController } from \"./LocalStorageController\";\n\n/**\n * Create a storage controller from a config object.\n *\n * For custom providers, implement `StorageController` directly instead\n * of going through this factory.\n */\nexport async function createStorageController(config: BackendStorageConfig): Promise<StorageController> {\n switch (config.type) {\n case \"local\":\n return new LocalStorageController(config);\n case \"s3\": {\n const { S3StorageController } = await import(\"./S3StorageController\");\n return new S3StorageController(config);\n }\n case \"gcs\": {\n const { GCSStorageController } = await import(\"./GCSStorageController\");\n return new GCSStorageController(config);\n }\n default:\n throw new Error(\n `Unknown storage type: ${(config as Record<string, unknown>).type}. ` +\n \"Built-in types: local, s3, gcs. \" +\n \"For other providers, implement the StorageController interface directly.\"\n );\n }\n}\n","import {\n BackendStorageConfig,\n createStorageController,\n DEFAULT_STORAGE_ID,\n DefaultStorageRegistry,\n StorageController,\n StorageRegistry\n} from \"../storage\";\nimport { logger } from \"../utils/logger\";\n\nexport async function initializeStorage(\n storageConfig: BackendStorageConfig | StorageController | Record<string, BackendStorageConfig | StorageController> | undefined,\n isProduction: boolean\n): Promise<{ storageRegistry?: StorageRegistry; storageController?: StorageController }> {\n if (!storageConfig) return {};\n\n logger.info(\"Configuring storage\");\n const controllers: Record<string, StorageController> = {};\n\n const toController = async (entry: BackendStorageConfig | StorageController, label: string): Promise<StorageController> => {\n if (typeof (entry as StorageController).putObject === \"function\") {\n return entry as StorageController;\n }\n const conf = entry as BackendStorageConfig;\n if (isProduction && conf.type === \"local\") {\n logger.warn(`Storage backend \"${label}\" uses local filesystem in production. ` +\n \"Files will be lost on container restart. \" +\n \"Configure S3-compatible storage or a custom StorageController.\");\n }\n return await createStorageController(conf);\n };\n\n if (\n typeof storageConfig === \"object\" &&\n (\"type\" in storageConfig || typeof (storageConfig as StorageController).putObject === \"function\")\n ) {\n controllers[DEFAULT_STORAGE_ID] = await toController(\n storageConfig as BackendStorageConfig | StorageController,\n DEFAULT_STORAGE_ID\n );\n } else {\n for (const [storageId, entry] of Object.entries(\n storageConfig as Record<string, BackendStorageConfig | StorageController>\n )) {\n controllers[storageId] = await toController(entry, storageId);\n }\n }\n\n if (Object.keys(controllers).length > 0) {\n const storageRegistry = DefaultStorageRegistry.create(controllers);\n const storageController = storageRegistry.getDefault();\n logger.info(\"Initialized storage backends\", { count: Object.keys(controllers).length });\n return { storageRegistry, storageController };\n }\n\n return {};\n}\n","import { Hono } from \"hono\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { HonoEnv } from \"../api/types\";\nimport { logger } from \"../utils/logger\";\n\nexport async function mountOpenApiDocs(\n app: Hono<HonoEnv>,\n basePath: string,\n enableSwagger: boolean | undefined,\n activeCollections: CollectionConfig[],\n requireAuth: boolean\n): Promise<void> {\n if (enableSwagger === false || activeCollections.length === 0) {\n return;\n }\n\n const { generateOpenApiSpec } = await import(\"../api/openapi-generator\");\n\n app.get(`${basePath}/docs`, (c) => {\n const spec = generateOpenApiSpec(activeCollections, {\n basePath,\n requireAuth\n });\n return c.json(spec);\n });\n\n if (process.env.NODE_ENV !== \"production\") {\n app.get(`${basePath}/swagger`, (c) => {\n return c.html(`<!DOCTYPE html>\n<html>\n<head>\n <title>Rebase API Documentation</title>\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\"/>\n <style>body{margin:0;padding:0;}</style>\n</head>\n<body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js\"></script>\n <script>SwaggerUIBundle({ url: '${basePath}/docs', dom_id: '#swagger-ui' });</script>\n</body>\n</html>`);\n });\n logger.info(\"Swagger UI available\", { path: `${basePath}/swagger` });\n }\n}\n","import { DataDriver, HealthCheckResult, isSQLAdmin } from \"@rebasepro/types\";\nimport { logger } from \"../utils/logger\";\n\nexport function createHealthCheck(defaultDriver: DataDriver): () => Promise<HealthCheckResult> {\n return async (): Promise<HealthCheckResult> => {\n const start = performance.now();\n try {\n const admin = defaultDriver.admin;\n if (isSQLAdmin(admin)) {\n await admin.executeSql(\"SELECT 1\");\n } else {\n await defaultDriver.fetchCollection({\n path: \"__health_check_nonexistent__\",\n limit: 1\n });\n }\n const latencyMs = Math.round(performance.now() - start);\n return {\n healthy: true,\n latencyMs\n };\n } catch (error: unknown) {\n const latencyMs = Math.round(performance.now() - start);\n logger.error(\"Health check failed\", {\n error: error instanceof Error ? error : new Error(String(error)),\n latencyMs\n });\n return {\n healthy: false,\n latencyMs,\n details: {\n error: error instanceof Error ? error.message : String(error)\n }\n };\n }\n };\n}\n","import { Server } from \"http\";\nimport { RealtimeProvider } from \"@rebasepro/types\";\nimport { logger } from \"../utils/logger\";\n\ninterface ShutdownConfig {\n server: Server;\n cronScheduler?: { stop(): void };\n realtimeServices: Record<string, RealtimeProvider>;\n}\n\n/**\n * Minimal structural view of the backend instance needed by\n * {@link installShutdownHandlers}. Structural (rather than importing\n * `RebaseBackendInstance`) to avoid a circular import with `../init`.\n */\ninterface ShutdownCapableBackend {\n shutdown(timeoutMs?: number): Promise<void>;\n}\n\nexport interface ShutdownHandlerOptions {\n /**\n * Cleanup to run after the backend has drained — e.g. closing your\n * database pool: `onCleanup: () => pool.end()`.\n */\n onCleanup?: () => Promise<void> | void;\n\n /**\n * Hard force-exit timeout in milliseconds. If the shutdown sequence\n * (drain + cleanup) has not completed by then, the process exits with\n * code 1. Also passed to `backend.shutdown()` as its drain timeout.\n *\n * @default 15000\n */\n timeoutMs?: number;\n\n /**\n * Process signals to handle.\n * @default [\"SIGTERM\", \"SIGINT\"]\n */\n signals?: NodeJS.Signals[];\n\n /** @internal Injectable exit function for tests. */\n exit?: (code: number) => void;\n}\n\n/**\n * Install graceful-shutdown signal handlers for a Rebase backend.\n *\n * On the first signal received, this drains the backend via\n * `backend.shutdown()` — which stops the cron scheduler, tears down\n * realtime services, and closes the HTTP server. Do **not** call\n * `server.close()` yourself in addition: closing an already-closing\n * server deadlocks, because the second close's callback never fires.\n *\n * After the drain, `onCleanup` runs (close your database pool here),\n * and the process exits 0. A force-exit timer guards the whole\n * sequence: if it has not completed within `timeoutMs`, the process\n * exits 1. Repeated signals while a shutdown is in flight are ignored.\n *\n * @returns An uninstall function that removes the signal listeners\n * (useful in tests).\n *\n * @example\n * ```ts\n * const backend = await initializeRebaseBackend({ ... });\n * installShutdownHandlers(backend, { onCleanup: () => pool.end() });\n * ```\n */\nexport function installShutdownHandlers(\n backend: ShutdownCapableBackend,\n options: ShutdownHandlerOptions = {}\n): () => void {\n const {\n onCleanup,\n timeoutMs = 15_000,\n signals = [\"SIGTERM\", \"SIGINT\"],\n exit = process.exit\n } = options;\n\n let shuttingDown = false;\n\n const shutdownSequence = async (signal: NodeJS.Signals): Promise<void> => {\n if (shuttingDown) return;\n shuttingDown = true;\n\n logger.info(`Received ${signal}, shutting down gracefully...`);\n\n // Hard backstop — must be armed before any awaits.\n const forceTimer = setTimeout(() => {\n logger.error(`Shutdown timed out after ${Math.round(timeoutMs / 1000)}s. Forcefully exiting.`);\n exit(1);\n }, timeoutMs);\n forceTimer.unref();\n\n try {\n await backend.shutdown(timeoutMs);\n if (onCleanup) {\n await onCleanup();\n }\n clearTimeout(forceTimer);\n logger.info(\"Graceful shutdown complete.\");\n exit(0);\n } catch (err) {\n logger.error(\"Error during shutdown cleanup:\", { error: err instanceof Error ? err : new Error(String(err)) });\n exit(1);\n }\n };\n\n const listeners = signals.map((signal) => {\n const listener = () => { void shutdownSequence(signal); };\n process.on(signal, listener);\n return { signal, listener } as const;\n });\n\n return () => {\n for (const { signal, listener } of listeners) {\n process.removeListener(signal, listener);\n }\n };\n}\n\nexport function createShutdown(config: ShutdownConfig): (timeoutMs?: number) => Promise<void> {\n return (timeoutMs = 15_000): Promise<void> => {\n return new Promise<void>((resolve) => {\n (async () => {\n logger.info(\"Shutting down Rebase Backend...\");\n\n // 1. Stop cron scheduler\n if (config.cronScheduler) {\n config.cronScheduler.stop();\n logger.info(\"Cron scheduler stopped\");\n }\n\n // 2. Tear down realtime services (LISTEN clients, debounce timers,\n // subscriptions). Must happen BEFORE pool.end() so that pending\n // timer callbacks don't fire against a closed pool.\n for (const [key, rt] of Object.entries(config.realtimeServices)) {\n try {\n if (typeof rt.destroy === \"function\") {\n await rt.destroy();\n logger.info(`Realtime service \"${key}\" destroyed`);\n } else if (typeof rt.stopListening === \"function\") {\n await rt.stopListening();\n logger.info(`Realtime service \"${key}\" LISTEN client stopped`);\n }\n } catch (err) {\n logger.warn(`Error destroying realtime service \"${key}\":`, { error: err });\n }\n }\n\n // 3. Close the HTTP server (stop accepting, drain in-flight)\n config.server.close(() => {\n logger.info(\"HTTP server closed\");\n resolve();\n });\n\n // 4. Force-resolve after timeout (unless disabled with 0)\n if (timeoutMs > 0) {\n setTimeout(() => {\n logger.warn(`Forced shutdown after ${timeoutMs / 1000}s timeout`);\n resolve();\n }, timeoutMs).unref();\n }\n })();\n });\n };\n}\n","import { DEFAULT_STORAGE_SOURCE_KEY, EntityReference, EntityRelation, GeoPoint, PUBLIC_STORAGE_PREFIX, RebaseApiError, RebaseApiError as RebaseApiError$1, RebaseClientError, Vector, isPublicStoragePath } from \"@rebasepro/types\";\nimport { QueryBuilder, and, cond, or, serializeFilter, serializeLogicalCondition, serializeOrderBy } from \"@rebasepro/common\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n//#region src/reviver.ts\nfunction rebaseReviver(_key, value) {\n\tif (value && typeof value === \"object\" && \"__type\" in value) {\n\t\tconst record = value;\n\t\tswitch (record.__type) {\n\t\t\tcase \"date\":\n\t\t\tcase \"Date\": {\n\t\t\t\tif (typeof record.value !== \"string\") return value;\n\t\t\t\tconst date = new Date(record.value);\n\t\t\t\treturn isNaN(date.getTime()) ? null : date;\n\t\t\t}\n\t\t\tcase \"reference\":\n\t\t\tcase \"EntityReference\": return new EntityReference({\n\t\t\t\tid: String(record.id),\n\t\t\t\tpath: record.path,\n\t\t\t\tdriver: record.driver,\n\t\t\t\tdatabaseId: record.databaseId\n\t\t\t});\n\t\t\tcase \"relation\":\n\t\t\tcase \"EntityRelation\": return new EntityRelation(record.id, record.path, record.data);\n\t\t\tcase \"GeoPoint\": return new GeoPoint(record.latitude, record.longitude);\n\t\t\tcase \"Vector\": return new Vector(record.value);\n\t\t\tdefault: return value;\n\t\t}\n\t}\n\treturn value;\n}\n//#endregion\n//#region src/transport.ts\nfunction buildQueryString(params) {\n\tif (!params) return \"\";\n\tconst parts = [];\n\tif (params.limit != null) parts.push(`limit=${params.limit}`);\n\tif (params.offset != null) parts.push(`offset=${params.offset}`);\n\tif (params.page != null) parts.push(`page=${params.page}`);\n\tif (params.orderBy) {\n\t\tconst wire = serializeOrderBy(params.orderBy);\n\t\tif (wire) parts.push(`orderBy=${encodeURIComponent(wire)}`);\n\t}\n\tif (params.searchString) parts.push(`searchString=${encodeURIComponent(params.searchString)}`);\n\tif (params.include && params.include.length > 0) parts.push(`include=${encodeURIComponent(params.include.join(\",\"))}`);\n\tif (params.logical) {\n\t\tconst root = params.logical;\n\t\tconst serialized = (root.conditions ?? []).map(serializeLogicalCondition).join(\",\");\n\t\tparts.push(`${root.type}=${encodeURIComponent(`(${serialized})`)}`);\n\t}\n\tif (params.where) {\n\t\tconst serialized = serializeFilter(params.where);\n\t\tfor (const [field, value] of Object.entries(serialized)) if (Array.isArray(value)) for (const v of value) parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(v)}`);\n\t\telse parts.push(`${encodeURIComponent(field)}=${encodeURIComponent(value)}`);\n\t}\n\treturn parts.length > 0 ? \"?\" + parts.join(\"&\") : \"\";\n}\nfunction createTransport(config) {\n\tconst fetchFn = config.fetch || globalThis.fetch;\n\tconst apiPath = config.apiPath || \"/api\";\n\tlet token = config.token;\n\tlet tokenGetter;\n\tlet onUnauthorizedHandler = config.onUnauthorized;\n\tfunction getHeaders(activeToken, init) {\n\t\treturn {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t...activeToken ? { Authorization: `Bearer ${activeToken}` } : {},\n\t\t\t...init?.headers || {}\n\t\t};\n\t}\n\tasync function request(path, init) {\n\t\tconst url = (config.baseUrl ? config.baseUrl.replace(/\\/$/, \"\") : \"\") + apiPath + path;\n\t\tlet activeToken = token;\n\t\tif (tokenGetter) try {\n\t\t\tconst fetched = await tokenGetter();\n\t\t\tif (fetched !== null && fetched !== void 0) activeToken = fetched;\n\t\t} catch (e) {}\n\t\tconst headers = getHeaders(activeToken, init);\n\t\tif (init?.body instanceof FormData) delete headers[\"Content-Type\"];\n\t\tconst res = await fetchFn(url, {\n\t\t\t...init,\n\t\t\theaders\n\t\t});\n\t\tif (res.status === 204) return void 0;\n\t\tconst text = await res.text().catch(() => \"\");\n\t\tlet body = {};\n\t\tif (text) try {\n\t\t\tbody = JSON.parse(text, rebaseReviver);\n\t\t} catch (e) {}\n\t\tconst getErrorField = (obj, field) => {\n\t\t\tconst err = obj?.error;\n\t\t\tif (err && typeof err === \"object\" && err !== null) return err[field];\n\t\t};\n\t\tif (res.status === 401 && onUnauthorizedHandler) {\n\t\t\tif (await onUnauthorizedHandler()) {\n\t\t\t\tlet retryToken = token;\n\t\t\t\tif (tokenGetter) try {\n\t\t\t\t\tconst fetched = await tokenGetter();\n\t\t\t\t\tif (fetched !== null && fetched !== void 0) retryToken = fetched;\n\t\t\t\t} catch (e) {}\n\t\t\t\tconst retryHeaders = getHeaders(retryToken, init);\n\t\t\t\tconst retryRes = await fetchFn(url, {\n\t\t\t\t\t...init,\n\t\t\t\t\theaders: retryHeaders\n\t\t\t\t});\n\t\t\t\tif (retryRes.status === 204) return void 0;\n\t\t\t\tconst retryText = await retryRes.text().catch(() => \"\");\n\t\t\t\tlet retryBody = {};\n\t\t\t\tif (retryText) try {\n\t\t\t\t\tretryBody = JSON.parse(retryText, rebaseReviver);\n\t\t\t\t} catch (e) {}\n\t\t\t\tif (!retryRes.ok) {\n\t\t\t\t\tlet fallbackMessage = retryRes.statusText;\n\t\t\t\t\tif (retryRes.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || \"GET\"} ${path}). This usually means the collection is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;\n\t\t\t\t\tthrow new RebaseApiError$1(String(getErrorField(retryBody, \"message\") || fallbackMessage || `Request failed with status ${retryRes.status}`), {\n\t\t\t\t\t\tstatus: retryRes.status,\n\t\t\t\t\t\tcode: getErrorField(retryBody, \"code\"),\n\t\t\t\t\t\tdetails: getErrorField(retryBody, \"details\")\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn retryBody;\n\t\t\t}\n\t\t}\n\t\tif (!res.ok) {\n\t\t\tlet fallbackMessage = res.statusText;\n\t\t\tif (res.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || \"GET\"} ${path}). This usually means the collection is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;\n\t\t\tthrow new RebaseApiError$1(String(getErrorField(body, \"message\") || fallbackMessage || `Request failed with status ${res.status}`), {\n\t\t\t\tstatus: res.status,\n\t\t\t\tcode: getErrorField(body, \"code\"),\n\t\t\t\tdetails: getErrorField(body, \"details\")\n\t\t\t});\n\t\t}\n\t\treturn body;\n\t}\n\treturn {\n\t\trequest,\n\t\tsetToken(newToken) {\n\t\t\ttoken = newToken || void 0;\n\t\t},\n\t\tsetAuthTokenGetter(getter) {\n\t\t\ttokenGetter = getter;\n\t\t},\n\t\tsetOnUnauthorized(handler) {\n\t\t\tonUnauthorizedHandler = handler;\n\t\t},\n\t\tget baseUrl() {\n\t\t\treturn config.baseUrl ? config.baseUrl.replace(/\\/$/, \"\") : \"\";\n\t\t},\n\t\tget apiPath() {\n\t\t\treturn apiPath;\n\t\t},\n\t\tget fetchFn() {\n\t\t\treturn fetchFn;\n\t\t},\n\t\tgetHeaders: (init) => getHeaders(token, init),\n\t\tresolveToken: async () => {\n\t\t\tif (tokenGetter) try {\n\t\t\t\tconst fetched = await tokenGetter();\n\t\t\t\tif (fetched !== null && fetched !== void 0) return fetched;\n\t\t\t} catch (e) {}\n\t\t\treturn token || null;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/auth.ts\n/** Map a raw user object from an auth response (`/login`, `/refresh`, `/me`) to a `User`. */\nfunction mapRawUser(raw) {\n\treturn {\n\t\tuid: raw.uid,\n\t\temail: raw.email ?? null,\n\t\tdisplayName: raw.displayName ?? null,\n\t\tphotoURL: raw.photoURL ?? null,\n\t\tproviderId: raw.providerId ?? \"password\",\n\t\tisAnonymous: raw.isAnonymous ?? false,\n\t\temailVerified: raw.emailVerified,\n\t\troles: raw.roles,\n\t\tmetadata: raw.metadata\n\t};\n}\n/** Placeholder user, used only as a last resort when none can be resolved. */\nvar EMPTY_USER = {\n\tuid: \"\",\n\temail: null,\n\tdisplayName: null,\n\tphotoURL: null,\n\tproviderId: \"password\",\n\tisAnonymous: false\n};\nfunction createMemoryStorage() {\n\tconst store = {};\n\treturn {\n\t\tgetItem(key) {\n\t\t\treturn store[key] ?? null;\n\t\t},\n\t\tsetItem(key, value) {\n\t\t\tstore[key] = value;\n\t\t},\n\t\tremoveItem(key) {\n\t\t\tdelete store[key];\n\t\t}\n\t};\n}\nfunction detectStorage() {\n\ttry {\n\t\tif (typeof localStorage !== \"undefined\") {\n\t\t\tlocalStorage.setItem(\"__rebase_test__\", \"1\");\n\t\t\tlocalStorage.removeItem(\"__rebase_test__\");\n\t\t\treturn localStorage;\n\t\t}\n\t} catch (e) {}\n\treturn createMemoryStorage();\n}\nfunction createAuth(transport, options) {\n\tconst opts = options || {};\n\tconst storage = opts.storage || detectStorage();\n\tconst authPath = opts.authPath || \"/auth\";\n\tconst autoRefresh = opts.autoRefresh !== false;\n\tconst persistSession = opts.persistSession !== false;\n\tconst authFlowMode = opts.authFlowMode || \"json\";\n\tconst STORAGE_KEY = \"rebase_auth\";\n\tconst REFRESH_BUFFER_MS = 12e4;\n\tconst MAX_REFRESH_RETRIES = 5;\n\tconst REFRESH_RETRY_BASE_MS = 1e3;\n\tconst REFRESH_RETRY_MAX_MS = 3e4;\n\tlet currentSession = null;\n\tconst listeners = /* @__PURE__ */ new Set();\n\tlet refreshTimeout = null;\n\tlet inFlightRefresh = null;\n\tlet resolveInitialized;\n\tconst isInitialized = new Promise((resolve) => {\n\t\tresolveInitialized = resolve;\n\t});\n\tfunction authUrl(endpoint) {\n\t\treturn transport.baseUrl + transport.apiPath + authPath + endpoint;\n\t}\n\tfunction getFetch() {\n\t\treturn transport.fetchFn || globalThis.fetch;\n\t}\n\tfunction throwApiError(status, body, statusText) {\n\t\tthrow new RebaseApiError(body?.error?.message || body?.message || statusText, {\n\t\t\tstatus,\n\t\t\tcode: body?.error?.code || body?.code,\n\t\t\tdetails: body?.error?.details || body?.details\n\t\t});\n\t}\n\tfunction emit(event, session) {\n\t\tfor (const fn of listeners) try {\n\t\t\tfn(event, session);\n\t\t} catch (e) {}\n\t}\n\tfunction saveSession(session) {\n\t\tif (!persistSession || authFlowMode === \"cookie\") return;\n\t\ttry {\n\t\t\tstorage.setItem(STORAGE_KEY, JSON.stringify(session));\n\t\t} catch (e) {}\n\t}\n\tfunction clearStoredSession() {\n\t\ttry {\n\t\t\tstorage.removeItem(STORAGE_KEY);\n\t\t} catch (e) {}\n\t}\n\tfunction loadStoredSession() {\n\t\ttry {\n\t\t\tconst raw = storage.getItem(STORAGE_KEY);\n\t\t\tif (raw) return JSON.parse(raw);\n\t\t} catch (e) {}\n\t\treturn null;\n\t}\n\t/**\n\t* A refresh failure is only fatal if the refresh token itself is rejected\n\t* (expired / invalid / forbidden). Network blips, timeouts, and 5xx (e.g. a\n\t* backend restart mid-session) are transient and must NOT log the user out.\n\t*/\n\tfunction isFatalRefreshError(err) {\n\t\tif (!(err instanceof RebaseApiError)) return false;\n\t\tif (err.code === \"INVALID_TOKEN\" || err.code === \"TOKEN_EXPIRED\") return true;\n\t\treturn err.status === 401 || err.status === 403;\n\t}\n\tasync function attemptScheduledRefresh(attempt) {\n\t\ttry {\n\t\t\tawait refreshSession();\n\t\t} catch (err) {\n\t\t\tif (isFatalRefreshError(err)) {\n\t\t\t\tsignOut();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (attempt >= MAX_REFRESH_RETRIES) {\n\t\t\t\tsignOut();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst backoff = Math.min(REFRESH_RETRY_BASE_MS * 2 ** attempt, REFRESH_RETRY_MAX_MS);\n\t\t\trefreshTimeout = setTimeout(() => {\n\t\t\t\tattemptScheduledRefresh(attempt + 1);\n\t\t\t}, backoff);\n\t\t}\n\t}\n\tfunction scheduleRefresh(expiresAt) {\n\t\tif (refreshTimeout) clearTimeout(refreshTimeout);\n\t\tif (!autoRefresh) return;\n\t\tconst delay = expiresAt - REFRESH_BUFFER_MS - Date.now();\n\t\tif (delay <= 0) {\n\t\t\tattemptScheduledRefresh(0);\n\t\t\treturn;\n\t\t}\n\t\trefreshTimeout = setTimeout(() => {\n\t\t\tattemptScheduledRefresh(0);\n\t\t}, delay);\n\t}\n\tfunction handleAuthResponse(data, event) {\n\t\tconst user = mapRawUser(data.user);\n\t\tconst session = {\n\t\t\taccessToken: data.tokens.accessToken,\n\t\t\trefreshToken: data.tokens.refreshToken || currentSession?.refreshToken || \"\",\n\t\t\texpiresAt: data.tokens.accessTokenExpiresAt,\n\t\t\tuser\n\t\t};\n\t\tcurrentSession = session;\n\t\tsaveSession(session);\n\t\ttransport.setToken(session.accessToken);\n\t\tscheduleRefresh(session.expiresAt);\n\t\temit(event || \"SIGNED_IN\", session);\n\t\treturn session;\n\t}\n\tasync function signInWithEmail(email, password) {\n\t\tconst res = await getFetch()(authUrl(\"/login\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\temail,\n\t\t\t\tpassword\n\t\t\t}),\n\t\t\tcredentials: authFlowMode === \"cookie\" ? \"include\" : void 0\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\tconst session = handleAuthResponse(body, \"SIGNED_IN\");\n\t\treturn {\n\t\t\tuser: session.user,\n\t\t\taccessToken: session.accessToken,\n\t\t\trefreshToken: session.refreshToken\n\t\t};\n\t}\n\tasync function signUp(email, password, displayName) {\n\t\tconst fetchFn = getFetch();\n\t\tconst payload = {\n\t\t\temail,\n\t\t\tpassword\n\t\t};\n\t\tif (displayName !== void 0) payload.displayName = displayName;\n\t\tconst res = await fetchFn(authUrl(\"/register\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify(payload),\n\t\t\tcredentials: authFlowMode === \"cookie\" ? \"include\" : void 0\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\tconst session = handleAuthResponse(body, \"SIGNED_IN\");\n\t\treturn {\n\t\t\tuser: session.user,\n\t\t\taccessToken: session.accessToken,\n\t\t\trefreshToken: session.refreshToken\n\t\t};\n\t}\n\t/**\n\t* Sign in with Google.\n\t*\n\t* Supports three invocation styles:\n\t* - `signInWithGoogle({ idToken })` — ID-token flow (One Tap / Sign In button)\n\t* - `signInWithGoogle({ accessToken })` — Access-token flow (popup)\n\t* - `signInWithGoogle({ code, redirectUri })` — Authorization code flow (most secure)\n\t*/\n\tasync function signInWithGoogle(payload) {\n\t\tconst res = await getFetch()(authUrl(\"/google\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify(payload),\n\t\t\tcredentials: authFlowMode === \"cookie\" ? \"include\" : void 0\n\t\t});\n\t\tconst responseBody = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, responseBody, res.statusText);\n\t\tconst session = handleAuthResponse(responseBody, \"SIGNED_IN\");\n\t\treturn {\n\t\t\tuser: session.user,\n\t\t\taccessToken: session.accessToken,\n\t\t\trefreshToken: session.refreshToken\n\t\t};\n\t}\n\tasync function signInWithLinkedin(code, redirectUri) {\n\t\tconst res = await getFetch()(authUrl(\"/linkedin\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\tcode,\n\t\t\t\tredirectUri\n\t\t\t}),\n\t\t\tcredentials: authFlowMode === \"cookie\" ? \"include\" : void 0\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\tconst session = handleAuthResponse(body, \"SIGNED_IN\");\n\t\treturn {\n\t\t\tuser: session.user,\n\t\t\taccessToken: session.accessToken,\n\t\t\trefreshToken: session.refreshToken\n\t\t};\n\t}\n\t/**\n\t* Generic OAuth sign-in. Posts the given payload to `/auth/{providerId}`.\n\t* Use this for any provider registered on the backend.\n\t*/\n\tasync function signInWithOAuth(providerId, payload) {\n\t\tconst res = await getFetch()(authUrl(`/${providerId}`), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify(payload),\n\t\t\tcredentials: authFlowMode === \"cookie\" ? \"include\" : void 0\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\tconst session = handleAuthResponse(body, \"SIGNED_IN\");\n\t\treturn {\n\t\t\tuser: session.user,\n\t\t\taccessToken: session.accessToken,\n\t\t\trefreshToken: session.refreshToken\n\t\t};\n\t}\n\tasync function signInWithGitHub(code, redirectUri) {\n\t\treturn signInWithOAuth(\"github\", {\n\t\t\tcode,\n\t\t\tredirectUri\n\t\t});\n\t}\n\tasync function signInWithMicrosoft(code, redirectUri) {\n\t\treturn signInWithOAuth(\"microsoft\", {\n\t\t\tcode,\n\t\t\tredirectUri\n\t\t});\n\t}\n\tasync function signInWithApple(code, redirectUri, user) {\n\t\treturn signInWithOAuth(\"apple\", {\n\t\t\tcode,\n\t\t\tredirectUri,\n\t\t\tuser\n\t\t});\n\t}\n\tasync function signInWithFacebook(code, redirectUri) {\n\t\treturn signInWithOAuth(\"facebook\", {\n\t\t\tcode,\n\t\t\tredirectUri\n\t\t});\n\t}\n\tasync function signInWithTwitter(code, redirectUri, codeVerifier) {\n\t\treturn signInWithOAuth(\"twitter\", {\n\t\t\tcode,\n\t\t\tredirectUri,\n\t\t\tcodeVerifier\n\t\t});\n\t}\n\tasync function signInWithDiscord(code, redirectUri) {\n\t\treturn signInWithOAuth(\"discord\", {\n\t\t\tcode,\n\t\t\tredirectUri\n\t\t});\n\t}\n\tasync function signInWithGitLab(code, redirectUri) {\n\t\treturn signInWithOAuth(\"gitlab\", {\n\t\t\tcode,\n\t\t\tredirectUri\n\t\t});\n\t}\n\tasync function signInWithBitbucket(code, redirectUri) {\n\t\treturn signInWithOAuth(\"bitbucket\", {\n\t\t\tcode,\n\t\t\tredirectUri\n\t\t});\n\t}\n\tasync function signInWithSlack(code, redirectUri) {\n\t\treturn signInWithOAuth(\"slack\", {\n\t\t\tcode,\n\t\t\tredirectUri\n\t\t});\n\t}\n\tasync function signInWithSpotify(code, redirectUri) {\n\t\treturn signInWithOAuth(\"spotify\", {\n\t\t\tcode,\n\t\t\tredirectUri\n\t\t});\n\t}\n\tasync function signOut() {\n\t\tconst fetchFn = getFetch();\n\t\ttry {\n\t\t\tif (authFlowMode === \"cookie\" || currentSession?.refreshToken) await fetchFn(authUrl(\"/logout\"), {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ refreshToken: currentSession?.refreshToken }),\n\t\t\t\tcredentials: authFlowMode === \"cookie\" ? \"include\" : void 0\n\t\t\t});\n\t\t} catch (e) {}\n\t\tcurrentSession = null;\n\t\tclearStoredSession();\n\t\tif (refreshTimeout) {\n\t\t\tclearTimeout(refreshTimeout);\n\t\t\trefreshTimeout = null;\n\t\t}\n\t\ttransport.setToken(null);\n\t\temit(\"SIGNED_OUT\", null);\n\t}\n\tfunction refreshSession() {\n\t\tif (inFlightRefresh) return inFlightRefresh;\n\t\tinFlightRefresh = doRefreshSession().finally(() => {\n\t\t\tinFlightRefresh = null;\n\t\t});\n\t\treturn inFlightRefresh;\n\t}\n\tasync function doRefreshSession() {\n\t\tif (authFlowMode !== \"cookie\" && !currentSession?.refreshToken) throw new Error(\"No active session to refresh\");\n\t\tconst res = await getFetch()(authUrl(\"/refresh\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ refreshToken: currentSession?.refreshToken }),\n\t\t\tcredentials: authFlowMode === \"cookie\" ? \"include\" : void 0\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\tconst accessToken = body.tokens.accessToken;\n\t\ttransport.setToken(accessToken);\n\t\tlet user = currentSession?.user;\n\t\tif (body.user && typeof body.user.uid === \"string\") user = mapRawUser(body.user);\n\t\telse if (!user || !user.uid) try {\n\t\t\tuser = await getUser();\n\t\t} catch {}\n\t\tconst session = {\n\t\t\taccessToken,\n\t\t\trefreshToken: body.tokens.refreshToken || currentSession?.refreshToken || \"\",\n\t\t\texpiresAt: body.tokens.accessTokenExpiresAt,\n\t\t\tuser: user ?? EMPTY_USER\n\t\t};\n\t\tcurrentSession = session;\n\t\tsaveSession(session);\n\t\ttransport.setToken(session.accessToken);\n\t\tscheduleRefresh(session.expiresAt);\n\t\temit(\"TOKEN_REFRESHED\", session);\n\t\treturn session;\n\t}\n\tasync function getUser() {\n\t\treturn (await transport.request(authPath + \"/me\", { method: \"GET\" })).user;\n\t}\n\t/**\n\t* Resolve an email to a minimal public profile (`uid`, `displayName`,\n\t* `photoURL`) for invite-by-email flows. Returns `null` when no account\n\t* matches. Requires the backend to opt in via `auth.allowUserLookup`;\n\t* otherwise the endpoint is absent and this rejects.\n\t*/\n\tasync function findUserByEmail(email) {\n\t\treturn (await transport.request(authPath + \"/find-user\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({ email })\n\t\t})).user;\n\t}\n\tasync function updateUser(updates) {\n\t\tconst data = await transport.request(authPath + \"/me\", {\n\t\t\tmethod: \"PATCH\",\n\t\t\tbody: JSON.stringify(updates)\n\t\t});\n\t\tif (currentSession) {\n\t\t\tcurrentSession = {\n\t\t\t\t...currentSession,\n\t\t\t\tuser: data.user\n\t\t\t};\n\t\t\tsaveSession(currentSession);\n\t\t\temit(\"USER_UPDATED\", currentSession);\n\t\t}\n\t\treturn data.user;\n\t}\n\tasync function resetPasswordForEmail(email) {\n\t\tconst res = await getFetch()(authUrl(\"/forgot-password\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ email })\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\treturn body;\n\t}\n\tasync function resetPassword(token, password) {\n\t\tconst res = await getFetch()(authUrl(\"/reset-password\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttoken,\n\t\t\t\tpassword\n\t\t\t})\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\treturn body;\n\t}\n\tasync function changePassword(oldPassword, newPassword) {\n\t\treturn transport.request(authPath + \"/change-password\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\toldPassword,\n\t\t\t\tnewPassword\n\t\t\t})\n\t\t});\n\t}\n\tasync function sendVerificationEmail() {\n\t\treturn transport.request(authPath + \"/send-verification\", { method: \"POST\" });\n\t}\n\tasync function verifyEmail(token) {\n\t\tconst res = await getFetch()(authUrl(\"/verify-email?token=\" + encodeURIComponent(token)), {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" }\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\treturn body;\n\t}\n\tasync function sendMagicLink(email) {\n\t\tconst res = await getFetch()(authUrl(\"/magic-link\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ email })\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\treturn body;\n\t}\n\tasync function verifyMagicLink(token) {\n\t\tconst res = await getFetch()(authUrl(\"/magic-link/verify\"), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({ token }),\n\t\t\tcredentials: authFlowMode === \"cookie\" ? \"include\" : void 0\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\tconst session = handleAuthResponse(body, \"SIGNED_IN\");\n\t\treturn {\n\t\t\tuser: session.user,\n\t\t\taccessToken: session.accessToken,\n\t\t\trefreshToken: session.refreshToken\n\t\t};\n\t}\n\tasync function getSessions() {\n\t\treturn (await transport.request(authPath + \"/sessions\", { method: \"GET\" })).sessions;\n\t}\n\tasync function revokeSession(sessionId) {\n\t\treturn transport.request(authPath + \"/sessions/\" + encodeURIComponent(sessionId), { method: \"DELETE\" });\n\t}\n\tasync function revokeAllSessions() {\n\t\tconst result = await transport.request(authPath + \"/sessions\", { method: \"DELETE\" });\n\t\tcurrentSession = null;\n\t\tclearStoredSession();\n\t\tif (refreshTimeout) {\n\t\t\tclearTimeout(refreshTimeout);\n\t\t\trefreshTimeout = null;\n\t\t}\n\t\ttransport.setToken(null);\n\t\temit(\"SIGNED_OUT\", null);\n\t\treturn result;\n\t}\n\tasync function getAuthConfig() {\n\t\tconst res = await getFetch()(authUrl(\"/config\"), {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" }\n\t\t});\n\t\tconst body = await res.json().catch(() => ({}));\n\t\tif (!res.ok) throwApiError(res.status, body, res.statusText);\n\t\treturn body;\n\t}\n\tfunction getSession() {\n\t\treturn currentSession;\n\t}\n\tfunction onAuthStateChange(callback) {\n\t\tlisteners.add(callback);\n\t\treturn () => listeners.delete(callback);\n\t}\n\tif (persistSession) {\n\t\tconst stored = loadStoredSession();\n\t\tif (stored && stored.accessToken) if (stored.expiresAt > Date.now()) {\n\t\t\tcurrentSession = stored;\n\t\t\ttransport.setToken(stored.accessToken);\n\t\t\tscheduleRefresh(stored.expiresAt);\n\t\t\tresolveInitialized();\n\t\t} else if (authFlowMode === \"cookie\" || stored.refreshToken) {\n\t\t\tcurrentSession = stored;\n\t\t\trefreshSession().then(() => {\n\t\t\t\tresolveInitialized();\n\t\t\t}).catch(() => {\n\t\t\t\tcurrentSession = null;\n\t\t\t\tclearStoredSession();\n\t\t\t\ttransport.setToken(null);\n\t\t\t\tresolveInitialized();\n\t\t\t});\n\t\t} else resolveInitialized();\n\t\telse if (authFlowMode === \"cookie\") refreshSession().then(() => {\n\t\t\tresolveInitialized();\n\t\t}).catch(() => {\n\t\t\tresolveInitialized();\n\t\t});\n\t\telse resolveInitialized();\n\t} else resolveInitialized();\n\treturn {\n\t\tsignInWithEmail,\n\t\tsignUp,\n\t\tsignInWithGoogle,\n\t\tsignInWithLinkedin,\n\t\tsignInWithOAuth,\n\t\tsignInWithGitHub,\n\t\tsignInWithMicrosoft,\n\t\tsignInWithApple,\n\t\tsignInWithFacebook,\n\t\tsignInWithTwitter,\n\t\tsignInWithDiscord,\n\t\tsignInWithGitLab,\n\t\tsignInWithBitbucket,\n\t\tsignInWithSlack,\n\t\tsignInWithSpotify,\n\t\tsignOut,\n\t\trefreshSession,\n\t\tgetUser,\n\t\tfindUserByEmail,\n\t\tupdateUser,\n\t\tresetPasswordForEmail,\n\t\tresetPassword,\n\t\tchangePassword,\n\t\tsendVerificationEmail,\n\t\tverifyEmail,\n\t\tsendMagicLink,\n\t\tverifyMagicLink,\n\t\tgetSessions,\n\t\trevokeSession,\n\t\trevokeAllSessions,\n\t\tgetAuthConfig,\n\t\tgetSession,\n\t\tonAuthStateChange,\n\t\tisInitialized: () => isInitialized\n\t};\n}\nfunction createCookieStorage(options = {}) {\n\tconst defaultOptions = {\n\t\tpath: \"/\",\n\t\tsameSite: \"Lax\",\n\t\t...options\n\t};\n\treturn {\n\t\tgetItem(key) {\n\t\t\tif (typeof document === \"undefined\") return null;\n\t\t\tconst nameEQ = encodeURIComponent(key) + \"=\";\n\t\t\tconst ca = document.cookie.split(\";\");\n\t\t\tfor (let i = 0; i < ca.length; i++) {\n\t\t\t\tlet c = ca[i];\n\t\t\t\twhile (c.charAt(0) === \" \") c = c.substring(1, c.length);\n\t\t\t\tif (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tsetItem(key, value) {\n\t\t\tif (typeof document === \"undefined\") return;\n\t\t\tlet cookieStr = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n\t\t\tif (defaultOptions.path) cookieStr += `; path=${defaultOptions.path}`;\n\t\t\tif (defaultOptions.domain) cookieStr += `; domain=${defaultOptions.domain}`;\n\t\t\tif (defaultOptions.maxAge !== void 0) cookieStr += `; max-age=${defaultOptions.maxAge}`;\n\t\t\telse cookieStr += `; max-age=${365 * 24 * 60 * 60}`;\n\t\t\tif (defaultOptions.secure) cookieStr += \"; secure\";\n\t\t\tif (defaultOptions.sameSite) cookieStr += `; samesite=${defaultOptions.sameSite}`;\n\t\t\tdocument.cookie = cookieStr;\n\t\t},\n\t\tremoveItem(key) {\n\t\t\tif (typeof document === \"undefined\") return;\n\t\t\tlet cookieStr = `${encodeURIComponent(key)}=; path=${defaultOptions.path || \"/\"}; max-age=-1`;\n\t\t\tif (defaultOptions.domain) cookieStr += `; domain=${defaultOptions.domain}`;\n\t\t\tdocument.cookie = cookieStr;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/admin.ts\nfunction createAdmin(transport, options) {\n\tconst adminPath = (options || {}).adminPath || \"/admin\";\n\tasync function listUsers() {\n\t\treturn transport.request(adminPath + \"/users\", { method: \"GET\" });\n\t}\n\tasync function listUsersPaginated(options) {\n\t\tconst params = new URLSearchParams();\n\t\tif (options?.limit !== void 0) params.set(\"limit\", String(options.limit));\n\t\tif (options?.offset !== void 0) params.set(\"offset\", String(options.offset));\n\t\tif (options?.search) params.set(\"search\", options.search);\n\t\tif (options?.orderBy) params.set(\"orderBy\", options.orderBy);\n\t\tif (options?.orderDir) params.set(\"orderDir\", options.orderDir);\n\t\tconst qs = params.toString();\n\t\treturn transport.request(adminPath + \"/users\" + (qs ? \"?\" + qs : \"\"), { method: \"GET\" });\n\t}\n\tasync function getUser(userId) {\n\t\treturn transport.request(adminPath + \"/users/\" + encodeURIComponent(userId), { method: \"GET\" });\n\t}\n\tasync function createUser(data) {\n\t\treturn transport.request(adminPath + \"/users\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(data)\n\t\t});\n\t}\n\tasync function updateUser(userId, data) {\n\t\treturn transport.request(adminPath + \"/users/\" + encodeURIComponent(userId), {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: JSON.stringify(data)\n\t\t});\n\t}\n\tasync function deleteUser(userId) {\n\t\treturn transport.request(adminPath + \"/users/\" + encodeURIComponent(userId), { method: \"DELETE\" });\n\t}\n\tasync function resetPassword(userId, options) {\n\t\treturn transport.request(adminPath + \"/users/\" + encodeURIComponent(userId) + \"/reset-password\", {\n\t\t\tmethod: \"POST\",\n\t\t\t...options?.password ? { body: JSON.stringify({ password: options.password }) } : {}\n\t\t});\n\t}\n\tasync function listRoles() {\n\t\treturn transport.request(adminPath + \"/roles\", { method: \"GET\" });\n\t}\n\tasync function bootstrap() {\n\t\treturn transport.request(adminPath + \"/bootstrap\", { method: \"POST\" });\n\t}\n\treturn {\n\t\tlistUsers,\n\t\tlistUsersPaginated,\n\t\tgetUser,\n\t\tcreateUser,\n\t\tupdateUser,\n\t\tdeleteUser,\n\t\tresetPassword,\n\t\tlistRoles,\n\t\tbootstrap\n\t};\n}\n//#endregion\n//#region src/cron.ts\nfunction createCron(transport, options) {\n\tconst cronPath = options?.cronPath || \"/cron\";\n\tasync function listJobs() {\n\t\treturn transport.request(cronPath, { method: \"GET\" });\n\t}\n\tasync function getJob(jobId) {\n\t\treturn transport.request(cronPath + \"/\" + encodeURIComponent(jobId), { method: \"GET\" });\n\t}\n\tasync function triggerJob(jobId) {\n\t\treturn transport.request(cronPath + \"/\" + encodeURIComponent(jobId) + \"/trigger\", { method: \"POST\" });\n\t}\n\tasync function getJobLogs(jobId, options) {\n\t\tconst params = new URLSearchParams();\n\t\tif (options?.limit !== void 0) params.set(\"limit\", String(options.limit));\n\t\tconst qs = params.toString();\n\t\treturn transport.request(cronPath + \"/\" + encodeURIComponent(jobId) + \"/logs\" + (qs ? \"?\" + qs : \"\"), { method: \"GET\" });\n\t}\n\tasync function toggleJob(jobId, enabled) {\n\t\treturn transport.request(cronPath + \"/\" + encodeURIComponent(jobId), {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: JSON.stringify({ enabled })\n\t\t});\n\t}\n\treturn {\n\t\tlistJobs,\n\t\tgetJob,\n\t\ttriggerJob,\n\t\tgetJobLogs,\n\t\ttoggleJob\n\t};\n}\n//#endregion\n//#region src/api-keys.ts\n/**\n* Creates a client for managing API keys via the admin routes.\n*\n* @param transport - The shared HTTP transport created by `createTransport`.\n* @param options - Optional overrides (e.g. a custom base path).\n*/\nfunction createApiKeys(transport, options) {\n\tconst apiKeysPath = options?.apiKeysPath || \"/admin/api-keys\";\n\t/** List all API keys (masked). */\n\tasync function listKeys() {\n\t\treturn transport.request(apiKeysPath, { method: \"GET\" });\n\t}\n\t/** Get a single API key by ID (masked). */\n\tasync function getKey(id) {\n\t\treturn transport.request(apiKeysPath + \"/\" + encodeURIComponent(id), { method: \"GET\" });\n\t}\n\t/** Create a new API key. The full secret is included in the response. */\n\tasync function createKey(data) {\n\t\treturn transport.request(apiKeysPath, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(data)\n\t\t});\n\t}\n\t/** Update an existing API key. */\n\tasync function updateKey(id, data) {\n\t\treturn transport.request(apiKeysPath + \"/\" + encodeURIComponent(id), {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: JSON.stringify(data)\n\t\t});\n\t}\n\t/** Revoke (soft-delete) an API key. */\n\tasync function revokeKey(id) {\n\t\treturn transport.request(apiKeysPath + \"/\" + encodeURIComponent(id), { method: \"DELETE\" });\n\t}\n\treturn {\n\t\tlistKeys,\n\t\tgetKey,\n\t\tcreateKey,\n\t\tupdateKey,\n\t\trevokeKey\n\t};\n}\n//#endregion\n//#region src/sdk_query_builder.ts\n/**\n* SDK Query Builder — returns flat rows (`FindResult<M>`) instead of\n* Entity-wrapped results (`FindResponse<M>`).\n*\n* @example\n* const { data } = await rebase.data.posts\n* .where(\"status\", \"==\", \"published\")\n* .orderBy(\"created_at\", \"desc\")\n* .limit(10)\n* .find();\n*\n* console.log(data[0].title); // flat access\n*/\nvar SDKQueryBuilder = class {\n\tcollection;\n\tparams = { where: {} };\n\tconstructor(collection) {\n\t\tthis.collection = collection;\n\t}\n\twhere(columnOrCondition, operator, value) {\n\t\tif (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n\t\t\tthis.params.logical = columnOrCondition;\n\t\t\treturn this;\n\t\t}\n\t\tif (!this.params.where) this.params.where = {};\n\t\tconst column = columnOrCondition;\n\t\tconst condition = [operator, value];\n\t\tconst existing = this.params.where[column];\n\t\tif (existing === void 0) this.params.where[column] = condition;\n\t\telse if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) this.params.where[column].push(condition);\n\t\telse {\n\t\t\tlet firstCondition;\n\t\t\tif (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") firstCondition = existing;\n\t\t\telse firstCondition = [\"==\", existing];\n\t\t\tthis.params.where[column] = [firstCondition, condition];\n\t\t}\n\t\treturn this;\n\t}\n\t/**\n\t* Order the results by a specific column.\n\t*/\n\torderBy(column, direction = \"asc\") {\n\t\tthis.params.orderBy = [column, direction];\n\t\treturn this;\n\t}\n\t/**\n\t* Limit the number of results returned.\n\t*/\n\tlimit(count) {\n\t\tthis.params.limit = count;\n\t\treturn this;\n\t}\n\t/**\n\t* Skip the first N results.\n\t*/\n\toffset(count) {\n\t\tthis.params.offset = count;\n\t\treturn this;\n\t}\n\t/**\n\t* Set a free-text search string if supported by the backend.\n\t*/\n\tsearch(searchString) {\n\t\tthis.params.searchString = searchString;\n\t\treturn this;\n\t}\n\t/**\n\t* Include related entities in the response.\n\t* Relations will be populated with full data instead of just IDs.\n\t*\n\t* @param relations - Relation names to include, or \"*\" for all.\n\t* @example\n\t* client.data.posts.include(\"tags\", \"author\").find()\n\t*/\n\tinclude(...relations) {\n\t\tthis.params.include = relations;\n\t\treturn this;\n\t}\n\t/**\n\t* Execute the find query and return the results as flat rows.\n\t*/\n\tasync find() {\n\t\treturn this.collection.find(this.params);\n\t}\n\t/**\n\t* Count the records matching this query.\n\t*/\n\tasync count() {\n\t\tif (!this.collection.count) throw new Error(\"count() is not supported by this collection client.\");\n\t\treturn this.collection.count(this.params);\n\t}\n\t/**\n\t* Listen to realtime updates matching this query.\n\t*/\n\tlisten(onUpdate, onError) {\n\t\tif (!this.collection.listen) throw new Error(\"Listen is only available when RebaseClient is configured with a websocketUrl.\");\n\t\treturn this.collection.listen(this.params, onUpdate, onError);\n\t}\n};\n//#endregion\n//#region src/collection.ts\nfunction createCollectionClient(transport, slug, ws) {\n\tconst basePath = `/data/${slug}`;\n\tconst client = {\n\t\tasync find(params) {\n\t\t\tconst qs = buildQueryString(params);\n\t\t\tconst raw = await transport.request(basePath + qs, { method: \"GET\" });\n\t\t\treturn {\n\t\t\t\tdata: raw.data || [],\n\t\t\t\tmeta: raw.meta\n\t\t\t};\n\t\t},\n\t\tasync findById(id) {\n\t\t\ttry {\n\t\t\t\tconst raw = await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, { method: \"GET\" });\n\t\t\t\tif (!raw) return void 0;\n\t\t\t\treturn raw;\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof RebaseApiError && err.status === 404) return;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t},\n\t\tasync create(data, id) {\n\t\t\tconst body = { ...data };\n\t\t\tif (id !== void 0) body.id = id;\n\t\t\treturn await transport.request(basePath, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body)\n\t\t\t});\n\t\t},\n\t\tasync update(id, data) {\n\t\t\treturn await transport.request(`${basePath}/${encodeURIComponent(String(id))}`, {\n\t\t\t\tmethod: \"PUT\",\n\t\t\t\tbody: JSON.stringify(data)\n\t\t\t});\n\t\t},\n\t\tasync delete(id) {\n\t\t\tawait transport.request(`${basePath}/${encodeURIComponent(String(id))}`, { method: \"DELETE\" });\n\t\t},\n\t\tasync count(params) {\n\t\t\tconst qs = buildQueryString({\n\t\t\t\t...params,\n\t\t\t\tlimit: void 0,\n\t\t\t\toffset: void 0\n\t\t\t});\n\t\t\treturn (await transport.request(basePath + \"/count\" + qs, { method: \"GET\" })).count ?? 0;\n\t\t},\n\t\twhere(columnOrCondition, operator, value) {\n\t\t\tconst builder = new SDKQueryBuilder(client);\n\t\t\tif (typeof columnOrCondition === \"object\") return builder.where(columnOrCondition);\n\t\t\treturn builder.where(columnOrCondition, operator, value);\n\t\t},\n\t\torderBy(column, direction) {\n\t\t\treturn new SDKQueryBuilder(client).orderBy(column, direction);\n\t\t},\n\t\tlimit(count) {\n\t\t\treturn new SDKQueryBuilder(client).limit(count);\n\t\t},\n\t\toffset(count) {\n\t\t\treturn new SDKQueryBuilder(client).offset(count);\n\t\t},\n\t\tsearch(searchString) {\n\t\t\treturn new SDKQueryBuilder(client).search(searchString);\n\t\t},\n\t\tinclude(...relations) {\n\t\t\treturn new SDKQueryBuilder(client).include(...relations);\n\t\t}\n\t};\n\tif (ws) {\n\t\tclient.listen = (params, onUpdate, onError) => {\n\t\t\tlet active = true;\n\t\t\tlet lastUpdateId = 0;\n\t\t\tconst unsub = ws.listenCollection({\n\t\t\t\tpath: slug,\n\t\t\t\tfilter: params?.where,\n\t\t\t\tlimit: params?.limit,\n\t\t\t\tstartAfter: params?.offset ? String(params.offset) : void 0,\n\t\t\t\torderBy: params?.orderBy?.[0],\n\t\t\t\torder: params?.orderBy?.[1],\n\t\t\t\tsearchString: params?.searchString\n\t\t\t}, (incomingRows) => {\n\t\t\t\tconst currentUpdateId = ++lastUpdateId;\n\t\t\t\tconst requestedLimit = params?.limit || 20;\n\t\t\t\tconst offset = params?.offset || 0;\n\t\t\t\tconst rows = incomingRows;\n\t\t\t\tconst heuristicTotal = rows.length;\n\t\t\t\tconst heuristicHasMore = rows.length >= requestedLimit;\n\t\t\t\tif (client.count) client.count(params).then((total) => {\n\t\t\t\t\tif (active && currentUpdateId === lastUpdateId) onUpdate({\n\t\t\t\t\t\tdata: rows,\n\t\t\t\t\t\tmeta: {\n\t\t\t\t\t\t\ttotal,\n\t\t\t\t\t\t\tlimit: requestedLimit,\n\t\t\t\t\t\t\toffset,\n\t\t\t\t\t\t\thasMore: offset + rows.length < total\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}).catch(() => {\n\t\t\t\t\tif (active && currentUpdateId === lastUpdateId) onUpdate({\n\t\t\t\t\t\tdata: rows,\n\t\t\t\t\t\tmeta: {\n\t\t\t\t\t\t\ttotal: heuristicTotal,\n\t\t\t\t\t\t\tlimit: requestedLimit,\n\t\t\t\t\t\t\toffset,\n\t\t\t\t\t\t\thasMore: heuristicHasMore\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\telse onUpdate({\n\t\t\t\t\tdata: rows,\n\t\t\t\t\tmeta: {\n\t\t\t\t\t\ttotal: heuristicTotal,\n\t\t\t\t\t\tlimit: requestedLimit,\n\t\t\t\t\t\toffset,\n\t\t\t\t\t\thasMore: heuristicHasMore\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}, onError);\n\t\t\treturn () => {\n\t\t\t\tactive = false;\n\t\t\t\tunsub();\n\t\t\t};\n\t\t};\n\t\tclient.listenById = (id, onUpdate, onError) => {\n\t\t\treturn ws.listenOne({\n\t\t\t\tpath: slug,\n\t\t\t\tid: String(id)\n\t\t\t}, (row) => {\n\t\t\t\tif (row) onUpdate(row);\n\t\t\t\telse onUpdate(void 0);\n\t\t\t}, onError);\n\t\t};\n\t}\n\treturn client;\n}\n//#endregion\n//#region src/functions.ts\n/**\n* Create a `FunctionsClient` backed by the given transport.\n*\n* The transport already handles:\n* - Base URL resolution\n* - JWT injection via `Authorization: Bearer`\n* - 401 retry / `onUnauthorized` flow\n* - Consistent error throwing via `RebaseApiError`\n*\n* @internal\n*/\nfunction createFunctionsClient(transport) {\n\treturn { async invoke(name, payload, options) {\n\t\tconst method = options?.method ?? \"POST\";\n\t\tconst subPath = options?.path ? `/${options.path.replace(/^\\//, \"\")}` : \"\";\n\t\tconst routePath = `/functions/${encodeURIComponent(name)}${subPath}`;\n\t\tconst init = { method };\n\t\tif (payload !== void 0 && method !== \"GET\") init.body = JSON.stringify(payload);\n\t\tif (options?.headers) init.headers = options.headers;\n\t\treturn transport.request(routePath, init);\n\t} };\n}\n//#endregion\n//#region src/storage.ts\n/**\n* Create a StorageSource that talks to the Rebase backend REST API.\n*\n* @param transport - HTTP transport instance\n* @param storageId - Optional storage-source key for multi-backend routing.\n* When set, it is forwarded to the server so the correct\n* `StorageController` is resolved from the registry.\n*/\nfunction createStorage(transport, storageId) {\n\tconst urlsCache = /* @__PURE__ */ new Map();\n\t/** Append ?storageId=... to a path when multi-backend routing is active. */\n\tconst withStorageId = (path) => {\n\t\tif (!storageId) return path;\n\t\treturn `${path}${path.includes(\"?\") ? \"&\" : \"?\"}storageId=${encodeURIComponent(storageId)}`;\n\t};\n\tasync function putObject({ file, key, metadata, bucket, public: isPublic }) {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", file);\n\t\tlet effectiveKey = key;\n\t\tif (isPublic && effectiveKey && !isPublicStoragePath(effectiveKey)) effectiveKey = `${PUBLIC_STORAGE_PREFIX}${effectiveKey.replace(/^\\/+/, \"\")}`;\n\t\tif (effectiveKey) formData.append(\"key\", effectiveKey);\n\t\tif (bucket) formData.append(\"bucket\", bucket);\n\t\tif (storageId) formData.append(\"storageId\", storageId);\n\t\tif (metadata) {\n\t\t\tfor (const [key, value] of Object.entries(metadata)) if (value !== void 0 && value !== null) formData.append(`metadata_${key}`, typeof value === \"string\" ? value : JSON.stringify(value));\n\t\t}\n\t\treturn (await transport.request(withStorageId(\"/storage/upload\"), {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: formData,\n\t\t\theaders: {}\n\t\t})).data;\n\t}\n\tasync function getSignedUrl(keyOrUrl, bucket) {\n\t\tconst cacheKey = bucket ? `${bucket}/${keyOrUrl}` : keyOrUrl;\n\t\tconst cachedEntry = urlsCache.get(cacheKey);\n\t\tif (cachedEntry) {\n\t\t\tif (!cachedEntry.expiresAt || cachedEntry.expiresAt > Date.now()) return cachedEntry.config;\n\t\t\turlsCache.delete(cacheKey);\n\t\t}\n\t\tlet filePath = keyOrUrl;\n\t\tif (filePath && (filePath.startsWith(\"local://\") || filePath.startsWith(\"s3://\") || filePath.startsWith(\"gs://\"))) filePath = filePath.substring(filePath.indexOf(\"://\") + 3);\n\t\tif (bucket && filePath && !filePath.startsWith(bucket)) filePath = `${bucket}/${filePath}`;\n\t\tif (!filePath || filePath.trim() === \"\" || filePath === \"/\") return {\n\t\t\turl: null,\n\t\t\tfileNotFound: true\n\t\t};\n\t\tif (isPublicStoragePath(filePath)) {\n\t\t\tconst publicConfig = { url: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`) };\n\t\t\turlsCache.set(cacheKey, { config: publicConfig });\n\t\t\treturn publicConfig;\n\t\t}\n\t\ttry {\n\t\t\tconst result = await transport.request(withStorageId(`/storage/metadata/${filePath}`));\n\t\t\tif (result.data.public) {\n\t\t\t\tconst publicConfig = {\n\t\t\t\t\turl: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}`),\n\t\t\t\t\tmetadata: result.data\n\t\t\t\t};\n\t\t\t\turlsCache.set(cacheKey, { config: publicConfig });\n\t\t\t\treturn publicConfig;\n\t\t\t}\n\t\t\tconst scopedToken = result.data.token;\n\t\t\tconst tokenQuery = scopedToken ? `?token=${scopedToken}` : \"\";\n\t\t\tconst downloadConfig = {\n\t\t\t\turl: withStorageId(`${transport.baseUrl}${transport.apiPath}/storage/file/${filePath}${tokenQuery}`),\n\t\t\t\tmetadata: result.data\n\t\t\t};\n\t\t\tconst expiresAt = result.data.tokenExpiresIn ? Date.now() + (result.data.tokenExpiresIn - 10) * 1e3 : void 0;\n\t\t\turlsCache.set(cacheKey, {\n\t\t\t\tconfig: downloadConfig,\n\t\t\t\texpiresAt\n\t\t\t});\n\t\t\treturn downloadConfig;\n\t\t} catch (e) {\n\t\t\tif (e instanceof Error && \"status\" in e && e.status === 404) return {\n\t\t\t\turl: null,\n\t\t\t\tfileNotFound: true\n\t\t\t};\n\t\t\tthrow e;\n\t\t}\n\t}\n\tasync function getObject(key, bucket) {\n\t\tconst downloadConfig = await getSignedUrl(key, bucket);\n\t\tif (downloadConfig.fileNotFound || !downloadConfig.url) return null;\n\t\tconst response = await transport.fetchFn(downloadConfig.url, { headers: {} });\n\t\tif (response.status === 404) return null;\n\t\tif (!response.ok) throw new Error(\"Failed to get file\");\n\t\tconst blob = await response.blob();\n\t\tconst fileName = (bucket ? `${bucket}/${key}` : key).split(\"/\").pop() || \"file\";\n\t\treturn new File([blob], fileName, { type: blob.type });\n\t}\n\tasync function deleteObject(key, bucket) {\n\t\tlet filePath = key;\n\t\tif (filePath && (filePath.startsWith(\"local://\") || filePath.startsWith(\"s3://\") || filePath.startsWith(\"gs://\"))) filePath = filePath.substring(filePath.indexOf(\"://\") + 3);\n\t\tif (bucket && filePath && !filePath.startsWith(bucket)) filePath = `${bucket}/${filePath}`;\n\t\tif (!filePath || filePath.trim() === \"\" || filePath === \"/\") return;\n\t\ttry {\n\t\t\tawait transport.request(withStorageId(`/storage/file/${filePath}`), { method: \"DELETE\" });\n\t\t} catch (e) {\n\t\t\tif (!(e instanceof Error && \"status\" in e && e.status === 404)) throw e;\n\t\t}\n\t\turlsCache.delete(bucket ? `${bucket}/${key}` : key);\n\t}\n\tasync function listObjects(prefix, options) {\n\t\tconst params = new URLSearchParams();\n\t\tif (prefix) params.set(\"prefix\", prefix);\n\t\tif (options?.bucket) params.set(\"bucket\", options.bucket);\n\t\tif (options?.maxResults) params.set(\"maxResults\", String(options.maxResults));\n\t\tif (options?.pageToken) params.set(\"pageToken\", options.pageToken);\n\t\tif (storageId) params.set(\"storageId\", storageId);\n\t\treturn (await transport.request(`/storage/list?${params.toString()}`)).data;\n\t}\n\treturn {\n\t\tputObject,\n\t\tgetSignedUrl,\n\t\tgetObject,\n\t\tdeleteObject,\n\t\tlistObjects\n\t};\n}\n//#endregion\n//#region src/storage-registry.ts\n/**\n* Default implementation of the client-side `StorageSourceRegistry`.\n*/\nvar ClientStorageSourceRegistry = class ClientStorageSourceRegistry {\n\tsources = /* @__PURE__ */ new Map();\n\t/**\n\t* Register a storage source.\n\t* @param key - Unique key matching a `StorageSourceDefinition.key`\n\t* @param source - The `StorageSource` instance\n\t*/\n\tregister(key, source) {\n\t\tthis.sources.set(key, source);\n\t}\n\tgetDefault() {\n\t\tconst source = this.sources.get(DEFAULT_STORAGE_SOURCE_KEY);\n\t\tif (!source) throw new Error(`[StorageSourceRegistry] No default storage source registered. Register one with key \"${DEFAULT_STORAGE_SOURCE_KEY}\".`);\n\t\treturn source;\n\t}\n\tget(key) {\n\t\tif (key === void 0 || key === null) return this.sources.get(DEFAULT_STORAGE_SOURCE_KEY);\n\t\treturn this.sources.get(key);\n\t}\n\tgetOrDefault(key) {\n\t\tif (key === void 0 || key === null) return this.getDefault();\n\t\tconst source = this.sources.get(key);\n\t\tif (source) return source;\n\t\tconsole.warn(`[StorageSourceRegistry] Storage source \"${key}\" not found, falling back to \"${DEFAULT_STORAGE_SOURCE_KEY}\".`);\n\t\treturn this.getDefault();\n\t}\n\thas(key) {\n\t\treturn this.sources.has(key);\n\t}\n\tlist() {\n\t\treturn Array.from(this.sources.keys());\n\t}\n\t/**\n\t* Build a registry from `StorageSourceDefinition[]` and an HTTP transport.\n\t*\n\t* - Sources with `transport: \"server\"` are auto-wired via `createStorage(transport, key)`.\n\t* - Sources with `transport: \"direct\"` are **not** auto-wired — they must\n\t* be registered manually after this call (e.g. via a Firebase hook).\n\t*\n\t* @param definitions - Array of storage source definitions\n\t* @param transport - HTTP transport for server-backed sources\n\t*/\n\tstatic fromDefinitions(definitions, transport) {\n\t\tconst registry = new ClientStorageSourceRegistry();\n\t\tfor (const def of definitions) if (def.transport === \"server\") {\n\t\t\tconst source = createStorage(transport, def.key === DEFAULT_STORAGE_SOURCE_KEY ? void 0 : def.key);\n\t\t\tregistry.register(def.key, source);\n\t\t}\n\t\treturn registry;\n\t}\n};\n//#endregion\n//#region src/websocket.ts\n/**\n* Extract error message and code from a WebSocket message payload.\n* Handles both `{ error: string }` and `{ error: { message, code } }` shapes.\n*/\nfunction extractMessageError(message) {\n\tconst payload = message.payload;\n\tconst errPayload = payload?.error;\n\treturn {\n\t\terrorMessage: typeof errPayload === \"object\" ? errPayload.message : payload?.message || (typeof errPayload === \"string\" ? errPayload : void 0) || message.error || \"Unknown error\",\n\t\terrorCode: typeof errPayload === \"object\" ? errPayload.code : payload?.code\n\t};\n}\n/**\n* Low-level realtime WebSocket client.\n*\n* @internal Not a stable app-facing API. `createRebaseClient()` constructs and\n* manages this internally (exposed as `client.ws`, typed by the minimal\n* `RebaseWebSocket` contract in `@rebasepro/types`). It is re-exported from the\n* package root only because the `@rebasepro/client-postgresql` driver\n* instantiates it directly; its surface may change without a major bump.\n*/\nvar RebaseWebSocketClient = class {\n\twebsocketUrl;\n\tws = null;\n\tgetAuthToken;\n\tsubscriptions = /* @__PURE__ */ new Map();\n\tlisteners = /* @__PURE__ */ new Map();\n\ton(event, cb) {\n\t\tif (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());\n\t\tthis.listeners.get(event).add(cb);\n\t\treturn () => this.listeners.get(event).delete(cb);\n\t}\n\temit(event, ...args) {\n\t\tif (this.listeners.has(event)) this.listeners.get(event).forEach((cb) => cb(...args));\n\t}\n\tcollectionSubscriptions = /* @__PURE__ */ new Map();\n\tsingleSubscriptions = /* @__PURE__ */ new Map();\n\tbackendToCollectionKey = /* @__PURE__ */ new Map();\n\tbackendToEntityKey = /* @__PURE__ */ new Map();\n\tpendingRequests = /* @__PURE__ */ new Map();\n\treconnectAttempts = 0;\n\tmaxReconnectAttempts = 5;\n\tisConnected = false;\n\tmessageQueue = [];\n\trequestTimeoutMs = 3e4;\n\treconnectTimeout = null;\n\tisAuthenticated = false;\n\tauthPromise = null;\n\tWebSocketConstructor;\n\tonUnauthorized;\n\trefreshInProgress = null;\n\tconstructor(config) {\n\t\tthis.websocketUrl = config.websocketUrl;\n\t\tthis.getAuthToken = config.getAuthToken;\n\t\tthis.onUnauthorized = config.onUnauthorized;\n\t\tthis.WebSocketConstructor = config.WebSocket || (typeof WebSocket !== \"undefined\" ? WebSocket : void 0);\n\t\tif (!this.WebSocketConstructor) console.warn(\"WebSocket is not defined in this environment. Realtime subscriptions will not work unless you provide a WebSocket implementation in the config.\");\n\t\telse this.initWebSocket();\n\t}\n\t/**\n\t* Authenticate the WebSocket connection\n\t*/\n\tasync authenticate(token) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst requestId = `auth_${Date.now()}`;\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(requestId);\n\t\t\t\tthis.authPromise = null;\n\t\t\t\treject(/* @__PURE__ */ new Error(\"Authentication timeout\"));\n\t\t\t}, 3e4);\n\t\t\tthis.pendingRequests.set(requestId, {\n\t\t\t\tresolve: () => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tthis.isAuthenticated = true;\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst message = {\n\t\t\t\ttype: \"AUTHENTICATE\",\n\t\t\t\trequestId,\n\t\t\t\tpayload: { token }\n\t\t\t};\n\t\t\tif (!this.isConnected || !this.ws) this.messageQueue.unshift(message);\n\t\t\telse this.ws.send(JSON.stringify(message));\n\t\t});\n\t}\n\t/**\n\t* Set the auth token getter function\n\t*/\n\tsetAuthTokenGetter(getAuthToken) {\n\t\tthis.getAuthToken = getAuthToken;\n\t\tif (this.isConnected && !this.isAuthenticated && !this.authPromise) {\n\t\t\tconsole.debug(\"WebSocket auto-authenticating after token getter set\");\n\t\t\tthis.getAuthToken().then((token) => {\n\t\t\t\tif (!this.ws) return;\n\t\t\t\tif (token) this.authenticate(token).catch((e) => {\n\t\t\t\t\tif (this.ws) console.debug(\"WebSocket auto-auth skipped:\", e?.message || e);\n\t\t\t\t});\n\t\t\t}).catch((e) => {\n\t\t\t\tif (this.ws) console.debug(\"WebSocket auto-auth skipped:\", e?.message || e);\n\t\t\t});\n\t\t}\n\t}\n\tdisconnect() {\n\t\tthis.isAuthenticated = false;\n\t\tthis.authPromise = null;\n\t\tif (this.reconnectTimeout) {\n\t\t\tclearTimeout(this.reconnectTimeout);\n\t\t\tthis.reconnectTimeout = null;\n\t\t}\n\t\tif (this.ws) {\n\t\t\tthis.ws.onclose = null;\n\t\t\tthis.ws.onerror = null;\n\t\t\tthis.ws.onopen = null;\n\t\t\tthis.ws.onmessage = null;\n\t\t\tthis.ws.close();\n\t\t\tthis.ws = null;\n\t\t}\n\t}\n\tinitWebSocket() {\n\t\tif (!this.WebSocketConstructor) return;\n\t\tif (this.ws?.readyState === this.WebSocketConstructor.OPEN) return;\n\t\tif (this.ws) {\n\t\t\tthis.ws.onclose = null;\n\t\t\tthis.ws.close();\n\t\t\tthis.ws = null;\n\t\t}\n\t\ttry {\n\t\t\tthis.ws = new this.WebSocketConstructor(this.websocketUrl);\n\t\t\tthis.ws.onopen = async () => {\n\t\t\t\tconsole.debug(\"Connected to PostgreSQL backend\");\n\t\t\t\tconst wasReconnect = this.reconnectAttempts > 0;\n\t\t\t\tthis.isConnected = true;\n\t\t\t\tthis.reconnectAttempts = 0;\n\t\t\t\tif (this.getAuthToken && !this.isAuthenticated) try {\n\t\t\t\t\tconst token = await this.getAuthToken();\n\t\t\t\t\tif (token) {\n\t\t\t\t\t\tawait this.authenticate(token);\n\t\t\t\t\t\tconsole.debug(\"WebSocket auto-authenticated\");\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconsole.debug(\"WebSocket connected without auth:\", error?.message || error);\n\t\t\t\t}\n\t\t\t\tthis.emit(wasReconnect ? \"reconnect\" : \"connect\");\n\t\t\t\tthis.processMessageQueue();\n\t\t\t\tif (wasReconnect) this.resubscribeAll();\n\t\t\t};\n\t\t\tthis.ws.onmessage = (event) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst message = JSON.parse(event.data, rebaseReviver);\n\t\t\t\t\tthis.handleWebSocketMessage(message);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconsole.error(\"Error parsing WebSocket message:\", error);\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.ws.onclose = () => {\n\t\t\t\tconsole.debug(\"Disconnected from PostgreSQL backend\");\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.isAuthenticated = false;\n\t\t\t\tthis.authPromise = null;\n\t\t\t\tthis.emit(\"disconnect\");\n\t\t\t\tfor (const [reqId, request] of this.pendingRequests.entries()) {\n\t\t\t\t\tif (reqId.startsWith(\"auth_\")) request.reject(/* @__PURE__ */ new Error(\"Connection closed during authentication\"));\n\t\t\t\t\telse if (request.message) {\n\t\t\t\t\t\trequest.message._queuedResolve = request.resolve;\n\t\t\t\t\t\trequest.message._queuedReject = request.reject;\n\t\t\t\t\t\tthis.messageQueue.push(request.message);\n\t\t\t\t\t} else request.reject(new RebaseApiError$1(\"Connection closed\"));\n\t\t\t\t\tthis.pendingRequests.delete(reqId);\n\t\t\t\t}\n\t\t\t\tthis.attemptReconnect();\n\t\t\t};\n\t\t\tthis.ws.onerror = (error) => {\n\t\t\t\tconsole.error(\"WebSocket error:\", error);\n\t\t\t\tthis.isConnected = false;\n\t\t\t\tthis.emit(\"error\", error);\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Failed to initialize WebSocket:\", error);\n\t\t\tthis.attemptReconnect();\n\t\t}\n\t}\n\tprocessMessageQueue() {\n\t\twhile (this.messageQueue.length > 0 && this.isConnected) {\n\t\t\tconst message = this.messageQueue.shift();\n\t\t\tif (message) this.sendMessage(message);\n\t\t}\n\t}\n\tattemptReconnect() {\n\t\tif (this.reconnectAttempts >= this.maxReconnectAttempts) {\n\t\t\tconsole.error(\"Max reconnection attempts reached\");\n\t\t\treturn;\n\t\t}\n\t\tthis.reconnectAttempts++;\n\t\tconst delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);\n\t\tconsole.debug(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);\n\t\tif (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);\n\t\tthis.reconnectTimeout = setTimeout(() => {\n\t\t\tthis.reconnectTimeout = null;\n\t\t\tthis.initWebSocket();\n\t\t}, delay);\n\t}\n\tisAuthError(message) {\n\t\tif (message.type === \"AUTH_ERROR\") return true;\n\t\tconst { errorMessage, errorCode } = extractMessageError(message);\n\t\tif (errorCode === \"UNAUTHORIZED\" || errorCode === \"JWT_EXPIRED\" || errorCode === \"AUTH_ERROR\") return true;\n\t\tconst lowerMessage = errorMessage.toLowerCase();\n\t\treturn lowerMessage.includes(\"unauthorized\") || lowerMessage.includes(\"token expired\") || lowerMessage.includes(\"token is expired\") || lowerMessage.includes(\"invalid token\") || lowerMessage.includes(\"session expired\") || lowerMessage.includes(\"auth error\");\n\t}\n\tasync handleAuthFailure() {\n\t\tif (this.refreshInProgress) return this.refreshInProgress;\n\t\tthis.refreshInProgress = (async () => {\n\t\t\tthis.isAuthenticated = false;\n\t\t\tthis.authPromise = null;\n\t\t\tif (this.onUnauthorized) try {\n\t\t\t\tif (await this.onUnauthorized() && this.getAuthToken) {\n\t\t\t\t\tconst token = await this.getAuthToken();\n\t\t\t\t\tif (token) {\n\t\t\t\t\t\tawait this.authenticate(token);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"WebSocket auth refresh failed:\", error);\n\t\t\t}\n\t\t\treturn false;\n\t\t})();\n\t\ttry {\n\t\t\treturn await this.refreshInProgress;\n\t\t} finally {\n\t\t\tthis.refreshInProgress = null;\n\t\t}\n\t}\n\t/**\n\t* Shared logic for re-subscribing a collection or row subscription\n\t* after an auth error is resolved by refreshing credentials.\n\t*/\n\tresubscribeAfterAuthRefresh(message, subscription, subscriptionKey, idPrefix, backendKeyMap, messageType) {\n\t\tthis.handleAuthFailure().then((refreshed) => {\n\t\t\tif (refreshed) {\n\t\t\t\tconst oldBackendId = subscription.backendSubscriptionId;\n\t\t\t\tconst newBackendId = `${idPrefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\t\t\t\tsubscription.backendSubscriptionId = newBackendId;\n\t\t\t\tbackendKeyMap.delete(oldBackendId);\n\t\t\t\tbackendKeyMap.set(newBackendId, subscriptionKey);\n\t\t\t\tthis.sendMessage({\n\t\t\t\t\ttype: messageType,\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\t...subscription.props,\n\t\t\t\t\t\tsubscriptionId: newBackendId\n\t\t\t\t\t}\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tconsole.error(`[WS] Failed to re-subscribe ${idPrefix} after auth refresh:`, subscriptionKey, error);\n\t\t\t\t\tsubscription.callbacks.forEach((callback) => {\n\t\t\t\t\t\tif (callback.onError) callback.onError(error);\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst { errorMessage, errorCode } = extractMessageError(message);\n\t\t\t\tconst error = new RebaseApiError$1(errorMessage, { code: errorCode });\n\t\t\t\tsubscription.callbacks.forEach((callback) => {\n\t\t\t\t\tif (callback.onError) callback.onError(error);\n\t\t\t\t});\n\t\t\t}\n\t\t}).catch((err) => {\n\t\t\tsubscription.callbacks.forEach((callback) => {\n\t\t\t\tif (callback.onError) callback.onError(err);\n\t\t\t});\n\t\t});\n\t}\n\thandleWebSocketMessage(message) {\n\t\tconst { type, requestId, subscriptionId } = message;\n\t\tif (requestId && this.pendingRequests.has(requestId)) {\n\t\t\tconst pendingReq = this.pendingRequests.get(requestId);\n\t\t\tif (type === \"ERROR\" || type === \"AUTH_ERROR\" || message.error) if (this.isAuthError(message)) {\n\t\t\t\tthis.pendingRequests.delete(requestId);\n\t\t\t\tthis.handleAuthFailure().then((refreshed) => {\n\t\t\t\t\tif (refreshed && pendingReq.message) this.doSendMessage(pendingReq.message, pendingReq.resolve, pendingReq.reject).catch(pendingReq.reject);\n\t\t\t\t\telse {\n\t\t\t\t\t\tconst { errorMessage, errorCode } = extractMessageError(message);\n\t\t\t\t\t\tpendingReq.reject(new RebaseApiError$1(errorMessage, { code: errorCode }));\n\t\t\t\t\t}\n\t\t\t\t}).catch((err) => {\n\t\t\t\t\tpendingReq.reject(err);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tthis.pendingRequests.delete(requestId);\n\t\t\t\tconst { errorMessage, errorCode } = extractMessageError(message);\n\t\t\t\tpendingReq.reject(new RebaseApiError$1(errorMessage, { code: errorCode }));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.pendingRequests.delete(requestId);\n\t\t\t\tpendingReq.resolve(message.payload || message);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (subscriptionId && type === \"collection_update\") {\n\t\t\tconst subscriptionKey = this.backendToCollectionKey.get(subscriptionId);\n\t\t\tif (subscriptionKey) {\n\t\t\t\tconst collectionSub = this.collectionSubscriptions.get(subscriptionKey);\n\t\t\t\tif (collectionSub) {\n\t\t\t\t\tconst incomingRows = message.rows || [];\n\t\t\t\t\tconst rows = this.mergeRows(collectionSub.latestData, incomingRows);\n\t\t\t\t\tcollectionSub.latestData = rows;\n\t\t\t\t\tcollectionSub.lastUpdated = Date.now();\n\t\t\t\t\tcollectionSub.isInitialDataReceived = true;\n\t\t\t\t\tcollectionSub.callbacks.forEach((callback) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcallback.onUpdate(rows);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconsole.error(\"Error in collection subscription callback:\", error);\n\t\t\t\t\t\t\tif (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (subscriptionId && type === \"collection_patch\") {\n\t\t\tconst subscriptionKey = this.backendToCollectionKey.get(subscriptionId);\n\t\t\tif (subscriptionKey) {\n\t\t\t\tconst collectionSub = this.collectionSubscriptions.get(subscriptionKey);\n\t\t\t\tif (collectionSub && collectionSub.isInitialDataReceived && collectionSub.latestData) {\n\t\t\t\t\tconst patchWireEntity = message.row ?? null;\n\t\t\t\t\tconst patchEntityId = message.id;\n\t\t\t\t\tconst patchRow = patchWireEntity ? patchWireEntity : null;\n\t\t\t\t\tlet updated;\n\t\t\t\t\tif (patchRow === null) updated = collectionSub.latestData.filter((e) => String(e.id) !== String(patchEntityId));\n\t\t\t\t\telse {\n\t\t\t\t\t\tconst idx = collectionSub.latestData.findIndex((e) => String(e.id) === String(patchRow.id));\n\t\t\t\t\t\tif (idx >= 0) {\n\t\t\t\t\t\t\tupdated = [...collectionSub.latestData];\n\t\t\t\t\t\t\tupdated[idx] = patchRow;\n\t\t\t\t\t\t} else updated = [patchRow, ...collectionSub.latestData];\n\t\t\t\t\t}\n\t\t\t\t\tcollectionSub.latestData = updated;\n\t\t\t\t\tcollectionSub.lastUpdated = Date.now();\n\t\t\t\t\tcollectionSub.callbacks.forEach((callback) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcallback.onUpdate(updated);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconsole.error(\"Error in collection patch callback:\", error);\n\t\t\t\t\t\t\tif (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (subscriptionId && type === \"single_update\") {\n\t\t\tconst subscriptionKey = this.backendToEntityKey.get(subscriptionId);\n\t\t\tif (subscriptionKey) {\n\t\t\t\tconst entitySub = this.singleSubscriptions.get(subscriptionKey);\n\t\t\t\tif (entitySub) {\n\t\t\t\t\tconst wireEntity = message.row ?? null;\n\t\t\t\t\tconst row = wireEntity ? wireEntity : null;\n\t\t\t\t\tentitySub.latestData = row;\n\t\t\t\t\tentitySub.lastUpdated = Date.now();\n\t\t\t\t\tentitySub.isInitialDataReceived = true;\n\t\t\t\t\tentitySub.callbacks.forEach((callback) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcallback.onUpdate(row);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconsole.error(\"Error in row subscription callback:\", error);\n\t\t\t\t\t\t\tif (callback.onError) callback.onError(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (subscriptionId && (type === \"ERROR\" || message.error)) {\n\t\t\tconst collectionKey = this.backendToCollectionKey.get(subscriptionId);\n\t\t\tif (collectionKey) {\n\t\t\t\tconst collectionSub = this.collectionSubscriptions.get(collectionKey);\n\t\t\t\tif (collectionSub) {\n\t\t\t\t\tif (this.isAuthError(message)) {\n\t\t\t\t\t\tthis.resubscribeAfterAuthRefresh(message, collectionSub, collectionKey, \"collection\", this.backendToCollectionKey, \"subscribe_collection\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst { errorMessage, errorCode } = extractMessageError(message);\n\t\t\t\t\tconst error = new RebaseApiError$1(errorMessage, { code: errorCode });\n\t\t\t\t\tcollectionSub.callbacks.forEach((callback) => {\n\t\t\t\t\t\tif (callback.onError) callback.onError(error);\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst entityKey = this.backendToEntityKey.get(subscriptionId);\n\t\t\tif (entityKey) {\n\t\t\t\tconst entitySub = this.singleSubscriptions.get(entityKey);\n\t\t\t\tif (entitySub) {\n\t\t\t\t\tif (this.isAuthError(message)) {\n\t\t\t\t\t\tthis.resubscribeAfterAuthRefresh(message, entitySub, entityKey, \"row\", this.backendToEntityKey, \"subscribe_one\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst { errorMessage, errorCode } = extractMessageError(message);\n\t\t\t\t\tconst error = new RebaseApiError$1(errorMessage, { code: errorCode });\n\t\t\t\t\tentitySub.callbacks.forEach((callback) => {\n\t\t\t\t\t\tif (callback.onError) callback.onError(error);\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (subscriptionId && this.subscriptions.has(subscriptionId)) {\n\t\t\tconst callback = this.subscriptions.get(subscriptionId);\n\t\t\tif (!callback) throw new Error(`Subscription callback not found for subscriptionId: ${subscriptionId}`);\n\t\t\tif (message.type === \"ERROR\" || message.error) {\n\t\t\t\tif (callback.onError) {\n\t\t\t\t\tconst { errorMessage, errorCode } = extractMessageError(message);\n\t\t\t\t\tcallback.onError(new RebaseApiError$1(errorMessage, { code: errorCode }));\n\t\t\t\t}\n\t\t\t} else callback.onUpdate(message);\n\t\t}\n\t}\n\tasync ensureAuthenticated(retryCount = 3) {\n\t\tif (this.isAuthenticated || !this.getAuthToken) return;\n\t\tif (this.authPromise) {\n\t\t\tawait this.authPromise;\n\t\t\treturn;\n\t\t}\n\t\tlet lastError = null;\n\t\tfor (let attempt = 0; attempt < retryCount; attempt++) try {\n\t\t\tconst token = await this.getAuthToken();\n\t\t\tif (!token) throw new Error(\"user not logged in\");\n\t\t\tthis.authPromise = this.authenticate(token);\n\t\t\tawait this.authPromise;\n\t\t\tthis.authPromise = null;\n\t\t\tconsole.debug(\"WebSocket authenticated on demand\");\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tthis.authPromise = null;\n\t\t\tlastError = error;\n\t\t\tconst errMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errMsg.includes(\"not logged in\") || errMsg.includes(\"Session expired\")) {\n\t\t\t\tconsole.warn(\"WebSocket auth failed: user not logged in\");\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (errMsg.includes(\"still loading\")) {\n\t\t\t\tif (attempt < retryCount - 1) {\n\t\t\t\t\tconst delay = Math.min(500 * (attempt + 1), 2e3);\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (attempt < retryCount - 1) {\n\t\t\t\tconst delay = Math.min(1e3 * (attempt + 1), 3e3);\n\t\t\t\tconsole.debug(`WebSocket auth attempt ${attempt + 1} failed, retrying in ${delay}ms...`);\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\t\t}\n\t\t}\n\t\tconsole.warn(\"WebSocket on-demand auth failed after retries:\", lastError);\n\t\tthrow lastError;\n\t}\n\tasync reauthenticate() {\n\t\tif (!this.getAuthToken) return;\n\t\tthis.isAuthenticated = false;\n\t\ttry {\n\t\t\tconst token = await this.getAuthToken();\n\t\t\tif (!token) throw new Error(\"user not logged in\");\n\t\t\tawait this.authenticate(token);\n\t\t\tconsole.debug(\"WebSocket reauthenticated successfully\");\n\t\t} catch (error) {\n\t\t\tconsole.error(\"WebSocket reauthentication failed:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\tsendMessage(message) {\n\t\tconst queuedMsg = message;\n\t\tif (queuedMsg._queuedResolve && queuedMsg._queuedReject) return this.doSendMessage(message, queuedMsg._queuedResolve, queuedMsg._queuedReject);\n\t\tif (!this.isConnected || !this.ws) return new Promise((resolve, reject) => {\n\t\t\tconst queueable = message;\n\t\t\tqueueable._queuedResolve = resolve;\n\t\t\tqueueable._queuedReject = reject;\n\t\t\tthis.messageQueue.push(message);\n\t\t});\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.doSendMessage(message, resolve, reject);\n\t\t});\n\t}\n\tasync doSendMessage(message, resolve, reject) {\n\t\tif (message.type !== \"AUTHENTICATE\" && this.getAuthToken && !this.isAuthenticated) try {\n\t\t\tawait this.ensureAuthenticated();\n\t\t} catch (error) {\n\t\t\treject(new RebaseApiError$1(error instanceof Error ? error.message : \"Authentication required\"));\n\t\t\treturn;\n\t\t}\n\t\tconst requestId = message.requestId || `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\t\tmessage.requestId = requestId;\n\t\tconst expectsResponse = ![\n\t\t\t\"subscribe_collection\",\n\t\t\t\"subscribe_one\",\n\t\t\t\"unsubscribe\",\n\t\t\t\"join_channel\",\n\t\t\t\"leave_channel\",\n\t\t\t\"broadcast\",\n\t\t\t\"presence_track\",\n\t\t\t\"presence_untrack\",\n\t\t\t\"presence_state\"\n\t\t].includes(message.type);\n\t\tif (expectsResponse && !this.pendingRequests.has(requestId)) {\n\t\t\tconst timeoutHandle = setTimeout(() => {\n\t\t\t\tif (this.pendingRequests.has(requestId)) {\n\t\t\t\t\tthis.pendingRequests.delete(requestId);\n\t\t\t\t\treject(new RebaseApiError$1(\"Request timed out\"));\n\t\t\t\t}\n\t\t\t}, this.requestTimeoutMs);\n\t\t\tthis.pendingRequests.set(requestId, {\n\t\t\t\tresolve: (value) => {\n\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timeoutHandle);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t\tmessage\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tthis.ws.send(JSON.stringify(message));\n\t\t\tif (!expectsResponse) resolve(void 0);\n\t\t} catch (error) {\n\t\t\tif (expectsResponse) this.pendingRequests.delete(requestId);\n\t\t\treject(new RebaseApiError$1(\"Failed to send message\", { cause: error }));\n\t\t}\n\t}\n\tasync fetchCollection(props) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"FETCH_COLLECTION\",\n\t\t\tpayload: props\n\t\t})).rows || [];\n\t}\n\tasync fetchOne(props) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"FETCH_ONE\",\n\t\t\tpayload: props\n\t\t})).row ?? void 0;\n\t}\n\tasync save(props) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"SAVE\",\n\t\t\tpayload: props\n\t\t})).row;\n\t}\n\tasync delete(props) {\n\t\tawait this.sendMessage({\n\t\t\ttype: \"DELETE\",\n\t\t\tpayload: props\n\t\t});\n\t}\n\tasync executeSql(sql, options) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"EXECUTE_SQL\",\n\t\t\tpayload: {\n\t\t\t\tsql,\n\t\t\t\toptions\n\t\t\t}\n\t\t})).result || [];\n\t}\n\tasync fetchAvailableDatabases() {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"FETCH_DATABASES\",\n\t\t\tpayload: {}\n\t\t})).databases || [];\n\t}\n\tasync fetchAvailableRoles() {\n\t\treturn (await this.sendMessage({ type: \"FETCH_ROLES\" })).roles || [];\n\t}\n\tasync fetchCurrentDatabase() {\n\t\treturn (await this.sendMessage({ type: \"FETCH_CURRENT_DATABASE\" })).database;\n\t}\n\tasync checkUniqueField(path, name, value, id, collection) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"CHECK_UNIQUE_FIELD\",\n\t\t\tpayload: {\n\t\t\t\tpath,\n\t\t\t\tname,\n\t\t\t\tvalue,\n\t\t\t\tid,\n\t\t\t\tcollection\n\t\t\t}\n\t\t})).isUnique;\n\t}\n\tasync count(props) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"COUNT\",\n\t\t\tpayload: props\n\t\t})).count;\n\t}\n\tasync fetchUnmappedTables(mappedPaths) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"FETCH_UNMAPPED_TABLES\",\n\t\t\tpayload: { mappedPaths }\n\t\t})).tables || [];\n\t}\n\tasync fetchTableMetadata(tableName) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"FETCH_TABLE_METADATA\",\n\t\t\tpayload: { tableName }\n\t\t})).metadata || {\n\t\t\tcolumns: [],\n\t\t\tforeignKeys: [],\n\t\t\tjunctions: [],\n\t\t\tpolicies: []\n\t\t};\n\t}\n\tasync createBranch(name, options) {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"CREATE_BRANCH\",\n\t\t\tpayload: {\n\t\t\t\tname,\n\t\t\t\toptions\n\t\t\t}\n\t\t})).branch;\n\t}\n\tasync deleteBranch(name) {\n\t\tawait this.sendMessage({\n\t\t\ttype: \"DELETE_BRANCH\",\n\t\t\tpayload: { name }\n\t\t});\n\t}\n\tasync listBranches() {\n\t\treturn (await this.sendMessage({\n\t\t\ttype: \"LIST_BRANCHES\",\n\t\t\tpayload: {}\n\t\t})).branches || [];\n\t}\n\t/**\n\t* Recursively compare two values for structural equality.\n\t* Handles primitives, null, undefined, Date, RegExp, arrays, and plain objects.\n\t*/\n\tdeepEqual(a, b) {\n\t\tif (a === b) return true;\n\t\tif (a === null || b === null || a === void 0 || b === void 0) return false;\n\t\tif (typeof a !== typeof b) return false;\n\t\tif (typeof a !== \"object\") return false;\n\t\tif (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n\t\tif (a instanceof Date || b instanceof Date) return false;\n\t\tif (a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;\n\t\tif (a instanceof RegExp || b instanceof RegExp) return false;\n\t\tconst aIsArray = Array.isArray(a);\n\t\tconst bIsArray = Array.isArray(b);\n\t\tif (aIsArray !== bIsArray) return false;\n\t\tif (aIsArray && bIsArray) {\n\t\t\tif (a.length !== b.length) return false;\n\t\t\tfor (let i = 0; i < a.length; i++) if (!this.deepEqual(a[i], b[i])) return false;\n\t\t\treturn true;\n\t\t}\n\t\tconst aObj = a;\n\t\tconst bObj = b;\n\t\tconst aKeys = Object.keys(aObj);\n\t\tconst bKeys = Object.keys(bObj);\n\t\tif (aKeys.length !== bKeys.length) return false;\n\t\tfor (const key of aKeys) {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(bObj, key)) return false;\n\t\t\tif (!this.deepEqual(aObj[key], bObj[key])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tnormalizeForComparison(val) {\n\t\tif (!val) return val;\n\t\tif (Array.isArray(val)) return val.map((item) => this.normalizeForComparison(item));\n\t\tif (typeof val === \"object\") {\n\t\t\tif (val instanceof Date) return val;\n\t\t\tif (val instanceof RegExp) return val;\n\t\t\tconst obj = val;\n\t\t\tif (obj.__type === \"relation\") {\n\t\t\t\tconst { data, ...rest } = obj;\n\t\t\t\treturn rest;\n\t\t\t}\n\t\t\tconst result = {};\n\t\t\tfor (const [k, v] of Object.entries(obj)) result[k] = this.normalizeForComparison(v);\n\t\t\treturn result;\n\t\t}\n\t\treturn val;\n\t}\n\t/**\n\t* Merge incoming rows with cached data, preserving cached references\n\t* for rows whose values haven't changed. This avoids unnecessary\n\t* React re-renders when the server refetches all rows but most\n\t* haven't actually changed.\n\t*/\n\tmergeRows(cached, incoming) {\n\t\tif (!cached || cached.length === 0) return incoming;\n\t\tconst cachedById = /* @__PURE__ */ new Map();\n\t\tfor (const row of cached) cachedById.set(row.id, row);\n\t\treturn incoming.map((incomingRow) => {\n\t\t\tconst cachedRow = cachedById.get(incomingRow.id);\n\t\t\tif (!cachedRow) return incomingRow;\n\t\t\tconst normCached = this.normalizeForComparison(cachedRow);\n\t\t\tconst normIncoming = this.normalizeForComparison(incomingRow);\n\t\t\tif (this.deepEqual(normCached, normIncoming)) return cachedRow;\n\t\t\telse {\n\t\t\t\tconst mismatches = {};\n\t\t\t\tconst allKeys = new Set([...Object.keys(normCached), ...Object.keys(normIncoming)]);\n\t\t\t\tfor (const key of allKeys) if (!this.deepEqual(normCached[key], normIncoming[key])) mismatches[key] = {\n\t\t\t\t\tcached: normCached[key],\n\t\t\t\t\tincoming: normIncoming[key]\n\t\t\t\t};\n\t\t\t\tconsole.debug(`[RebaseWS] Row ${incomingRow.id} refetch mismatch:\\n`, JSON.stringify(mismatches, null, 2));\n\t\t\t}\n\t\t\treturn incomingRow;\n\t\t});\n\t}\n\tlistenCollection(props, onUpdate, onError) {\n\t\tconst subscriptionKey = this.createCollectionSubscriptionKey(props);\n\t\tconst callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\t\tconst existingSubscription = this.collectionSubscriptions.get(subscriptionKey);\n\t\tif (existingSubscription) {\n\t\t\tconst callbackMap = existingSubscription.callbacks;\n\t\t\tcallbackMap.set(callbackId, {\n\t\t\t\tonUpdate,\n\t\t\t\tonError\n\t\t\t});\n\t\t\tif (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) try {\n\t\t\t\tonUpdate(existingSubscription.latestData);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Error in collection subscription callback:\", error);\n\t\t\t\tif (onError) onError(error instanceof Error ? error : new Error(String(error)));\n\t\t\t}\n\t\t\treturn () => {\n\t\t\t\tcallbackMap.delete(callbackId);\n\t\t\t\tif (callbackMap.size === 0) {\n\t\t\t\t\tthis.collectionSubscriptions.delete(subscriptionKey);\n\t\t\t\t\tthis.backendToCollectionKey.delete(existingSubscription.backendSubscriptionId);\n\t\t\t\t\tif (this.isConnected && this.ws) this.sendMessage({\n\t\t\t\t\t\ttype: \"unsubscribe\",\n\t\t\t\t\t\tpayload: { subscriptionId: existingSubscription.backendSubscriptionId }\n\t\t\t\t\t}).catch(console.error);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tconst backendSubscriptionId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\t\tconst callbackMap = /* @__PURE__ */ new Map();\n\t\tcallbackMap.set(callbackId, {\n\t\t\tonUpdate,\n\t\t\tonError\n\t\t});\n\t\tthis.collectionSubscriptions.set(subscriptionKey, {\n\t\t\tbackendSubscriptionId,\n\t\t\tcallbacks: callbackMap,\n\t\t\tprops\n\t\t});\n\t\tthis.backendToCollectionKey.set(backendSubscriptionId, subscriptionKey);\n\t\tthis.sendMessage({\n\t\t\ttype: \"subscribe_collection\",\n\t\t\tpayload: {\n\t\t\t\t...props,\n\t\t\t\tsubscriptionId: backendSubscriptionId\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tif (onError) onError(error);\n\t\t});\n\t\treturn () => {\n\t\t\tconst subscription = this.collectionSubscriptions.get(subscriptionKey);\n\t\t\tif (subscription) {\n\t\t\t\tconst callbacks = subscription.callbacks;\n\t\t\t\tcallbacks.delete(callbackId);\n\t\t\t\tif (callbacks.size === 0) {\n\t\t\t\t\tthis.collectionSubscriptions.delete(subscriptionKey);\n\t\t\t\t\tthis.backendToCollectionKey.delete(subscription.backendSubscriptionId);\n\t\t\t\t\tif (this.isConnected && this.ws) this.sendMessage({\n\t\t\t\t\t\ttype: \"unsubscribe\",\n\t\t\t\t\t\tpayload: { subscriptionId: subscription.backendSubscriptionId }\n\t\t\t\t\t}).catch(console.error);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\tlistenOne(props, onUpdate, onError) {\n\t\tconst subscriptionKey = this.createSingleSubscriptionKey(props);\n\t\tconst callbackId = `callback_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\t\tconst existingSubscription = this.singleSubscriptions.get(subscriptionKey);\n\t\tif (existingSubscription) {\n\t\t\tconst callbackMap = existingSubscription.callbacks;\n\t\t\tcallbackMap.set(callbackId, {\n\t\t\t\tonUpdate,\n\t\t\t\tonError\n\t\t\t});\n\t\t\tif (existingSubscription.latestData !== void 0 && existingSubscription.isInitialDataReceived) try {\n\t\t\t\tonUpdate(existingSubscription.latestData);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Error in row subscription callback:\", error);\n\t\t\t\tif (onError) onError(error instanceof Error ? error : new Error(String(error)));\n\t\t\t}\n\t\t\treturn () => {\n\t\t\t\tcallbackMap.delete(callbackId);\n\t\t\t\tif (callbackMap.size === 0) {\n\t\t\t\t\tthis.singleSubscriptions.delete(subscriptionKey);\n\t\t\t\t\tthis.backendToEntityKey.delete(existingSubscription.backendSubscriptionId);\n\t\t\t\t\tif (this.isConnected && this.ws) this.sendMessage({\n\t\t\t\t\t\ttype: \"unsubscribe\",\n\t\t\t\t\t\tpayload: { subscriptionId: existingSubscription.backendSubscriptionId }\n\t\t\t\t\t}).catch(console.error);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tconst backendSubscriptionId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\t\tconst callbackMap = /* @__PURE__ */ new Map();\n\t\tcallbackMap.set(callbackId, {\n\t\t\tonUpdate,\n\t\t\tonError\n\t\t});\n\t\tthis.singleSubscriptions.set(subscriptionKey, {\n\t\t\tbackendSubscriptionId,\n\t\t\tcallbacks: callbackMap,\n\t\t\tprops\n\t\t});\n\t\tthis.backendToEntityKey.set(backendSubscriptionId, subscriptionKey);\n\t\tthis.sendMessage({\n\t\t\ttype: \"subscribe_one\",\n\t\t\tpayload: {\n\t\t\t\t...props,\n\t\t\t\tsubscriptionId: backendSubscriptionId\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tif (onError) onError(error);\n\t\t});\n\t\treturn () => {\n\t\t\tconst subscription = this.singleSubscriptions.get(subscriptionKey);\n\t\t\tif (subscription) {\n\t\t\t\tconst callbacks = subscription.callbacks;\n\t\t\t\tcallbacks.delete(callbackId);\n\t\t\t\tif (callbacks.size === 0) {\n\t\t\t\t\tthis.singleSubscriptions.delete(subscriptionKey);\n\t\t\t\t\tthis.backendToEntityKey.delete(subscription.backendSubscriptionId);\n\t\t\t\t\tif (this.isConnected && this.ws) this.sendMessage({\n\t\t\t\t\t\ttype: \"unsubscribe\",\n\t\t\t\t\t\tpayload: { subscriptionId: subscription.backendSubscriptionId }\n\t\t\t\t\t}).catch(console.error);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Re-send all active subscriptions to the backend after a reconnect.\n\t* The server wipes subscription state when a client disconnects, so\n\t* we need to re-register everything to resume receiving updates.\n\t*/\n\tresubscribeAll() {\n\t\tconsole.debug(`[WS] Re-subscribing: ${this.collectionSubscriptions.size} collection(s), ${this.singleSubscriptions.size} row(ies)`);\n\t\tfor (const [key, sub] of this.collectionSubscriptions.entries()) {\n\t\t\tconst oldBackendId = sub.backendSubscriptionId;\n\t\t\tconst newBackendId = `collection_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\t\t\tsub.backendSubscriptionId = newBackendId;\n\t\t\tthis.backendToCollectionKey.delete(oldBackendId);\n\t\t\tthis.backendToCollectionKey.set(newBackendId, key);\n\t\t\tthis.sendMessage({\n\t\t\t\ttype: \"subscribe_collection\",\n\t\t\t\tpayload: {\n\t\t\t\t\t...sub.props,\n\t\t\t\t\tsubscriptionId: newBackendId\n\t\t\t\t}\n\t\t\t}).catch((error) => {\n\t\t\t\tconsole.error(\"[WS] Failed to re-subscribe collection:\", key, error);\n\t\t\t});\n\t\t}\n\t\tfor (const [key, sub] of this.singleSubscriptions.entries()) {\n\t\t\tconst oldBackendId = sub.backendSubscriptionId;\n\t\t\tconst newBackendId = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n\t\t\tsub.backendSubscriptionId = newBackendId;\n\t\t\tthis.backendToEntityKey.delete(oldBackendId);\n\t\t\tthis.backendToEntityKey.set(newBackendId, key);\n\t\t\tthis.sendMessage({\n\t\t\t\ttype: \"subscribe_one\",\n\t\t\t\tpayload: {\n\t\t\t\t\t...sub.props,\n\t\t\t\t\tsubscriptionId: newBackendId\n\t\t\t\t}\n\t\t\t}).catch((error) => {\n\t\t\t\tconsole.error(\"[WS] Failed to re-subscribe row:\", key, error);\n\t\t\t});\n\t\t}\n\t}\n\tcreateCollectionSubscriptionKey(props) {\n\t\tconst key = {\n\t\t\tpath: props.path,\n\t\t\tfilter: props.filter,\n\t\t\tlimit: props.limit,\n\t\t\tstartAfter: props.startAfter,\n\t\t\torderBy: props.orderBy,\n\t\t\torder: props.order,\n\t\t\tsearchString: props.searchString,\n\t\t\tcollection: props.collection?.name\n\t\t};\n\t\treturn JSON.stringify(key, (_, value) => {\n\t\t\tif (value && typeof value === \"object\" && !Array.isArray(value)) return Object.keys(value).sort().reduce((sorted, k) => {\n\t\t\t\tsorted[k] = value[k];\n\t\t\t\treturn sorted;\n\t\t\t}, {});\n\t\t\treturn value;\n\t\t});\n\t}\n\tcreateSingleSubscriptionKey(props) {\n\t\treturn `${props.path}|${props.id}`;\n\t}\n};\n//#endregion\n//#region src/index.ts\n/**\n* Derive a WebSocket URL from an HTTP base URL.\n* `http://` → `ws://`, `https://` → `wss://`.\n*/\nfunction deriveWebSocketUrl(baseUrl) {\n\tif (typeof window !== \"undefined\") {\n\t\tlet absoluteUrl = \"\";\n\t\tif (!baseUrl) absoluteUrl = window.location.origin;\n\t\telse if (/^https?:\\/\\//i.test(baseUrl) || /^wss?:\\/\\//i.test(baseUrl)) absoluteUrl = baseUrl;\n\t\telse try {\n\t\t\tabsoluteUrl = new URL(baseUrl, window.location.href).origin;\n\t\t} catch {\n\t\t\tabsoluteUrl = window.location.origin;\n\t\t}\n\t\tconst protocol = absoluteUrl.startsWith(\"https:\") || absoluteUrl.startsWith(\"wss:\") ? \"wss:\" : \"ws:\";\n\t\treturn absoluteUrl.replace(/^https?:\\/\\//i, `${protocol}//`).replace(/^wss?:\\/\\//i, `${protocol}//`).replace(/\\/$/, \"\");\n\t}\n\tif (!baseUrl) return \"\";\n\tif (!/^https?:\\/\\//i.test(baseUrl) && !/^wss?:\\/\\//i.test(baseUrl)) return \"\";\n\treturn baseUrl.replace(/^https?:\\/\\//i, (match) => match.toLowerCase() === \"https://\" ? \"wss://\" : \"ws://\").replace(/\\/$/, \"\");\n}\nfunction createRebaseClient(options) {\n\tconst transport = createTransport(options);\n\tconst auth = createAuth(transport, options.auth);\n\tconst admin = createAdmin(transport, options.admin);\n\tconst cron = createCron(transport, options.cron);\n\tconst apiKeys = createApiKeys(transport, options.apiKeys);\n\tconst storage = createStorage(transport);\n\tconst functions = createFunctionsClient(transport);\n\tconst createStorageSource = (storageId) => storageId === DEFAULT_STORAGE_SOURCE_KEY ? storage : createStorage(transport, storageId);\n\tconst storageRegistry = new ClientStorageSourceRegistry();\n\tstorageRegistry.register(DEFAULT_STORAGE_SOURCE_KEY, storage);\n\tfor (const def of options.storageSources ?? []) if (def.transport === \"server\" && def.key !== DEFAULT_STORAGE_SOURCE_KEY) storageRegistry.register(def.key, createStorageSource(def.key));\n\tlet storageSourcesPromise;\n\tconst fetchStorageSources = () => {\n\t\tif (storageSourcesPromise) return storageSourcesPromise;\n\t\tstorageSourcesPromise = transport.request(\"/storage/sources\").then((res) => {\n\t\t\tconst defs = res.data ?? [];\n\t\t\tfor (const def of defs) if (def.transport === \"server\" && def.key !== DEFAULT_STORAGE_SOURCE_KEY && !storageRegistry.has(def.key)) storageRegistry.register(def.key, createStorageSource(def.key));\n\t\t\treturn defs;\n\t\t}).catch((e) => {\n\t\t\tstorageSourcesPromise = void 0;\n\t\t\tthrow e;\n\t\t});\n\t\treturn storageSourcesPromise;\n\t};\n\tconst resolvedWsUrl = options.websocketUrl ?? deriveWebSocketUrl(options.baseUrl);\n\tlet ws;\n\tif (resolvedWsUrl) {\n\t\tws = new RebaseWebSocketClient({\n\t\t\twebsocketUrl: resolvedWsUrl,\n\t\t\tgetAuthToken: async () => {\n\t\t\t\tlet session = auth.getSession();\n\t\t\t\tif (session && session.expiresAt <= Date.now() + 1e4) try {\n\t\t\t\t\tsession = await auth.refreshSession();\n\t\t\t\t} catch (e) {}\n\t\t\t\treturn session?.accessToken || options.token || \"\";\n\t\t\t},\n\t\t\tonUnauthorized: options.onUnauthorized || (async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait auth.refreshSession();\n\t\t\t\t\treturn true;\n\t\t\t\t} catch (e) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t})\n\t\t});\n\t\tauth.onAuthStateChange((event, session) => {\n\t\t\tif (!ws) return;\n\t\t\tif (event === \"SIGNED_OUT\") ws.disconnect();\n\t\t\telse if (event === \"SIGNED_IN\" || event === \"TOKEN_REFRESHED\") {\n\t\t\t\tif (session?.accessToken) ws.authenticate(session.accessToken).catch(console.warn);\n\t\t\t}\n\t\t});\n\t}\n\tif (!options.onUnauthorized) transport.setOnUnauthorized(async () => {\n\t\ttry {\n\t\t\tawait auth.refreshSession();\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\treturn false;\n\t\t}\n\t});\n\t/**\n\t* Suggest the closest known collection key for a mistyped accessor.\n\t* Uses edit-distance-1 and prefix matching — no external dependency.\n\t*/\n\tfunction suggestCollection(prop, knownKeys) {\n\t\tconst prefixMatch = knownKeys.find((k) => k.startsWith(prop) || prop.startsWith(k));\n\t\tif (prefixMatch) return prefixMatch;\n\t\tfor (const key of knownKeys) {\n\t\t\tif (Math.abs(key.length - prop.length) > 1) continue;\n\t\t\tlet diffs = 0;\n\t\t\tconst longer = key.length >= prop.length ? key : prop;\n\t\t\tconst shorter = key.length >= prop.length ? prop : key;\n\t\t\tif (longer.length === shorter.length) for (let i = 0; i < longer.length; i++) {\n\t\t\t\tif (longer[i] !== shorter[i]) {\n\t\t\t\t\tif (i + 1 < longer.length && longer[i] === shorter[i + 1] && longer[i + 1] === shorter[i]) {\n\t\t\t\t\t\tdiffs++;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t\tif (diffs > 1) break;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tdiffs++;\n\t\t\t\t}\n\t\t\t\tif (diffs > 1) break;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlet li = 0;\n\t\t\t\tlet si = 0;\n\t\t\t\twhile (li < longer.length) {\n\t\t\t\t\tif (si < shorter.length && longer[li] === shorter[si]) si++;\n\t\t\t\t\telse diffs++;\n\t\t\t\t\tli++;\n\t\t\t\t\tif (diffs > 1) break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (diffs <= 1) return key;\n\t\t}\n\t}\n\tconst collectionClients = /* @__PURE__ */ new Map();\n\tlet untypedWarned = false;\n\tfunction collection(slug) {\n\t\tif (!collectionClients.has(slug)) collectionClients.set(slug, createCollectionClient(transport, slug, ws));\n\t\treturn collectionClients.get(slug);\n\t}\n\tconst dataProxy = new Proxy({ collection }, { get(_target, prop) {\n\t\tif (prop === \"collection\") return collection;\n\t\tif (typeof prop === \"symbol\") return void 0;\n\t\tif (typeof prop === \"string\" && prop !== \"then\" && prop !== \"toJSON\" && prop !== \"$$typeof\") {\n\t\t\tif (options.collections) {\n\t\t\t\tif (prop in options.collections) return collection(options.collections[prop]);\n\t\t\t\tconst knownKeys = Object.keys(options.collections);\n\t\t\t\tconst suggestion = suggestCollection(prop, knownKeys);\n\t\t\t\tlet msg = `Unknown collection accessor \"${prop}\". Known collections: ${knownKeys.join(\", \")}.`;\n\t\t\t\tif (suggestion) msg += ` Did you mean \"${suggestion}\"?`;\n\t\t\t\tmsg += ` Use data.collection(\"<slug>\") for dynamic slugs.`;\n\t\t\t\tthrow new RebaseClientError(msg);\n\t\t\t}\n\t\t\tif (!untypedWarned) {\n\t\t\t\tuntypedWarned = true;\n\t\t\t\tconsole.warn(`[Rebase] Untyped data access detected (client.data.${prop}). Collection names are resolved via snake_case conversion, which may cause silent 404s at request time. Pass a \\`collections\\` dictionary to createRebaseClient() or use the generated SDK for type-safe access.`);\n\t\t\t}\n\t\t\treturn collection(toSnakeCase(prop));\n\t\t}\n\t} });\n\treturn {\n\t\tauth,\n\t\tadmin,\n\t\tcron,\n\t\tapiKeys,\n\t\tfunctions,\n\t\tstorage,\n\t\tstorageRegistry,\n\t\tcreateStorageSource,\n\t\tfetchStorageSources,\n\t\tws,\n\t\tsetToken: transport.setToken,\n\t\tsetAuthTokenGetter: transport.setAuthTokenGetter,\n\t\tsetOnUnauthorized: transport.setOnUnauthorized,\n\t\tresolveToken: transport.resolveToken,\n\t\tbaseUrl: transport.baseUrl,\n\t\tcollection,\n\t\tcall: async (endpoint, payload) => {\n\t\t\tconst prefix = endpoint.startsWith(\"/\") ? \"\" : \"/\";\n\t\t\tconst res = await transport.request(`${prefix}${endpoint}`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: payload ? JSON.stringify(payload) : void 0\n\t\t\t});\n\t\t\treturn res.data ?? res;\n\t\t},\n\t\tdata: dataProxy\n\t};\n}\n//#endregion\nexport { QueryBuilder, RebaseApiError, RebaseClientError, RebaseWebSocketClient, and, cond, createCookieStorage, createMemoryStorage, createRebaseClient, or };\n\n//# sourceMappingURL=index.es.js.map","import { Hono } from \"hono\";\nimport { HonoEnv } from \"../api/types\";\nimport { BackendCollectionRegistry } from \"../collections/BackendCollectionRegistry\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { DataDriver } from \"@rebasepro/types\";\n/**\n * Create Hono routes for entity history.\n * Mounted at `{basePath}/data/:slug/:id/history`.\n */\nexport interface HistoryService {\n fetchHistory(tableName: string, id: string, options: { limit: number, offset: number }): Promise<{ data: Record<string, unknown>[], total: number }>;\n fetchHistoryEntry(historyId: string): Promise<Record<string, unknown> | null>;\n}\n\nexport function createHistoryRoutes(params: {\n historyService: HistoryService;\n registry: BackendCollectionRegistry;\n driver: DataDriver;\n}): Hono<HonoEnv> {\n const { historyService, registry, driver } = params;\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n /**\n * GET /:slug/:id/history - List history entries for a entity\n *\n * Query params:\n * limit (default 20)\n * offset (default 0)\n */\n router.get(\"/:slug/:id/history\", async (c) => {\n const slug = c.req.param(\"slug\");\n const id = c.req.param(\"id\");\n const parsedLimit = parseInt(c.req.query(\"limit\") ?? \"20\", 10);\n const parsedOffset = parseInt(c.req.query(\"offset\") ?? \"0\", 10);\n const limit = Number.isNaN(parsedLimit) ? 20 : parsedLimit;\n const offset = Number.isNaN(parsedOffset) ? 0 : parsedOffset;\n\n // Resolve the collection to get the actual table name\n const collection = registry.getCollections().find(\n col => col.slug === slug || false\n );\n\n if (!collection) {\n throw ApiError.notFound(`Collection '${slug}' not found`);\n }\n\n if (!collection.history) {\n throw ApiError.badRequest(`History is not enabled for collection '${slug}'`);\n }\n\n const tableName = collection.slug;\n\n const result = await historyService.fetchHistory(tableName, id, {\n limit: Math.min(limit, 100),\n offset: Math.max(offset, 0)\n });\n\n return c.json({\n data: result.data,\n meta: {\n total: result.total,\n limit,\n offset,\n hasMore: offset + result.data.length < result.total\n }\n });\n });\n\n /**\n * POST /:slug/:id/history/:historyId/revert - Revert entity to a historical version\n *\n * This goes through the normal save path, so it creates its own history entry.\n */\n router.post(\"/:slug/:id/history/:historyId/revert\", async (c) => {\n const slug = c.req.param(\"slug\");\n const id = c.req.param(\"id\");\n const historyId = c.req.param(\"historyId\");\n\n const collection = registry.getCollections().find(\n col => col.slug === slug || false\n );\n\n if (!collection) {\n throw ApiError.notFound(`Collection '${slug}' not found`);\n }\n\n if (!collection.history) {\n throw ApiError.badRequest(`History is not enabled for collection '${slug}'`);\n }\n\n // Fetch the history entry\n const historyEntry = await historyService.fetchHistoryEntry(historyId);\n\n if (!historyEntry) {\n throw ApiError.notFound(`History entry '${historyId}' not found`);\n }\n\n // Verify the history entry belongs to this entity (prevent cross-entity revert)\n const tableName = collection.slug;\n if (historyEntry.entity_id !== String(id) || historyEntry.table_name !== tableName) {\n throw ApiError.badRequest(\"History entry does not belong to this entity\");\n }\n\n if (!historyEntry.values) {\n throw ApiError.badRequest(\"Cannot revert: history entry has no stored values\");\n }\n\n // Revert by saving through the normal driver path — this will\n // itself create another history entry, giving a full audit trail.\n const authDriver = c.get(\"driver\") || driver;\n const path = collection.slug;\n\n const savedEntity = await authDriver.save({\n path,\n id: String(id),\n values: historyEntry.values,\n collection,\n status: \"existing\"\n });\n\n return c.json({\n data: savedEntity,\n meta: { reverted_from: historyId }\n });\n });\n\n return router;\n}\n","import type { Transporter } from \"nodemailer\";\nimport { EmailConfig, EmailSendOptions, EmailService } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\nlet _nodemailer: typeof import(\"nodemailer\") | undefined;\n\nasync function loadNodemailer() {\n if (!_nodemailer) {\n try {\n _nodemailer = await import(\"nodemailer\");\n } catch {\n throw new Error(\n \"nodemailer is required for SMTP email. \" +\n \"Install it: pnpm add nodemailer\"\n );\n }\n }\n return _nodemailer;\n}\n\n/**\n * Safely parse a hostname from a URL string\n */\nfunction getHostname(urlStr: string): string | undefined {\n try {\n const url = new URL(urlStr.includes(\"://\") ? urlStr : `https://${urlStr}`);\n return url.hostname;\n } catch {\n return undefined;\n }\n}\n\n/**\n * SMTP Email Service implementation using Nodemailer\n */\nexport class SMTPEmailService implements EmailService {\n private transporter: Transporter | null = null;\n private config: EmailConfig;\n private _initialized = false;\n\n constructor(config: EmailConfig) {\n this.config = config;\n }\n\n /**\n * Lazily initialize the SMTP transporter on first use\n */\n private async ensureTransporter(): Promise<void> {\n if (this._initialized) return;\n this._initialized = true;\n\n if (this.config.smtp) {\n const nodemailer = await loadNodemailer();\n\n let smtpName = this.config.smtp.name;\n if (!smtpName) {\n const urlsToTry = [\n process.env.FRONTEND_URL,\n this.config.resetPasswordUrl,\n this.config.verifyEmailUrl\n ];\n for (const urlStr of urlsToTry) {\n if (urlStr) {\n const hostname = getHostname(urlStr);\n if (hostname) {\n smtpName = hostname;\n break;\n }\n }\n }\n }\n\n this.transporter = nodemailer.createTransport({\n name: smtpName,\n host: this.config.smtp.host,\n port: this.config.smtp.port,\n secure: this.config.smtp.secure ?? (this.config.smtp.port === 465),\n auth: this.config.smtp.auth ? {\n user: this.config.smtp.auth.user,\n pass: this.config.smtp.auth.pass\n } : undefined\n });\n }\n }\n\n /**\n * Check if the email service is properly configured\n */\n isConfigured(): boolean {\n return !!(this.config.smtp || this.config.sendEmail);\n }\n\n /**\n * Send an email using SMTP or custom send function\n */\n async send(options: EmailSendOptions): Promise<void> {\n // Use custom send function if provided\n if (this.config.sendEmail) {\n await this.config.sendEmail(options);\n return;\n }\n\n // Use SMTP transporter\n await this.ensureTransporter();\n\n if (!this.transporter) {\n throw new Error(\"Email service not configured. Provide SMTP config or sendEmail function.\");\n }\n\n const to = Array.isArray(options.to) ? options.to.join(\", \") : options.to;\n\n try {\n await this.transporter.sendMail({\n from: this.config.from,\n to,\n subject: options.subject,\n html: options.html,\n text: options.text,\n replyTo: options.replyTo\n });\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(\"Failed to send email\", { detail: message });\n throw new Error(`Failed to send email: ${message}`);\n }\n }\n\n /**\n * Verify SMTP connection (useful for startup checks)\n */\n async verifyConnection(): Promise<boolean> {\n await this.ensureTransporter();\n\n if (!this.transporter) {\n return !!this.config.sendEmail;\n }\n\n try {\n await this.transporter.verify();\n return true;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(\"SMTP connection verification failed\", { detail: message });\n return false;\n }\n }\n}\n\n/**\n * Create an email service from configuration\n */\nexport function createEmailService(config: EmailConfig): EmailService {\n return new SMTPEmailService(config);\n}\n","import type { RebaseServerClient } from \"@rebasepro/types\";\n\nlet _instance: RebaseServerClient | null = null;\n\n/**\n * @internal Called once during server initialization to set the backing instance.\n * This is invoked by `initializeRebaseBackend()` — never call it manually.\n */\nexport function _initRebase(client: RebaseServerClient): void {\n _instance = client;\n}\n\n/**\n * @internal Allows overriding the underlying instance for unit testing.\n * Throws an error if used in a non-test environment to prevent production abuse.\n */\nexport function _setRebaseMock(mockInstance: Partial<RebaseServerClient>): void {\n if (process.env.NODE_ENV !== \"test\") {\n throw new Error(\"_setRebaseMock can only be called in a test environment (NODE_ENV=test).\");\n }\n _instance = { ...(_instance || {} as RebaseServerClient),\n...mockInstance } as RebaseServerClient;\n}\n\n/**\n * @internal Resets the singleton instance, useful for afterEach() in test suites.\n */\nexport function _resetRebaseMock(): void {\n if (process.env.NODE_ENV !== \"test\") {\n throw new Error(\"_resetRebaseMock can only be called in a test environment.\");\n }\n _instance = null;\n}\n\n/**\n * The server-side Rebase singleton.\n *\n * Initialized automatically during server startup. Provides access to all\n * app-scoped services: **data**, **auth**, **storage**, and **email**.\n *\n * **Admin data plane** (`rebase.dataAsAdmin`):\n * Backed by the native DataDriver — calls go directly to the database without\n * JSON serialization, HTTP dispatch, or middleware overhead. The driver is\n * scoped as `{ uid: \"service\", roles: [\"admin\"] }`, so **every read and write\n * bypasses row-level-security policies**. No `REBASE_SERVICE_KEY` is required.\n *\n * ⚠️ Because it bypasses RLS, `rebase.dataAsAdmin` is for trusted background\n * work (cron jobs, migrations, service tasks) — **not** for serving user-facing\n * data. Inside a request handler, run user-scoped queries through the\n * request-scoped driver (`c.var.driver`), which carries the caller's identity\n * so RLS applies.\n *\n * `rebase.data` is a **deprecated alias** for `rebase.dataAsAdmin` — identical\n * admin scope at runtime. Prefer `dataAsAdmin` so the privilege is explicit.\n *\n * **Control plane** (`rebase.auth`, `rebase.admin`, `rebase.storage`, etc.):\n * Routes through the Hono app's internal request handler. An internal per-boot\n * credential is generated automatically when `REBASE_SERVICE_KEY` is not set,\n * so control-plane calls always authenticate.\n *\n * @example\n * ```typescript\n * import { rebase } from \"@rebasepro/server-core\";\n *\n * // In a cron job, hook, or trusted service file (admin scope, bypasses RLS):\n * await rebase.email.send({ to: \"admin@co.com\", subject: \"Alert\", html: \"<p>Hi</p>\" });\n * const jobs = await rebase.dataAsAdmin.jobs.find({ limit: 10 });\n * ```\n */\nexport const rebase: RebaseServerClient = new Proxy({} as RebaseServerClient, {\n get(_, prop) {\n if (!_instance) {\n throw new Error(\n `rebase.${String(prop)}: server not initialized yet. ` +\n \"The singleton is available after Rebase starts — don't call it at import time.\"\n );\n }\n return _instance[prop as keyof RebaseServerClient];\n },\n set(_, prop) {\n throw new Error(\n `Cannot set rebase.${String(prop)} directly. ` +\n \"The singleton is read-only. Use _initRebase() during server startup.\"\n );\n }\n});\n","import {\n AuthAdapter,\n BackendBootstrapper,\n BootstrappedAuth,\n DatabaseAdapter,\n DataDriver,\n DataSourceDefinition,\n CollectionCallbacks,\n CollectionConfig,\n HealthCheckResult,\n HistoryConfig,\n InitializedDriver,\n isPostgresCollectionConfig,\n isSQLAdmin,\n RealtimeProvider,\n SecurityRule\n} from \"@rebasepro/types\";\nimport { createDataSourceRegistry, resolveDataSource, buildSdkData, buildRoutedRebaseData } from \"@rebasepro/common\";\nimport { randomBytes } from \"node:crypto\";\nimport { BackendCollectionRegistry } from \"./collections/BackendCollectionRegistry\";\nimport { loadCollectionsFromDirectory } from \"./collections/loader\";\nimport { DEFAULT_DRIVER_ID, DefaultDriverRegistry, DriverRegistry } from \"./services/driver-registry\";\nimport { createRoutedRealtimeService } from \"./services/routed-realtime-service\";\nimport { Server } from \"http\";\n\nimport { RestApiGenerator } from \"./api/rest/api-generator\";\nimport { createAuthMiddleware } from \"./auth/middleware\";\nimport { createAdapterAuthMiddleware } from \"./auth/adapter-middleware\";\nimport { scopeDataDriver } from \"./auth/rls-scope\";\nimport { createBuiltinAuthAdapter } from \"./auth/builtin-auth-adapter\";\nimport { errorHandler } from \"./api/errors\";\nimport { Hono } from \"hono\";\nimport { bodyLimit } from \"hono/body-limit\";\nimport { HonoEnv } from \"./api/types\";\nimport { configureLogLevel } from \"./utils/logging\";\nimport { logger } from \"./utils/logger\";\nimport { configureMiddlewares } from \"./init/middlewares\";\nimport { initializeStorage } from \"./init/storage\";\nimport { mountOpenApiDocs } from \"./init/docs\";\nimport { createHealthCheck } from \"./init/health\";\nimport { createShutdown } from \"./init/shutdown\";\nimport { configureJwt, requireAdmin, requireAuth } from \"./auth\";\nimport {\n BackendStorageConfig,\n createStorageRoutes,\n StorageController,\n StorageRegistry\n} from \"./storage\";\nimport type { ApiKeyStore } from \"./auth/api-keys/api-key-store\";\nimport { createApiKeyStore } from \"./auth/api-keys/api-key-store\";\nimport { createApiKeyRoutes } from \"./auth/api-keys/api-key-routes\";\nimport { createApiKeyRateLimiter } from \"./auth/rate-limiter\";\nimport { createRebaseClient } from \"@rebasepro/client\";\n\nimport { createHistoryRoutes } from \"./history\";\nimport type { EmailService } from \"./email\";\nimport { createEmailService, EmailConfig } from \"./email\";\nimport type { OAuthProvider } from \"./auth/interfaces\";\nimport type { AuthHooks } from \"./auth/auth-hooks\";\nimport { _initRebase } from \"./singleton\";\n\nexport interface RebaseAuthConfig {\n /**\n * The collection that represents auth users.\n *\n * When provided, this collection's underlying database table is used\n * for all auth operations (login, registration, password reset, etc.).\n *\n * Import the built-in default:\n * ```ts\n * import { defaultUsersCollection } from \"@rebasepro/common\";\n * auth: { collection: defaultUsersCollection, jwtSecret: \"...\" }\n * ```\n *\n * Or pass your own collection with the required auth fields\n * (email, passwordHash, displayName, etc.).\n */\n collection?: CollectionConfig;\n jwtSecret?: string;\n accessExpiresIn?: string;\n refreshExpiresIn?: string;\n requireAuth?: boolean;\n allowRegistration?: boolean;\n /**\n * Opt-in: expose `POST /auth/find-user` so an authenticated user can resolve\n * an email address to a minimal public profile (`uid`, `displayName`,\n * `photoURL` only). This powers invite-by-email flows without a custom\n * admin server function. Off by default because it enables user enumeration\n * by any signed-in user. Available on the client as `auth.findUserByEmail`.\n */\n allowUserLookup?: boolean;\n /**\n * A static secret key for server-to-server / script authentication.\n *\n * When a request includes `Authorization: Bearer <serviceKey>`, it is\n * granted admin-level access without JWT verification. This is the\n * Rebase equivalent of a Service Account key.\n *\n * Generate with: `node -e \"logger.info(require('crypto').randomBytes(48).toString('base64'))\"`\n *\n * Set via `REBASE_SERVICE_KEY` in your `.env`.\n * Must be at least 32 characters.\n */\n serviceKey?: string;\n email?: EmailConfig;\n // ── Convenience shortcuts ─────────────────────────────────────────\n // Each named field below is syntactic sugar that internally resolves\n // to an `OAuthProvider` via the corresponding `create*Provider`\n // factory at startup. They are equivalent to constructing the\n // provider manually and passing it in the `providers` array.\n //\n // For providers not listed here, or for full control over the\n // provider configuration, use the `providers` array directly.\n google?: { clientId: string; clientSecret?: string };\n linkedin?: { clientId: string; clientSecret: string };\n github?: { clientId: string; clientSecret: string };\n microsoft?: { clientId: string; clientSecret: string; tenantId?: string };\n apple?: { clientId: string; teamId: string; keyId: string; privateKey: string };\n facebook?: { clientId: string; clientSecret: string };\n twitter?: { clientId: string; clientSecret: string };\n discord?: { clientId: string; clientSecret: string };\n gitlab?: { clientId: string; clientSecret: string; baseUrl?: string };\n bitbucket?: { clientId: string; clientSecret: string };\n slack?: { clientId: string; clientSecret: string };\n spotify?: { clientId: string; clientSecret: string };\n defaultRole?: string;\n /**\n * Canonical array of OAuth providers.\n *\n * This is the primary extension point for **all** OAuth integrations.\n * Each entry is an `OAuthProvider<unknown>` constructed via one of\n * the `create*Provider` factories exported from `@rebasepro/server-core`\n * (e.g. `createGoogleProvider`, `createGitHubProvider`).\n *\n * The named convenience fields above (`google`, `github`, etc.) are\n * automatically resolved into this array at startup. You can mix both\n * approaches; named fields and explicit entries are merged (named\n * fields are appended after explicit entries).\n *\n * @example\n * ```ts\n * import { createGoogleProvider } from \"@rebasepro/server-core\";\n *\n * auth: {\n * providers: [\n * createGoogleProvider({ clientId: \"…\", clientSecret: \"…\" }),\n * ],\n * }\n * ```\n */\n providers?: OAuthProvider<unknown>[];\n /**\n * Override specific parts of the built-in auth implementation.\n *\n * Each override replaces one piece of the default behavior while\n * keeping everything else intact. Unset overrides fall through\n * to the built-in defaults (scrypt passwords, standard validation, etc.).\n *\n * @example bcrypt passwords with a custom hash\n * ```ts\n * import bcrypt from \"bcrypt\";\n *\n * hooks: {\n * hashPassword: (pw) => bcrypt.hash(pw, 12),\n * verifyPassword: (pw, hash) => bcrypt.compare(pw, hash),\n * }\n * ```\n */\n hooks?: AuthHooks;\n\n /**\n * Enable magic link (passwordless email) authentication.\n * Requires email to be configured.\n */\n magicLink?: boolean;\n /**\n * Opt-in httpOnly cookie mode for refresh tokens.\n *\n * When set, the refresh token is delivered as an `httpOnly`, `Secure`,\n * `SameSite` cookie instead of in the JSON response body. This\n * prevents XSS from stealing the long-lived refresh token.\n *\n * The access token remains in the JSON body so the client can use it\n * in `Authorization: Bearer` headers for API calls.\n *\n * **Requires** `credentials: \"include\"` on client-side fetch calls to\n * auth endpoints, and CORS must allow credentials (no `origin: \"*\"`).\n */\n cookieAuth?: import(\"./auth\").CookieAuthConfig;\n}\n\nexport interface RebaseBackendConfig {\n collections?: CollectionConfig[];\n collectionsDir?: string;\n server: Server;\n app: Hono<HonoEnv>;\n basePath?: string;\n\n /**\n * Declared data sources, shared with the frontend `<Rebase dataSources>`.\n *\n * Used to resolve each collection's engine (capabilities) and transport.\n * Collections on a `direct`/`custom` transport are client-only: the backend\n * still owns their schema/registry but does **not** generate server data\n * routes for them. Server-mediated sources (the default) need no entry.\n */\n dataSources?: DataSourceDefinition[];\n\n /**\n * Database bootstrappers.\n */\n bootstrappers?: BackendBootstrapper[];\n /**\n * Database adapter.\n *\n * When set, this takes precedence over `bootstrappers`.\n *\n * @example\n * ```ts\n * import { createPostgresAdapter } from \"@rebasepro/server-postgresql\";\n * database: createPostgresAdapter({ connection: db, schema }),\n * ```\n */\n database?: DatabaseAdapter;\n\n logging?: {\n level?: \"error\" | \"warn\" | \"info\" | \"debug\";\n };\n\n /**\n * Authentication configuration.\n *\n * Accepts **either**:\n * - `RebaseAuthConfig` — built-in configuration\n * - `AuthAdapter` — pluggable adapter for external auth (Clerk, Auth0, etc.)\n *\n * When a plain config object is provided, the built-in adapter is created\n * automatically from the bootstrapper's `initializeAuth()` result.\n */\n auth?: RebaseAuthConfig | AuthAdapter;\n\n /**\n * Storage configuration. Accepts:\n *\n * - A `BackendStorageConfig` object (`{ type: 'local' | 's3' | 'gcs', ... }`)\n * - A `StorageController` instance (for custom providers like Azure, etc.)\n * - A `Record<string, ...>` of either, for multi-backend setups\n */\n storage?: BackendStorageConfig | StorageController | Record<string, BackendStorageConfig | StorageController>;\n\n /**\n * Declared storage sources. Drives the client-side StorageSourceRegistry\n * and the transport distinction (server vs direct).\n *\n * Server-backed sources are auto-derived from the `storage` map — you\n * only need explicit entries for \"direct\" transport sources (e.g.\n * external storage) that the backend does not proxy.\n */\n storageSources?: import(\"@rebasepro/types\").StorageSourceDefinition[];\n\n /**\n * Entity history / audit-log configuration.\n *\n * - `true` — enable history with default settings\n * - `{ retention?: number }` — enable with optional retention period (days)\n */\n history?: HistoryConfig;\n /**\n * Default security rules applied to any collection that does not define\n * its own `securityRules`. Opt-in — if not set, collections without\n * explicit rules remain unrestricted (beyond `requireAuth`).\n *\n * @example\n * ```ts\n * defaultSecurityRules: [\n * { operation: \"select\", access: \"public\" },\n * { operations: [\"insert\", \"update\", \"delete\"], roles: [\"admin\"] }\n * ]\n * ```\n */\n defaultSecurityRules?: SecurityRule[];\n enableSwagger?: boolean;\n functionsDir?: string;\n cronsDir?: string;\n /**\n * Enable/disable database persistence for cron job execution logs.\n * When set to false, cron jobs will run but logs will not be persisted to the database.\n * Default: true.\n */\n cronPersistence?: boolean;\n /**\n * Maximum request body size in bytes for API routes (default: 10MB).\n * Set to 0 to disable the global limit entirely.\n *\n * Note: Storage upload routes use their own limit from the storage config's\n * `maxFileSize` property (default: 50MB), which takes precedence over this.\n */\n maxBodySize?: number;\n /**\n * CSRF protection configuration. **Opt-in** — disabled by default.\n *\n * BaaS APIs are consumed by mobile apps, SPAs on different domains,\n * and CLI tools, so CSRF is intentionally not enabled unless you\n * explicitly configure it with allowed origins.\n *\n * @example\n * ```ts\n * csrf: { origin: [\"https://myapp.com\", \"https://admin.myapp.com\"] }\n * ```\n */\n csrf?: {\n /** Allowed origins for CSRF validation. */\n origin: string | string[] | ((origin: string) => boolean);\n };\n /**\n * Global lifecycle callbacks applied to every collection.\n *\n * Same type as per-collection `callbacks` — fires on **every** data path\n * (REST API, WebSocket / realtime, server-side `rebase.data`).\n *\n * Execution order: global callbacks → collection callbacks → property callbacks.\n *\n * @example\n * ```ts\n * callbacks: {\n * afterRead({ row, collection }) {\n * console.log(`Read ${collection.slug}/${row.id}`);\n * return row;\n * }\n * }\n * ```\n */\n callbacks?: CollectionCallbacks;\n}\n\n/**\n * Type guard to detect whether the `auth` config is an `AuthAdapter`\n * (has a `verifyRequest` method) vs a plain `RebaseAuthConfig` (plain object).\n */\nexport function isAuthAdapter(auth: RebaseAuthConfig | AuthAdapter): auth is AuthAdapter {\n return typeof auth === \"object\" && auth !== null && \"verifyRequest\" in auth && typeof (auth as AuthAdapter).verifyRequest === \"function\";\n}\n\n/**\n * Type guard to detect whether `database` is a `DatabaseAdapter`.\n */\nexport function isDatabaseAdapter(db: unknown): db is DatabaseAdapter {\n return typeof db === \"object\" && db !== null && \"initializeDriver\" in db && \"type\" in db && !(\"initializeAuth\" in db);\n}\n\n/**\n * Resolve the `requireAuth` flag from either a `RebaseAuthConfig` or an `AuthAdapter`.\n *\n * - `RebaseAuthConfig` has an explicit `requireAuth` boolean\n * - `AuthAdapter` always implies auth is required (secure by default)\n * - If no auth config is provided at all, default to `true`\n */\nfunction resolveRequireAuth(auth?: RebaseAuthConfig | AuthAdapter): boolean {\n if (!auth) return true;\n if (isAuthAdapter(auth)) return true; // AuthAdapters are always secure-by-default\n return (auth as RebaseAuthConfig).requireAuth !== false;\n}\n\nexport interface RebaseBackendInstance {\n driverRegistry: DriverRegistry;\n driver: DataDriver;\n realtimeServices: Record<string, RealtimeProvider>;\n realtimeService: RealtimeProvider;\n auth?: BootstrappedAuth;\n history?: { historyService: import(\"./history/history-routes\").HistoryService };\n storageRegistry?: StorageRegistry;\n storageController?: StorageController;\n collectionRegistry: BackendCollectionRegistry;\n cronScheduler?: import(\"./cron\").CronScheduler;\n\n /**\n * Deep health check that verifies database connectivity.\n * Returns latency and component status.\n */\n healthCheck(): Promise<HealthCheckResult>;\n\n /**\n * Graceful shutdown helper for the BaaS instance.\n * Stops the cron scheduler and closes the HTTP server, allowing\n * in-flight requests to drain within the given timeout.\n *\n * @param timeoutMs - Maximum time (ms) to wait for drain before force-exit (default: 15000).\n * Pass 0 to skip the force-exit timer (useful in tests).\n */\n shutdown(timeoutMs?: number): Promise<void>;\n}\n\nexport async function initializeRebaseBackend(config: RebaseBackendConfig): Promise<RebaseBackendInstance> {\n // No try/catch: let init errors propagate to the caller.\n // The app entry point (e.g. startServer()) should catch and process.exit(1).\n // Returning a fake instance hides critical failures and leads to silent data loss.\n return await _initializeRebaseBackend(config);\n}\n\nasync function _initializeRebaseBackend(config: RebaseBackendConfig): Promise<RebaseBackendInstance> {\n if (config.logging?.level) {\n configureLogLevel(config.logging.level);\n } else {\n configureLogLevel();\n }\n\n logger.info(\"Initializing Rebase Backend\");\n\n const basePath = config.basePath || \"/api\";\n const isProduction = process.env.NODE_ENV === \"production\";\n\n // Configure Hono middlewares (Request ID, body limit, CSRF, CORS warning, logging)\n configureMiddlewares(config.app, basePath, isProduction, config);\n\n const collectionRegistry = new BackendCollectionRegistry();\n // Declared data sources — drives engine resolution (capabilities) and the\n // server-vs-direct transport distinction. Set before collections register\n // so normalization can resolve each collection's engine.\n const dataSourceRegistry = createDataSourceRegistry(config.dataSources);\n collectionRegistry.setDataSources(dataSourceRegistry);\n\n // Global lifecycle callbacks — applied to every collection, on all data paths.\n if (config.callbacks) {\n collectionRegistry.setGlobalCallbacks(config.callbacks);\n }\n let activeCollections = config.collections || [];\n if (config.collectionsDir && activeCollections.length === 0) {\n activeCollections = await loadCollectionsFromDirectory(config.collectionsDir);\n logger.info(\"Auto-discovered collections\", {\n count: activeCollections.length,\n dir: config.collectionsDir\n });\n }\n\n // Apply default security rules to collections that don't define their own\n if (config.defaultSecurityRules?.length) {\n for (const collection of activeCollections) {\n if (isPostgresCollectionConfig(collection) && (!collection.securityRules || collection.securityRules.length === 0)) {\n collection.securityRules = config.defaultSecurityRules;\n }\n }\n logger.info(\"Default security rules applied to collections without explicit rules\");\n }\n\n const realtimeServices: Record<string, RealtimeProvider> = {};\n const delegates: Record<string, DataDriver> = {};\n\n // ─── Resolve bootstrappers ───────────────────────────────────────────\n let bootstrappers: BackendBootstrapper[] = config.bootstrappers || [];\n if (config.database) {\n const dbAdapter = config.database;\n logger.info(\"Using DatabaseAdapter\", { type: dbAdapter.type });\n const wrappedBootstrapper: BackendBootstrapper = {\n type: dbAdapter.type,\n initializeDriver: (initConfig: unknown) =>\n dbAdapter.initializeDriver(initConfig as import(\"@rebasepro/types\").DatabaseAdapterInitConfig),\n initializeRealtime: dbAdapter.initializeRealtime\n ? (_config: unknown, driverResult: InitializedDriver) =>\n dbAdapter.initializeRealtime!(driverResult)\n : undefined,\n initializeAuth: dbAdapter.initializeAuth,\n initializeHistory: dbAdapter.initializeHistory,\n initializeWebsockets: dbAdapter.initializeWebsockets,\n getAdmin: dbAdapter.getAdmin,\n mountRoutes: dbAdapter.mountRoutes\n };\n bootstrappers = [wrappedBootstrapper];\n }\n\n if (bootstrappers.length === 0) {\n throw new Error(\"No bootstrappers or database adapter provided. Cannot initialize database drivers.\");\n }\n\n let defaultDriverId = DEFAULT_DRIVER_ID;\n\n let defaultDriverResult: InitializedDriver | undefined = undefined;\n\n // 1. Initialize all drivers\n for (const bootstrapper of bootstrappers) {\n const b = bootstrapper;\n logger.info(\"Running bootstrapper for driver\", { driverId: b.id || bootstrapper.type });\n if (b.isDefault) {\n defaultDriverId = b.id || bootstrapper.type;\n }\n\n const driverResult = await bootstrapper.initializeDriver({\n collections: activeCollections,\n collectionRegistry\n });\n delegates[b.id || bootstrapper.type] = driverResult.driver;\n\n if ((b.id || bootstrapper.type) === defaultDriverId || !defaultDriverResult) {\n defaultDriverResult = driverResult;\n }\n\n if (bootstrapper.initializeRealtime) {\n const realtime = await bootstrapper.initializeRealtime({}, driverResult);\n if (realtime) {\n realtimeServices[b.id || bootstrapper.type] = realtime;\n }\n }\n }\n\n const driverRegistry = DefaultDriverRegistry.create(delegates);\n activeCollections.forEach(collection => collectionRegistry.register(collection));\n\n const defaultDriver = driverRegistry.getOrDefault(defaultDriverId);\n if (!defaultDriver || !defaultDriverResult) {\n throw new Error(\"Default driver not initialized by bootstrappers\");\n }\n const defaultBootstrapper = bootstrappers.find(b => b.id === defaultDriverId || b.type === defaultDriverId) || bootstrappers[0];\n const defaultRealtimeService = defaultDriverResult.realtimeProvider;\n\n // Resolve a collection path (e.g. \"products\", \"authors/1/posts\") to its\n // data-source key — shared by the data-driver router and the realtime\n // router. Falls back to the default key for unknown paths.\n const keyForCollectionPath = (collectionPath: string): string => {\n const slug = collectionPath.replace(/^\\/+/, \"\").split(\"/\")[0]?.split(\"?\")[0];\n if (!slug) return DEFAULT_DRIVER_ID;\n const collection = collectionRegistry.get(slug) ?? collectionRegistry.getCollectionByPath(slug);\n if (!collection) return DEFAULT_DRIVER_ID;\n return resolveDataSource(collection, dataSourceRegistry).key;\n };\n\n // ── Data-source misconfiguration check ────────────────────────────────\n // A server-transport collection whose resolved data-source key has no\n // registered driver delegate would silently fall back to the default\n // driver — i.e. land in the wrong database. Warn loudly so this surfaces\n // at boot rather than as mysterious data going to the wrong engine.\n {\n const unresolved = new Map<string, string[]>();\n const nonRlsEngines = new Set<string>();\n for (const collection of activeCollections) {\n const ds = resolveDataSource(collection, dataSourceRegistry);\n if (ds.transport !== \"server\") continue; // direct/custom are client-only\n // Server engines without row-level security enforce authorization\n // only at the application layer — surface this so it isn't a\n // silent assumption. (The default Postgres engine supports RLS.)\n if (!ds.capabilities.supportsRLS) nonRlsEngines.add(ds.engine);\n if (ds.key === DEFAULT_DRIVER_ID) continue; // always maps to the default\n if (!driverRegistry.has(ds.key)) {\n const slugs = unresolved.get(ds.key) ?? [];\n slugs.push(collection.slug ?? collection.name ?? \"?\");\n unresolved.set(ds.key, slugs);\n }\n }\n for (const [key, slugs] of unresolved) {\n logger.warn(\n `[DataSource] No driver registered for data source \"${key}\" ` +\n `(used by: ${slugs.join(\", \")}). These collections will fall back to the ` +\n `default driver \"${defaultDriverId}\" — register a bootstrapper with this id, ` +\n `or mark the data source as a direct/custom transport in \\`dataSources\\`.`\n );\n }\n for (const engine of nonRlsEngines) {\n logger.warn(\n `[DataSource] Engine \"${engine}\" does not support row-level security; ` +\n `authorization for its collections is enforced only at the application layer ` +\n `(authentication still applies). Ensure app-level checks or engine-native rules are in place.`\n );\n }\n }\n\n // 2. Initialize Auth & History via the default driver's bootstrapper\n let authConfigResult: BootstrappedAuth | undefined = undefined;\n let serviceKey: string | undefined;\n let authAdapter: AuthAdapter | undefined;\n\n if (config.auth) {\n if (isAuthAdapter(config.auth)) {\n // ── New path: User provided an AuthAdapter directly ──────────\n authAdapter = config.auth;\n serviceKey = authAdapter.serviceKey;\n\n if (authAdapter.initialize) {\n await authAdapter.initialize();\n }\n\n logger.info(\"Using AuthAdapter\", { id: authAdapter.id });\n\n // Populate authConfigResult for backward compatibility\n // (the return type still exposes `auth?: BootstrappedAuth`)\n authConfigResult = {\n userService: authAdapter.userManagement ?? {}\n };\n } else {\n // ── RebaseAuthConfig — wrap in built-in adapter ──\n const safeAuthConfig = config.auth as RebaseAuthConfig;\n\n // Auto-discover the auth collection from activeCollections if not explicitly set\n if (!safeAuthConfig.collection) {\n const foundAuthCollection = activeCollections.find(c => {\n const isAuth = c.auth;\n return isAuth === true || (isAuth && typeof isAuth === \"object\" && isAuth.enabled === true);\n });\n if (foundAuthCollection) {\n safeAuthConfig.collection = foundAuthCollection;\n logger.info(\"Auto-discovered auth collection from collection definitions\", { slug: foundAuthCollection.slug });\n }\n }\n\n // The built-in auth subsystem (users, sessions, repository) is\n // bootstrapped on the DEFAULT driver. If the auth collection is\n // routed to a non-default data source, login would read/write the\n // default engine while the collection's data views hit another —\n // a split-brain user store. Warn loudly.\n if (safeAuthConfig.collection) {\n const authDs = resolveDataSource(safeAuthConfig.collection, dataSourceRegistry);\n if (authDs.key !== DEFAULT_DRIVER_ID) {\n logger.warn(\n `[Auth] The auth collection \"${safeAuthConfig.collection.slug}\" is on data source ` +\n `\"${authDs.key}\", but the built-in auth system always uses the default data source. ` +\n `Move the auth collection to the default data source, or replace auth with an AuthAdapter ` +\n `that manages users in \"${authDs.key}\".`\n );\n }\n }\n\n // Warn if the auth collection relies on data callbacks for lifecycle\n // side effects. User creation/updates via the auth subsystem\n // (registration, admin user management, OAuth) write directly to the\n // user store and do NOT go through the collection save pipeline, so\n // `beforeSave`/`afterSave`/`beforeDelete`/`afterDelete` never fire for\n // those paths. Use the auth hooks (`afterUserCreate`, etc.) instead.\n if (safeAuthConfig.collection?.callbacks) {\n const cb = safeAuthConfig.collection.callbacks as Record<string, unknown>;\n const dataCallbacks = [\"beforeSave\", \"afterSave\", \"beforeDelete\", \"afterDelete\"].filter(k => typeof cb[k] === \"function\");\n if (dataCallbacks.length > 0) {\n logger.warn(\n `[Auth] The auth collection \"${safeAuthConfig.collection.slug}\" defines ` +\n `${dataCallbacks.join(\"/\")} callback(s), but these do NOT fire when users are ` +\n `created or updated through the auth system (registration, admin, OAuth) — ` +\n `that path bypasses the collection save pipeline. Use auth hooks ` +\n `(afterUserCreate, beforeUserCreate, afterUserDelete, …) for those side effects.`\n );\n }\n }\n\n // Extract the collection-level auth config (if `auth` is an object, not just `true`)\n const collectionAuth = safeAuthConfig.collection ? safeAuthConfig.collection.auth : undefined;\n const collectionAuthConfig = (typeof collectionAuth === \"object\" && collectionAuth !== null) ? collectionAuth : undefined;\n if (safeAuthConfig.jwtSecret) {\n configureJwt({\n secret: safeAuthConfig.jwtSecret,\n accessExpiresIn: safeAuthConfig.accessExpiresIn || \"1h\",\n refreshExpiresIn: safeAuthConfig.refreshExpiresIn || \"30d\"\n });\n }\n\n // ── Service Key Validation ───────────────────────────────────\n if (safeAuthConfig.serviceKey) {\n if (safeAuthConfig.serviceKey.length < 32) {\n throw new Error(\n \"REBASE_SERVICE_KEY is too short. Must be at least 32 characters. \" +\n \"Generate one with: node -e \\\"logger.info(require('crypto').randomBytes(48).toString('base64'))\\\"\"\n );\n }\n serviceKey = safeAuthConfig.serviceKey;\n logger.info(\"Service key configured for script/server-to-server authentication\");\n }\n\n if (defaultBootstrapper.initializeAuth) {\n logger.info(\"Bootstrapping authentication via driver protocol\");\n authConfigResult = await defaultBootstrapper.initializeAuth(config.auth, defaultDriverResult);\n\n // The built-in auth adapter is created after OAuth providers\n // are resolved (below) so it only needs to be constructed once.\n\n logger.info(\"Authentication initialized\");\n } else {\n logger.warn(\"Auth requested but default bootstrapper does not support initializeAuth\");\n }\n }\n }\n\n let historyConfigResult: { historyService: import(\"./history/history-routes\").HistoryService } | undefined = undefined;\n if (config.history) {\n if (defaultBootstrapper.initializeHistory) {\n logger.info(\"Bootstrapping entity history via driver protocol\");\n historyConfigResult = await defaultBootstrapper.initializeHistory(config.history, defaultDriverResult) as { historyService: import(\"./history/history-routes\").HistoryService } | undefined;\n\n // Inject the historyService into the driver so save/delete can record history.\n // The driver was created during initializeDriver() (before history was initialized),\n // so we must set it retroactively here.\n if (historyConfigResult?.historyService && defaultDriverResult.internals) {\n const internals = defaultDriverResult.internals as Record<string, unknown>;\n const driver = internals.driver as Record<string, unknown> | undefined;\n if (driver && \"historyService\" in driver) {\n driver.historyService = historyConfigResult.historyService;\n }\n }\n\n logger.info(\"Entity history initialized\");\n } else {\n logger.warn(\"History requested but default bootstrapper does not support initializeHistory\");\n }\n }\n\n // 3. Initialize Storage\n const { storageRegistry, storageController } = await initializeStorage(config.storage, isProduction);\n\n // basePath already resolved above\n\n // 4. Mount API Routes\n if (config.auth) {\n // ── Auth Capabilities Endpoint ───────────────────────────────────\n // Exposes adapter capabilities so the frontend knows what's available\n // (login form vs external redirect, OAuth providers, etc.)\n config.app.get(`${basePath}/auth/config`, async (c) => {\n const capabilities = await authAdapter!.getCapabilities();\n return c.json(capabilities);\n });\n\n if (!isAuthAdapter(config.auth)) {\n const safeAuthConfig = config.auth as RebaseAuthConfig;\n const oauthProviders: OAuthProvider<unknown>[] = [...(safeAuthConfig.providers || [])];\n\n // Resolve configured OAuth providers via data-driven registration.\n // Each entry maps a config key to its factory function name and required fields.\n const OAUTH_PROVIDERS: Array<{\n key: keyof RebaseAuthConfig;\n factory: string;\n requiredFields: string[];\n }> = [\n { key: \"google\", factory: \"createGoogleProvider\", requiredFields: [\"clientId\"] },\n { key: \"linkedin\", factory: \"createLinkedinProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"github\", factory: \"createGitHubProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"microsoft\", factory: \"createMicrosoftProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"apple\", factory: \"createAppleProvider\", requiredFields: [\"clientId\", \"teamId\", \"keyId\", \"privateKey\"] },\n { key: \"facebook\", factory: \"createFacebookProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"twitter\", factory: \"createTwitterProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"discord\", factory: \"createDiscordProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"gitlab\", factory: \"createGitLabProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"bitbucket\", factory: \"createBitbucketProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"slack\", factory: \"createSlackProvider\", requiredFields: [\"clientId\", \"clientSecret\"] },\n { key: \"spotify\", factory: \"createSpotifyProvider\", requiredFields: [\"clientId\", \"clientSecret\"] }\n ];\n\n for (const { key, factory, requiredFields } of OAUTH_PROVIDERS) {\n const providerConfig = safeAuthConfig[key] as Record<string, unknown> | undefined;\n if (providerConfig && requiredFields.every(f => Boolean(providerConfig[f]))) {\n const authModule = await import(\"./auth\");\n const createFn = (authModule as unknown as Record<string, (cfg: unknown) => OAuthProvider<unknown>>)[factory];\n oauthProviders.push(createFn(providerConfig));\n }\n }\n\n // Re-create the built-in adapter with all resolved OAuth providers\n const reCollectionAuth = safeAuthConfig.collection ? safeAuthConfig.collection.auth : undefined;\n const collectionAuthConfig = (typeof reCollectionAuth === \"object\" && reCollectionAuth !== null) ? reCollectionAuth : undefined;\n authAdapter = createBuiltinAuthAdapter({\n authRepository: authConfigResult!.authRepository as import(\"./auth/interfaces\").AuthRepository ?? authConfigResult!.userService as import(\"./auth/interfaces\").AuthRepository,\n emailService: authConfigResult!.emailService as import(\"./email\").EmailService,\n emailConfig: safeAuthConfig.email,\n allowRegistration: safeAuthConfig.allowRegistration ?? false,\n allowUserLookup: safeAuthConfig.allowUserLookup ?? false,\n defaultRole: safeAuthConfig.defaultRole,\n oauthProviders,\n serviceKey,\n authHooks: safeAuthConfig.hooks,\n collectionAuthConfig,\n enableMagicLink: safeAuthConfig.magicLink ?? false,\n cookieAuth: safeAuthConfig.cookieAuth\n });\n\n if (safeAuthConfig.cookieAuth) {\n if (!isProduction && !process.env.CORS_ORIGINS && !process.env.FRONTEND_URL) {\n logger.warn(\n \"[Auth] Cookie authentication (cookieAuth) is enabled, but no CORS restrictions are detected. \" +\n \"Browser-based clients will require credentials: 'include' and the server MUST NOT use \" +\n \"Access-Control-Allow-Origin: '*'. Ensure CORS_ORIGINS is set to your frontend URL.\"\n );\n }\n }\n }\n\n // ── Mount auth & admin routes via the adapter ────────────────────\n if (authAdapter && authAdapter.createAuthRoutes) {\n const authRoutes = authAdapter.createAuthRoutes();\n if (authRoutes) {\n config.app.route(`${basePath}/auth`, authRoutes);\n logger.info(\"Auth routes mounted via adapter\", { adapter: authAdapter.id });\n }\n }\n\n if (authAdapter && authAdapter.createAdminRoutes) {\n const adminRoutes = authAdapter.createAdminRoutes();\n if (adminRoutes) {\n config.app.route(`${basePath}/admin`, adminRoutes);\n logger.info(\"Admin routes mounted via adapter\", { adapter: authAdapter.id });\n }\n }\n }\n\n // ─── Internal per-process credential ───────────────────────────────────\n // When the user hasn't configured a REBASE_SERVICE_KEY, generate a random\n // per-boot key so the singleton's control-plane APIs (auth, admin, storage,\n // functions) can still authenticate against the server's own middleware.\n // This key never leaves the process and is never logged.\n const internalServiceKey = serviceKey || randomBytes(48).toString(\"base64\");\n if (!serviceKey) {\n logger.info(\"No REBASE_SERVICE_KEY configured. Generated internal per-boot key for singleton control-plane APIs.\");\n }\n\n // Update the auth adapter's service key to include the internal key\n // so that the singleton's control-plane requests are recognized.\n if (authAdapter && !authAdapter.serviceKey) {\n authAdapter.serviceKey = internalServiceKey;\n }\n\n // ─── API Key Store Bootstrap ──────────────────────────────────────────\n let apiKeyStore: ApiKeyStore | undefined;\n const apiKeyStoreResult = createApiKeyStore(defaultDriver);\n if (apiKeyStoreResult) {\n apiKeyStore = apiKeyStoreResult;\n await apiKeyStore.ensureTable();\n logger.info(\"Service API Keys initialized\");\n\n // Mount API key admin routes\n const apiKeyRoutes = createApiKeyRoutes({\n store: apiKeyStore,\n serviceKey: internalServiceKey\n });\n config.app.route(`${basePath}/admin/api-keys`, apiKeyRoutes);\n logger.info(\"API key admin routes mounted\", { path: `${basePath}/admin/api-keys` });\n }\n\n if (config.collectionsDir) {\n if (process.env.NODE_ENV !== \"production\") {\n const { createSchemaEditorRoutes } = await import(\"./api/schema-editor-routes\");\n const schemaEditorRoutes = createSchemaEditorRoutes(config.collectionsDir);\n\n if (authAdapter && !isAuthAdapter(config.auth!)) {\n const safeAuth = config.auth as RebaseAuthConfig;\n if (safeAuth.requireAuth !== false && !!safeAuth.jwtSecret) {\n schemaEditorRoutes.use(\"/*\", requireAuth, requireAdmin);\n }\n } else if (authAdapter) {\n // External auth adapter — still protect schema editor\n schemaEditorRoutes.use(\"/*\", requireAuth, requireAdmin);\n }\n\n config.app.route(`${basePath}/schema-editor`, schemaEditorRoutes);\n logger.info(\"Schema Editor mounted\", { path: `${basePath}/schema-editor` });\n }\n }\n\n if (storageController) {\n // Storage uploads get their own body limit, derived from the storage config's\n // maxFileSize (default 50MB), which overrides the global API body limit.\n const storageMaxSize = (\n config.storage && typeof config.storage === \"object\" && \"type\" in config.storage\n ? (config.storage as BackendStorageConfig).maxFileSize\n : undefined\n ) ?? 50 * 1024 * 1024;\n\n const storageRoutes = createStorageRoutes({\n controller: storageController,\n registry: storageRegistry,\n sources: config.storageSources,\n requireAuth: resolveRequireAuth(config.auth),\n authAdapter\n });\n\n // Apply a permissive body limit specifically for the upload endpoint\n storageRoutes.use(\"/upload\", bodyLimit({\n maxSize: storageMaxSize,\n onError: (c) => {\n return c.json({\n error: {\n message: `File too large. Maximum upload size is ${Math.round(storageMaxSize / 1024 / 1024)}MB.`,\n code: \"PAYLOAD_TOO_LARGE\"\n }\n }, 413);\n }\n }));\n\n config.app.route(`${basePath}/storage`, storageRoutes);\n }\n\n if (activeCollections.length > 0) {\n const dataRouter = new Hono<HonoEnv>();\n dataRouter.onError(errorHandler);\n\n // Secure by default: require auth when auth is configured.\n // Developers who intentionally want public data access (relying\n // entirely on Postgres RLS) must explicitly set `auth.requireAuth: false`.\n const dataRequireAuth = resolveRequireAuth(config.auth);\n\n if (!dataRequireAuth) {\n logger.warn(\n \"Data routes running WITHOUT authentication enforcement. \" +\n \"Access control is fully delegated to Postgres RLS policies. \" +\n \"If no RLS policies exist, data is publicly accessible. \" +\n \"Set auth.requireAuth to true (or remove it) to require authentication.\"\n );\n }\n\n // Multi-data-source routing: when more than one database engine is\n // registered (e.g. Postgres + MongoDB in one instance), resolve the\n // delegate per request from the request's collection data source. The\n // auth middleware then scopes that delegate (RLS for Postgres, no-op\n // for engines without `withAuth()`) into the request context. For a\n // single-engine backend this is omitted — behaviour is unchanged.\n const dataPathMarker = `${basePath}/data/`;\n const resolveRequestDriver = (reqPath: string): DataDriver => {\n const i = reqPath.indexOf(dataPathMarker);\n const collectionPath = i >= 0 ? reqPath.slice(i + dataPathMarker.length) : reqPath;\n const key = keyForCollectionPath(collectionPath);\n // Use the authoritative default for the default key; otherwise the\n // named delegate, falling back to default if it isn't registered.\n if (!key || key === DEFAULT_DRIVER_ID) return defaultDriver;\n return driverRegistry.get(key) ?? defaultDriver;\n };\n const multiEngine = bootstrappers.length > 1;\n const resolveDriver = multiEngine ? ((c: { req: { path: string } }) => resolveRequestDriver(c.req.path)) : undefined;\n\n // Use adapter middleware when an AuthAdapter is available,\n // falling back to the built-in JWT middleware otherwise.\n if (authAdapter) {\n dataRouter.use(\"/*\", createAdapterAuthMiddleware({\n adapter: authAdapter,\n driver: defaultDriver,\n resolveDriver,\n requireAuth: dataRequireAuth,\n apiKeyStore\n }));\n } else {\n dataRouter.use(\"/*\", createAuthMiddleware({\n driver: defaultDriver,\n resolveDriver,\n requireAuth: dataRequireAuth,\n serviceKey: internalServiceKey,\n apiKeyStore\n }));\n }\n\n // Per-API-key rate limiting (no-op for non-API-key requests)\n if (apiKeyStore) {\n dataRouter.use(\"/*\", createApiKeyRateLimiter());\n }\n\n // Mount history routes BEFORE the REST API subcollection catch-all so\n // that /:slug/:id/history is matched by the dedicated handler first.\n if (historyConfigResult && historyConfigResult.historyService) {\n const historyRoutes = createHistoryRoutes({\n historyService: historyConfigResult.historyService,\n registry: collectionRegistry,\n driver: defaultDriver\n });\n dataRouter.route(\"/\", historyRoutes);\n }\n\n // Only generate server data routes for server-mediated collections.\n // Collections on a direct/custom transport are client-only — the\n // backend must not expose a (mis-engined) endpoint for them.\n const serverCollections = activeCollections.filter(\n (collection) => resolveDataSource(collection, dataSourceRegistry).transport === \"server\"\n );\n\n const restGenerator = new RestApiGenerator(\n serverCollections,\n defaultDriver,\n authAdapter\n );\n dataRouter.route(\"/\", restGenerator.generateRoutes());\n\n config.app.route(`${basePath}/data`, dataRouter);\n }\n\n // ── OpenAPI / Swagger ─────────────────────────────────────────────────\n await mountOpenApiDocs(config.app, basePath, config.enableSwagger, activeCollections, resolveRequireAuth(config.auth));\n\n // ─── Server-side singleton ────────────────────────────────────────────\n // Build the RebaseClient for control-plane APIs (auth, admin, storage,\n // functions, cron). These still route through the Hono app because they\n // genuinely need route dispatch + middleware.\n // `rebase.data` is replaced below with a native driver-backed data plane.\n const serverClient = createRebaseClient({\n baseUrl: \"http://localhost\",\n apiPath: basePath,\n websocketUrl: \"\",\n token: internalServiceKey,\n fetch: async (input: RequestInfo | URL, init?: RequestInit) => {\n return await config.app.request(input as string | Request | URL, init);\n }\n });\n\n // ─── Native data plane ────────────────────────────────────────────────\n // Replace the HTTP-transport data layer with a driver-backed RebaseData.\n // This eliminates JSON serialize → Hono dispatch → auth → deserialize for\n // every rebase.data call. RLS semantics are preserved: the driver is scoped\n // once as { uid: \"service\", roles: [\"admin\"] }, matching the identity the\n // service-key HTTP path produced.\n const serviceIdentity = { uid: \"service\", roles: [\"admin\"] as string[] };\n\n const scopedDefaultDriver = await scopeDataDriver(defaultDriver, serviceIdentity);\n const defaultData = buildSdkData(scopedDefaultDriver);\n\n // Multi-engine: scope and wrap each non-default delegate so\n // rebase.data on a non-default-engine collection reaches the correct driver.\n const dataSourcesByKey: Record<string, import(\"@rebasepro/types\").RebaseSdkData> = {};\n for (const driverKey of driverRegistry.list()) {\n if (driverKey === DEFAULT_DRIVER_ID) continue;\n const delegate = driverRegistry.get(driverKey);\n if (!delegate) continue;\n const scopedDelegate = await scopeDataDriver(delegate, serviceIdentity);\n dataSourcesByKey[driverKey] = buildSdkData(scopedDelegate);\n }\n\n const serverData = buildRoutedRebaseData({\n defaultData,\n sources: dataSourcesByKey,\n resolveKey: (slugOrPath: string) => keyForCollectionPath(slugOrPath)\n });\n\n // Overwrite the HTTP-transport data proxy with the native driver-backed one.\n // The rest of the client (auth, admin, cron, functions, storage) keeps using\n // the HTTP transport, which is fine — they are low-frequency control-plane ops.\n //\n // `dataAsAdmin` is the loud, explicitly-named admin accessor; `data` is kept\n // as a (deprecated) alias pointing at the same admin-scoped, RLS-bypassing\n // object — same trust level, clearer name at the call site.\n Object.assign(serverClient, { data: serverData, dataAsAdmin: serverData });\n logger.info(\"Native data plane attached to singleton (bypasses HTTP loop)\");\n\n // Attach email service to the server client when configured.\n // The email service may come from the auth bootstrapper or from the auth config directly.\n let emailService: EmailService | undefined;\n if (authConfigResult?.emailService) {\n emailService = authConfigResult.emailService as EmailService;\n } else if (config.auth && !isAuthAdapter(config.auth) && (config.auth as RebaseAuthConfig).email) {\n emailService = createEmailService((config.auth as RebaseAuthConfig).email!);\n }\n\n if (emailService) {\n Object.assign(serverClient, { email: emailService });\n logger.info(\"Email service attached to singleton\", { configured: emailService.isConfigured() });\n\n if (emailService.isConfigured() && typeof emailService.verifyConnection === \"function\") {\n emailService.verifyConnection().then((success) => {\n if (!success) {\n logger.warn(\"Warning: SMTP connection verification failed. Email delivery may fail.\");\n } else {\n logger.info(\"SMTP connection verified successfully.\");\n }\n }).catch((err) => {\n logger.warn(\"Warning: SMTP connection verification failed. Email delivery may fail.\", { error: err });\n });\n }\n }\n\n // Attach raw SQL capability when the driver supports it (Postgres, MySQL).\n // Document databases (MongoDB, Firestore) won't have this.\n const driverAdmin = defaultBootstrapper.getAdmin?.(defaultDriverResult);\n if (isSQLAdmin(driverAdmin)) {\n Object.assign(serverClient, {\n sql: (query: string, options?: { database?: string; role?: string }) =>\n driverAdmin.executeSql(query, options)\n });\n logger.info(\"SQL capability attached to singleton\");\n }\n\n // The server client is assembled dynamically above (native data plane,\n // dataAsAdmin, email, sql attached via Object.assign), so TS can't see the\n // full RebaseServerClient shape statically — cast at the boundary.\n _initRebase(serverClient as unknown as import(\"@rebasepro/types\").RebaseServerClient);\n logger.info(\"Rebase singleton initialized\");\n\n // Retroactively inject the server client into the driver so that\n // entity callbacks receive `context.client` at runtime.\n // The driver is created before the client (which depends on the mounted\n // Hono app), so we set it here, mirroring the historyService injection above.\n if (defaultDriverResult.internals) {\n const internals = defaultDriverResult.internals as Record<string, unknown>;\n const driver = internals.driver as Record<string, unknown> | undefined;\n if (driver && \"client\" in driver) {\n driver.client = serverClient;\n }\n }\n\n // 5. Mount Custom Functions\n if (config.functionsDir) {\n const { loadFunctionsFromDirectory } = await import(\"./functions/function-loader\");\n const { createFunctionRoutes } = await import(\"./functions/function-routes\");\n\n const loadedFunctions = await loadFunctionsFromDirectory(config.functionsDir);\n\n if (loadedFunctions.length > 0) {\n const functionsRouter = new Hono<HonoEnv>();\n functionsRouter.onError(errorHandler);\n\n // Custom functions do NOT require authentication at the global level by default.\n // This allows custom functions to define public endpoints (like webhooks).\n // Per-route auth can be further refined inside individual functions using `requireAuth`.\n const functionsRequireAuth = false;\n\n // Use adapter middleware when available, fallback to built-in\n if (authAdapter) {\n functionsRouter.use(\"/*\", createAdapterAuthMiddleware({\n adapter: authAdapter,\n driver: defaultDriver,\n requireAuth: functionsRequireAuth,\n apiKeyStore\n }));\n } else {\n functionsRouter.use(\"/*\", createAuthMiddleware({\n driver: defaultDriver,\n requireAuth: functionsRequireAuth,\n serviceKey: internalServiceKey,\n apiKeyStore\n }));\n }\n\n const fnRoutes = createFunctionRoutes(loadedFunctions);\n functionsRouter.route(\"/\", fnRoutes);\n config.app.route(`${basePath}/functions`, functionsRouter);\n logger.info(\"Mounted custom functions\", {\n count: loadedFunctions.length,\n path: `${basePath}/functions`\n });\n }\n }\n\n // 6. Mount Cron Jobs\n let cronScheduler: import(\"./cron\").CronScheduler | undefined;\n if (config.cronsDir) {\n const { loadCronJobsFromDirectory } = await import(\"./cron/cron-loader\");\n const { CronScheduler } = await import(\"./cron/cron-scheduler\");\n const { createCronRoutes } = await import(\"./cron/cron-routes\");\n const { createCronStore } = await import(\"./cron/cron-store\");\n\n const loadedCronJobs = await loadCronJobsFromDirectory(config.cronsDir);\n\n if (loadedCronJobs.length > 0) {\n cronScheduler = new CronScheduler();\n\n // The cron scheduler uses the same serverClient as the singleton.\n // ctx.client inside cron handlers IS the same `rebase` instance.\n cronScheduler.setClient(serverClient);\n\n cronScheduler.registerJobs(loadedCronJobs);\n\n // Attach database persistence if the driver supports SQL and persistence is enabled\n const admin = defaultBootstrapper.getAdmin?.(defaultDriverResult);\n const store = (admin && config.cronPersistence !== false) ? createCronStore(defaultDriver) : undefined;\n if (store) {\n await store.ensureTable();\n cronScheduler.setStore(store);\n }\n\n const cronRouter = new Hono<HonoEnv>();\n\n // Cron admin routes require authentication + admin role\n if (authAdapter && !isAuthAdapter(config.auth!)) {\n const safeAuth = config.auth as RebaseAuthConfig;\n if (safeAuth.requireAuth !== false && !!safeAuth.jwtSecret) {\n cronRouter.use(\"/*\", requireAuth, requireAdmin);\n }\n } else if (authAdapter) {\n cronRouter.use(\"/*\", requireAuth, requireAdmin);\n }\n\n cronRouter.route(\"/\", createCronRoutes(cronScheduler));\n config.app.route(`${basePath}/cron`, cronRouter);\n\n // Start the scheduler\n cronScheduler.start();\n\n logger.info(\"Mounted cron jobs\", {\n count: loadedCronJobs.length,\n path: `${basePath}/cron`\n });\n }\n }\n\n // With multiple realtime-capable engines, route subscriptions to the\n // provider owning each collection (the realtime counterpart of the data\n // router). The single WebSocket server is driven by this composite.\n // Single-engine setups use the default provider unchanged.\n const effectiveRealtimeService: RealtimeProvider = Object.keys(realtimeServices).length > 1\n ? createRoutedRealtimeService({\n providers: realtimeServices,\n defaultKey: defaultDriverId,\n resolveKey: keyForCollectionPath\n })\n : defaultRealtimeService as RealtimeProvider;\n\n if (defaultBootstrapper.initializeWebsockets && effectiveRealtimeService) {\n await defaultBootstrapper.initializeWebsockets(config.server, effectiveRealtimeService, defaultDriver, config.auth, authAdapter);\n }\n\n logger.info(\"Rebase Backend Initialized\");\n\n // ── Deep Health Check ─────────────────────────────────────────────────\n const healthCheck = createHealthCheck(defaultDriver);\n\n // ── Graceful Shutdown ─────────────────────────────────────────────────\n const shutdown = createShutdown({\n server: config.server,\n cronScheduler,\n realtimeServices\n });\n\n return {\n driverRegistry,\n driver: defaultDriver,\n realtimeServices,\n realtimeService: effectiveRealtimeService,\n auth: authConfigResult,\n history: historyConfigResult,\n storageRegistry,\n storageController,\n collectionRegistry,\n cronScheduler,\n healthCheck,\n shutdown\n };\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { Hono } from \"hono\";\nimport { logger } from \"../utils/logger.js\";\nimport { nativeDynamicImport, type ModuleImporter } from \"../utils/dynamic-import.js\";\n\nexport interface LoadedFunction {\n /** Endpoint name derived from filename (e.g., \"send-invoice\") */\n name: string;\n /** The Hono sub-app to mount */\n app: Hono<import(\"hono\").Env>;\n}\n\n/**\n * Auto-discover Hono route files from a directory.\n *\n * Each file should default-export a Hono app (or router).\n * The filename (without extension) becomes the mount path:\n * `functions/send-invoice.ts` → mounted at `/send-invoice`\n *\n * This mirrors how `loadCollectionsFromDirectory` works for collections.\n */\nexport async function loadFunctionsFromDirectory(\n directory: string,\n importModule: ModuleImporter = nativeDynamicImport\n): Promise<LoadedFunction[]> {\n const functions: LoadedFunction[] = [];\n // Aggregate problem files so a broken function surfaces as one loud\n // summary line, not just a warning buried per-file. We still don't throw:\n // a single malformed function must not crash server boot.\n const problems: string[] = [];\n\n if (!fs.existsSync(directory)) {\n return functions;\n }\n\n const files = fs.readdirSync(directory);\n for (const file of files) {\n if (\n (file.endsWith(\".ts\") || file.endsWith(\".js\")) &&\n !file.includes(\".test.\") &&\n !file.endsWith(\".d.ts\") &&\n file !== \"index.ts\" &&\n file !== \"index.js\"\n ) {\n const filePath = path.join(directory, file);\n try {\n const fileUrl = pathToFileURL(filePath).href;\n\n const mod = await importModule(fileUrl);\n\n const exported = mod.default;\n\n if (!exported) {\n logger.warn(`[functions] ${file}: no default export. Skipping.`);\n problems.push(`${file} (no default export)`);\n continue;\n }\n\n // Accept a Hono instance — use duck-typing to handle different\n // Hono versions which may not share the same prototype.\n if (isHonoLike(exported)) {\n const name = path.basename(file, path.extname(file));\n functions.push({ name,\napp: exported as Hono });\n logger.info(`⚡ Loaded function route: ${name}`);\n continue;\n }\n\n // Also accept a factory function that returns a Hono instance\n if (typeof exported === \"function\") {\n const result = exported();\n if (isHonoLike(result)) {\n const name = path.basename(file, path.extname(file));\n functions.push({ name,\napp: result as Hono });\n logger.info(`⚡ Loaded function route: ${name}`);\n continue;\n }\n }\n\n // Provide actionable diagnostics\n const exportType = typeof exported;\n const keys = exported && typeof exported === \"object\"\n ? Object.getOwnPropertyNames(Object.getPrototypeOf(exported)).slice(0, 10).join(\", \")\n : \"N/A\";\n logger.warn(\n `[functions] ${file}: default export is not a Hono app or factory. Skipping.\\n` +\n ` export type: ${exportType}${exported?.constructor?.name ? ` (${exported.constructor.name})` : \"\"}\\n` +\n ` prototype methods: ${keys}\\n` +\n \" Hint: ensure the function exports a Hono app created with the same hono version as the server.\\n\" +\n \" Author with `defineFunction(...)` from @rebasepro/server-core for a typed, checked contract.\\n\" +\n \" The loader checks for .fetch() and .routes — any Hono-compatible app will work.\"\n );\n problems.push(`${file} (not a Hono app or factory)`);\n } catch (err: unknown) {\n const message =\n err instanceof Error ? err.message : String(err);\n logger.error(`[functions] Failed to load ${file}: ${message}`);\n problems.push(`${file} (threw: ${message})`);\n }\n }\n }\n\n if (problems.length > 0) {\n logger.warn(\n `[functions] ${problems.length} function file(s) were skipped and will NOT be served:\\n` +\n problems.map((p) => ` - ${p}`).join(\"\\n\") + \"\\n\" +\n \" Fix these or author them with `defineFunction(...)` for a typed, compile-checked contract.\"\n );\n }\n\n return functions;\n}\n\n/**\n * Duck-type check for Hono apps.\n * We avoid `instanceof Hono` because different Hono versions\n * installed in the user's project vs. our dependencies will\n * not share the same prototype, causing false negatives.\n */\nfunction isHonoLike(obj: unknown): boolean {\n if (!obj || typeof obj !== \"object\") return false;\n // Hono instances always have .fetch() and .routes\n const record = obj as Record<string, unknown>;\n return (\n typeof record.fetch === \"function\" &&\n Array.isArray(record.routes)\n );\n}\n","import { Hono } from \"hono\";\nimport { HonoEnv } from \"../api/types\";\nimport { LoadedFunction } from \"./function-loader\";\n\n/**\n * Mount all loaded function routes under a single Hono router.\n *\n * Each function is mounted at `/<function-name>`, preserving\n * whatever HTTP methods and middleware the Hono sub-app defines.\n */\nexport function createFunctionRoutes(\n functions: LoadedFunction[]\n): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n // Listing endpoint: GET / → list available functions\n router.get(\"/\", (c) => {\n return c.json({\n functions: functions.map((fn) => ({\n name: fn.name,\n endpoint: `/functions/${fn.name}`\n }))\n });\n });\n\n for (const fn of functions) {\n router.route(`/${fn.name}`, fn.app);\n }\n\n return router;\n}\n","import { Hono } from \"hono\";\nimport type { RebaseServerClient } from \"@rebasepro/types\";\nimport type { HonoEnv } from \"../api/types\";\nimport { rebase } from \"../singleton\";\n\n/**\n * Typed context injected into a function authored with {@link defineFunction}.\n *\n * Surfaces the app-scoped Rebase singleton so handlers don't need to reach\n * for the global `rebase` import. Request-scoped values (the authenticated\n * `user`, the RLS-scoped `driver`, the `apiKey`, the `requestId`) are typed\n * on the Hono context via {@link HonoEnv} — read them with `c.get(\"user\")`\n * / `c.var.driver` inside a handler.\n */\nexport interface RebaseFunctionContext {\n /**\n * The server-side Rebase singleton (`dataAsAdmin`, `auth`, `storage`,\n * `email`, `sql`).\n *\n * `rebase.dataAsAdmin` runs with **admin privileges and bypasses RLS** — use\n * it only for trusted admin work. For user-scoped queries inside a handler,\n * use the request `driver` (`c.var.driver`), which carries the caller's\n * identity so RLS applies. (`rebase.data` is a deprecated alias for\n * `rebase.dataAsAdmin`.)\n */\n rebase: RebaseServerClient;\n}\n\n/**\n * Typed authoring contract for a custom backend function.\n *\n * A custom function is a file in the `functionsDir` that default-exports a\n * Hono app; the loader mounts it at `/<filename>`. `defineFunction` is the\n * typed opt-in for that contract: it hands you a pre-typed `Hono<HonoEnv>`\n * app (so `c.var.user` / `c.var.driver` are typed) plus a\n * {@link RebaseFunctionContext}, and returns exactly the Hono app the loader\n * already accepts — so it is fully interchangeable with a plain\n * `export default new Hono()`.\n *\n * @example\n * ```ts\n * import { defineFunction, requireAuth } from \"@rebasepro/server-core\";\n *\n * export default defineFunction((app, { rebase }) => {\n * app.use(\"/*\", requireAuth);\n * app.get(\"/home\", async (c) => {\n * const [stats] = await rebase.sql!(`SELECT count(*) AS n FROM orders`);\n * return c.json({ orders: Number(stats.n) });\n * });\n * });\n * ```\n *\n * @param definition Receives the function's Hono app and the typed context.\n * Register routes on the provided `app` and return nothing, or return your\n * own `Hono<HonoEnv>` app to use instead.\n * @returns The Hono app to default-export from the function file.\n */\nexport function defineFunction(\n definition: (app: Hono<HonoEnv>, ctx: RebaseFunctionContext) => void | Hono<HonoEnv>\n): Hono<HonoEnv> {\n const app = new Hono<HonoEnv>();\n const returned = definition(app, { rebase });\n return returned instanceof Hono ? returned : app;\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport type { CronJobDefinition } from \"@rebasepro/types\";\nimport { logger } from \"../utils/logger.js\";\nimport { nativeDynamicImport, type ModuleImporter } from \"../utils/dynamic-import.js\";\n\nexport interface LoadedCronJob {\n /** Job ID derived from filename (e.g. \"cleanup-sessions\"). */\n id: string;\n /** The full definition. */\n definition: CronJobDefinition;\n}\n\n/**\n * Auto-discover cron job files from a directory.\n *\n * Each file should default-export a `CronJobDefinition`.\n * The filename (without extension) becomes the job ID:\n * `crons/cleanup-sessions.ts` → id = \"cleanup-sessions\"\n *\n * Follows the same discovery pattern as `loadFunctionsFromDirectory`.\n */\nexport async function loadCronJobsFromDirectory(\n directory: string,\n importModule: ModuleImporter = nativeDynamicImport\n): Promise<LoadedCronJob[]> {\n const jobs: LoadedCronJob[] = [];\n\n if (!fs.existsSync(directory)) {\n return jobs;\n }\n\n const files = fs.readdirSync(directory);\n for (const file of files) {\n if (\n (file.endsWith(\".ts\") || file.endsWith(\".js\")) &&\n !file.includes(\".test.\") &&\n !file.endsWith(\".d.ts\") &&\n file !== \"index.ts\" &&\n file !== \"index.js\"\n ) {\n const filePath = path.join(directory, file);\n try {\n const fileUrl = pathToFileURL(filePath).href;\n\n const mod = await importModule(fileUrl);\n\n const exported: unknown = mod.default;\n\n if (!exported || typeof exported !== \"object\") {\n logger.warn(`[cron] ${file}: no valid default export. Skipping.`);\n continue;\n }\n\n const def = exported as Record<string, unknown>;\n if (typeof def.schedule !== \"string\" || typeof def.handler !== \"function\") {\n logger.warn(`[cron] ${file}: default export missing required 'schedule' or 'handler'. Skipping.`);\n continue;\n }\n\n const id = path.basename(file, path.extname(file));\n const definition: CronJobDefinition = {\n schedule: def.schedule as string,\n name: (def.name as string) || id,\n description: def.description as string | undefined,\n enabled: def.enabled !== false,\n timeoutSeconds: (def.timeoutSeconds as number) || 300,\n handler: def.handler as CronJobDefinition[\"handler\"]\n };\n\n jobs.push({ id,\ndefinition });\n logger.info(`⏰ Loaded cron job: ${id} (${definition.schedule})`);\n } catch (err: unknown) {\n const message =\n err instanceof Error ? err.message : String(err);\n logger.error(`[cron] Failed to load ${file}: ${message}`);\n }\n }\n }\n\n return jobs;\n}\n","import type { CronJobDefinition } from \"@rebasepro/types\";\n\n/**\n * Typed authoring helper for a cron job file. Identity at runtime —\n * a plain default-exported {@link CronJobDefinition} works identically;\n * this adds type inference and autocomplete.\n *\n * @see {@link defineFunction} for the equivalent custom-functions helper.\n *\n * @example\n * ```ts\n * import { defineCron } from \"@rebasepro/server-core\";\n *\n * export default defineCron({\n * name: \"Nightly cleanup\",\n * schedule: \"0 3 * * *\",\n * async handler({ client, log }) {\n * const { data: expired } = await client.data.sessions.find({\n * where: { expired: [\"==\", true] },\n * });\n * for (const session of expired) {\n * await client.data.sessions.delete(session.id);\n * }\n * log(`Deleted ${expired.length} expired sessions`);\n * },\n * });\n * ```\n */\nexport function defineCron(definition: CronJobDefinition): CronJobDefinition {\n return definition;\n}\n","import type {\n CronJobDefinition,\n CronJobStatus,\n CronJobLogEntry,\n CronJobRunState,\n CronJobContext\n} from \"@rebasepro/types\";\nimport type { RebaseClient } from \"@rebasepro/types\";\nimport type { LoadedCronJob } from \"./cron-loader\";\nimport type { CronStore } from \"./cron-store\";\nimport { logger } from \"../utils/logger.js\";\n\n// ─── Cron expression parser (minimal, no external dependency) ────────\n// Supports standard 5-field cron (minute hour dom month dow).\n// Returns the next Date after `after` that matches the expression.\n\n/**\n * Expand a single cron field into an ordered array of allowed values.\n * Supports: `*`, `N`, `N-M`, `N/S`, `N-M/S`, `*\\/S`, and comma-separated combinations.\n */\nfunction expandCronField(field: string, min: number, max: number): number[] {\n const results = new Set<number>();\n for (const segment of field.split(\",\")) {\n const trimmed = segment.trim();\n if (trimmed === \"*\") {\n for (let i = min; i <= max; i++) results.add(i);\n } else if (trimmed.includes(\"/\")) {\n const [rangeStr, stepStr] = trimmed.split(\"/\");\n const step = parseInt(stepStr, 10);\n if (isNaN(step) || step <= 0) {\n throw new Error(`Invalid step value \"${stepStr}\" in cron field \"${field}\"`);\n }\n let start = min;\n let end = max;\n if (rangeStr !== \"*\") {\n if (rangeStr.includes(\"-\")) {\n const [a, b] = rangeStr.split(\"-\").map(Number);\n start = a;\n end = b;\n } else {\n start = parseInt(rangeStr, 10);\n }\n }\n for (let i = start; i <= end; i += step) results.add(i);\n } else if (trimmed.includes(\"-\")) {\n const [a, b] = trimmed.split(\"-\").map(Number);\n for (let i = a; i <= b; i++) results.add(i);\n } else {\n const val = parseInt(trimmed, 10);\n if (isNaN(val)) {\n throw new Error(`Invalid value \"${trimmed}\" in cron field \"${field}\"`);\n }\n results.add(val);\n }\n }\n return [...results].sort((a, b) => a - b);\n}\n\n/**\n * Validates a standard 5-field cron expression structurally and semantically.\n * Returns `{ valid: true }` or `{ valid: false, reason: string }`.\n */\nexport function validateCronExpression(schedule: string): { valid: true } | { valid: false; reason: string } {\n if (!schedule || typeof schedule !== \"string\") {\n return { valid: false,\nreason: \"Schedule must be a non-empty string\" };\n }\n const parts = schedule.trim().split(/\\s+/);\n if (parts.length !== 5) {\n return { valid: false,\nreason: `Expected 5 fields, got ${parts.length}` };\n }\n const fieldRanges: [string, number, number][] = [\n [\"minute\", 0, 59],\n [\"hour\", 0, 23],\n [\"day of month\", 1, 31],\n [\"month\", 1, 12],\n [\"day of week\", 0, 6]\n ];\n for (let i = 0; i < 5; i++) {\n const [name, min, max] = fieldRanges[i];\n try {\n const values = expandCronField(parts[i], min, max);\n if (values.length === 0) {\n return { valid: false,\nreason: `${name} field \"${parts[i]}\" produces no values` };\n }\n for (const v of values) {\n if (v < min || v > max) {\n return { valid: false,\nreason: `${name} field value ${v} out of range [${min}–${max}]` };\n }\n }\n } catch (err) {\n return { valid: false,\nreason: `${name} field: ${err instanceof Error ? err.message : String(err)}` };\n }\n }\n return { valid: true };\n}\n\n/**\n * Calculate the next Date after `after` that matches the cron expression.\n * Throws on invalid expressions.\n */\nfunction parseCronExpression(expression: string, after: Date): Date {\n const parts = expression.trim().split(/\\s+/);\n if (parts.length < 5) {\n throw new Error(`Invalid cron expression: \"${expression}\". Expected 5 fields.`);\n }\n\n const [minField, hourField, domField, monField, dowField] = parts;\n\n const minutes = expandCronField(minField, 0, 59);\n const hours = expandCronField(hourField, 0, 23);\n const doms = expandCronField(domField, 1, 31);\n const months = expandCronField(monField, 1, 12);\n const dows = expandCronField(dowField, 0, 6); // 0=Sunday\n\n // Forward-search from `after + 1 minute`\n const candidate = new Date(after);\n candidate.setSeconds(0, 0);\n candidate.setMinutes(candidate.getMinutes() + 1);\n\n const maxIterations = 525960; // ~1 year in minutes\n for (let i = 0; i < maxIterations; i++) {\n const month = candidate.getMonth() + 1; // 1-12\n const dom = candidate.getDate();\n const dow = candidate.getDay(); // 0=Sunday\n const hour = candidate.getHours();\n const minute = candidate.getMinutes();\n\n if (\n months.includes(month) &&\n doms.includes(dom) &&\n dows.includes(dow) &&\n hours.includes(hour) &&\n minutes.includes(minute)\n ) {\n return candidate;\n }\n candidate.setMinutes(candidate.getMinutes() + 1);\n }\n\n // Fallback — should not happen with valid expressions\n const fallback = new Date(after);\n fallback.setMinutes(fallback.getMinutes() + 1);\n return fallback;\n}\n\n// ─── In-memory ring buffer for logs ──────────────────────────────────\n\nconst MAX_LOGS_PER_JOB = 50;\n\n/**\n * Minimum milliseconds between scheduled executions of the same job.\n * Prevents tight re-execution loops caused by jitter or clock drift.\n */\nconst MIN_SCHEDULE_INTERVAL_MS = 5_000; // 5 seconds\n\n// ─── CronScheduler ───────────────────────────────────────────────────\n\ninterface RegisteredJob {\n id: string;\n definition: CronJobDefinition;\n enabled: boolean;\n state: CronJobRunState;\n lastRunAt?: Date;\n nextRunAt?: Date;\n lastDurationMs?: number;\n lastError?: string;\n totalRuns: number;\n totalFailures: number;\n timerId?: ReturnType<typeof setTimeout>;\n logs: CronJobLogEntry[];\n /** True while a handler is actively executing (prevents concurrent runs). */\n executing: boolean;\n}\n\nexport class CronScheduler {\n private jobs = new Map<string, RegisteredJob>();\n private started = false;\n private store?: CronStore;\n private client?: RebaseClient;\n\n /**\n * Set the RebaseClient instance to make it available to cron job handlers.\n */\n setClient(client: RebaseClient): void {\n this.client = client;\n }\n\n /**\n * Attach a persistence store for cron logs.\n * When set, execution logs are written to the database after each run,\n * and counters are seeded from the database on start.\n */\n setStore(store: CronStore): void {\n this.store = store;\n }\n\n /**\n * Register a batch of loaded cron jobs.\n *\n * If the scheduler is already started, newly registered jobs are\n * automatically scheduled (so late-registered jobs don't sit idle).\n *\n * Validates the cron schedule on registration — invalid schedules\n * are rejected with a warning and the job is NOT registered.\n */\n registerJobs(loadedJobs: LoadedCronJob[]): void {\n for (const loaded of loadedJobs) {\n // Validate schedule up-front — reject invalid schedules\n const validation = validateCronExpression(loaded.definition.schedule);\n if (!validation.valid) {\n logger.error(`[cron] Rejecting job \"${loaded.id}\": invalid schedule \"${loaded.definition.schedule}\" — ${validation.reason}`);\n continue;\n }\n\n const existing = this.jobs.get(loaded.id);\n if (existing) {\n logger.warn(`[cron] Duplicate cron job id: \"${loaded.id}\". Overwriting.`);\n this.stopJob(loaded.id);\n }\n\n const enabled = loaded.definition.enabled !== false;\n\n this.jobs.set(loaded.id, {\n id: loaded.id,\n definition: loaded.definition,\n enabled,\n state: enabled ? \"idle\" : \"disabled\",\n totalRuns: 0,\n totalFailures: 0,\n logs: [],\n executing: false\n });\n\n // If the scheduler is already running, auto-schedule new jobs\n if (this.started && enabled) {\n this.scheduleNext(loaded.id);\n }\n }\n }\n\n /**\n * Start the scheduler — begins ticking all enabled jobs.\n */\n start(): void {\n if (this.started) return;\n this.started = true;\n\n // Seed counters from DB (non-blocking — scheduler starts immediately)\n if (this.store) {\n this.store.fetchJobStats().then((stats) => {\n for (const [jobId, data] of stats) {\n const job = this.jobs.get(jobId);\n if (job) {\n job.totalRuns = data.totalRuns;\n job.totalFailures = data.totalFailures;\n if (data.lastRunAt) {\n job.lastRunAt = new Date(data.lastRunAt);\n }\n }\n }\n }).catch((err) => {\n logger.warn(\"[cron] Failed to seed job stats from database\", { error: err });\n });\n }\n\n for (const [id, job] of this.jobs) {\n if (job.enabled) {\n this.scheduleNext(id);\n }\n }\n logger.info(`⏰ Cron scheduler started with ${this.jobs.size} job(s)`);\n }\n\n /**\n * Stop the scheduler and clear all timers.\n *\n * Currently-executing handlers run to completion (they are async),\n * but no further scheduling occurs after stop.\n */\n stop(): void {\n this.started = false;\n for (const [id] of this.jobs) {\n this.stopJob(id);\n }\n }\n\n /**\n * List all registered jobs with their current status.\n */\n listJobs(): CronJobStatus[] {\n return [...this.jobs.values()].map((job) => this.toStatus(job));\n }\n\n /**\n * Get a single job status by ID.\n */\n getJob(id: string): CronJobStatus | undefined {\n const job = this.jobs.get(id);\n return job ? this.toStatus(job) : undefined;\n }\n\n /**\n * Get log entries for a job.\n */\n getJobLogs(id: string, limit?: number): CronJobLogEntry[] {\n const job = this.jobs.get(id);\n if (!job) return [];\n const logs = [...job.logs].reverse(); // newest first\n return limit ? logs.slice(0, limit) : logs;\n }\n\n /**\n * Get log entries for a job from the database (if store is available).\n * Falls back to in-memory logs if no store is configured.\n */\n async getJobLogsFromDb(id: string, limit?: number): Promise<CronJobLogEntry[]> {\n if (this.store) {\n const dbLogs = await this.store.fetchLogs(id, limit);\n if (dbLogs.length > 0) return dbLogs;\n }\n // Fallback to in-memory\n return this.getJobLogs(id, limit);\n }\n\n /**\n * Enable or disable a job at runtime.\n */\n setJobEnabled(id: string, enabled: boolean): CronJobStatus | undefined {\n const job = this.jobs.get(id);\n if (!job) return undefined;\n\n job.enabled = enabled;\n\n if (enabled && this.started) {\n job.state = \"idle\";\n this.scheduleNext(id);\n } else if (!enabled) {\n this.stopJob(id);\n job.state = \"disabled\";\n }\n\n return this.toStatus(job);\n }\n\n /**\n * Manually trigger a job execution immediately.\n *\n * Returns `undefined` if the job doesn't exist.\n * If the job is currently executing, returns the log entry with\n * a `skipped: true` result rather than running concurrently.\n */\n async triggerJob(id: string): Promise<CronJobLogEntry | undefined> {\n const job = this.jobs.get(id);\n if (!job) return undefined;\n\n // Concurrency guard — don't run two instances simultaneously\n if (job.executing) {\n logger.warn(`[cron] Skipping manual trigger of \"${id}\" — already executing`);\n const logEntry: CronJobLogEntry = {\n jobId: id,\n startedAt: new Date().toISOString(),\n finishedAt: new Date().toISOString(),\n durationMs: 0,\n success: true,\n result: { skipped: true,\nreason: \"already_executing\" },\n logs: [\"Skipped: job is already running\"],\n manual: true\n };\n job.logs.push(logEntry);\n if (job.logs.length > MAX_LOGS_PER_JOB) job.logs.shift();\n return logEntry;\n }\n\n return this.executeJob(job, true);\n }\n\n // ─── Internal ────────────────────────────────────────────────────\n\n /**\n * Schedule the next execution for a job.\n *\n * Safety guarantees:\n * 1. Clears any existing timer first (prevents leaked/duplicate timers)\n * 2. Enforces a minimum delay to prevent tight loops from jitter\n * 3. Unref's the timer so it doesn't prevent process exit\n * 4. Re-checks enabled & started state before executing\n * 5. Concurrency guard prevents overlapping handler executions\n */\n private scheduleNext(id: string): void {\n const job = this.jobs.get(id);\n if (!job || !job.enabled || !this.started) return;\n\n // Clear any previously scheduled timer to prevent double-firing\n this.stopJob(id);\n\n try {\n const now = new Date();\n const nextRun = parseCronExpression(job.definition.schedule, now);\n job.nextRunAt = nextRun;\n\n const rawDelay = nextRun.getTime() - now.getTime();\n // Enforce a minimum delay to prevent tight re-execution loops\n // from event loop jitter or near-zero setTimeout drift\n const delay = Math.max(rawDelay, MIN_SCHEDULE_INTERVAL_MS);\n\n const timer = setTimeout(async () => {\n // Re-check state: scheduler may have been stopped or job disabled\n // between when we scheduled and when we fire\n if (!job.enabled || !this.started) return;\n\n // Concurrency guard: if somehow we're already executing, skip\n if (job.executing) {\n logger.warn(`[cron] Skipping scheduled run of \"${id}\" — still executing from previous run`);\n // Re-schedule to try again later\n this.scheduleNext(id);\n return;\n }\n\n await this.executeJob(job, false);\n\n // Schedule the next tick (only if still started + enabled)\n if (this.started && job.enabled) {\n this.scheduleNext(id);\n }\n }, delay);\n\n // Unref the timer so it doesn't prevent Node.js from exiting\n // during graceful shutdown\n if (timer && typeof timer === \"object\" && \"unref\" in timer) {\n timer.unref();\n }\n\n job.timerId = timer;\n } catch (err: unknown) {\n logger.error(`[cron] Failed to schedule \"${id}\"`, { error: err });\n job.state = \"error\";\n job.lastError = err instanceof Error ? err.message : String(err);\n }\n }\n\n /**\n * Stop a single job's timer and clear its next run state.\n */\n private stopJob(id: string): void {\n const job = this.jobs.get(id);\n if (job?.timerId) {\n clearTimeout(job.timerId);\n job.timerId = undefined;\n job.nextRunAt = undefined;\n }\n }\n\n /**\n * Execute a job's handler with full isolation and safety.\n *\n * - Sets a concurrency flag to prevent overlapping runs\n * - Wraps handler in a timeout race\n * - Captures all logs, errors, and results\n * - Persists to store (non-blocking) if available\n * - Always restores state even on catastrophic errors\n */\n private async executeJob(\n job: RegisteredJob,\n manual: boolean\n ): Promise<CronJobLogEntry> {\n const startedAt = new Date();\n const capturedLogs: string[] = [];\n\n // Set executing flag — prevents concurrent runs\n job.executing = true;\n\n const ctx: CronJobContext = {\n jobId: job.id,\n scheduledAt: startedAt,\n log: (...args: unknown[]) => {\n const line = args.map((a) =>\n typeof a === \"string\" ? a : JSON.stringify(a)\n ).join(\" \");\n capturedLogs.push(line);\n },\n client: this.client!\n };\n\n job.state = \"running\";\n job.lastRunAt = startedAt;\n job.totalRuns++;\n\n let success = true;\n let error: string | undefined;\n let result: unknown;\n\n try {\n // Race with timeout\n const timeout = (job.definition.timeoutSeconds ?? 300) * 1000;\n const handlerPromise = Promise.resolve(job.definition.handler(ctx));\n let timeoutHandle: ReturnType<typeof setTimeout>;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutHandle = setTimeout(\n () => reject(new Error(`Cron job \"${job.id}\" timed out after ${timeout}ms`)),\n timeout\n );\n });\n\n try {\n result = await Promise.race([handlerPromise, timeoutPromise]);\n } finally {\n clearTimeout(timeoutHandle!);\n }\n } catch (err: unknown) {\n success = false;\n error = err instanceof Error ? err.message : String(err);\n job.totalFailures++;\n } finally {\n // Always clear executing flag — even on catastrophic errors\n job.executing = false;\n }\n\n const finishedAt = new Date();\n const durationMs = finishedAt.getTime() - startedAt.getTime();\n\n job.state = success ? (job.enabled ? \"idle\" : \"disabled\") : \"error\";\n job.lastDurationMs = durationMs;\n job.lastError = error;\n\n const logEntry: CronJobLogEntry = {\n jobId: job.id,\n startedAt: startedAt.toISOString(),\n finishedAt: finishedAt.toISOString(),\n durationMs,\n success,\n error,\n result: result !== undefined ? result : undefined,\n logs: capturedLogs,\n manual\n };\n\n // Push to ring buffer\n job.logs.push(logEntry);\n if (job.logs.length > MAX_LOGS_PER_JOB) {\n job.logs.shift();\n }\n\n // Persist to database (non-blocking)\n if (this.store) {\n this.store.insertLog(logEntry).catch((persistErr) => {\n logger.error(`[cron] Failed to persist log for \"${job.id}\"`, { error: persistErr });\n });\n }\n\n if (success) {\n logger.info(`✅ [cron] \"${job.id}\" completed in ${durationMs}ms`);\n } else {\n logger.error(`❌ [cron] \"${job.id}\" failed in ${durationMs}ms: ${error}`);\n }\n\n return logEntry;\n }\n\n private toStatus(job: RegisteredJob): CronJobStatus {\n return {\n id: job.id,\n name: job.definition.name,\n description: job.definition.description,\n schedule: job.definition.schedule,\n enabled: job.enabled,\n state: job.state,\n lastRunAt: job.lastRunAt?.toISOString(),\n nextRunAt: job.nextRunAt?.toISOString(),\n lastDurationMs: job.lastDurationMs,\n lastError: job.lastError,\n totalRuns: job.totalRuns,\n totalFailures: job.totalFailures\n };\n }\n}\n","import { Hono } from \"hono\";\nimport type { HonoEnv } from \"../api/types\";\nimport type { CronScheduler } from \"./cron-scheduler\";\nimport { ApiError, errorHandler } from \"../api/errors\";\n\n/**\n * Create admin REST routes for managing cron jobs.\n *\n * Routes:\n * GET / → list all cron jobs\n * GET /:id → get a single job's status\n * POST /:id/trigger → manually trigger a job\n * GET /:id/logs → get execution logs for a job\n * PUT /:id → update job (enable/disable)\n */\nexport function createCronRoutes(scheduler: CronScheduler): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n // Hono's onError does NOT propagate from parent to child routers, so this\n // child router registers its own handler to format thrown ApiErrors.\n router.onError(errorHandler);\n\n // List all jobs\n router.get(\"/\", (c) => {\n const jobs = scheduler.listJobs();\n return c.json({ jobs });\n });\n\n // Get single job\n router.get(\"/:id\", (c) => {\n const id = c.req.param(\"id\");\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n return c.json({ job });\n });\n\n // Trigger a job manually\n router.post(\"/:id/trigger\", async (c) => {\n const id = c.req.param(\"id\");\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n const log = await scheduler.triggerJob(id);\n return c.json({ log,\njob: scheduler.getJob(id) });\n });\n\n // Get job logs\n router.get(\"/:id/logs\", async (c) => {\n const id = c.req.param(\"id\");\n const limitStr = c.req.query(\"limit\");\n const limit = limitStr ? parseInt(limitStr, 10) : undefined;\n\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n const logs = await scheduler.getJobLogsFromDb(id, limit);\n return c.json({ logs });\n });\n\n // Enable/disable a job\n router.put(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const body = await c.req.json().catch(() => ({})) as { enabled: boolean };\n\n if (typeof body.enabled !== \"boolean\") {\n throw ApiError.badRequest(\"Missing 'enabled' boolean in body\");\n }\n\n const job = scheduler.setJobEnabled(id, body.enabled);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n return c.json({ job });\n });\n\n return router;\n}\n","import type { CronJobLogEntry } from \"@rebasepro/types\";\nimport type { DataDriver } from \"@rebasepro/types\";\nimport { isSQLAdmin } from \"@rebasepro/types\";\nimport { logger } from \"../utils/logger.js\";\n\n/**\n * Persistence layer for cron job execution logs.\n *\n * Uses the DataDriver's `admin.executeSql` capability to store logs in a\n * `rebase.cron_logs` table. Falls back gracefully if the driver doesn't\n * support SQL (e.g. MongoDB) — in that case, no persistence occurs.\n */\nexport interface CronStore {\n /** Ensure the backing table exists. Called once on startup. */\n ensureTable(): Promise<void>;\n\n /** Persist a single log entry after execution. */\n insertLog(entry: CronJobLogEntry): Promise<void>;\n\n /**\n * Fetch the most recent logs for a job.\n * @param jobId The job identifier\n * @param limit Max entries to return (default 50)\n * @returns Logs sorted newest-first\n */\n fetchLogs(jobId: string, limit?: number): Promise<CronJobLogEntry[]>;\n\n /**\n * Fetch aggregate stats for all jobs (totalRuns, totalFailures, lastRunAt).\n * Used to seed in-memory counters on startup.\n */\n fetchJobStats(): Promise<Map<string, { totalRuns: number; totalFailures: number; lastRunAt?: string }>>;\n}\n\n// ─── SQL-based implementation ────────────────────────────────────────\n\nconst TABLE = \"rebase.cron_logs\";\n\nexport function createCronStore(driver: DataDriver): CronStore | undefined {\n const admin = driver.admin;\n if (!isSQLAdmin(admin)) {\n logger.warn(\"⚠️ [cron-store] DataDriver does not support SQL admin — cron logs will not be persisted.\");\n return undefined;\n }\n\n const exec = (sqlText: string, options?: { params?: unknown[] }) =>\n admin.executeSql(sqlText, options?.params ? { params: options.params } : undefined);\n\n return {\n async ensureTable(): Promise<void> {\n try {\n await exec(\"CREATE SCHEMA IF NOT EXISTS rebase\");\n await exec(`\n CREATE TABLE IF NOT EXISTS ${TABLE} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n job_id TEXT NOT NULL,\n started_at TIMESTAMPTZ NOT NULL,\n finished_at TIMESTAMPTZ NOT NULL,\n duration_ms INTEGER NOT NULL,\n success BOOLEAN NOT NULL DEFAULT true,\n error TEXT,\n result JSONB,\n logs JSONB,\n manual BOOLEAN NOT NULL DEFAULT false\n )\n `);\n\n await exec(`\n CREATE INDEX IF NOT EXISTS idx_cron_logs_job\n ON ${TABLE}(job_id, started_at DESC)\n `);\n\n logger.info(\"✅ Cron logs table ready\");\n } catch (err) {\n logger.error(\"❌ Failed to create cron logs table\", { error: err });\n logger.warn(\"⚠️ Continuing without cron log persistence.\");\n }\n },\n\n async insertLog(entry: CronJobLogEntry): Promise<void> {\n try {\n const resultJson = entry.result !== undefined ? JSON.stringify(entry.result) : null;\n const logsJson = entry.logs.length > 0 ? JSON.stringify(entry.logs) : null;\n\n await exec(\n `INSERT INTO ${TABLE} (job_id, started_at, finished_at, duration_ms, success, error, result, logs, manual)\n VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8::jsonb, $9)`,\n { params: [\n entry.jobId,\n entry.startedAt,\n entry.finishedAt,\n entry.durationMs,\n entry.success,\n entry.error || null,\n resultJson,\n logsJson,\n entry.manual\n ]}\n );\n } catch (err) {\n // Non-blocking — log persistence should never crash the scheduler\n logger.error(`[cron-store] Failed to persist log for \"${entry.jobId}\"`, { error: err });\n }\n },\n\n async fetchLogs(jobId: string, limit = 50): Promise<CronJobLogEntry[]> {\n try {\n const rows = await exec(\n `SELECT job_id, started_at, finished_at, duration_ms, success, error, result, logs, manual\n FROM ${TABLE}\n WHERE job_id = $1\n ORDER BY started_at DESC\n LIMIT $2`,\n { params: [jobId, limit] }\n );\n\n return rows.map(rowToLogEntry);\n } catch (err) {\n logger.error(`[cron-store] Failed to fetch logs for \"${jobId}\"`, { error: err });\n return [];\n }\n },\n\n async fetchJobStats(): Promise<Map<string, { totalRuns: number; totalFailures: number; lastRunAt?: string }>> {\n const stats = new Map<string, { totalRuns: number; totalFailures: number; lastRunAt?: string }>();\n try {\n const rows = await exec(`\n SELECT\n job_id,\n COUNT(*)::int AS total_runs,\n COUNT(*) FILTER (WHERE NOT success)::int AS total_failures,\n MAX(started_at) AS last_run_at\n FROM ${TABLE}\n GROUP BY job_id\n `);\n\n for (const row of rows) {\n stats.set(row.job_id as string, {\n totalRuns: row.total_runs as number,\n totalFailures: row.total_failures as number,\n lastRunAt: row.last_run_at ? new Date(row.last_run_at as string).toISOString() : undefined\n });\n }\n } catch (err) {\n logger.error(\"[cron-store] Failed to fetch job stats\", { error: err });\n }\n return stats;\n }\n };\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction rowToLogEntry(row: Record<string, unknown>): CronJobLogEntry {\n return {\n jobId: row.job_id as string,\n startedAt: new Date(row.started_at as string).toISOString(),\n finishedAt: new Date(row.finished_at as string).toISOString(),\n durationMs: row.duration_ms as number,\n success: row.success as boolean,\n error: (row.error as string) ?? undefined,\n result: row.result ?? undefined,\n logs: Array.isArray(row.logs) ? row.logs : (row.logs ? (() => { try { return JSON.parse(row.logs as string); } catch { return []; } })() : []),\n manual: row.manual as boolean\n };\n}\n","import { sql, SQL } from \"drizzle-orm\";\n\n/**\n * Returns a SQL chunk calling `auth.uid()` — the current user's ID.\n * This is a PostgreSQL RLS helper function created in the `auth` schema\n * that reads `app.user_id` set per-transaction by `withAuth()`.\n *\n * @example\n * sql`${table.user_id} = ${authUid()}`\n */\nexport const authUid = (): SQL => {\n return sql`auth.uid()`;\n};\n\n/**\n * Returns a SQL chunk calling `auth.roles()` — the current user's roles\n * as a comma-separated string.\n * Reads `app.user_roles` set per-transaction by `withAuth()`.\n *\n * @example\n * sql`auth.roles() ~ 'admin'`\n */\nexport const authRoles = (): SQL => {\n return sql`auth.roles()`;\n};\n\n/**\n * Returns a SQL chunk calling `auth.jwt()` — the full JWT claims as JSONB.\n * Reads `app.jwt` set per-transaction by `withAuth()`.\n *\n * @example\n * sql`auth.jwt()->>'sub'`\n */\nexport const authJwt = (): SQL => {\n return sql`auth.jwt()`;\n};\n\n\n","import { z } from \"zod\";\nimport * as crypto from \"crypto\";\nimport { logger } from \"./utils/logger\";\n\n/**\n * Generate a cryptographically secure random secret (hex-encoded).\n * Used as a fallback when secrets are not explicitly configured —\n * avoids the need for hardcoded dev secrets.\n */\nfunction generateSecret(bytes = 48): string {\n return crypto.randomBytes(bytes).toString(\"hex\");\n}\n\n/**\n * Zod coercion helper: transforms `\"true\"` → `true`, everything else → `false`.\n */\nconst boolString = z.enum([\"true\", \"false\", \"\"]).default(\"false\").transform(v => v === \"true\");\n\n/**\n * Zod coercion helper for optional boolean strings.\n */\nconst optionalBoolString = z.enum([\"true\", \"false\", \"\"]).optional().transform(v => v === \"true\");\n\n/**\n * Helper to determine if a string is a localhost or loopback address/URL.\n */\nfunction isLocalhostOrLoopback(value: string): boolean {\n const trimmed = value.trim();\n if (!trimmed) return false;\n\n // 1. Try parsing as URL\n try {\n const parsed = new URL(trimmed);\n const host = parsed.hostname.toLowerCase();\n if (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"::1\" ||\n host.startsWith(\"127.\")\n ) {\n return true;\n }\n } catch {\n // Not a standard URL, or custom protocol that URL class fails to parse\n }\n\n // 2. Custom protocol parser fallback (e.g. postgres://, mongodb://, etc.)\n const protocolMatch = trimmed.match(/^[a-zA-Z0-9+-.]+:\\/\\/(?:[^@/]+@)?(?:\\[([^\\]]+)\\]|([^:/]+))/);\n if (protocolMatch) {\n const host = (protocolMatch[1] || protocolMatch[2] || \"\").toLowerCase();\n if (\n host === \"localhost\" ||\n host === \"127.0.0.1\" ||\n host === \"::1\" ||\n host.startsWith(\"127.\")\n ) {\n return true;\n }\n }\n\n // 3. Plain hostname / host:port checker (e.g. \"localhost\", \"127.0.0.1:5432\", \"[::1]:6379\")\n let plainHost = trimmed.toLowerCase();\n if (plainHost.startsWith(\"[\") && plainHost.includes(\"]\")) {\n const endBracket = plainHost.indexOf(\"]\");\n plainHost = plainHost.slice(1, endBracket);\n } else {\n const colonIndex = plainHost.lastIndexOf(\":\");\n if (colonIndex !== -1 && plainHost.indexOf(\":\") === colonIndex) {\n plainHost = plainHost.substring(0, colonIndex);\n }\n }\n\n if (\n plainHost === \"localhost\" ||\n plainHost === \"127.0.0.1\" ||\n plainHost === \"::1\" ||\n plainHost.startsWith(\"127.\")\n ) {\n return true;\n }\n\n return false;\n}\n\n/**\n * The full set of environment variables recognized by a Rebase backend.\n */\nconst rebaseEnvSchema = z.object({\n NODE_ENV: z.enum([\"development\", \"production\", \"test\"]).default(\"development\"),\n PORT: z.string().default(\"3001\").transform(Number),\n DATABASE_URL: z.string().url(\"DATABASE_URL must be a valid URL\"),\n ADMIN_CONNECTION_STRING: z.string().url().optional(),\n JWT_SECRET: z.string().min(32, \"JWT_SECRET must be at least 32 characters long\"),\n JWT_ACCESS_EXPIRES_IN: z.string().default(\"1h\"),\n JWT_REFRESH_EXPIRES_IN: z.string().default(\"30d\"),\n GOOGLE_CLIENT_ID: z.string().optional(),\n GOOGLE_CLIENT_SECRET: z.string().optional(),\n REBASE_SERVICE_KEY: z.string().optional(),\n ALLOW_REGISTRATION: boolString,\n ALLOW_LOCALHOST_IN_PRODUCTION: optionalBoolString,\n CORS_ORIGINS: z.string().optional(),\n FRONTEND_URL: z.string().optional(),\n DB_POOL_MAX: z.string().default(\"20\").transform(Number),\n DB_POOL_IDLE_TIMEOUT: z.string().default(\"30000\").transform(Number),\n DB_POOL_CONNECT_TIMEOUT: z.string().default(\"10000\").transform(Number),\n DATABASE_DIRECT_URL: z.string().url().optional(),\n DATABASE_READ_URL: z.string().url().optional(),\n FORCE_LOCAL_STORAGE: optionalBoolString,\n STORAGE_TYPE: z.enum([\"local\", \"s3\"]).default(\"local\"),\n STORAGE_PATH: z.string().optional(),\n S3_BUCKET: z.string().optional(),\n S3_REGION: z.string().optional(),\n S3_ACCESS_KEY_ID: z.string().optional(),\n S3_SECRET_ACCESS_KEY: z.string().optional(),\n S3_ENDPOINT: z.string().url().optional(),\n S3_FORCE_PATH_STYLE: optionalBoolString\n});\n\n/** Inferred type of the validated environment. */\nexport type RebaseEnv = z.infer<typeof rebaseEnvSchema>;\n\n/**\n * Load and validate the Rebase environment configuration from `process.env`.\n *\n * Call this **after** your `.env` file has been loaded (via `dotenv`, `--env-file`,\n * container injection, etc.). This function does not load `.env` files itself —\n * that is a deployment concern, not a framework concern.\n *\n * Behavior:\n * - Auto-generates ephemeral `JWT_SECRET` and `REBASE_SERVICE_KEY` in\n * non-production mode so developers can start without manual setup.\n * - Blocks auto-generated secrets in production.\n * - Returns a fully typed, validated env object.\n *\n * Use `extend` to add your own typed env variables on top of the base Rebase schema:\n *\n * @example\n * ```ts\n * import dotenv from \"dotenv\";\n * import { z } from \"zod\";\n * import { loadEnv } from \"@rebasepro/server-core\";\n *\n * dotenv.config({ path: \"../../.env\" });\n *\n * // Basic — just Rebase env vars:\n * export const env = loadEnv();\n *\n * // Extended — add your own typed vars:\n * export const env = loadEnv({\n * extend: z.object({\n * SMTP_HOST: z.string().optional(),\n * SMTP_PORT: z.string().default(\"587\").transform(Number),\n * STRIPE_SECRET_KEY: z.string(),\n * })\n * });\n * // env.SMTP_HOST → string | undefined (fully typed)\n * // env.STRIPE_SECRET_KEY → string (validated, required)\n * ```\n */\nexport function loadEnv(): RebaseEnv;\nexport function loadEnv<E extends z.ZodObject<z.ZodRawShape>>(options: { extend: E }): RebaseEnv & z.infer<E>;\nexport function loadEnv(options?: { extend?: z.ZodObject<z.ZodRawShape> }): Record<string, unknown> {\n // Auto-generate dev secrets before validation so the Zod schema sees valid values.\n const isProduction = process.env.NODE_ENV === \"production\";\n const autoGeneratedSecrets: string[] = [];\n\n if (!isProduction) {\n if (!process.env.JWT_SECRET) {\n process.env.JWT_SECRET = generateSecret();\n autoGeneratedSecrets.push(\"JWT_SECRET\");\n }\n if (!process.env.REBASE_SERVICE_KEY) {\n process.env.REBASE_SERVICE_KEY = generateSecret();\n autoGeneratedSecrets.push(\"REBASE_SERVICE_KEY\");\n }\n }\n\n // Merge base schema with user extensions (if provided).\n const combinedSchema = options?.extend\n ? rebaseEnvSchema.merge(options.extend)\n : rebaseEnvSchema;\n\n // Validate with production-specific refinements.\n const schema = combinedSchema.superRefine((data, ctx) => {\n const d = data as RebaseEnv & Record<string, unknown>;\n if (d.NODE_ENV === \"production\" && !d.CORS_ORIGINS && !d.FRONTEND_URL) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"CORS_ORIGINS or FRONTEND_URL must be set in production to secure the API.\",\n path: [\"CORS_ORIGINS\"]\n });\n }\n if (d.NODE_ENV === \"production\" && autoGeneratedSecrets.length > 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `${autoGeneratedSecrets.join(\", \")} must be explicitly set in production. ` +\n \"Do not rely on auto-generated secrets outside development.\",\n path: [autoGeneratedSecrets[0]]\n });\n }\n if (d.NODE_ENV === \"production\" && !d.ALLOW_LOCALHOST_IN_PRODUCTION) {\n for (const [key, value] of Object.entries(data)) {\n if (key === \"CORS_ORIGINS\") continue;\n if (typeof value === \"string\" && isLocalhostOrLoopback(value)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Environment variable ${key} contains a local/loopback URL or host \"${value}\". Deployed instances must not connect to localhost.`,\n path: [key]\n });\n }\n }\n }\n });\n\n const env = schema.parse(process.env);\n\n // Warn after successful parse so the server still starts in dev.\n if (autoGeneratedSecrets.length > 0) {\n logger.warn(\n `⚠️ Auto-generated secrets for: ${autoGeneratedSecrets.join(\", \")}. ` +\n \"These are ephemeral — existing tokens will be invalidated on restart. \" +\n \"Set them explicitly in .env for persistent sessions.\"\n );\n }\n\n return env as Record<string, unknown>;\n}\n","/**\n * Dev-mode port resolution utilities.\n *\n * Provides a `listen` wrapper that automatically retries the next port when\n * the requested one is already in use, and writes the resolved port to a\n * well-known temp file so the CLI / frontend can discover it.\n *\n * Port affinity: when a port file already exists (e.g. after a tsx watch\n * restart), the saved port is tried FIRST so the backend stays on the same\n * port the frontend was configured with.\n *\n * This module is dev-only and should never run in production.\n */\nimport type { Server } from \"http\";\nimport path from \"path\";\nimport fs from \"fs\";\n\nconst MAX_PORT_ATTEMPTS = 20;\n\n/** Filename written next to the project `.env` so the CLI can read it. */\nexport const DEV_PORT_FILENAME = \".rebase-dev-port\";\n\n/**\n * Try to `listen` on `startPort`. If the port is busy (`EADDRINUSE`), increment\n * and retry up to `maxAttempts` times.\n *\n * When a port file already exists (written by a previous run), the saved port\n * is tried first to maintain port affinity across tsx watch restarts.\n *\n * Resolves with the port that was actually bound.\n *\n * @internal Not part of the stable public API. Exported only because the\n * official app template (`packages/cli/templates/template/backend/src/index.ts`\n * and `app/backend/src/index.ts`) calls it directly in dev mode. Its dev-only\n * port-affinity behavior is an implementation detail and may change without\n * a major version bump.\n */\nexport function listenWithPortRetry(\n server: Server,\n startPort: number,\n options?: {\n host?: string;\n maxAttempts?: number;\n /** Absolute path to write the resolved port file into. Defaults to `process.cwd()`. */\n portFileDir?: string;\n /** Service key to include in the state file for MCP server auto-discovery. */\n serviceKey?: string;\n }\n): Promise<number> {\n const host = options?.host ?? \"0.0.0.0\";\n const maxAttempts = options?.maxAttempts ?? MAX_PORT_ATTEMPTS;\n const portFileDir = options?.portFileDir;\n\n const isProd = process.env.NODE_ENV === \"production\";\n if (isProd) {\n return new Promise<number>((resolve, reject) => {\n const onError = (err: Error) => {\n reject(err);\n };\n server.once(\"error\", onError);\n server.listen(startPort, host, () => {\n server.removeListener(\"error\", onError);\n resolve(startPort);\n });\n });\n }\n\n // Read affinity port from a previous run's port file.\n // This ensures tsx watch restarts land on the same port the frontend was\n // configured with, even if the CLI-computed port was different.\n let affinityPort: number | null = null;\n if (portFileDir) {\n try {\n const portFile = path.join(portFileDir, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) {\n const saved = parseInt(fs.readFileSync(portFile, \"utf-8\").trim(), 10);\n if (saved > 0 && saved < 65536 && saved !== startPort) {\n affinityPort = saved;\n }\n }\n } catch { /* ignore */ }\n }\n\n return new Promise<number>((resolve, reject) => {\n let attempt = 0;\n // Build the ordered list of ports to try:\n // 1. The affinity port (if different from startPort)\n // 2. startPort, startPort+1, startPort+2, ...\n const portsToTry: number[] = [];\n if (affinityPort) portsToTry.push(affinityPort);\n for (let i = 0; i < maxAttempts; i++) {\n const p = startPort + i;\n if (p !== affinityPort) portsToTry.push(p);\n }\n\n function tryNext(index: number) {\n if (index >= portsToTry.length) {\n reject(new Error(\n \"All attempted ports are in use. \" +\n \"Stop other Rebase instances or specify a different port with --port.\"\n ));\n return;\n }\n\n const port = portsToTry[index];\n attempt++;\n\n const onError = (err: NodeJS.ErrnoException) => {\n if (err.code === \"EADDRINUSE\") {\n server.removeListener(\"error\", onError);\n tryNext(index + 1);\n } else {\n reject(err);\n }\n };\n\n server.once(\"error\", onError);\n\n server.listen(port, host, () => {\n server.removeListener(\"error\", onError);\n\n // Write the port file so the CLI can pick it up\n if (portFileDir) {\n try {\n const portFile = path.join(portFileDir, DEV_PORT_FILENAME);\n fs.writeFileSync(portFile, String(port), \"utf-8\");\n } catch {\n // Non-fatal — the CLI will fall back to parsing stdout\n }\n\n // Write .rebase/state.json so external scripts can discover\n // the running server port, URL, etc.\n writeStateFile(portFileDir, port, options?.serviceKey);\n }\n\n resolve(port);\n });\n }\n\n tryNext(0);\n });\n}\n\n/**\n * Clean up the dev port file and state file (call on graceful shutdown).\n *\n * @internal Not part of the stable public API. See {@link listenWithPortRetry}.\n */\nexport function cleanupDevPortFile(dir: string): void {\n try {\n const portFile = path.join(dir, DEV_PORT_FILENAME);\n if (fs.existsSync(portFile)) {\n fs.unlinkSync(portFile);\n }\n } catch {\n // ignore\n }\n try {\n const stateFile = path.join(dir, \".rebase\", \"state.json\");\n if (fs.existsSync(stateFile)) {\n fs.unlinkSync(stateFile);\n }\n } catch {\n // ignore\n }\n}\n\n/**\n * Write `.rebase/state.json` with runtime info for external scripts.\n *\n * Scripts can read this file to discover:\n * - `port` — the actual port the backend is listening on\n * - `baseUrl` — full URL including protocol and port\n * - `pid` — the backend process ID\n * - `startedAt` — ISO timestamp of when the server started\n * - `serviceKey` — (dev only) the REBASE_SERVICE_KEY for MCP auto-discovery\n *\n * @example Reading from a script:\n * ```ts\n * const state = JSON.parse(fs.readFileSync('.rebase/state.json', 'utf-8'));\n * const apiUrl = state.baseUrl; // \"http://localhost:3519\"\n * ```\n */\nfunction writeStateFile(projectRoot: string, port: number, serviceKey?: string): void {\n try {\n const rebaseDir = path.join(projectRoot, \".rebase\");\n if (!fs.existsSync(rebaseDir)) {\n fs.mkdirSync(rebaseDir, { recursive: true });\n }\n const stateFile = path.join(rebaseDir, \"state.json\");\n const state: Record<string, unknown> = {\n port,\n baseUrl: `http://localhost:${port}`,\n pid: process.pid,\n startedAt: new Date().toISOString()\n };\n if (serviceKey) {\n state.serviceKey = serviceKey;\n }\n fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), \"utf-8\");\n } catch {\n // Non-fatal\n }\n}\n","import { Hono } from \"hono\";\nimport { serveStatic } from \"@hono/node-server/serve-static\";\nimport * as path from \"path\";\nimport * as fs from \"fs\";\nimport fsp from \"node:fs/promises\";\nimport { logger } from \"./utils/logger.js\";\n\n/**\n * Configuration for serving a Single Page Application\n */\nexport interface ServeSPAConfig {\n /**\n * Absolute path to the frontend build directory\n * @example path.join(__dirname, \"../../frontend/dist\")\n */\n frontendPath: string;\n\n /**\n * Base path for API routes (default: \"/api\")\n * Requests to this path will be passed through to API handlers\n */\n apiBasePath?: string;\n\n /**\n * Additional paths to exclude from SPA handling\n * These paths will be passed through to other handlers\n * @example [\"/health\", \"/ws\", \"/metrics\"]\n */\n excludePaths?: string[];\n\n /**\n * Index file to serve for SPA routes (default: \"index.html\")\n */\n indexFile?: string;\n}\n\n/**\n * Serve a Single Page Application from an Hono app.\n *\n * @internal Not part of the stable public API. Exported only because the\n * official app template (`packages/cli/templates/template/backend/src/index.ts`\n * and `app/backend/src/index.ts`) calls it to serve the built frontend in\n * production. Its request-handling behavior is an implementation detail and\n * may change without a major version bump.\n */\nexport function serveSPA<E extends import(\"hono\").Env>(app: Hono<E>, config: ServeSPAConfig): void {\n const {\n frontendPath,\n apiBasePath = \"/api\",\n excludePaths = [],\n indexFile = \"index.html\"\n } = config;\n\n // Validate frontend path exists\n if (!fs.existsSync(frontendPath)) {\n logger.warn(`⚠️ Frontend build path does not exist: ${frontendPath}`);\n logger.warn(\" SPA serving is disabled. Build your frontend first.\");\n return;\n }\n\n // Serve static files from frontend build\n app.use(\"/*\", serveStatic({\n root: path.relative(process.cwd(), frontendPath)\n }));\n\n // Build list of paths to exclude from SPA handling\n const allExcludePaths = [apiBasePath, ...excludePaths];\n\n // Cache the index.html content to avoid re-reading from disk on every navigation request.\n let cachedHtml: string | null = null;\n\n // SPA fallback - serve index.html for all non-excluded routes\n app.get(\"*\", async (c, next) => {\n // Skip excluded paths (API, health checks, etc.)\n if (allExcludePaths.some(p => c.req.path.startsWith(p))) {\n return next();\n }\n\n const indexPath = path.join(frontendPath, indexFile);\n\n if (!cachedHtml) {\n try {\n cachedHtml = await fsp.readFile(indexPath, \"utf-8\");\n } catch {\n logger.warn(`⚠️ Index file not found: ${indexPath}`);\n return next();\n }\n }\n\n return c.html(cachedHtml);\n });\n\n logger.info(`✅ SPA serving enabled from: ${frontendPath}`);\n}\n\n"],"x_google_ignore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