@spfn/auth 0.1.0-alpha.87 → 0.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +1385 -1199
  2. package/dist/config.d.ts +405 -0
  3. package/dist/config.js +240 -0
  4. package/dist/config.js.map +1 -0
  5. package/dist/dto-81uR9gzF.d.ts +630 -0
  6. package/dist/errors.d.ts +196 -0
  7. package/dist/errors.js +173 -0
  8. package/dist/errors.js.map +1 -0
  9. package/dist/index.d.ts +273 -14
  10. package/dist/index.js +511 -6665
  11. package/dist/index.js.map +1 -1
  12. package/dist/nextjs/api.js +345 -0
  13. package/dist/nextjs/api.js.map +1 -0
  14. package/dist/{adapters/nextjs → nextjs}/server.d.ts +47 -65
  15. package/dist/nextjs/server.js +179 -0
  16. package/dist/nextjs/server.js.map +1 -0
  17. package/dist/server.d.ts +4328 -529
  18. package/dist/server.js +7841 -1247
  19. package/dist/server.js.map +1 -1
  20. package/migrations/{0000_familiar_firebrand.sql → 0000_mysterious_colossus.sql} +53 -23
  21. package/migrations/meta/0000_snapshot.json +281 -46
  22. package/migrations/meta/_journal.json +2 -2
  23. package/package.json +33 -33
  24. package/dist/adapters/nextjs/api.d.ts +0 -446
  25. package/dist/adapters/nextjs/api.js +0 -3279
  26. package/dist/adapters/nextjs/api.js.map +0 -1
  27. package/dist/adapters/nextjs/server.js +0 -3645
  28. package/dist/adapters/nextjs/server.js.map +0 -1
  29. package/dist/lib/api/auth-codes-verify.d.ts +0 -37
  30. package/dist/lib/api/auth-codes-verify.js +0 -2949
  31. package/dist/lib/api/auth-codes-verify.js.map +0 -1
  32. package/dist/lib/api/auth-codes.d.ts +0 -37
  33. package/dist/lib/api/auth-codes.js +0 -2949
  34. package/dist/lib/api/auth-codes.js.map +0 -1
  35. package/dist/lib/api/auth-exists.d.ts +0 -38
  36. package/dist/lib/api/auth-exists.js +0 -2949
  37. package/dist/lib/api/auth-exists.js.map +0 -1
  38. package/dist/lib/api/auth-invitations-accept.d.ts +0 -38
  39. package/dist/lib/api/auth-invitations-accept.js +0 -2883
  40. package/dist/lib/api/auth-invitations-accept.js.map +0 -1
  41. package/dist/lib/api/auth-invitations-cancel.d.ts +0 -37
  42. package/dist/lib/api/auth-invitations-cancel.js +0 -2883
  43. package/dist/lib/api/auth-invitations-cancel.js.map +0 -1
  44. package/dist/lib/api/auth-invitations-delete.d.ts +0 -36
  45. package/dist/lib/api/auth-invitations-delete.js +0 -2883
  46. package/dist/lib/api/auth-invitations-delete.js.map +0 -1
  47. package/dist/lib/api/auth-invitations-resend.d.ts +0 -37
  48. package/dist/lib/api/auth-invitations-resend.js +0 -2883
  49. package/dist/lib/api/auth-invitations-resend.js.map +0 -1
  50. package/dist/lib/api/auth-invitations.d.ts +0 -109
  51. package/dist/lib/api/auth-invitations.js +0 -2887
  52. package/dist/lib/api/auth-invitations.js.map +0 -1
  53. package/dist/lib/api/auth-keys-rotate.d.ts +0 -37
  54. package/dist/lib/api/auth-keys-rotate.js +0 -2949
  55. package/dist/lib/api/auth-keys-rotate.js.map +0 -1
  56. package/dist/lib/api/auth-login.d.ts +0 -39
  57. package/dist/lib/api/auth-login.js +0 -2949
  58. package/dist/lib/api/auth-login.js.map +0 -1
  59. package/dist/lib/api/auth-logout.d.ts +0 -36
  60. package/dist/lib/api/auth-logout.js +0 -2949
  61. package/dist/lib/api/auth-logout.js.map +0 -1
  62. package/dist/lib/api/auth-me.d.ts +0 -50
  63. package/dist/lib/api/auth-me.js +0 -2949
  64. package/dist/lib/api/auth-me.js.map +0 -1
  65. package/dist/lib/api/auth-password.d.ts +0 -36
  66. package/dist/lib/api/auth-password.js +0 -2949
  67. package/dist/lib/api/auth-password.js.map +0 -1
  68. package/dist/lib/api/auth-register.d.ts +0 -38
  69. package/dist/lib/api/auth-register.js +0 -2949
  70. package/dist/lib/api/auth-register.js.map +0 -1
  71. package/dist/lib/api/index.d.ts +0 -356
  72. package/dist/lib/api/index.js +0 -3261
  73. package/dist/lib/api/index.js.map +0 -1
  74. package/dist/lib/config.d.ts +0 -70
  75. package/dist/lib/config.js +0 -64
  76. package/dist/lib/config.js.map +0 -1
  77. package/dist/lib/contracts/auth.d.ts +0 -302
  78. package/dist/lib/contracts/auth.js +0 -2951
  79. package/dist/lib/contracts/auth.js.map +0 -1
  80. package/dist/lib/contracts/index.d.ts +0 -3
  81. package/dist/lib/contracts/index.js +0 -3190
  82. package/dist/lib/contracts/index.js.map +0 -1
  83. package/dist/lib/contracts/invitation.d.ts +0 -243
  84. package/dist/lib/contracts/invitation.js +0 -2883
  85. package/dist/lib/contracts/invitation.js.map +0 -1
  86. package/dist/lib/crypto.d.ts +0 -76
  87. package/dist/lib/crypto.js +0 -127
  88. package/dist/lib/crypto.js.map +0 -1
  89. package/dist/lib/index.d.ts +0 -4
  90. package/dist/lib/index.js +0 -313
  91. package/dist/lib/index.js.map +0 -1
  92. package/dist/lib/session.d.ts +0 -68
  93. package/dist/lib/session.js +0 -126
  94. package/dist/lib/session.js.map +0 -1
  95. package/dist/lib/types/api.d.ts +0 -45
  96. package/dist/lib/types/api.js +0 -1
  97. package/dist/lib/types/api.js.map +0 -1
  98. package/dist/lib/types/index.d.ts +0 -3
  99. package/dist/lib/types/index.js +0 -2647
  100. package/dist/lib/types/index.js.map +0 -1
  101. package/dist/lib/types/schemas.d.ts +0 -45
  102. package/dist/lib/types/schemas.js +0 -2647
  103. package/dist/lib/types/schemas.js.map +0 -1
  104. package/dist/lib.js +0 -1
  105. package/dist/lib.js.map +0 -1
  106. package/dist/plugin.d.ts +0 -12
  107. package/dist/plugin.js +0 -9083
  108. package/dist/plugin.js.map +0 -1
  109. package/dist/server/entities/index.d.ts +0 -11
  110. package/dist/server/entities/index.js +0 -395
  111. package/dist/server/entities/index.js.map +0 -1
  112. package/dist/server/entities/invitations.d.ts +0 -241
  113. package/dist/server/entities/invitations.js +0 -184
  114. package/dist/server/entities/invitations.js.map +0 -1
  115. package/dist/server/entities/permissions.d.ts +0 -196
  116. package/dist/server/entities/permissions.js +0 -49
  117. package/dist/server/entities/permissions.js.map +0 -1
  118. package/dist/server/entities/role-permissions.d.ts +0 -107
  119. package/dist/server/entities/role-permissions.js +0 -115
  120. package/dist/server/entities/role-permissions.js.map +0 -1
  121. package/dist/server/entities/roles.d.ts +0 -196
  122. package/dist/server/entities/roles.js +0 -50
  123. package/dist/server/entities/roles.js.map +0 -1
  124. package/dist/server/entities/schema.d.ts +0 -14
  125. package/dist/server/entities/schema.js +0 -7
  126. package/dist/server/entities/schema.js.map +0 -1
  127. package/dist/server/entities/user-permissions.d.ts +0 -163
  128. package/dist/server/entities/user-permissions.js +0 -193
  129. package/dist/server/entities/user-permissions.js.map +0 -1
  130. package/dist/server/entities/user-public-keys.d.ts +0 -227
  131. package/dist/server/entities/user-public-keys.js +0 -156
  132. package/dist/server/entities/user-public-keys.js.map +0 -1
  133. package/dist/server/entities/user-social-accounts.d.ts +0 -189
  134. package/dist/server/entities/user-social-accounts.js +0 -149
  135. package/dist/server/entities/user-social-accounts.js.map +0 -1
  136. package/dist/server/entities/users.d.ts +0 -235
  137. package/dist/server/entities/users.js +0 -117
  138. package/dist/server/entities/users.js.map +0 -1
  139. package/dist/server/entities/verification-codes.d.ts +0 -191
  140. package/dist/server/entities/verification-codes.js +0 -49
  141. package/dist/server/entities/verification-codes.js.map +0 -1
  142. package/dist/server/routes/auth/index.d.ts +0 -10
  143. package/dist/server/routes/auth/index.js +0 -4460
  144. package/dist/server/routes/auth/index.js.map +0 -1
  145. package/dist/server/routes/index.d.ts +0 -6
  146. package/dist/server/routes/index.js +0 -6584
  147. package/dist/server/routes/index.js.map +0 -1
  148. package/dist/server/routes/invitations/index.d.ts +0 -10
  149. package/dist/server/routes/invitations/index.js +0 -4395
  150. package/dist/server/routes/invitations/index.js.map +0 -1
  151. /package/dist/{lib.d.ts → nextjs/api.d.ts} +0 -0
@@ -1,4460 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __esm = (fn, res) => function __init() {
4
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
- };
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
-
11
- // src/server/entities/schema.ts
12
- import { createFunctionSchema } from "@spfn/core/db";
13
- var authSchema;
14
- var init_schema = __esm({
15
- "src/server/entities/schema.ts"() {
16
- "use strict";
17
- authSchema = createFunctionSchema("@spfn/auth");
18
- }
19
- });
20
-
21
- // src/server/entities/verification-codes.ts
22
- import { text, timestamp, index } from "drizzle-orm/pg-core";
23
- import { id, timestamps } from "@spfn/core/db";
24
- var verificationCodes;
25
- var init_verification_codes = __esm({
26
- "src/server/entities/verification-codes.ts"() {
27
- "use strict";
28
- init_schema();
29
- verificationCodes = authSchema.table(
30
- "verification_codes",
31
- {
32
- id: id(),
33
- // Target (email or phone)
34
- target: text("target").notNull(),
35
- // Email address or E.164 phone number
36
- targetType: text(
37
- "target_type",
38
- {
39
- enum: ["email", "phone"]
40
- }
41
- ).notNull(),
42
- // Code
43
- code: text("code").notNull(),
44
- // 6-digit code by default (configurable)
45
- // Purpose
46
- purpose: text(
47
- "purpose",
48
- {
49
- enum: ["registration", "login", "password_reset", "email_change", "phone_change"]
50
- }
51
- ).notNull(),
52
- // Expiry
53
- expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
54
- // Usage tracking
55
- usedAt: timestamp("used_at", { withTimezone: true }),
56
- attempts: text("attempts").notNull().default("0"),
57
- // Track failed verification attempts
58
- ...timestamps()
59
- },
60
- (table) => [
61
- // Index for quick lookup by target and purpose
62
- index("target_purpose_idx").on(table.target, table.purpose, table.expiresAt)
63
- ]
64
- );
65
- }
66
- });
67
-
68
- // src/server/entities/roles.ts
69
- import { text as text2, boolean, integer, index as index2 } from "drizzle-orm/pg-core";
70
- import { id as id2, timestamps as timestamps2 } from "@spfn/core/db";
71
- var roles;
72
- var init_roles = __esm({
73
- "src/server/entities/roles.ts"() {
74
- "use strict";
75
- init_schema();
76
- roles = authSchema.table(
77
- "roles",
78
- {
79
- // Primary key
80
- id: id2(),
81
- // Role identifier (used in code, e.g., 'admin', 'editor')
82
- // Must be unique, lowercase, kebab-case recommended
83
- name: text2("name").notNull().unique(),
84
- // Display name for UI (e.g., 'Administrator', 'Content Editor')
85
- displayName: text2("display_name").notNull(),
86
- // Role description
87
- description: text2("description"),
88
- // Built-in role flag
89
- // true: Core package roles (user, admin, superadmin) - cannot be deleted
90
- // false: Custom or preset roles - can be deleted
91
- isBuiltin: boolean("is_builtin").notNull().default(false),
92
- // System role flag
93
- // true: Defined in code (builtin or preset) - deletion restricted
94
- // false: Runtime created custom role - fully manageable
95
- isSystem: boolean("is_system").notNull().default(false),
96
- // Active status
97
- // false: Deactivated role (users cannot be assigned)
98
- isActive: boolean("is_active").notNull().default(true),
99
- // Priority level (higher = more privileged)
100
- // superadmin: 100, admin: 80, user: 10
101
- // Used for role hierarchy and conflict resolution
102
- priority: integer("priority").notNull().default(10),
103
- ...timestamps2()
104
- },
105
- (table) => [
106
- index2("roles_name_idx").on(table.name),
107
- index2("roles_is_system_idx").on(table.isSystem),
108
- index2("roles_is_active_idx").on(table.isActive),
109
- index2("roles_is_builtin_idx").on(table.isBuiltin),
110
- index2("roles_priority_idx").on(table.priority)
111
- ]
112
- );
113
- }
114
- });
115
-
116
- // src/server/entities/users.ts
117
- import { text as text3, timestamp as timestamp2, check, boolean as boolean2, bigint, index as index3 } from "drizzle-orm/pg-core";
118
- import { id as id3, timestamps as timestamps3 } from "@spfn/core/db";
119
- import { sql } from "drizzle-orm";
120
- var users;
121
- var init_users = __esm({
122
- "src/server/entities/users.ts"() {
123
- "use strict";
124
- init_roles();
125
- init_schema();
126
- users = authSchema.table(
127
- "users",
128
- {
129
- // Identity
130
- id: id3(),
131
- // Email address (unique identifier)
132
- // Used for: login, password reset, notifications
133
- email: text3("email").unique(),
134
- // Phone number in E.164 international format
135
- // Format: +[country code][number] (e.g., +821012345678)
136
- // Used for: SMS login, 2FA, notifications
137
- phone: text3("phone").unique(),
138
- // Authentication
139
- // Bcrypt password hash ($2b$10$[salt][hash], 60 chars)
140
- // Nullable to support OAuth-only accounts
141
- passwordHash: text3("password_hash"),
142
- // Force password change on next login
143
- // Use cases: initial setup, security breach, policy violation
144
- passwordChangeRequired: boolean2("password_change_required").notNull().default(false),
145
- // Authorization (Role-Based Access Control)
146
- // Foreign key to roles table
147
- // References built-in roles: user (default), admin, superadmin
148
- // Can also reference custom roles created at runtime
149
- roleId: bigint("role_id", { mode: "number" }).references(() => roles.id).notNull(),
150
- // Account status
151
- // - active: Normal operation (default)
152
- // - inactive: Deactivated (user request, dormant)
153
- // - suspended: Locked (security incident, ToS violation)
154
- status: text3(
155
- "status",
156
- {
157
- enum: ["active", "inactive", "suspended"]
158
- }
159
- ).notNull().default("active"),
160
- // Verification timestamps
161
- // null = unverified, timestamp = verified at this time
162
- // Email verification (via verification code or magic link)
163
- emailVerifiedAt: timestamp2("email_verified_at", { withTimezone: true }),
164
- // Phone verification (via SMS OTP)
165
- phoneVerifiedAt: timestamp2("phone_verified_at", { withTimezone: true }),
166
- // Metadata
167
- // Last successful login timestamp
168
- // Used for: security auditing, dormant account detection
169
- lastLoginAt: timestamp2("last_login_at", { withTimezone: true }),
170
- ...timestamps3()
171
- },
172
- (table) => [
173
- // Database constraints
174
- // Ensure at least one identifier exists (email OR phone)
175
- check(
176
- "email_or_phone_check",
177
- sql`${table.email} IS NOT NULL OR ${table.phone} IS NOT NULL`
178
- ),
179
- // Indexes for query optimization
180
- index3("users_email_idx").on(table.email),
181
- index3("users_phone_idx").on(table.phone),
182
- index3("users_status_idx").on(table.status),
183
- index3("users_role_id_idx").on(table.roleId)
184
- ]
185
- );
186
- }
187
- });
188
-
189
- // src/server/entities/user-social-accounts.ts
190
- import { text as text4, timestamp as timestamp3, uniqueIndex } from "drizzle-orm/pg-core";
191
- import { id as id4, timestamps as timestamps4, foreignKey } from "@spfn/core/db";
192
- var userSocialAccounts;
193
- var init_user_social_accounts = __esm({
194
- "src/server/entities/user-social-accounts.ts"() {
195
- "use strict";
196
- init_users();
197
- init_schema();
198
- userSocialAccounts = authSchema.table(
199
- "user_social_accounts",
200
- {
201
- id: id4(),
202
- // Foreign key to users
203
- userId: foreignKey("user", () => users.id),
204
- // Provider info
205
- provider: text4(
206
- "provider",
207
- {
208
- enum: ["google", "github", "kakao", "naver"]
209
- }
210
- ).notNull(),
211
- providerUserId: text4("provider_user_id").notNull(),
212
- providerEmail: text4("provider_email"),
213
- // OAuth tokens (encrypted in production)
214
- accessToken: text4("access_token"),
215
- refreshToken: text4("refresh_token"),
216
- tokenExpiresAt: timestamp3("token_expires_at", { withTimezone: true }),
217
- ...timestamps4()
218
- },
219
- (table) => [
220
- // Unique constraint: one provider account per provider
221
- uniqueIndex("provider_user_unique_idx").on(table.provider, table.providerUserId)
222
- ]
223
- );
224
- }
225
- });
226
-
227
- // src/server/entities/user-public-keys.ts
228
- import { text as text5, timestamp as timestamp4, boolean as boolean3, index as index4 } from "drizzle-orm/pg-core";
229
- import { id as id5, foreignKey as foreignKey2 } from "@spfn/core/db";
230
- var userPublicKeys;
231
- var init_user_public_keys = __esm({
232
- "src/server/entities/user-public-keys.ts"() {
233
- "use strict";
234
- init_users();
235
- init_schema();
236
- userPublicKeys = authSchema.table(
237
- "user_public_keys",
238
- {
239
- id: id5(),
240
- // User reference
241
- userId: foreignKey2("user", () => users.id),
242
- // Key identification (client-generated UUID)
243
- keyId: text5("key_id").notNull().unique(),
244
- // Public key in Base64-encoded DER format (SPKI)
245
- publicKey: text5("public_key").notNull(),
246
- // Algorithm used (ES256 recommended, RS256 fallback)
247
- algorithm: text5("algorithm", {
248
- enum: ["ES256", "RS256"]
249
- }).notNull().default("ES256"),
250
- // Key fingerprint (SHA-256 hash for quick identification)
251
- fingerprint: text5("fingerprint").notNull(),
252
- // Key status
253
- isActive: boolean3("is_active").notNull().default(true),
254
- // Timestamps
255
- createdAt: timestamp4("created_at", { mode: "date", withTimezone: true }).notNull().defaultNow(),
256
- lastUsedAt: timestamp4("last_used_at", { mode: "date", withTimezone: true }),
257
- expiresAt: timestamp4("expires_at", { mode: "date", withTimezone: true }),
258
- // Revocation
259
- revokedAt: timestamp4("revoked_at", { mode: "date", withTimezone: true }),
260
- revokedReason: text5("revoked_reason")
261
- },
262
- (table) => [
263
- index4("user_public_keys_user_id_idx").on(table.userId),
264
- index4("user_public_keys_key_id_idx").on(table.keyId),
265
- index4("user_public_keys_active_idx").on(table.isActive),
266
- index4("user_public_keys_fingerprint_idx").on(table.fingerprint)
267
- ]
268
- );
269
- }
270
- });
271
-
272
- // src/server/entities/invitations.ts
273
- import { text as text6, timestamp as timestamp5, bigint as bigint2, index as index5, jsonb } from "drizzle-orm/pg-core";
274
- import { id as id6, timestamps as timestamps5 } from "@spfn/core/db";
275
- var invitations;
276
- var init_invitations = __esm({
277
- "src/server/entities/invitations.ts"() {
278
- "use strict";
279
- init_roles();
280
- init_users();
281
- init_schema();
282
- invitations = authSchema.table(
283
- "user_invitations",
284
- {
285
- // Primary key
286
- id: id6(),
287
- // Target email address for the invitation
288
- // Will become the user's email upon acceptance
289
- email: text6("email").notNull(),
290
- // Unique invitation token (UUID v4)
291
- // Used in invitation URL: /auth/invite/{token}
292
- // Single-use token that expires after acceptance
293
- token: text6("token").notNull().unique(),
294
- // Role to be assigned when invitation is accepted
295
- // Foreign key to roles table
296
- roleId: bigint2("role_id", { mode: "number" }).references(() => roles.id).notNull(),
297
- // User who created this invitation
298
- // Foreign key to users table
299
- // Used for: audit trail, permission checks
300
- invitedBy: bigint2("invited_by", { mode: "number" }).references(() => users.id).notNull(),
301
- // Invitation status
302
- // - pending: Invitation sent, awaiting acceptance
303
- // - accepted: User accepted and account created
304
- // - expired: Invitation expired (automatic)
305
- // - cancelled: Invitation cancelled by admin
306
- status: text6(
307
- "status",
308
- {
309
- enum: ["pending", "accepted", "expired", "cancelled"]
310
- }
311
- ).notNull().default("pending"),
312
- // Expiration timestamp (default: 7 days from creation)
313
- // Invitation cannot be accepted after this time
314
- // Background job should update status to 'expired'
315
- expiresAt: timestamp5("expires_at", { withTimezone: true }).notNull(),
316
- // Timestamp when invitation was accepted
317
- // null = not yet accepted
318
- // Used for: audit trail, analytics
319
- acceptedAt: timestamp5("accepted_at", { withTimezone: true }),
320
- // Timestamp when invitation was cancelled
321
- // null = not cancelled
322
- // Used for: audit trail
323
- cancelledAt: timestamp5("cancelled_at", { withTimezone: true }),
324
- // Additional metadata (JSONB)
325
- // Use cases:
326
- // - Custom welcome message
327
- // - Onboarding instructions
328
- // - Team/department assignment
329
- // - Custom fields for app-specific data
330
- // Example: { message: "Welcome!", department: "Engineering" }
331
- metadata: jsonb("metadata"),
332
- ...timestamps5()
333
- },
334
- (table) => [
335
- // Indexes for query optimization
336
- index5("invitations_token_idx").on(table.token),
337
- index5("invitations_email_idx").on(table.email),
338
- index5("invitations_status_idx").on(table.status),
339
- index5("invitations_invited_by_idx").on(table.invitedBy),
340
- index5("invitations_expires_at_idx").on(table.expiresAt),
341
- // For cleanup jobs
342
- index5("invitations_role_id_idx").on(table.roleId)
343
- ]
344
- );
345
- }
346
- });
347
-
348
- // src/server/entities/permissions.ts
349
- import { text as text7, boolean as boolean4, index as index6 } from "drizzle-orm/pg-core";
350
- import { id as id7, timestamps as timestamps6 } from "@spfn/core/db";
351
- var permissions;
352
- var init_permissions = __esm({
353
- "src/server/entities/permissions.ts"() {
354
- "use strict";
355
- init_schema();
356
- permissions = authSchema.table(
357
- "permissions",
358
- {
359
- // Primary key
360
- id: id7(),
361
- // Permission identifier (e.g., 'user:delete', 'post:publish')
362
- // Format: resource:action or namespace:resource:action
363
- // Must be unique
364
- name: text7("name").notNull().unique(),
365
- // Display name for UI
366
- displayName: text7("display_name").notNull(),
367
- // Permission description
368
- description: text7("description"),
369
- // Category for grouping (e.g., 'user', 'post', 'admin', 'system')
370
- category: text7("category"),
371
- // Built-in permission flag
372
- // true: Core package permissions - cannot be deleted
373
- // false: Custom or preset permissions
374
- isBuiltin: boolean4("is_builtin").notNull().default(false),
375
- // System permission flag
376
- // true: Defined in code (builtin or preset)
377
- // false: Runtime created custom permission
378
- isSystem: boolean4("is_system").notNull().default(false),
379
- // Active status
380
- // false: Deactivated permission (not enforced)
381
- isActive: boolean4("is_active").notNull().default(true),
382
- ...timestamps6()
383
- },
384
- (table) => [
385
- index6("permissions_name_idx").on(table.name),
386
- index6("permissions_category_idx").on(table.category),
387
- index6("permissions_is_system_idx").on(table.isSystem),
388
- index6("permissions_is_active_idx").on(table.isActive),
389
- index6("permissions_is_builtin_idx").on(table.isBuiltin)
390
- ]
391
- );
392
- }
393
- });
394
-
395
- // src/server/entities/role-permissions.ts
396
- import { bigint as bigint3, index as index7, unique } from "drizzle-orm/pg-core";
397
- import { id as id8, timestamps as timestamps7 } from "@spfn/core/db";
398
- var rolePermissions;
399
- var init_role_permissions = __esm({
400
- "src/server/entities/role-permissions.ts"() {
401
- "use strict";
402
- init_roles();
403
- init_permissions();
404
- init_schema();
405
- rolePermissions = authSchema.table(
406
- "role_permissions",
407
- {
408
- // Primary key
409
- id: id8(),
410
- // Foreign key to roles table
411
- roleId: bigint3("role_id", { mode: "number" }).notNull().references(() => roles.id, { onDelete: "cascade" }),
412
- // Foreign key to permissions table
413
- permissionId: bigint3("permission_id", { mode: "number" }).notNull().references(() => permissions.id, { onDelete: "cascade" }),
414
- ...timestamps7()
415
- },
416
- (table) => [
417
- // Indexes for query performance
418
- index7("role_permissions_role_id_idx").on(table.roleId),
419
- index7("role_permissions_permission_id_idx").on(table.permissionId),
420
- // Unique constraint: one role-permission pair only
421
- unique("role_permissions_unique").on(table.roleId, table.permissionId)
422
- ]
423
- );
424
- }
425
- });
426
-
427
- // src/server/entities/user-permissions.ts
428
- import { bigint as bigint4, boolean as boolean5, text as text8, timestamp as timestamp6, index as index8, unique as unique2 } from "drizzle-orm/pg-core";
429
- import { id as id9, timestamps as timestamps8 } from "@spfn/core/db";
430
- var userPermissions;
431
- var init_user_permissions = __esm({
432
- "src/server/entities/user-permissions.ts"() {
433
- "use strict";
434
- init_users();
435
- init_permissions();
436
- init_schema();
437
- userPermissions = authSchema.table(
438
- "user_permissions",
439
- {
440
- // Primary key
441
- id: id9(),
442
- // Foreign key to users table
443
- userId: bigint4("user_id", { mode: "number" }).notNull().references(() => users.id, { onDelete: "cascade" }),
444
- // Foreign key to permissions table
445
- permissionId: bigint4("permission_id", { mode: "number" }).notNull().references(() => permissions.id, { onDelete: "cascade" }),
446
- // Grant or revoke
447
- // true: Grant this permission (even if role doesn't have it)
448
- // false: Revoke this permission (even if role has it)
449
- granted: boolean5("granted").notNull().default(true),
450
- // Reason for grant/revocation (audit trail)
451
- reason: text8("reason"),
452
- // Expiration timestamp (optional)
453
- // null: Permanent override
454
- // timestamp: Permission expires at this time
455
- expiresAt: timestamp6("expires_at", { withTimezone: true }),
456
- ...timestamps8()
457
- },
458
- (table) => [
459
- // Indexes for query performance
460
- index8("user_permissions_user_id_idx").on(table.userId),
461
- index8("user_permissions_permission_id_idx").on(table.permissionId),
462
- index8("user_permissions_expires_at_idx").on(table.expiresAt),
463
- // Unique constraint: one user-permission pair only
464
- unique2("user_permissions_unique").on(table.userId, table.permissionId)
465
- ]
466
- );
467
- }
468
- });
469
-
470
- // src/server/entities/index.ts
471
- var init_entities = __esm({
472
- "src/server/entities/index.ts"() {
473
- "use strict";
474
- init_schema();
475
- init_users();
476
- init_user_social_accounts();
477
- init_user_public_keys();
478
- init_verification_codes();
479
- init_invitations();
480
- init_roles();
481
- init_permissions();
482
- init_role_permissions();
483
- init_user_permissions();
484
- }
485
- });
486
-
487
- // src/server/services/role.service.ts
488
- var role_service_exports = {};
489
- __export(role_service_exports, {
490
- addPermissionToRole: () => addPermissionToRole,
491
- createRole: () => createRole,
492
- deleteRole: () => deleteRole,
493
- getAllRoles: () => getAllRoles,
494
- getRoleByName: () => getRoleByName,
495
- getRolePermissions: () => getRolePermissions,
496
- removePermissionFromRole: () => removePermissionFromRole,
497
- setRolePermissions: () => setRolePermissions,
498
- updateRole: () => updateRole
499
- });
500
- import { getDatabase as getDatabase3 } from "@spfn/core/db";
501
- import { eq as eq3, and as and3 } from "drizzle-orm";
502
- async function createRole(data) {
503
- const db = getDatabase3();
504
- if (!db) {
505
- throw new Error("[Auth] Database not initialized");
506
- }
507
- const existing = await db.select().from(roles).where(eq3(roles.name, data.name)).limit(1);
508
- if (existing.length > 0) {
509
- throw new Error(`Role with name '${data.name}' already exists`);
510
- }
511
- const [newRole] = await db.insert(roles).values({
512
- name: data.name,
513
- displayName: data.displayName,
514
- description: data.description,
515
- priority: data.priority ?? 10,
516
- isSystem: false,
517
- // Custom roles are never system roles
518
- isBuiltin: false
519
- }).returning();
520
- if (data.permissionIds && data.permissionIds.length > 0) {
521
- const mappings = data.permissionIds.map((permId) => ({
522
- roleId: newRole.id,
523
- permissionId: Number(permId)
524
- }));
525
- await db.insert(rolePermissions).values(mappings);
526
- }
527
- console.log(`[Auth] \u2705 Created custom role: ${data.name}`);
528
- return newRole;
529
- }
530
- async function updateRole(roleId, data) {
531
- const db = getDatabase3();
532
- if (!db) {
533
- throw new Error("[Auth] Database not initialized");
534
- }
535
- const roleIdNum = Number(roleId);
536
- const [role] = await db.select().from(roles).where(eq3(roles.id, roleIdNum)).limit(1);
537
- if (!role) {
538
- throw new Error("Role not found");
539
- }
540
- if (role.isBuiltin && data.priority !== void 0) {
541
- throw new Error("Cannot modify priority of built-in roles");
542
- }
543
- const [updated] = await db.update(roles).set(data).where(eq3(roles.id, roleIdNum)).returning();
544
- return updated;
545
- }
546
- async function deleteRole(roleId) {
547
- const db = getDatabase3();
548
- if (!db) {
549
- throw new Error("[Auth] Database not initialized");
550
- }
551
- const roleIdNum = Number(roleId);
552
- const [role] = await db.select().from(roles).where(eq3(roles.id, roleIdNum)).limit(1);
553
- if (!role) {
554
- throw new Error("Role not found");
555
- }
556
- if (role.isBuiltin) {
557
- throw new Error(`Cannot delete built-in role: ${role.name}`);
558
- }
559
- if (role.isSystem) {
560
- throw new Error(`Cannot delete system role: ${role.name}. Deactivate it instead.`);
561
- }
562
- await db.delete(roles).where(eq3(roles.id, roleIdNum));
563
- console.log(`[Auth] \u{1F5D1}\uFE0F Deleted role: ${role.name}`);
564
- }
565
- async function addPermissionToRole(roleId, permissionId) {
566
- const db = getDatabase3();
567
- if (!db) {
568
- throw new Error("[Auth] Database not initialized");
569
- }
570
- const roleIdNum = Number(roleId);
571
- const permissionIdNum = Number(permissionId);
572
- const existing = await db.select().from(rolePermissions).where(
573
- and3(
574
- eq3(rolePermissions.roleId, roleIdNum),
575
- eq3(rolePermissions.permissionId, permissionIdNum)
576
- )
577
- ).limit(1);
578
- if (existing.length > 0) {
579
- return;
580
- }
581
- await db.insert(rolePermissions).values({
582
- roleId: roleIdNum,
583
- permissionId: permissionIdNum
584
- });
585
- }
586
- async function removePermissionFromRole(roleId, permissionId) {
587
- const db = getDatabase3();
588
- if (!db) {
589
- throw new Error("[Auth] Database not initialized");
590
- }
591
- const roleIdNum = Number(roleId);
592
- const permissionIdNum = Number(permissionId);
593
- await db.delete(rolePermissions).where(
594
- and3(
595
- eq3(rolePermissions.roleId, roleIdNum),
596
- eq3(rolePermissions.permissionId, permissionIdNum)
597
- )
598
- );
599
- }
600
- async function setRolePermissions(roleId, permissionIds) {
601
- const db = getDatabase3();
602
- if (!db) {
603
- throw new Error("[Auth] Database not initialized");
604
- }
605
- const roleIdNum = Number(roleId);
606
- await db.delete(rolePermissions).where(eq3(rolePermissions.roleId, roleIdNum));
607
- if (permissionIds.length > 0) {
608
- const mappings = permissionIds.map((permId) => ({
609
- roleId: roleIdNum,
610
- permissionId: Number(permId)
611
- }));
612
- await db.insert(rolePermissions).values(mappings);
613
- }
614
- }
615
- async function getAllRoles(includeInactive = false) {
616
- const db = getDatabase3();
617
- if (!db) {
618
- throw new Error("[Auth] Database not initialized");
619
- }
620
- const query = db.select().from(roles);
621
- if (!includeInactive) {
622
- return query.where(eq3(roles.isActive, true));
623
- }
624
- return query;
625
- }
626
- async function getRoleByName(name) {
627
- const db = getDatabase3();
628
- if (!db) {
629
- throw new Error("[Auth] Database not initialized");
630
- }
631
- const [role] = await db.select().from(roles).where(eq3(roles.name, name)).limit(1);
632
- return role || null;
633
- }
634
- async function getRolePermissions(roleId) {
635
- const db = getDatabase3();
636
- if (!db) {
637
- throw new Error("[Auth] Database not initialized");
638
- }
639
- const roleIdNum = Number(roleId);
640
- const perms = await db.select({ name: permissions.name }).from(rolePermissions).innerJoin(permissions, eq3(rolePermissions.permissionId, permissions.id)).where(eq3(rolePermissions.roleId, roleIdNum));
641
- return perms.map((p) => p.name);
642
- }
643
- var init_role_service = __esm({
644
- "src/server/services/role.service.ts"() {
645
- "use strict";
646
- init_entities();
647
- }
648
- });
649
-
650
- // src/server/routes/auth/index.ts
651
- import { createApp } from "@spfn/core/route";
652
-
653
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/guard/value.mjs
654
- var value_exports = {};
655
- __export(value_exports, {
656
- HasPropertyKey: () => HasPropertyKey,
657
- IsArray: () => IsArray,
658
- IsAsyncIterator: () => IsAsyncIterator,
659
- IsBigInt: () => IsBigInt,
660
- IsBoolean: () => IsBoolean,
661
- IsDate: () => IsDate,
662
- IsFunction: () => IsFunction,
663
- IsIterator: () => IsIterator,
664
- IsNull: () => IsNull,
665
- IsNumber: () => IsNumber,
666
- IsObject: () => IsObject,
667
- IsRegExp: () => IsRegExp,
668
- IsString: () => IsString,
669
- IsSymbol: () => IsSymbol,
670
- IsUint8Array: () => IsUint8Array,
671
- IsUndefined: () => IsUndefined
672
- });
673
- function HasPropertyKey(value, key) {
674
- return key in value;
675
- }
676
- function IsAsyncIterator(value) {
677
- return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.asyncIterator in value;
678
- }
679
- function IsArray(value) {
680
- return Array.isArray(value);
681
- }
682
- function IsBigInt(value) {
683
- return typeof value === "bigint";
684
- }
685
- function IsBoolean(value) {
686
- return typeof value === "boolean";
687
- }
688
- function IsDate(value) {
689
- return value instanceof globalThis.Date;
690
- }
691
- function IsFunction(value) {
692
- return typeof value === "function";
693
- }
694
- function IsIterator(value) {
695
- return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.iterator in value;
696
- }
697
- function IsNull(value) {
698
- return value === null;
699
- }
700
- function IsNumber(value) {
701
- return typeof value === "number";
702
- }
703
- function IsObject(value) {
704
- return typeof value === "object" && value !== null;
705
- }
706
- function IsRegExp(value) {
707
- return value instanceof globalThis.RegExp;
708
- }
709
- function IsString(value) {
710
- return typeof value === "string";
711
- }
712
- function IsSymbol(value) {
713
- return typeof value === "symbol";
714
- }
715
- function IsUint8Array(value) {
716
- return value instanceof globalThis.Uint8Array;
717
- }
718
- function IsUndefined(value) {
719
- return value === void 0;
720
- }
721
-
722
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs
723
- function ArrayType(value) {
724
- return value.map((value2) => Visit(value2));
725
- }
726
- function DateType(value) {
727
- return new Date(value.getTime());
728
- }
729
- function Uint8ArrayType(value) {
730
- return new Uint8Array(value);
731
- }
732
- function RegExpType(value) {
733
- return new RegExp(value.source, value.flags);
734
- }
735
- function ObjectType(value) {
736
- const result = {};
737
- for (const key of Object.getOwnPropertyNames(value)) {
738
- result[key] = Visit(value[key]);
739
- }
740
- for (const key of Object.getOwnPropertySymbols(value)) {
741
- result[key] = Visit(value[key]);
742
- }
743
- return result;
744
- }
745
- function Visit(value) {
746
- return IsArray(value) ? ArrayType(value) : IsDate(value) ? DateType(value) : IsUint8Array(value) ? Uint8ArrayType(value) : IsRegExp(value) ? RegExpType(value) : IsObject(value) ? ObjectType(value) : value;
747
- }
748
- function Clone(value) {
749
- return Visit(value);
750
- }
751
-
752
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs
753
- function CloneType(schema, options) {
754
- return options === void 0 ? Clone(schema) : Clone({ ...options, ...schema });
755
- }
756
-
757
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs
758
- function IsObject2(value) {
759
- return value !== null && typeof value === "object";
760
- }
761
- function IsArray2(value) {
762
- return globalThis.Array.isArray(value) && !globalThis.ArrayBuffer.isView(value);
763
- }
764
- function IsUndefined2(value) {
765
- return value === void 0;
766
- }
767
- function IsNumber2(value) {
768
- return typeof value === "number";
769
- }
770
-
771
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/system/policy.mjs
772
- var TypeSystemPolicy;
773
- (function(TypeSystemPolicy2) {
774
- TypeSystemPolicy2.InstanceMode = "default";
775
- TypeSystemPolicy2.ExactOptionalPropertyTypes = false;
776
- TypeSystemPolicy2.AllowArrayObject = false;
777
- TypeSystemPolicy2.AllowNaN = false;
778
- TypeSystemPolicy2.AllowNullVoid = false;
779
- function IsExactOptionalProperty(value, key) {
780
- return TypeSystemPolicy2.ExactOptionalPropertyTypes ? key in value : value[key] !== void 0;
781
- }
782
- TypeSystemPolicy2.IsExactOptionalProperty = IsExactOptionalProperty;
783
- function IsObjectLike(value) {
784
- const isObject = IsObject2(value);
785
- return TypeSystemPolicy2.AllowArrayObject ? isObject : isObject && !IsArray2(value);
786
- }
787
- TypeSystemPolicy2.IsObjectLike = IsObjectLike;
788
- function IsRecordLike(value) {
789
- return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array);
790
- }
791
- TypeSystemPolicy2.IsRecordLike = IsRecordLike;
792
- function IsNumberLike(value) {
793
- return TypeSystemPolicy2.AllowNaN ? IsNumber2(value) : Number.isFinite(value);
794
- }
795
- TypeSystemPolicy2.IsNumberLike = IsNumberLike;
796
- function IsVoidLike(value) {
797
- const isUndefined = IsUndefined2(value);
798
- return TypeSystemPolicy2.AllowNullVoid ? isUndefined || value === null : isUndefined;
799
- }
800
- TypeSystemPolicy2.IsVoidLike = IsVoidLike;
801
- })(TypeSystemPolicy || (TypeSystemPolicy = {}));
802
-
803
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/create/immutable.mjs
804
- function ImmutableArray(value) {
805
- return globalThis.Object.freeze(value).map((value2) => Immutable(value2));
806
- }
807
- function ImmutableDate(value) {
808
- return value;
809
- }
810
- function ImmutableUint8Array(value) {
811
- return value;
812
- }
813
- function ImmutableRegExp(value) {
814
- return value;
815
- }
816
- function ImmutableObject(value) {
817
- const result = {};
818
- for (const key of Object.getOwnPropertyNames(value)) {
819
- result[key] = Immutable(value[key]);
820
- }
821
- for (const key of Object.getOwnPropertySymbols(value)) {
822
- result[key] = Immutable(value[key]);
823
- }
824
- return globalThis.Object.freeze(result);
825
- }
826
- function Immutable(value) {
827
- return IsArray(value) ? ImmutableArray(value) : IsDate(value) ? ImmutableDate(value) : IsUint8Array(value) ? ImmutableUint8Array(value) : IsRegExp(value) ? ImmutableRegExp(value) : IsObject(value) ? ImmutableObject(value) : value;
828
- }
829
-
830
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/create/type.mjs
831
- function CreateType(schema, options) {
832
- const result = options !== void 0 ? { ...options, ...schema } : schema;
833
- switch (TypeSystemPolicy.InstanceMode) {
834
- case "freeze":
835
- return Immutable(result);
836
- case "clone":
837
- return Clone(result);
838
- default:
839
- return result;
840
- }
841
- }
842
-
843
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/error/error.mjs
844
- var TypeBoxError = class extends Error {
845
- constructor(message) {
846
- super(message);
847
- }
848
- };
849
-
850
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/symbols/symbols.mjs
851
- var TransformKind = Symbol.for("TypeBox.Transform");
852
- var ReadonlyKind = Symbol.for("TypeBox.Readonly");
853
- var OptionalKind = Symbol.for("TypeBox.Optional");
854
- var Hint = Symbol.for("TypeBox.Hint");
855
- var Kind = Symbol.for("TypeBox.Kind");
856
-
857
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs
858
- function IsReadonly(value) {
859
- return IsObject(value) && value[ReadonlyKind] === "Readonly";
860
- }
861
- function IsOptional(value) {
862
- return IsObject(value) && value[OptionalKind] === "Optional";
863
- }
864
- function IsAny(value) {
865
- return IsKindOf(value, "Any");
866
- }
867
- function IsArgument(value) {
868
- return IsKindOf(value, "Argument");
869
- }
870
- function IsArray3(value) {
871
- return IsKindOf(value, "Array");
872
- }
873
- function IsAsyncIterator2(value) {
874
- return IsKindOf(value, "AsyncIterator");
875
- }
876
- function IsBigInt2(value) {
877
- return IsKindOf(value, "BigInt");
878
- }
879
- function IsBoolean2(value) {
880
- return IsKindOf(value, "Boolean");
881
- }
882
- function IsComputed(value) {
883
- return IsKindOf(value, "Computed");
884
- }
885
- function IsConstructor(value) {
886
- return IsKindOf(value, "Constructor");
887
- }
888
- function IsDate2(value) {
889
- return IsKindOf(value, "Date");
890
- }
891
- function IsFunction2(value) {
892
- return IsKindOf(value, "Function");
893
- }
894
- function IsInteger(value) {
895
- return IsKindOf(value, "Integer");
896
- }
897
- function IsIntersect(value) {
898
- return IsKindOf(value, "Intersect");
899
- }
900
- function IsIterator2(value) {
901
- return IsKindOf(value, "Iterator");
902
- }
903
- function IsKindOf(value, kind) {
904
- return IsObject(value) && Kind in value && value[Kind] === kind;
905
- }
906
- function IsLiteralValue(value) {
907
- return IsBoolean(value) || IsNumber(value) || IsString(value);
908
- }
909
- function IsLiteral(value) {
910
- return IsKindOf(value, "Literal");
911
- }
912
- function IsMappedKey(value) {
913
- return IsKindOf(value, "MappedKey");
914
- }
915
- function IsMappedResult(value) {
916
- return IsKindOf(value, "MappedResult");
917
- }
918
- function IsNever(value) {
919
- return IsKindOf(value, "Never");
920
- }
921
- function IsNot(value) {
922
- return IsKindOf(value, "Not");
923
- }
924
- function IsNull2(value) {
925
- return IsKindOf(value, "Null");
926
- }
927
- function IsNumber3(value) {
928
- return IsKindOf(value, "Number");
929
- }
930
- function IsObject3(value) {
931
- return IsKindOf(value, "Object");
932
- }
933
- function IsPromise(value) {
934
- return IsKindOf(value, "Promise");
935
- }
936
- function IsRecord(value) {
937
- return IsKindOf(value, "Record");
938
- }
939
- function IsRef(value) {
940
- return IsKindOf(value, "Ref");
941
- }
942
- function IsRegExp2(value) {
943
- return IsKindOf(value, "RegExp");
944
- }
945
- function IsString2(value) {
946
- return IsKindOf(value, "String");
947
- }
948
- function IsSymbol2(value) {
949
- return IsKindOf(value, "Symbol");
950
- }
951
- function IsTemplateLiteral(value) {
952
- return IsKindOf(value, "TemplateLiteral");
953
- }
954
- function IsThis(value) {
955
- return IsKindOf(value, "This");
956
- }
957
- function IsTransform(value) {
958
- return IsObject(value) && TransformKind in value;
959
- }
960
- function IsTuple(value) {
961
- return IsKindOf(value, "Tuple");
962
- }
963
- function IsUndefined3(value) {
964
- return IsKindOf(value, "Undefined");
965
- }
966
- function IsUnion(value) {
967
- return IsKindOf(value, "Union");
968
- }
969
- function IsUint8Array2(value) {
970
- return IsKindOf(value, "Uint8Array");
971
- }
972
- function IsUnknown(value) {
973
- return IsKindOf(value, "Unknown");
974
- }
975
- function IsUnsafe(value) {
976
- return IsKindOf(value, "Unsafe");
977
- }
978
- function IsVoid(value) {
979
- return IsKindOf(value, "Void");
980
- }
981
- function IsKind(value) {
982
- return IsObject(value) && Kind in value && IsString(value[Kind]);
983
- }
984
- function IsSchema(value) {
985
- return IsAny(value) || IsArgument(value) || IsArray3(value) || IsBoolean2(value) || IsBigInt2(value) || IsAsyncIterator2(value) || IsComputed(value) || IsConstructor(value) || IsDate2(value) || IsFunction2(value) || IsInteger(value) || IsIntersect(value) || IsIterator2(value) || IsLiteral(value) || IsMappedKey(value) || IsMappedResult(value) || IsNever(value) || IsNot(value) || IsNull2(value) || IsNumber3(value) || IsObject3(value) || IsPromise(value) || IsRecord(value) || IsRef(value) || IsRegExp2(value) || IsString2(value) || IsSymbol2(value) || IsTemplateLiteral(value) || IsThis(value) || IsTuple(value) || IsUndefined3(value) || IsUnion(value) || IsUint8Array2(value) || IsUnknown(value) || IsUnsafe(value) || IsVoid(value) || IsKind(value);
986
- }
987
-
988
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/guard/type.mjs
989
- var type_exports = {};
990
- __export(type_exports, {
991
- IsAny: () => IsAny2,
992
- IsArgument: () => IsArgument2,
993
- IsArray: () => IsArray4,
994
- IsAsyncIterator: () => IsAsyncIterator3,
995
- IsBigInt: () => IsBigInt3,
996
- IsBoolean: () => IsBoolean3,
997
- IsComputed: () => IsComputed2,
998
- IsConstructor: () => IsConstructor2,
999
- IsDate: () => IsDate3,
1000
- IsFunction: () => IsFunction3,
1001
- IsImport: () => IsImport,
1002
- IsInteger: () => IsInteger2,
1003
- IsIntersect: () => IsIntersect2,
1004
- IsIterator: () => IsIterator3,
1005
- IsKind: () => IsKind2,
1006
- IsKindOf: () => IsKindOf2,
1007
- IsLiteral: () => IsLiteral2,
1008
- IsLiteralBoolean: () => IsLiteralBoolean,
1009
- IsLiteralNumber: () => IsLiteralNumber,
1010
- IsLiteralString: () => IsLiteralString,
1011
- IsLiteralValue: () => IsLiteralValue2,
1012
- IsMappedKey: () => IsMappedKey2,
1013
- IsMappedResult: () => IsMappedResult2,
1014
- IsNever: () => IsNever2,
1015
- IsNot: () => IsNot2,
1016
- IsNull: () => IsNull3,
1017
- IsNumber: () => IsNumber4,
1018
- IsObject: () => IsObject4,
1019
- IsOptional: () => IsOptional2,
1020
- IsPromise: () => IsPromise2,
1021
- IsProperties: () => IsProperties,
1022
- IsReadonly: () => IsReadonly2,
1023
- IsRecord: () => IsRecord2,
1024
- IsRecursive: () => IsRecursive,
1025
- IsRef: () => IsRef2,
1026
- IsRegExp: () => IsRegExp3,
1027
- IsSchema: () => IsSchema2,
1028
- IsString: () => IsString3,
1029
- IsSymbol: () => IsSymbol3,
1030
- IsTemplateLiteral: () => IsTemplateLiteral2,
1031
- IsThis: () => IsThis2,
1032
- IsTransform: () => IsTransform2,
1033
- IsTuple: () => IsTuple2,
1034
- IsUint8Array: () => IsUint8Array3,
1035
- IsUndefined: () => IsUndefined4,
1036
- IsUnion: () => IsUnion2,
1037
- IsUnionLiteral: () => IsUnionLiteral,
1038
- IsUnknown: () => IsUnknown2,
1039
- IsUnsafe: () => IsUnsafe2,
1040
- IsVoid: () => IsVoid2,
1041
- TypeGuardUnknownTypeError: () => TypeGuardUnknownTypeError
1042
- });
1043
- var TypeGuardUnknownTypeError = class extends TypeBoxError {
1044
- };
1045
- var KnownTypes = [
1046
- "Argument",
1047
- "Any",
1048
- "Array",
1049
- "AsyncIterator",
1050
- "BigInt",
1051
- "Boolean",
1052
- "Computed",
1053
- "Constructor",
1054
- "Date",
1055
- "Enum",
1056
- "Function",
1057
- "Integer",
1058
- "Intersect",
1059
- "Iterator",
1060
- "Literal",
1061
- "MappedKey",
1062
- "MappedResult",
1063
- "Not",
1064
- "Null",
1065
- "Number",
1066
- "Object",
1067
- "Promise",
1068
- "Record",
1069
- "Ref",
1070
- "RegExp",
1071
- "String",
1072
- "Symbol",
1073
- "TemplateLiteral",
1074
- "This",
1075
- "Tuple",
1076
- "Undefined",
1077
- "Union",
1078
- "Uint8Array",
1079
- "Unknown",
1080
- "Void"
1081
- ];
1082
- function IsPattern(value) {
1083
- try {
1084
- new RegExp(value);
1085
- return true;
1086
- } catch {
1087
- return false;
1088
- }
1089
- }
1090
- function IsControlCharacterFree(value) {
1091
- if (!IsString(value))
1092
- return false;
1093
- for (let i = 0; i < value.length; i++) {
1094
- const code = value.charCodeAt(i);
1095
- if (code >= 7 && code <= 13 || code === 27 || code === 127) {
1096
- return false;
1097
- }
1098
- }
1099
- return true;
1100
- }
1101
- function IsAdditionalProperties(value) {
1102
- return IsOptionalBoolean(value) || IsSchema2(value);
1103
- }
1104
- function IsOptionalBigInt(value) {
1105
- return IsUndefined(value) || IsBigInt(value);
1106
- }
1107
- function IsOptionalNumber(value) {
1108
- return IsUndefined(value) || IsNumber(value);
1109
- }
1110
- function IsOptionalBoolean(value) {
1111
- return IsUndefined(value) || IsBoolean(value);
1112
- }
1113
- function IsOptionalString(value) {
1114
- return IsUndefined(value) || IsString(value);
1115
- }
1116
- function IsOptionalPattern(value) {
1117
- return IsUndefined(value) || IsString(value) && IsControlCharacterFree(value) && IsPattern(value);
1118
- }
1119
- function IsOptionalFormat(value) {
1120
- return IsUndefined(value) || IsString(value) && IsControlCharacterFree(value);
1121
- }
1122
- function IsOptionalSchema(value) {
1123
- return IsUndefined(value) || IsSchema2(value);
1124
- }
1125
- function IsReadonly2(value) {
1126
- return IsObject(value) && value[ReadonlyKind] === "Readonly";
1127
- }
1128
- function IsOptional2(value) {
1129
- return IsObject(value) && value[OptionalKind] === "Optional";
1130
- }
1131
- function IsAny2(value) {
1132
- return IsKindOf2(value, "Any") && IsOptionalString(value.$id);
1133
- }
1134
- function IsArgument2(value) {
1135
- return IsKindOf2(value, "Argument") && IsNumber(value.index);
1136
- }
1137
- function IsArray4(value) {
1138
- return IsKindOf2(value, "Array") && value.type === "array" && IsOptionalString(value.$id) && IsSchema2(value.items) && IsOptionalNumber(value.minItems) && IsOptionalNumber(value.maxItems) && IsOptionalBoolean(value.uniqueItems) && IsOptionalSchema(value.contains) && IsOptionalNumber(value.minContains) && IsOptionalNumber(value.maxContains);
1139
- }
1140
- function IsAsyncIterator3(value) {
1141
- return IsKindOf2(value, "AsyncIterator") && value.type === "AsyncIterator" && IsOptionalString(value.$id) && IsSchema2(value.items);
1142
- }
1143
- function IsBigInt3(value) {
1144
- return IsKindOf2(value, "BigInt") && value.type === "bigint" && IsOptionalString(value.$id) && IsOptionalBigInt(value.exclusiveMaximum) && IsOptionalBigInt(value.exclusiveMinimum) && IsOptionalBigInt(value.maximum) && IsOptionalBigInt(value.minimum) && IsOptionalBigInt(value.multipleOf);
1145
- }
1146
- function IsBoolean3(value) {
1147
- return IsKindOf2(value, "Boolean") && value.type === "boolean" && IsOptionalString(value.$id);
1148
- }
1149
- function IsComputed2(value) {
1150
- return IsKindOf2(value, "Computed") && IsString(value.target) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema));
1151
- }
1152
- function IsConstructor2(value) {
1153
- return IsKindOf2(value, "Constructor") && value.type === "Constructor" && IsOptionalString(value.$id) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema)) && IsSchema2(value.returns);
1154
- }
1155
- function IsDate3(value) {
1156
- return IsKindOf2(value, "Date") && value.type === "Date" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximumTimestamp) && IsOptionalNumber(value.exclusiveMinimumTimestamp) && IsOptionalNumber(value.maximumTimestamp) && IsOptionalNumber(value.minimumTimestamp) && IsOptionalNumber(value.multipleOfTimestamp);
1157
- }
1158
- function IsFunction3(value) {
1159
- return IsKindOf2(value, "Function") && value.type === "Function" && IsOptionalString(value.$id) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema)) && IsSchema2(value.returns);
1160
- }
1161
- function IsImport(value) {
1162
- return IsKindOf2(value, "Import") && HasPropertyKey(value, "$defs") && IsObject(value.$defs) && IsProperties(value.$defs) && HasPropertyKey(value, "$ref") && IsString(value.$ref) && value.$ref in value.$defs;
1163
- }
1164
- function IsInteger2(value) {
1165
- return IsKindOf2(value, "Integer") && value.type === "integer" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximum) && IsOptionalNumber(value.exclusiveMinimum) && IsOptionalNumber(value.maximum) && IsOptionalNumber(value.minimum) && IsOptionalNumber(value.multipleOf);
1166
- }
1167
- function IsProperties(value) {
1168
- return IsObject(value) && Object.entries(value).every(([key, schema]) => IsControlCharacterFree(key) && IsSchema2(schema));
1169
- }
1170
- function IsIntersect2(value) {
1171
- return IsKindOf2(value, "Intersect") && (IsString(value.type) && value.type !== "object" ? false : true) && IsArray(value.allOf) && value.allOf.every((schema) => IsSchema2(schema) && !IsTransform2(schema)) && IsOptionalString(value.type) && (IsOptionalBoolean(value.unevaluatedProperties) || IsOptionalSchema(value.unevaluatedProperties)) && IsOptionalString(value.$id);
1172
- }
1173
- function IsIterator3(value) {
1174
- return IsKindOf2(value, "Iterator") && value.type === "Iterator" && IsOptionalString(value.$id) && IsSchema2(value.items);
1175
- }
1176
- function IsKindOf2(value, kind) {
1177
- return IsObject(value) && Kind in value && value[Kind] === kind;
1178
- }
1179
- function IsLiteralString(value) {
1180
- return IsLiteral2(value) && IsString(value.const);
1181
- }
1182
- function IsLiteralNumber(value) {
1183
- return IsLiteral2(value) && IsNumber(value.const);
1184
- }
1185
- function IsLiteralBoolean(value) {
1186
- return IsLiteral2(value) && IsBoolean(value.const);
1187
- }
1188
- function IsLiteral2(value) {
1189
- return IsKindOf2(value, "Literal") && IsOptionalString(value.$id) && IsLiteralValue2(value.const);
1190
- }
1191
- function IsLiteralValue2(value) {
1192
- return IsBoolean(value) || IsNumber(value) || IsString(value);
1193
- }
1194
- function IsMappedKey2(value) {
1195
- return IsKindOf2(value, "MappedKey") && IsArray(value.keys) && value.keys.every((key) => IsNumber(key) || IsString(key));
1196
- }
1197
- function IsMappedResult2(value) {
1198
- return IsKindOf2(value, "MappedResult") && IsProperties(value.properties);
1199
- }
1200
- function IsNever2(value) {
1201
- return IsKindOf2(value, "Never") && IsObject(value.not) && Object.getOwnPropertyNames(value.not).length === 0;
1202
- }
1203
- function IsNot2(value) {
1204
- return IsKindOf2(value, "Not") && IsSchema2(value.not);
1205
- }
1206
- function IsNull3(value) {
1207
- return IsKindOf2(value, "Null") && value.type === "null" && IsOptionalString(value.$id);
1208
- }
1209
- function IsNumber4(value) {
1210
- return IsKindOf2(value, "Number") && value.type === "number" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximum) && IsOptionalNumber(value.exclusiveMinimum) && IsOptionalNumber(value.maximum) && IsOptionalNumber(value.minimum) && IsOptionalNumber(value.multipleOf);
1211
- }
1212
- function IsObject4(value) {
1213
- return IsKindOf2(value, "Object") && value.type === "object" && IsOptionalString(value.$id) && IsProperties(value.properties) && IsAdditionalProperties(value.additionalProperties) && IsOptionalNumber(value.minProperties) && IsOptionalNumber(value.maxProperties);
1214
- }
1215
- function IsPromise2(value) {
1216
- return IsKindOf2(value, "Promise") && value.type === "Promise" && IsOptionalString(value.$id) && IsSchema2(value.item);
1217
- }
1218
- function IsRecord2(value) {
1219
- return IsKindOf2(value, "Record") && value.type === "object" && IsOptionalString(value.$id) && IsAdditionalProperties(value.additionalProperties) && IsObject(value.patternProperties) && ((schema) => {
1220
- const keys = Object.getOwnPropertyNames(schema.patternProperties);
1221
- return keys.length === 1 && IsPattern(keys[0]) && IsObject(schema.patternProperties) && IsSchema2(schema.patternProperties[keys[0]]);
1222
- })(value);
1223
- }
1224
- function IsRecursive(value) {
1225
- return IsObject(value) && Hint in value && value[Hint] === "Recursive";
1226
- }
1227
- function IsRef2(value) {
1228
- return IsKindOf2(value, "Ref") && IsOptionalString(value.$id) && IsString(value.$ref);
1229
- }
1230
- function IsRegExp3(value) {
1231
- return IsKindOf2(value, "RegExp") && IsOptionalString(value.$id) && IsString(value.source) && IsString(value.flags) && IsOptionalNumber(value.maxLength) && IsOptionalNumber(value.minLength);
1232
- }
1233
- function IsString3(value) {
1234
- return IsKindOf2(value, "String") && value.type === "string" && IsOptionalString(value.$id) && IsOptionalNumber(value.minLength) && IsOptionalNumber(value.maxLength) && IsOptionalPattern(value.pattern) && IsOptionalFormat(value.format);
1235
- }
1236
- function IsSymbol3(value) {
1237
- return IsKindOf2(value, "Symbol") && value.type === "symbol" && IsOptionalString(value.$id);
1238
- }
1239
- function IsTemplateLiteral2(value) {
1240
- return IsKindOf2(value, "TemplateLiteral") && value.type === "string" && IsString(value.pattern) && value.pattern[0] === "^" && value.pattern[value.pattern.length - 1] === "$";
1241
- }
1242
- function IsThis2(value) {
1243
- return IsKindOf2(value, "This") && IsOptionalString(value.$id) && IsString(value.$ref);
1244
- }
1245
- function IsTransform2(value) {
1246
- return IsObject(value) && TransformKind in value;
1247
- }
1248
- function IsTuple2(value) {
1249
- return IsKindOf2(value, "Tuple") && value.type === "array" && IsOptionalString(value.$id) && IsNumber(value.minItems) && IsNumber(value.maxItems) && value.minItems === value.maxItems && // empty
1250
- (IsUndefined(value.items) && IsUndefined(value.additionalItems) && value.minItems === 0 || IsArray(value.items) && value.items.every((schema) => IsSchema2(schema)));
1251
- }
1252
- function IsUndefined4(value) {
1253
- return IsKindOf2(value, "Undefined") && value.type === "undefined" && IsOptionalString(value.$id);
1254
- }
1255
- function IsUnionLiteral(value) {
1256
- return IsUnion2(value) && value.anyOf.every((schema) => IsLiteralString(schema) || IsLiteralNumber(schema));
1257
- }
1258
- function IsUnion2(value) {
1259
- return IsKindOf2(value, "Union") && IsOptionalString(value.$id) && IsObject(value) && IsArray(value.anyOf) && value.anyOf.every((schema) => IsSchema2(schema));
1260
- }
1261
- function IsUint8Array3(value) {
1262
- return IsKindOf2(value, "Uint8Array") && value.type === "Uint8Array" && IsOptionalString(value.$id) && IsOptionalNumber(value.minByteLength) && IsOptionalNumber(value.maxByteLength);
1263
- }
1264
- function IsUnknown2(value) {
1265
- return IsKindOf2(value, "Unknown") && IsOptionalString(value.$id);
1266
- }
1267
- function IsUnsafe2(value) {
1268
- return IsKindOf2(value, "Unsafe");
1269
- }
1270
- function IsVoid2(value) {
1271
- return IsKindOf2(value, "Void") && value.type === "void" && IsOptionalString(value.$id);
1272
- }
1273
- function IsKind2(value) {
1274
- return IsObject(value) && Kind in value && IsString(value[Kind]) && !KnownTypes.includes(value[Kind]);
1275
- }
1276
- function IsSchema2(value) {
1277
- return IsObject(value) && (IsAny2(value) || IsArgument2(value) || IsArray4(value) || IsBoolean3(value) || IsBigInt3(value) || IsAsyncIterator3(value) || IsComputed2(value) || IsConstructor2(value) || IsDate3(value) || IsFunction3(value) || IsInteger2(value) || IsIntersect2(value) || IsIterator3(value) || IsLiteral2(value) || IsMappedKey2(value) || IsMappedResult2(value) || IsNever2(value) || IsNot2(value) || IsNull3(value) || IsNumber4(value) || IsObject4(value) || IsPromise2(value) || IsRecord2(value) || IsRef2(value) || IsRegExp3(value) || IsString3(value) || IsSymbol3(value) || IsTemplateLiteral2(value) || IsThis2(value) || IsTuple2(value) || IsUndefined4(value) || IsUnion2(value) || IsUint8Array3(value) || IsUnknown2(value) || IsUnsafe2(value) || IsVoid2(value) || IsKind2(value));
1278
- }
1279
-
1280
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/patterns/patterns.mjs
1281
- var PatternBoolean = "(true|false)";
1282
- var PatternNumber = "(0|[1-9][0-9]*)";
1283
- var PatternString = "(.*)";
1284
- var PatternNever = "(?!.*)";
1285
- var PatternBooleanExact = `^${PatternBoolean}$`;
1286
- var PatternNumberExact = `^${PatternNumber}$`;
1287
- var PatternStringExact = `^${PatternString}$`;
1288
- var PatternNeverExact = `^${PatternNever}$`;
1289
-
1290
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/sets/set.mjs
1291
- function SetIncludes(T, S) {
1292
- return T.includes(S);
1293
- }
1294
- function SetDistinct(T) {
1295
- return [...new Set(T)];
1296
- }
1297
- function SetIntersect(T, S) {
1298
- return T.filter((L) => S.includes(L));
1299
- }
1300
- function SetIntersectManyResolve(T, Init) {
1301
- return T.reduce((Acc, L) => {
1302
- return SetIntersect(Acc, L);
1303
- }, Init);
1304
- }
1305
- function SetIntersectMany(T) {
1306
- return T.length === 1 ? T[0] : T.length > 1 ? SetIntersectManyResolve(T.slice(1), T[0]) : [];
1307
- }
1308
- function SetUnionMany(T) {
1309
- const Acc = [];
1310
- for (const L of T)
1311
- Acc.push(...L);
1312
- return Acc;
1313
- }
1314
-
1315
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/any/any.mjs
1316
- function Any(options) {
1317
- return CreateType({ [Kind]: "Any" }, options);
1318
- }
1319
-
1320
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/array/array.mjs
1321
- function Array2(items, options) {
1322
- return CreateType({ [Kind]: "Array", type: "array", items }, options);
1323
- }
1324
-
1325
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/argument/argument.mjs
1326
- function Argument(index9) {
1327
- return CreateType({ [Kind]: "Argument", index: index9 });
1328
- }
1329
-
1330
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/async-iterator/async-iterator.mjs
1331
- function AsyncIterator(items, options) {
1332
- return CreateType({ [Kind]: "AsyncIterator", type: "AsyncIterator", items }, options);
1333
- }
1334
-
1335
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/computed/computed.mjs
1336
- function Computed(target, parameters, options) {
1337
- return CreateType({ [Kind]: "Computed", target, parameters }, options);
1338
- }
1339
-
1340
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/discard/discard.mjs
1341
- function DiscardKey(value, key) {
1342
- const { [key]: _, ...rest } = value;
1343
- return rest;
1344
- }
1345
- function Discard(value, keys) {
1346
- return keys.reduce((acc, key) => DiscardKey(acc, key), value);
1347
- }
1348
-
1349
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/never/never.mjs
1350
- function Never(options) {
1351
- return CreateType({ [Kind]: "Never", not: {} }, options);
1352
- }
1353
-
1354
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-result.mjs
1355
- function MappedResult(properties) {
1356
- return CreateType({
1357
- [Kind]: "MappedResult",
1358
- properties
1359
- });
1360
- }
1361
-
1362
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/constructor/constructor.mjs
1363
- function Constructor(parameters, returns, options) {
1364
- return CreateType({ [Kind]: "Constructor", type: "Constructor", parameters, returns }, options);
1365
- }
1366
-
1367
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/function/function.mjs
1368
- function Function(parameters, returns, options) {
1369
- return CreateType({ [Kind]: "Function", type: "Function", parameters, returns }, options);
1370
- }
1371
-
1372
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/union/union-create.mjs
1373
- function UnionCreate(T, options) {
1374
- return CreateType({ [Kind]: "Union", anyOf: T }, options);
1375
- }
1376
-
1377
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs
1378
- function IsUnionOptional(types) {
1379
- return types.some((type) => IsOptional(type));
1380
- }
1381
- function RemoveOptionalFromRest(types) {
1382
- return types.map((left) => IsOptional(left) ? RemoveOptionalFromType(left) : left);
1383
- }
1384
- function RemoveOptionalFromType(T) {
1385
- return Discard(T, [OptionalKind]);
1386
- }
1387
- function ResolveUnion(types, options) {
1388
- const isOptional = IsUnionOptional(types);
1389
- return isOptional ? Optional(UnionCreate(RemoveOptionalFromRest(types), options)) : UnionCreate(RemoveOptionalFromRest(types), options);
1390
- }
1391
- function UnionEvaluated(T, options) {
1392
- return T.length === 1 ? CreateType(T[0], options) : T.length === 0 ? Never(options) : ResolveUnion(T, options);
1393
- }
1394
-
1395
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/union/union.mjs
1396
- function Union(types, options) {
1397
- return types.length === 0 ? Never(options) : types.length === 1 ? CreateType(types[0], options) : UnionCreate(types, options);
1398
- }
1399
-
1400
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/template-literal/parse.mjs
1401
- var TemplateLiteralParserError = class extends TypeBoxError {
1402
- };
1403
- function Unescape(pattern) {
1404
- return pattern.replace(/\\\$/g, "$").replace(/\\\*/g, "*").replace(/\\\^/g, "^").replace(/\\\|/g, "|").replace(/\\\(/g, "(").replace(/\\\)/g, ")");
1405
- }
1406
- function IsNonEscaped(pattern, index9, char) {
1407
- return pattern[index9] === char && pattern.charCodeAt(index9 - 1) !== 92;
1408
- }
1409
- function IsOpenParen(pattern, index9) {
1410
- return IsNonEscaped(pattern, index9, "(");
1411
- }
1412
- function IsCloseParen(pattern, index9) {
1413
- return IsNonEscaped(pattern, index9, ")");
1414
- }
1415
- function IsSeparator(pattern, index9) {
1416
- return IsNonEscaped(pattern, index9, "|");
1417
- }
1418
- function IsGroup(pattern) {
1419
- if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1)))
1420
- return false;
1421
- let count = 0;
1422
- for (let index9 = 0; index9 < pattern.length; index9++) {
1423
- if (IsOpenParen(pattern, index9))
1424
- count += 1;
1425
- if (IsCloseParen(pattern, index9))
1426
- count -= 1;
1427
- if (count === 0 && index9 !== pattern.length - 1)
1428
- return false;
1429
- }
1430
- return true;
1431
- }
1432
- function InGroup(pattern) {
1433
- return pattern.slice(1, pattern.length - 1);
1434
- }
1435
- function IsPrecedenceOr(pattern) {
1436
- let count = 0;
1437
- for (let index9 = 0; index9 < pattern.length; index9++) {
1438
- if (IsOpenParen(pattern, index9))
1439
- count += 1;
1440
- if (IsCloseParen(pattern, index9))
1441
- count -= 1;
1442
- if (IsSeparator(pattern, index9) && count === 0)
1443
- return true;
1444
- }
1445
- return false;
1446
- }
1447
- function IsPrecedenceAnd(pattern) {
1448
- for (let index9 = 0; index9 < pattern.length; index9++) {
1449
- if (IsOpenParen(pattern, index9))
1450
- return true;
1451
- }
1452
- return false;
1453
- }
1454
- function Or(pattern) {
1455
- let [count, start] = [0, 0];
1456
- const expressions = [];
1457
- for (let index9 = 0; index9 < pattern.length; index9++) {
1458
- if (IsOpenParen(pattern, index9))
1459
- count += 1;
1460
- if (IsCloseParen(pattern, index9))
1461
- count -= 1;
1462
- if (IsSeparator(pattern, index9) && count === 0) {
1463
- const range2 = pattern.slice(start, index9);
1464
- if (range2.length > 0)
1465
- expressions.push(TemplateLiteralParse(range2));
1466
- start = index9 + 1;
1467
- }
1468
- }
1469
- const range = pattern.slice(start);
1470
- if (range.length > 0)
1471
- expressions.push(TemplateLiteralParse(range));
1472
- if (expressions.length === 0)
1473
- return { type: "const", const: "" };
1474
- if (expressions.length === 1)
1475
- return expressions[0];
1476
- return { type: "or", expr: expressions };
1477
- }
1478
- function And(pattern) {
1479
- function Group(value, index9) {
1480
- if (!IsOpenParen(value, index9))
1481
- throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`);
1482
- let count = 0;
1483
- for (let scan = index9; scan < value.length; scan++) {
1484
- if (IsOpenParen(value, scan))
1485
- count += 1;
1486
- if (IsCloseParen(value, scan))
1487
- count -= 1;
1488
- if (count === 0)
1489
- return [index9, scan];
1490
- }
1491
- throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`);
1492
- }
1493
- function Range(pattern2, index9) {
1494
- for (let scan = index9; scan < pattern2.length; scan++) {
1495
- if (IsOpenParen(pattern2, scan))
1496
- return [index9, scan];
1497
- }
1498
- return [index9, pattern2.length];
1499
- }
1500
- const expressions = [];
1501
- for (let index9 = 0; index9 < pattern.length; index9++) {
1502
- if (IsOpenParen(pattern, index9)) {
1503
- const [start, end] = Group(pattern, index9);
1504
- const range = pattern.slice(start, end + 1);
1505
- expressions.push(TemplateLiteralParse(range));
1506
- index9 = end;
1507
- } else {
1508
- const [start, end] = Range(pattern, index9);
1509
- const range = pattern.slice(start, end);
1510
- if (range.length > 0)
1511
- expressions.push(TemplateLiteralParse(range));
1512
- index9 = end - 1;
1513
- }
1514
- }
1515
- return expressions.length === 0 ? { type: "const", const: "" } : expressions.length === 1 ? expressions[0] : { type: "and", expr: expressions };
1516
- }
1517
- function TemplateLiteralParse(pattern) {
1518
- return IsGroup(pattern) ? TemplateLiteralParse(InGroup(pattern)) : IsPrecedenceOr(pattern) ? Or(pattern) : IsPrecedenceAnd(pattern) ? And(pattern) : { type: "const", const: Unescape(pattern) };
1519
- }
1520
- function TemplateLiteralParseExact(pattern) {
1521
- return TemplateLiteralParse(pattern.slice(1, pattern.length - 1));
1522
- }
1523
-
1524
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs
1525
- var TemplateLiteralFiniteError = class extends TypeBoxError {
1526
- };
1527
- function IsNumberExpression(expression) {
1528
- return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "0" && expression.expr[1].type === "const" && expression.expr[1].const === "[1-9][0-9]*";
1529
- }
1530
- function IsBooleanExpression(expression) {
1531
- return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "true" && expression.expr[1].type === "const" && expression.expr[1].const === "false";
1532
- }
1533
- function IsStringExpression(expression) {
1534
- return expression.type === "const" && expression.const === ".*";
1535
- }
1536
- function IsTemplateLiteralExpressionFinite(expression) {
1537
- return IsNumberExpression(expression) || IsStringExpression(expression) ? false : IsBooleanExpression(expression) ? true : expression.type === "and" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) : expression.type === "or" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) : expression.type === "const" ? true : (() => {
1538
- throw new TemplateLiteralFiniteError(`Unknown expression type`);
1539
- })();
1540
- }
1541
- function IsTemplateLiteralFinite(schema) {
1542
- const expression = TemplateLiteralParseExact(schema.pattern);
1543
- return IsTemplateLiteralExpressionFinite(expression);
1544
- }
1545
-
1546
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/template-literal/generate.mjs
1547
- var TemplateLiteralGenerateError = class extends TypeBoxError {
1548
- };
1549
- function* GenerateReduce(buffer) {
1550
- if (buffer.length === 1)
1551
- return yield* buffer[0];
1552
- for (const left of buffer[0]) {
1553
- for (const right of GenerateReduce(buffer.slice(1))) {
1554
- yield `${left}${right}`;
1555
- }
1556
- }
1557
- }
1558
- function* GenerateAnd(expression) {
1559
- return yield* GenerateReduce(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate(expr)]));
1560
- }
1561
- function* GenerateOr(expression) {
1562
- for (const expr of expression.expr)
1563
- yield* TemplateLiteralExpressionGenerate(expr);
1564
- }
1565
- function* GenerateConst(expression) {
1566
- return yield expression.const;
1567
- }
1568
- function* TemplateLiteralExpressionGenerate(expression) {
1569
- return expression.type === "and" ? yield* GenerateAnd(expression) : expression.type === "or" ? yield* GenerateOr(expression) : expression.type === "const" ? yield* GenerateConst(expression) : (() => {
1570
- throw new TemplateLiteralGenerateError("Unknown expression");
1571
- })();
1572
- }
1573
- function TemplateLiteralGenerate(schema) {
1574
- const expression = TemplateLiteralParseExact(schema.pattern);
1575
- return IsTemplateLiteralExpressionFinite(expression) ? [...TemplateLiteralExpressionGenerate(expression)] : [];
1576
- }
1577
-
1578
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/literal/literal.mjs
1579
- function Literal(value, options) {
1580
- return CreateType({
1581
- [Kind]: "Literal",
1582
- const: value,
1583
- type: typeof value
1584
- }, options);
1585
- }
1586
-
1587
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/boolean/boolean.mjs
1588
- function Boolean(options) {
1589
- return CreateType({ [Kind]: "Boolean", type: "boolean" }, options);
1590
- }
1591
-
1592
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/bigint/bigint.mjs
1593
- function BigInt(options) {
1594
- return CreateType({ [Kind]: "BigInt", type: "bigint" }, options);
1595
- }
1596
-
1597
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/number/number.mjs
1598
- function Number2(options) {
1599
- return CreateType({ [Kind]: "Number", type: "number" }, options);
1600
- }
1601
-
1602
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/string/string.mjs
1603
- function String2(options) {
1604
- return CreateType({ [Kind]: "String", type: "string" }, options);
1605
- }
1606
-
1607
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs
1608
- function* FromUnion(syntax) {
1609
- const trim = syntax.trim().replace(/"|'/g, "");
1610
- return trim === "boolean" ? yield Boolean() : trim === "number" ? yield Number2() : trim === "bigint" ? yield BigInt() : trim === "string" ? yield String2() : yield (() => {
1611
- const literals = trim.split("|").map((literal) => Literal(literal.trim()));
1612
- return literals.length === 0 ? Never() : literals.length === 1 ? literals[0] : UnionEvaluated(literals);
1613
- })();
1614
- }
1615
- function* FromTerminal(syntax) {
1616
- if (syntax[1] !== "{") {
1617
- const L = Literal("$");
1618
- const R = FromSyntax(syntax.slice(1));
1619
- return yield* [L, ...R];
1620
- }
1621
- for (let i = 2; i < syntax.length; i++) {
1622
- if (syntax[i] === "}") {
1623
- const L = FromUnion(syntax.slice(2, i));
1624
- const R = FromSyntax(syntax.slice(i + 1));
1625
- return yield* [...L, ...R];
1626
- }
1627
- }
1628
- yield Literal(syntax);
1629
- }
1630
- function* FromSyntax(syntax) {
1631
- for (let i = 0; i < syntax.length; i++) {
1632
- if (syntax[i] === "$") {
1633
- const L = Literal(syntax.slice(0, i));
1634
- const R = FromTerminal(syntax.slice(i));
1635
- return yield* [L, ...R];
1636
- }
1637
- }
1638
- yield Literal(syntax);
1639
- }
1640
- function TemplateLiteralSyntax(syntax) {
1641
- return [...FromSyntax(syntax)];
1642
- }
1643
-
1644
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/template-literal/pattern.mjs
1645
- var TemplateLiteralPatternError = class extends TypeBoxError {
1646
- };
1647
- function Escape(value) {
1648
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1649
- }
1650
- function Visit2(schema, acc) {
1651
- return IsTemplateLiteral(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) : IsUnion(schema) ? `(${schema.anyOf.map((schema2) => Visit2(schema2, acc)).join("|")})` : IsNumber3(schema) ? `${acc}${PatternNumber}` : IsInteger(schema) ? `${acc}${PatternNumber}` : IsBigInt2(schema) ? `${acc}${PatternNumber}` : IsString2(schema) ? `${acc}${PatternString}` : IsLiteral(schema) ? `${acc}${Escape(schema.const.toString())}` : IsBoolean2(schema) ? `${acc}${PatternBoolean}` : (() => {
1652
- throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`);
1653
- })();
1654
- }
1655
- function TemplateLiteralPattern(kinds) {
1656
- return `^${kinds.map((schema) => Visit2(schema, "")).join("")}$`;
1657
- }
1658
-
1659
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/template-literal/union.mjs
1660
- function TemplateLiteralToUnion(schema) {
1661
- const R = TemplateLiteralGenerate(schema);
1662
- const L = R.map((S) => Literal(S));
1663
- return UnionEvaluated(L);
1664
- }
1665
-
1666
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/template-literal/template-literal.mjs
1667
- function TemplateLiteral(unresolved, options) {
1668
- const pattern = IsString(unresolved) ? TemplateLiteralPattern(TemplateLiteralSyntax(unresolved)) : TemplateLiteralPattern(unresolved);
1669
- return CreateType({ [Kind]: "TemplateLiteral", type: "string", pattern }, options);
1670
- }
1671
-
1672
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs
1673
- function FromTemplateLiteral(templateLiteral) {
1674
- const keys = TemplateLiteralGenerate(templateLiteral);
1675
- return keys.map((key) => key.toString());
1676
- }
1677
- function FromUnion2(types) {
1678
- const result = [];
1679
- for (const type of types)
1680
- result.push(...IndexPropertyKeys(type));
1681
- return result;
1682
- }
1683
- function FromLiteral(literalValue) {
1684
- return [literalValue.toString()];
1685
- }
1686
- function IndexPropertyKeys(type) {
1687
- return [...new Set(IsTemplateLiteral(type) ? FromTemplateLiteral(type) : IsUnion(type) ? FromUnion2(type.anyOf) : IsLiteral(type) ? FromLiteral(type.const) : IsNumber3(type) ? ["[number]"] : IsInteger(type) ? ["[number]"] : [])];
1688
- }
1689
-
1690
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-result.mjs
1691
- function FromProperties(type, properties, options) {
1692
- const result = {};
1693
- for (const K2 of Object.getOwnPropertyNames(properties)) {
1694
- result[K2] = Index(type, IndexPropertyKeys(properties[K2]), options);
1695
- }
1696
- return result;
1697
- }
1698
- function FromMappedResult(type, mappedResult, options) {
1699
- return FromProperties(type, mappedResult.properties, options);
1700
- }
1701
- function IndexFromMappedResult(type, mappedResult, options) {
1702
- const properties = FromMappedResult(type, mappedResult, options);
1703
- return MappedResult(properties);
1704
- }
1705
-
1706
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs
1707
- function FromRest(types, key) {
1708
- return types.map((type) => IndexFromPropertyKey(type, key));
1709
- }
1710
- function FromIntersectRest(types) {
1711
- return types.filter((type) => !IsNever(type));
1712
- }
1713
- function FromIntersect(types, key) {
1714
- return IntersectEvaluated(FromIntersectRest(FromRest(types, key)));
1715
- }
1716
- function FromUnionRest(types) {
1717
- return types.some((L) => IsNever(L)) ? [] : types;
1718
- }
1719
- function FromUnion3(types, key) {
1720
- return UnionEvaluated(FromUnionRest(FromRest(types, key)));
1721
- }
1722
- function FromTuple(types, key) {
1723
- return key in types ? types[key] : key === "[number]" ? UnionEvaluated(types) : Never();
1724
- }
1725
- function FromArray(type, key) {
1726
- return key === "[number]" ? type : Never();
1727
- }
1728
- function FromProperty(properties, propertyKey) {
1729
- return propertyKey in properties ? properties[propertyKey] : Never();
1730
- }
1731
- function IndexFromPropertyKey(type, propertyKey) {
1732
- return IsIntersect(type) ? FromIntersect(type.allOf, propertyKey) : IsUnion(type) ? FromUnion3(type.anyOf, propertyKey) : IsTuple(type) ? FromTuple(type.items ?? [], propertyKey) : IsArray3(type) ? FromArray(type.items, propertyKey) : IsObject3(type) ? FromProperty(type.properties, propertyKey) : Never();
1733
- }
1734
- function IndexFromPropertyKeys(type, propertyKeys) {
1735
- return propertyKeys.map((propertyKey) => IndexFromPropertyKey(type, propertyKey));
1736
- }
1737
- function FromSchema(type, propertyKeys) {
1738
- return UnionEvaluated(IndexFromPropertyKeys(type, propertyKeys));
1739
- }
1740
- function Index(type, key, options) {
1741
- if (IsRef(type) || IsRef(key)) {
1742
- const error = `Index types using Ref parameters require both Type and Key to be of TSchema`;
1743
- if (!IsSchema(type) || !IsSchema(key))
1744
- throw new TypeBoxError(error);
1745
- return Computed("Index", [type, key]);
1746
- }
1747
- if (IsMappedResult(key))
1748
- return IndexFromMappedResult(type, key, options);
1749
- if (IsMappedKey(key))
1750
- return IndexFromMappedKey(type, key, options);
1751
- return CreateType(IsSchema(key) ? FromSchema(type, IndexPropertyKeys(key)) : FromSchema(type, key), options);
1752
- }
1753
-
1754
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs
1755
- function MappedIndexPropertyKey(type, key, options) {
1756
- return { [key]: Index(type, [key], Clone(options)) };
1757
- }
1758
- function MappedIndexPropertyKeys(type, propertyKeys, options) {
1759
- return propertyKeys.reduce((result, left) => {
1760
- return { ...result, ...MappedIndexPropertyKey(type, left, options) };
1761
- }, {});
1762
- }
1763
- function MappedIndexProperties(type, mappedKey, options) {
1764
- return MappedIndexPropertyKeys(type, mappedKey.keys, options);
1765
- }
1766
- function IndexFromMappedKey(type, mappedKey, options) {
1767
- const properties = MappedIndexProperties(type, mappedKey, options);
1768
- return MappedResult(properties);
1769
- }
1770
-
1771
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/iterator/iterator.mjs
1772
- function Iterator(items, options) {
1773
- return CreateType({ [Kind]: "Iterator", type: "Iterator", items }, options);
1774
- }
1775
-
1776
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/object/object.mjs
1777
- function RequiredKeys(properties) {
1778
- const keys = [];
1779
- for (let key in properties) {
1780
- if (!IsOptional(properties[key]))
1781
- keys.push(key);
1782
- }
1783
- return keys;
1784
- }
1785
- function _Object(properties, options) {
1786
- const required = RequiredKeys(properties);
1787
- const schematic = required.length > 0 ? { [Kind]: "Object", type: "object", properties, required } : { [Kind]: "Object", type: "object", properties };
1788
- return CreateType(schematic, options);
1789
- }
1790
- var Object2 = _Object;
1791
-
1792
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/promise/promise.mjs
1793
- function Promise2(item, options) {
1794
- return CreateType({ [Kind]: "Promise", type: "Promise", item }, options);
1795
- }
1796
-
1797
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly.mjs
1798
- function RemoveReadonly(schema) {
1799
- return CreateType(Discard(schema, [ReadonlyKind]));
1800
- }
1801
- function AddReadonly(schema) {
1802
- return CreateType({ ...schema, [ReadonlyKind]: "Readonly" });
1803
- }
1804
- function ReadonlyWithFlag(schema, F) {
1805
- return F === false ? RemoveReadonly(schema) : AddReadonly(schema);
1806
- }
1807
- function Readonly(schema, enable) {
1808
- const F = enable ?? true;
1809
- return IsMappedResult(schema) ? ReadonlyFromMappedResult(schema, F) : ReadonlyWithFlag(schema, F);
1810
- }
1811
-
1812
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs
1813
- function FromProperties2(K, F) {
1814
- const Acc = {};
1815
- for (const K2 of globalThis.Object.getOwnPropertyNames(K))
1816
- Acc[K2] = Readonly(K[K2], F);
1817
- return Acc;
1818
- }
1819
- function FromMappedResult2(R, F) {
1820
- return FromProperties2(R.properties, F);
1821
- }
1822
- function ReadonlyFromMappedResult(R, F) {
1823
- const P = FromMappedResult2(R, F);
1824
- return MappedResult(P);
1825
- }
1826
-
1827
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/tuple/tuple.mjs
1828
- function Tuple(types, options) {
1829
- return CreateType(types.length > 0 ? { [Kind]: "Tuple", type: "array", items: types, additionalItems: false, minItems: types.length, maxItems: types.length } : { [Kind]: "Tuple", type: "array", minItems: types.length, maxItems: types.length }, options);
1830
- }
1831
-
1832
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs
1833
- function FromMappedResult3(K, P) {
1834
- return K in P ? FromSchemaType(K, P[K]) : MappedResult(P);
1835
- }
1836
- function MappedKeyToKnownMappedResultProperties(K) {
1837
- return { [K]: Literal(K) };
1838
- }
1839
- function MappedKeyToUnknownMappedResultProperties(P) {
1840
- const Acc = {};
1841
- for (const L of P)
1842
- Acc[L] = Literal(L);
1843
- return Acc;
1844
- }
1845
- function MappedKeyToMappedResultProperties(K, P) {
1846
- return SetIncludes(P, K) ? MappedKeyToKnownMappedResultProperties(K) : MappedKeyToUnknownMappedResultProperties(P);
1847
- }
1848
- function FromMappedKey(K, P) {
1849
- const R = MappedKeyToMappedResultProperties(K, P);
1850
- return FromMappedResult3(K, R);
1851
- }
1852
- function FromRest2(K, T) {
1853
- return T.map((L) => FromSchemaType(K, L));
1854
- }
1855
- function FromProperties3(K, T) {
1856
- const Acc = {};
1857
- for (const K2 of globalThis.Object.getOwnPropertyNames(T))
1858
- Acc[K2] = FromSchemaType(K, T[K2]);
1859
- return Acc;
1860
- }
1861
- function FromSchemaType(K, T) {
1862
- const options = { ...T };
1863
- return (
1864
- // unevaluated modifier types
1865
- IsOptional(T) ? Optional(FromSchemaType(K, Discard(T, [OptionalKind]))) : IsReadonly(T) ? Readonly(FromSchemaType(K, Discard(T, [ReadonlyKind]))) : (
1866
- // unevaluated mapped types
1867
- IsMappedResult(T) ? FromMappedResult3(K, T.properties) : IsMappedKey(T) ? FromMappedKey(K, T.keys) : (
1868
- // unevaluated types
1869
- IsConstructor(T) ? Constructor(FromRest2(K, T.parameters), FromSchemaType(K, T.returns), options) : IsFunction2(T) ? Function(FromRest2(K, T.parameters), FromSchemaType(K, T.returns), options) : IsAsyncIterator2(T) ? AsyncIterator(FromSchemaType(K, T.items), options) : IsIterator2(T) ? Iterator(FromSchemaType(K, T.items), options) : IsIntersect(T) ? Intersect(FromRest2(K, T.allOf), options) : IsUnion(T) ? Union(FromRest2(K, T.anyOf), options) : IsTuple(T) ? Tuple(FromRest2(K, T.items ?? []), options) : IsObject3(T) ? Object2(FromProperties3(K, T.properties), options) : IsArray3(T) ? Array2(FromSchemaType(K, T.items), options) : IsPromise(T) ? Promise2(FromSchemaType(K, T.item), options) : T
1870
- )
1871
- )
1872
- );
1873
- }
1874
- function MappedFunctionReturnType(K, T) {
1875
- const Acc = {};
1876
- for (const L of K)
1877
- Acc[L] = FromSchemaType(L, T);
1878
- return Acc;
1879
- }
1880
- function Mapped(key, map, options) {
1881
- const K = IsSchema(key) ? IndexPropertyKeys(key) : key;
1882
- const RT = map({ [Kind]: "MappedKey", keys: K });
1883
- const R = MappedFunctionReturnType(K, RT);
1884
- return Object2(R, options);
1885
- }
1886
-
1887
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/optional/optional.mjs
1888
- function RemoveOptional(schema) {
1889
- return CreateType(Discard(schema, [OptionalKind]));
1890
- }
1891
- function AddOptional(schema) {
1892
- return CreateType({ ...schema, [OptionalKind]: "Optional" });
1893
- }
1894
- function OptionalWithFlag(schema, F) {
1895
- return F === false ? RemoveOptional(schema) : AddOptional(schema);
1896
- }
1897
- function Optional(schema, enable) {
1898
- const F = enable ?? true;
1899
- return IsMappedResult(schema) ? OptionalFromMappedResult(schema, F) : OptionalWithFlag(schema, F);
1900
- }
1901
-
1902
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs
1903
- function FromProperties4(P, F) {
1904
- const Acc = {};
1905
- for (const K2 of globalThis.Object.getOwnPropertyNames(P))
1906
- Acc[K2] = Optional(P[K2], F);
1907
- return Acc;
1908
- }
1909
- function FromMappedResult4(R, F) {
1910
- return FromProperties4(R.properties, F);
1911
- }
1912
- function OptionalFromMappedResult(R, F) {
1913
- const P = FromMappedResult4(R, F);
1914
- return MappedResult(P);
1915
- }
1916
-
1917
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-create.mjs
1918
- function IntersectCreate(T, options = {}) {
1919
- const allObjects = T.every((schema) => IsObject3(schema));
1920
- const clonedUnevaluatedProperties = IsSchema(options.unevaluatedProperties) ? { unevaluatedProperties: options.unevaluatedProperties } : {};
1921
- return CreateType(options.unevaluatedProperties === false || IsSchema(options.unevaluatedProperties) || allObjects ? { ...clonedUnevaluatedProperties, [Kind]: "Intersect", type: "object", allOf: T } : { ...clonedUnevaluatedProperties, [Kind]: "Intersect", allOf: T }, options);
1922
- }
1923
-
1924
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs
1925
- function IsIntersectOptional(types) {
1926
- return types.every((left) => IsOptional(left));
1927
- }
1928
- function RemoveOptionalFromType2(type) {
1929
- return Discard(type, [OptionalKind]);
1930
- }
1931
- function RemoveOptionalFromRest2(types) {
1932
- return types.map((left) => IsOptional(left) ? RemoveOptionalFromType2(left) : left);
1933
- }
1934
- function ResolveIntersect(types, options) {
1935
- return IsIntersectOptional(types) ? Optional(IntersectCreate(RemoveOptionalFromRest2(types), options)) : IntersectCreate(RemoveOptionalFromRest2(types), options);
1936
- }
1937
- function IntersectEvaluated(types, options = {}) {
1938
- if (types.length === 1)
1939
- return CreateType(types[0], options);
1940
- if (types.length === 0)
1941
- return Never(options);
1942
- if (types.some((schema) => IsTransform(schema)))
1943
- throw new Error("Cannot intersect transform types");
1944
- return ResolveIntersect(types, options);
1945
- }
1946
-
1947
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect.mjs
1948
- function Intersect(types, options) {
1949
- if (types.length === 1)
1950
- return CreateType(types[0], options);
1951
- if (types.length === 0)
1952
- return Never(options);
1953
- if (types.some((schema) => IsTransform(schema)))
1954
- throw new Error("Cannot intersect transform types");
1955
- return IntersectCreate(types, options);
1956
- }
1957
-
1958
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/ref/ref.mjs
1959
- function Ref(...args) {
1960
- const [$ref, options] = typeof args[0] === "string" ? [args[0], args[1]] : [args[0].$id, args[1]];
1961
- if (typeof $ref !== "string")
1962
- throw new TypeBoxError("Ref: $ref must be a string");
1963
- return CreateType({ [Kind]: "Ref", $ref }, options);
1964
- }
1965
-
1966
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs
1967
- function FromComputed(target, parameters) {
1968
- return Computed("Awaited", [Computed(target, parameters)]);
1969
- }
1970
- function FromRef($ref) {
1971
- return Computed("Awaited", [Ref($ref)]);
1972
- }
1973
- function FromIntersect2(types) {
1974
- return Intersect(FromRest3(types));
1975
- }
1976
- function FromUnion4(types) {
1977
- return Union(FromRest3(types));
1978
- }
1979
- function FromPromise(type) {
1980
- return Awaited(type);
1981
- }
1982
- function FromRest3(types) {
1983
- return types.map((type) => Awaited(type));
1984
- }
1985
- function Awaited(type, options) {
1986
- return CreateType(IsComputed(type) ? FromComputed(type.target, type.parameters) : IsIntersect(type) ? FromIntersect2(type.allOf) : IsUnion(type) ? FromUnion4(type.anyOf) : IsPromise(type) ? FromPromise(type.item) : IsRef(type) ? FromRef(type.$ref) : type, options);
1987
- }
1988
-
1989
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-keys.mjs
1990
- function FromRest4(types) {
1991
- const result = [];
1992
- for (const L of types)
1993
- result.push(KeyOfPropertyKeys(L));
1994
- return result;
1995
- }
1996
- function FromIntersect3(types) {
1997
- const propertyKeysArray = FromRest4(types);
1998
- const propertyKeys = SetUnionMany(propertyKeysArray);
1999
- return propertyKeys;
2000
- }
2001
- function FromUnion5(types) {
2002
- const propertyKeysArray = FromRest4(types);
2003
- const propertyKeys = SetIntersectMany(propertyKeysArray);
2004
- return propertyKeys;
2005
- }
2006
- function FromTuple2(types) {
2007
- return types.map((_, indexer) => indexer.toString());
2008
- }
2009
- function FromArray2(_) {
2010
- return ["[number]"];
2011
- }
2012
- function FromProperties5(T) {
2013
- return globalThis.Object.getOwnPropertyNames(T);
2014
- }
2015
- function FromPatternProperties(patternProperties) {
2016
- if (!includePatternProperties)
2017
- return [];
2018
- const patternPropertyKeys = globalThis.Object.getOwnPropertyNames(patternProperties);
2019
- return patternPropertyKeys.map((key) => {
2020
- return key[0] === "^" && key[key.length - 1] === "$" ? key.slice(1, key.length - 1) : key;
2021
- });
2022
- }
2023
- function KeyOfPropertyKeys(type) {
2024
- return IsIntersect(type) ? FromIntersect3(type.allOf) : IsUnion(type) ? FromUnion5(type.anyOf) : IsTuple(type) ? FromTuple2(type.items ?? []) : IsArray3(type) ? FromArray2(type.items) : IsObject3(type) ? FromProperties5(type.properties) : IsRecord(type) ? FromPatternProperties(type.patternProperties) : [];
2025
- }
2026
- var includePatternProperties = false;
2027
-
2028
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs
2029
- function FromComputed2(target, parameters) {
2030
- return Computed("KeyOf", [Computed(target, parameters)]);
2031
- }
2032
- function FromRef2($ref) {
2033
- return Computed("KeyOf", [Ref($ref)]);
2034
- }
2035
- function KeyOfFromType(type, options) {
2036
- const propertyKeys = KeyOfPropertyKeys(type);
2037
- const propertyKeyTypes = KeyOfPropertyKeysToRest(propertyKeys);
2038
- const result = UnionEvaluated(propertyKeyTypes);
2039
- return CreateType(result, options);
2040
- }
2041
- function KeyOfPropertyKeysToRest(propertyKeys) {
2042
- return propertyKeys.map((L) => L === "[number]" ? Number2() : Literal(L));
2043
- }
2044
- function KeyOf(type, options) {
2045
- return IsComputed(type) ? FromComputed2(type.target, type.parameters) : IsRef(type) ? FromRef2(type.$ref) : IsMappedResult(type) ? KeyOfFromMappedResult(type, options) : KeyOfFromType(type, options);
2046
- }
2047
-
2048
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs
2049
- function FromProperties6(properties, options) {
2050
- const result = {};
2051
- for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
2052
- result[K2] = KeyOf(properties[K2], Clone(options));
2053
- return result;
2054
- }
2055
- function FromMappedResult5(mappedResult, options) {
2056
- return FromProperties6(mappedResult.properties, options);
2057
- }
2058
- function KeyOfFromMappedResult(mappedResult, options) {
2059
- const properties = FromMappedResult5(mappedResult, options);
2060
- return MappedResult(properties);
2061
- }
2062
-
2063
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs
2064
- function CompositeKeys(T) {
2065
- const Acc = [];
2066
- for (const L of T)
2067
- Acc.push(...KeyOfPropertyKeys(L));
2068
- return SetDistinct(Acc);
2069
- }
2070
- function FilterNever(T) {
2071
- return T.filter((L) => !IsNever(L));
2072
- }
2073
- function CompositeProperty(T, K) {
2074
- const Acc = [];
2075
- for (const L of T)
2076
- Acc.push(...IndexFromPropertyKeys(L, [K]));
2077
- return FilterNever(Acc);
2078
- }
2079
- function CompositeProperties(T, K) {
2080
- const Acc = {};
2081
- for (const L of K) {
2082
- Acc[L] = IntersectEvaluated(CompositeProperty(T, L));
2083
- }
2084
- return Acc;
2085
- }
2086
- function Composite(T, options) {
2087
- const K = CompositeKeys(T);
2088
- const P = CompositeProperties(T, K);
2089
- const R = Object2(P, options);
2090
- return R;
2091
- }
2092
-
2093
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/date/date.mjs
2094
- function Date2(options) {
2095
- return CreateType({ [Kind]: "Date", type: "Date" }, options);
2096
- }
2097
-
2098
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/null/null.mjs
2099
- function Null(options) {
2100
- return CreateType({ [Kind]: "Null", type: "null" }, options);
2101
- }
2102
-
2103
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/symbol/symbol.mjs
2104
- function Symbol2(options) {
2105
- return CreateType({ [Kind]: "Symbol", type: "symbol" }, options);
2106
- }
2107
-
2108
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/undefined/undefined.mjs
2109
- function Undefined(options) {
2110
- return CreateType({ [Kind]: "Undefined", type: "undefined" }, options);
2111
- }
2112
-
2113
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/uint8array/uint8array.mjs
2114
- function Uint8Array2(options) {
2115
- return CreateType({ [Kind]: "Uint8Array", type: "Uint8Array" }, options);
2116
- }
2117
-
2118
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/unknown/unknown.mjs
2119
- function Unknown(options) {
2120
- return CreateType({ [Kind]: "Unknown" }, options);
2121
- }
2122
-
2123
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/const/const.mjs
2124
- function FromArray3(T) {
2125
- return T.map((L) => FromValue(L, false));
2126
- }
2127
- function FromProperties7(value) {
2128
- const Acc = {};
2129
- for (const K of globalThis.Object.getOwnPropertyNames(value))
2130
- Acc[K] = Readonly(FromValue(value[K], false));
2131
- return Acc;
2132
- }
2133
- function ConditionalReadonly(T, root) {
2134
- return root === true ? T : Readonly(T);
2135
- }
2136
- function FromValue(value, root) {
2137
- return IsAsyncIterator(value) ? ConditionalReadonly(Any(), root) : IsIterator(value) ? ConditionalReadonly(Any(), root) : IsArray(value) ? Readonly(Tuple(FromArray3(value))) : IsUint8Array(value) ? Uint8Array2() : IsDate(value) ? Date2() : IsObject(value) ? ConditionalReadonly(Object2(FromProperties7(value)), root) : IsFunction(value) ? ConditionalReadonly(Function([], Unknown()), root) : IsUndefined(value) ? Undefined() : IsNull(value) ? Null() : IsSymbol(value) ? Symbol2() : IsBigInt(value) ? BigInt() : IsNumber(value) ? Literal(value) : IsBoolean(value) ? Literal(value) : IsString(value) ? Literal(value) : Object2({});
2138
- }
2139
- function Const(T, options) {
2140
- return CreateType(FromValue(T, true), options);
2141
- }
2142
-
2143
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/constructor-parameters.mjs
2144
- function ConstructorParameters(schema, options) {
2145
- return IsConstructor(schema) ? Tuple(schema.parameters, options) : Never(options);
2146
- }
2147
-
2148
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/enum/enum.mjs
2149
- function Enum(item, options) {
2150
- if (IsUndefined(item))
2151
- throw new Error("Enum undefined or empty");
2152
- const values1 = globalThis.Object.getOwnPropertyNames(item).filter((key) => isNaN(key)).map((key) => item[key]);
2153
- const values2 = [...new Set(values1)];
2154
- const anyOf = values2.map((value) => Literal(value));
2155
- return Union(anyOf, { ...options, [Hint]: "Enum" });
2156
- }
2157
-
2158
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/extends/extends-check.mjs
2159
- var ExtendsResolverError = class extends TypeBoxError {
2160
- };
2161
- var ExtendsResult;
2162
- (function(ExtendsResult2) {
2163
- ExtendsResult2[ExtendsResult2["Union"] = 0] = "Union";
2164
- ExtendsResult2[ExtendsResult2["True"] = 1] = "True";
2165
- ExtendsResult2[ExtendsResult2["False"] = 2] = "False";
2166
- })(ExtendsResult || (ExtendsResult = {}));
2167
- function IntoBooleanResult(result) {
2168
- return result === ExtendsResult.False ? result : ExtendsResult.True;
2169
- }
2170
- function Throw(message) {
2171
- throw new ExtendsResolverError(message);
2172
- }
2173
- function IsStructuralRight(right) {
2174
- return type_exports.IsNever(right) || type_exports.IsIntersect(right) || type_exports.IsUnion(right) || type_exports.IsUnknown(right) || type_exports.IsAny(right);
2175
- }
2176
- function StructuralRight(left, right) {
2177
- return type_exports.IsNever(right) ? FromNeverRight(left, right) : type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsUnknown(right) ? FromUnknownRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : Throw("StructuralRight");
2178
- }
2179
- function FromAnyRight(left, right) {
2180
- return ExtendsResult.True;
2181
- }
2182
- function FromAny(left, right) {
2183
- return type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) && right.anyOf.some((schema) => type_exports.IsAny(schema) || type_exports.IsUnknown(schema)) ? ExtendsResult.True : type_exports.IsUnion(right) ? ExtendsResult.Union : type_exports.IsUnknown(right) ? ExtendsResult.True : type_exports.IsAny(right) ? ExtendsResult.True : ExtendsResult.Union;
2184
- }
2185
- function FromArrayRight(left, right) {
2186
- return type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : type_exports.IsNever(left) ? ExtendsResult.True : ExtendsResult.False;
2187
- }
2188
- function FromArray4(left, right) {
2189
- return type_exports.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsArray(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items));
2190
- }
2191
- function FromAsyncIterator(left, right) {
2192
- return IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsAsyncIterator(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items));
2193
- }
2194
- function FromBigInt(left, right) {
2195
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsBigInt(right) ? ExtendsResult.True : ExtendsResult.False;
2196
- }
2197
- function FromBooleanRight(left, right) {
2198
- return type_exports.IsLiteralBoolean(left) ? ExtendsResult.True : type_exports.IsBoolean(left) ? ExtendsResult.True : ExtendsResult.False;
2199
- }
2200
- function FromBoolean(left, right) {
2201
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsBoolean(right) ? ExtendsResult.True : ExtendsResult.False;
2202
- }
2203
- function FromConstructor(left, right) {
2204
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsConstructor(right) ? ExtendsResult.False : left.parameters.length > right.parameters.length ? ExtendsResult.False : !left.parameters.every((schema, index9) => IntoBooleanResult(Visit3(right.parameters[index9], schema)) === ExtendsResult.True) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.returns, right.returns));
2205
- }
2206
- function FromDate(left, right) {
2207
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsDate(right) ? ExtendsResult.True : ExtendsResult.False;
2208
- }
2209
- function FromFunction(left, right) {
2210
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsFunction(right) ? ExtendsResult.False : left.parameters.length > right.parameters.length ? ExtendsResult.False : !left.parameters.every((schema, index9) => IntoBooleanResult(Visit3(right.parameters[index9], schema)) === ExtendsResult.True) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.returns, right.returns));
2211
- }
2212
- function FromIntegerRight(left, right) {
2213
- return type_exports.IsLiteral(left) && value_exports.IsNumber(left.const) ? ExtendsResult.True : type_exports.IsNumber(left) || type_exports.IsInteger(left) ? ExtendsResult.True : ExtendsResult.False;
2214
- }
2215
- function FromInteger(left, right) {
2216
- return type_exports.IsInteger(right) || type_exports.IsNumber(right) ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : ExtendsResult.False;
2217
- }
2218
- function FromIntersectRight(left, right) {
2219
- return right.allOf.every((schema) => Visit3(left, schema) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2220
- }
2221
- function FromIntersect4(left, right) {
2222
- return left.allOf.some((schema) => Visit3(schema, right) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2223
- }
2224
- function FromIterator(left, right) {
2225
- return IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsIterator(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items));
2226
- }
2227
- function FromLiteral2(left, right) {
2228
- return type_exports.IsLiteral(right) && right.const === left.const ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsString(right) ? FromStringRight(left, right) : type_exports.IsNumber(right) ? FromNumberRight(left, right) : type_exports.IsInteger(right) ? FromIntegerRight(left, right) : type_exports.IsBoolean(right) ? FromBooleanRight(left, right) : ExtendsResult.False;
2229
- }
2230
- function FromNeverRight(left, right) {
2231
- return ExtendsResult.False;
2232
- }
2233
- function FromNever(left, right) {
2234
- return ExtendsResult.True;
2235
- }
2236
- function UnwrapTNot(schema) {
2237
- let [current, depth] = [schema, 0];
2238
- while (true) {
2239
- if (!type_exports.IsNot(current))
2240
- break;
2241
- current = current.not;
2242
- depth += 1;
2243
- }
2244
- return depth % 2 === 0 ? current : Unknown();
2245
- }
2246
- function FromNot(left, right) {
2247
- return type_exports.IsNot(left) ? Visit3(UnwrapTNot(left), right) : type_exports.IsNot(right) ? Visit3(left, UnwrapTNot(right)) : Throw("Invalid fallthrough for Not");
2248
- }
2249
- function FromNull(left, right) {
2250
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsNull(right) ? ExtendsResult.True : ExtendsResult.False;
2251
- }
2252
- function FromNumberRight(left, right) {
2253
- return type_exports.IsLiteralNumber(left) ? ExtendsResult.True : type_exports.IsNumber(left) || type_exports.IsInteger(left) ? ExtendsResult.True : ExtendsResult.False;
2254
- }
2255
- function FromNumber(left, right) {
2256
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsInteger(right) || type_exports.IsNumber(right) ? ExtendsResult.True : ExtendsResult.False;
2257
- }
2258
- function IsObjectPropertyCount(schema, count) {
2259
- return Object.getOwnPropertyNames(schema.properties).length === count;
2260
- }
2261
- function IsObjectStringLike(schema) {
2262
- return IsObjectArrayLike(schema);
2263
- }
2264
- function IsObjectSymbolLike(schema) {
2265
- return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "description" in schema.properties && type_exports.IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && (type_exports.IsString(schema.properties.description.anyOf[0]) && type_exports.IsUndefined(schema.properties.description.anyOf[1]) || type_exports.IsString(schema.properties.description.anyOf[1]) && type_exports.IsUndefined(schema.properties.description.anyOf[0]));
2266
- }
2267
- function IsObjectNumberLike(schema) {
2268
- return IsObjectPropertyCount(schema, 0);
2269
- }
2270
- function IsObjectBooleanLike(schema) {
2271
- return IsObjectPropertyCount(schema, 0);
2272
- }
2273
- function IsObjectBigIntLike(schema) {
2274
- return IsObjectPropertyCount(schema, 0);
2275
- }
2276
- function IsObjectDateLike(schema) {
2277
- return IsObjectPropertyCount(schema, 0);
2278
- }
2279
- function IsObjectUint8ArrayLike(schema) {
2280
- return IsObjectArrayLike(schema);
2281
- }
2282
- function IsObjectFunctionLike(schema) {
2283
- const length = Number2();
2284
- return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "length" in schema.properties && IntoBooleanResult(Visit3(schema.properties["length"], length)) === ExtendsResult.True;
2285
- }
2286
- function IsObjectConstructorLike(schema) {
2287
- return IsObjectPropertyCount(schema, 0);
2288
- }
2289
- function IsObjectArrayLike(schema) {
2290
- const length = Number2();
2291
- return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "length" in schema.properties && IntoBooleanResult(Visit3(schema.properties["length"], length)) === ExtendsResult.True;
2292
- }
2293
- function IsObjectPromiseLike(schema) {
2294
- const then = Function([Any()], Any());
2295
- return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "then" in schema.properties && IntoBooleanResult(Visit3(schema.properties["then"], then)) === ExtendsResult.True;
2296
- }
2297
- function Property(left, right) {
2298
- return Visit3(left, right) === ExtendsResult.False ? ExtendsResult.False : type_exports.IsOptional(left) && !type_exports.IsOptional(right) ? ExtendsResult.False : ExtendsResult.True;
2299
- }
2300
- function FromObjectRight(left, right) {
2301
- return type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : type_exports.IsNever(left) || type_exports.IsLiteralString(left) && IsObjectStringLike(right) || type_exports.IsLiteralNumber(left) && IsObjectNumberLike(right) || type_exports.IsLiteralBoolean(left) && IsObjectBooleanLike(right) || type_exports.IsSymbol(left) && IsObjectSymbolLike(right) || type_exports.IsBigInt(left) && IsObjectBigIntLike(right) || type_exports.IsString(left) && IsObjectStringLike(right) || type_exports.IsSymbol(left) && IsObjectSymbolLike(right) || type_exports.IsNumber(left) && IsObjectNumberLike(right) || type_exports.IsInteger(left) && IsObjectNumberLike(right) || type_exports.IsBoolean(left) && IsObjectBooleanLike(right) || type_exports.IsUint8Array(left) && IsObjectUint8ArrayLike(right) || type_exports.IsDate(left) && IsObjectDateLike(right) || type_exports.IsConstructor(left) && IsObjectConstructorLike(right) || type_exports.IsFunction(left) && IsObjectFunctionLike(right) ? ExtendsResult.True : type_exports.IsRecord(left) && type_exports.IsString(RecordKey(left)) ? (() => {
2302
- return right[Hint] === "Record" ? ExtendsResult.True : ExtendsResult.False;
2303
- })() : type_exports.IsRecord(left) && type_exports.IsNumber(RecordKey(left)) ? (() => {
2304
- return IsObjectPropertyCount(right, 0) ? ExtendsResult.True : ExtendsResult.False;
2305
- })() : ExtendsResult.False;
2306
- }
2307
- function FromObject(left, right) {
2308
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : !type_exports.IsObject(right) ? ExtendsResult.False : (() => {
2309
- for (const key of Object.getOwnPropertyNames(right.properties)) {
2310
- if (!(key in left.properties) && !type_exports.IsOptional(right.properties[key])) {
2311
- return ExtendsResult.False;
2312
- }
2313
- if (type_exports.IsOptional(right.properties[key])) {
2314
- return ExtendsResult.True;
2315
- }
2316
- if (Property(left.properties[key], right.properties[key]) === ExtendsResult.False) {
2317
- return ExtendsResult.False;
2318
- }
2319
- }
2320
- return ExtendsResult.True;
2321
- })();
2322
- }
2323
- function FromPromise2(left, right) {
2324
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) && IsObjectPromiseLike(right) ? ExtendsResult.True : !type_exports.IsPromise(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.item, right.item));
2325
- }
2326
- function RecordKey(schema) {
2327
- return PatternNumberExact in schema.patternProperties ? Number2() : PatternStringExact in schema.patternProperties ? String2() : Throw("Unknown record key pattern");
2328
- }
2329
- function RecordValue(schema) {
2330
- return PatternNumberExact in schema.patternProperties ? schema.patternProperties[PatternNumberExact] : PatternStringExact in schema.patternProperties ? schema.patternProperties[PatternStringExact] : Throw("Unable to get record value schema");
2331
- }
2332
- function FromRecordRight(left, right) {
2333
- const [Key, Value] = [RecordKey(right), RecordValue(right)];
2334
- return type_exports.IsLiteralString(left) && type_exports.IsNumber(Key) && IntoBooleanResult(Visit3(left, Value)) === ExtendsResult.True ? ExtendsResult.True : type_exports.IsUint8Array(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsString(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsArray(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsObject(left) ? (() => {
2335
- for (const key of Object.getOwnPropertyNames(left.properties)) {
2336
- if (Property(Value, left.properties[key]) === ExtendsResult.False) {
2337
- return ExtendsResult.False;
2338
- }
2339
- }
2340
- return ExtendsResult.True;
2341
- })() : ExtendsResult.False;
2342
- }
2343
- function FromRecord(left, right) {
2344
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsRecord(right) ? ExtendsResult.False : Visit3(RecordValue(left), RecordValue(right));
2345
- }
2346
- function FromRegExp(left, right) {
2347
- const L = type_exports.IsRegExp(left) ? String2() : left;
2348
- const R = type_exports.IsRegExp(right) ? String2() : right;
2349
- return Visit3(L, R);
2350
- }
2351
- function FromStringRight(left, right) {
2352
- return type_exports.IsLiteral(left) && value_exports.IsString(left.const) ? ExtendsResult.True : type_exports.IsString(left) ? ExtendsResult.True : ExtendsResult.False;
2353
- }
2354
- function FromString(left, right) {
2355
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsString(right) ? ExtendsResult.True : ExtendsResult.False;
2356
- }
2357
- function FromSymbol(left, right) {
2358
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsSymbol(right) ? ExtendsResult.True : ExtendsResult.False;
2359
- }
2360
- function FromTemplateLiteral2(left, right) {
2361
- return type_exports.IsTemplateLiteral(left) ? Visit3(TemplateLiteralToUnion(left), right) : type_exports.IsTemplateLiteral(right) ? Visit3(left, TemplateLiteralToUnion(right)) : Throw("Invalid fallthrough for TemplateLiteral");
2362
- }
2363
- function IsArrayOfTuple(left, right) {
2364
- return type_exports.IsArray(right) && left.items !== void 0 && left.items.every((schema) => Visit3(schema, right.items) === ExtendsResult.True);
2365
- }
2366
- function FromTupleRight(left, right) {
2367
- return type_exports.IsNever(left) ? ExtendsResult.True : type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : ExtendsResult.False;
2368
- }
2369
- function FromTuple3(left, right) {
2370
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True : type_exports.IsArray(right) && IsArrayOfTuple(left, right) ? ExtendsResult.True : !type_exports.IsTuple(right) ? ExtendsResult.False : value_exports.IsUndefined(left.items) && !value_exports.IsUndefined(right.items) || !value_exports.IsUndefined(left.items) && value_exports.IsUndefined(right.items) ? ExtendsResult.False : value_exports.IsUndefined(left.items) && !value_exports.IsUndefined(right.items) ? ExtendsResult.True : left.items.every((schema, index9) => Visit3(schema, right.items[index9]) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2371
- }
2372
- function FromUint8Array(left, right) {
2373
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsUint8Array(right) ? ExtendsResult.True : ExtendsResult.False;
2374
- }
2375
- function FromUndefined(left, right) {
2376
- return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsVoid(right) ? FromVoidRight(left, right) : type_exports.IsUndefined(right) ? ExtendsResult.True : ExtendsResult.False;
2377
- }
2378
- function FromUnionRight(left, right) {
2379
- return right.anyOf.some((schema) => Visit3(left, schema) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2380
- }
2381
- function FromUnion6(left, right) {
2382
- return left.anyOf.every((schema) => Visit3(schema, right) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False;
2383
- }
2384
- function FromUnknownRight(left, right) {
2385
- return ExtendsResult.True;
2386
- }
2387
- function FromUnknown(left, right) {
2388
- return type_exports.IsNever(right) ? FromNeverRight(left, right) : type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : type_exports.IsString(right) ? FromStringRight(left, right) : type_exports.IsNumber(right) ? FromNumberRight(left, right) : type_exports.IsInteger(right) ? FromIntegerRight(left, right) : type_exports.IsBoolean(right) ? FromBooleanRight(left, right) : type_exports.IsArray(right) ? FromArrayRight(left, right) : type_exports.IsTuple(right) ? FromTupleRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsUnknown(right) ? ExtendsResult.True : ExtendsResult.False;
2389
- }
2390
- function FromVoidRight(left, right) {
2391
- return type_exports.IsUndefined(left) ? ExtendsResult.True : type_exports.IsUndefined(left) ? ExtendsResult.True : ExtendsResult.False;
2392
- }
2393
- function FromVoid(left, right) {
2394
- return type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsUnknown(right) ? FromUnknownRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsVoid(right) ? ExtendsResult.True : ExtendsResult.False;
2395
- }
2396
- function Visit3(left, right) {
2397
- return (
2398
- // resolvable
2399
- type_exports.IsTemplateLiteral(left) || type_exports.IsTemplateLiteral(right) ? FromTemplateLiteral2(left, right) : type_exports.IsRegExp(left) || type_exports.IsRegExp(right) ? FromRegExp(left, right) : type_exports.IsNot(left) || type_exports.IsNot(right) ? FromNot(left, right) : (
2400
- // standard
2401
- type_exports.IsAny(left) ? FromAny(left, right) : type_exports.IsArray(left) ? FromArray4(left, right) : type_exports.IsBigInt(left) ? FromBigInt(left, right) : type_exports.IsBoolean(left) ? FromBoolean(left, right) : type_exports.IsAsyncIterator(left) ? FromAsyncIterator(left, right) : type_exports.IsConstructor(left) ? FromConstructor(left, right) : type_exports.IsDate(left) ? FromDate(left, right) : type_exports.IsFunction(left) ? FromFunction(left, right) : type_exports.IsInteger(left) ? FromInteger(left, right) : type_exports.IsIntersect(left) ? FromIntersect4(left, right) : type_exports.IsIterator(left) ? FromIterator(left, right) : type_exports.IsLiteral(left) ? FromLiteral2(left, right) : type_exports.IsNever(left) ? FromNever(left, right) : type_exports.IsNull(left) ? FromNull(left, right) : type_exports.IsNumber(left) ? FromNumber(left, right) : type_exports.IsObject(left) ? FromObject(left, right) : type_exports.IsRecord(left) ? FromRecord(left, right) : type_exports.IsString(left) ? FromString(left, right) : type_exports.IsSymbol(left) ? FromSymbol(left, right) : type_exports.IsTuple(left) ? FromTuple3(left, right) : type_exports.IsPromise(left) ? FromPromise2(left, right) : type_exports.IsUint8Array(left) ? FromUint8Array(left, right) : type_exports.IsUndefined(left) ? FromUndefined(left, right) : type_exports.IsUnion(left) ? FromUnion6(left, right) : type_exports.IsUnknown(left) ? FromUnknown(left, right) : type_exports.IsVoid(left) ? FromVoid(left, right) : Throw(`Unknown left type operand '${left[Kind]}'`)
2402
- )
2403
- );
2404
- }
2405
- function ExtendsCheck(left, right) {
2406
- return Visit3(left, right);
2407
- }
2408
-
2409
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-result.mjs
2410
- function FromProperties8(P, Right, True, False, options) {
2411
- const Acc = {};
2412
- for (const K2 of globalThis.Object.getOwnPropertyNames(P))
2413
- Acc[K2] = Extends(P[K2], Right, True, False, Clone(options));
2414
- return Acc;
2415
- }
2416
- function FromMappedResult6(Left, Right, True, False, options) {
2417
- return FromProperties8(Left.properties, Right, True, False, options);
2418
- }
2419
- function ExtendsFromMappedResult(Left, Right, True, False, options) {
2420
- const P = FromMappedResult6(Left, Right, True, False, options);
2421
- return MappedResult(P);
2422
- }
2423
-
2424
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs
2425
- function ExtendsResolve(left, right, trueType, falseType) {
2426
- const R = ExtendsCheck(left, right);
2427
- return R === ExtendsResult.Union ? Union([trueType, falseType]) : R === ExtendsResult.True ? trueType : falseType;
2428
- }
2429
- function Extends(L, R, T, F, options) {
2430
- return IsMappedResult(L) ? ExtendsFromMappedResult(L, R, T, F, options) : IsMappedKey(L) ? CreateType(ExtendsFromMappedKey(L, R, T, F, options)) : CreateType(ExtendsResolve(L, R, T, F), options);
2431
- }
2432
-
2433
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs
2434
- function FromPropertyKey(K, U, L, R, options) {
2435
- return {
2436
- [K]: Extends(Literal(K), U, L, R, Clone(options))
2437
- };
2438
- }
2439
- function FromPropertyKeys(K, U, L, R, options) {
2440
- return K.reduce((Acc, LK) => {
2441
- return { ...Acc, ...FromPropertyKey(LK, U, L, R, options) };
2442
- }, {});
2443
- }
2444
- function FromMappedKey2(K, U, L, R, options) {
2445
- return FromPropertyKeys(K.keys, U, L, R, options);
2446
- }
2447
- function ExtendsFromMappedKey(T, U, L, R, options) {
2448
- const P = FromMappedKey2(T, U, L, R, options);
2449
- return MappedResult(P);
2450
- }
2451
-
2452
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-template-literal.mjs
2453
- function ExcludeFromTemplateLiteral(L, R) {
2454
- return Exclude(TemplateLiteralToUnion(L), R);
2455
- }
2456
-
2457
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs
2458
- function ExcludeRest(L, R) {
2459
- const excluded = L.filter((inner) => ExtendsCheck(inner, R) === ExtendsResult.False);
2460
- return excluded.length === 1 ? excluded[0] : Union(excluded);
2461
- }
2462
- function Exclude(L, R, options = {}) {
2463
- if (IsTemplateLiteral(L))
2464
- return CreateType(ExcludeFromTemplateLiteral(L, R), options);
2465
- if (IsMappedResult(L))
2466
- return CreateType(ExcludeFromMappedResult(L, R), options);
2467
- return CreateType(IsUnion(L) ? ExcludeRest(L.anyOf, R) : ExtendsCheck(L, R) !== ExtendsResult.False ? Never() : L, options);
2468
- }
2469
-
2470
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs
2471
- function FromProperties9(P, U) {
2472
- const Acc = {};
2473
- for (const K2 of globalThis.Object.getOwnPropertyNames(P))
2474
- Acc[K2] = Exclude(P[K2], U);
2475
- return Acc;
2476
- }
2477
- function FromMappedResult7(R, T) {
2478
- return FromProperties9(R.properties, T);
2479
- }
2480
- function ExcludeFromMappedResult(R, T) {
2481
- const P = FromMappedResult7(R, T);
2482
- return MappedResult(P);
2483
- }
2484
-
2485
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-template-literal.mjs
2486
- function ExtractFromTemplateLiteral(L, R) {
2487
- return Extract(TemplateLiteralToUnion(L), R);
2488
- }
2489
-
2490
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs
2491
- function ExtractRest(L, R) {
2492
- const extracted = L.filter((inner) => ExtendsCheck(inner, R) !== ExtendsResult.False);
2493
- return extracted.length === 1 ? extracted[0] : Union(extracted);
2494
- }
2495
- function Extract(L, R, options) {
2496
- if (IsTemplateLiteral(L))
2497
- return CreateType(ExtractFromTemplateLiteral(L, R), options);
2498
- if (IsMappedResult(L))
2499
- return CreateType(ExtractFromMappedResult(L, R), options);
2500
- return CreateType(IsUnion(L) ? ExtractRest(L.anyOf, R) : ExtendsCheck(L, R) !== ExtendsResult.False ? L : Never(), options);
2501
- }
2502
-
2503
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs
2504
- function FromProperties10(P, T) {
2505
- const Acc = {};
2506
- for (const K2 of globalThis.Object.getOwnPropertyNames(P))
2507
- Acc[K2] = Extract(P[K2], T);
2508
- return Acc;
2509
- }
2510
- function FromMappedResult8(R, T) {
2511
- return FromProperties10(R.properties, T);
2512
- }
2513
- function ExtractFromMappedResult(R, T) {
2514
- const P = FromMappedResult8(R, T);
2515
- return MappedResult(P);
2516
- }
2517
-
2518
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/instance-type/instance-type.mjs
2519
- function InstanceType(schema, options) {
2520
- return IsConstructor(schema) ? CreateType(schema.returns, options) : Never(options);
2521
- }
2522
-
2523
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/readonly-optional/readonly-optional.mjs
2524
- function ReadonlyOptional(schema) {
2525
- return Readonly(Optional(schema));
2526
- }
2527
-
2528
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/record/record.mjs
2529
- function RecordCreateFromPattern(pattern, T, options) {
2530
- return CreateType({ [Kind]: "Record", type: "object", patternProperties: { [pattern]: T } }, options);
2531
- }
2532
- function RecordCreateFromKeys(K, T, options) {
2533
- const result = {};
2534
- for (const K2 of K)
2535
- result[K2] = T;
2536
- return Object2(result, { ...options, [Hint]: "Record" });
2537
- }
2538
- function FromTemplateLiteralKey(K, T, options) {
2539
- return IsTemplateLiteralFinite(K) ? RecordCreateFromKeys(IndexPropertyKeys(K), T, options) : RecordCreateFromPattern(K.pattern, T, options);
2540
- }
2541
- function FromUnionKey(key, type, options) {
2542
- return RecordCreateFromKeys(IndexPropertyKeys(Union(key)), type, options);
2543
- }
2544
- function FromLiteralKey(key, type, options) {
2545
- return RecordCreateFromKeys([key.toString()], type, options);
2546
- }
2547
- function FromRegExpKey(key, type, options) {
2548
- return RecordCreateFromPattern(key.source, type, options);
2549
- }
2550
- function FromStringKey(key, type, options) {
2551
- const pattern = IsUndefined(key.pattern) ? PatternStringExact : key.pattern;
2552
- return RecordCreateFromPattern(pattern, type, options);
2553
- }
2554
- function FromAnyKey(_, type, options) {
2555
- return RecordCreateFromPattern(PatternStringExact, type, options);
2556
- }
2557
- function FromNeverKey(_key, type, options) {
2558
- return RecordCreateFromPattern(PatternNeverExact, type, options);
2559
- }
2560
- function FromBooleanKey(_key, type, options) {
2561
- return Object2({ true: type, false: type }, options);
2562
- }
2563
- function FromIntegerKey(_key, type, options) {
2564
- return RecordCreateFromPattern(PatternNumberExact, type, options);
2565
- }
2566
- function FromNumberKey(_, type, options) {
2567
- return RecordCreateFromPattern(PatternNumberExact, type, options);
2568
- }
2569
- function Record(key, type, options = {}) {
2570
- return IsUnion(key) ? FromUnionKey(key.anyOf, type, options) : IsTemplateLiteral(key) ? FromTemplateLiteralKey(key, type, options) : IsLiteral(key) ? FromLiteralKey(key.const, type, options) : IsBoolean2(key) ? FromBooleanKey(key, type, options) : IsInteger(key) ? FromIntegerKey(key, type, options) : IsNumber3(key) ? FromNumberKey(key, type, options) : IsRegExp2(key) ? FromRegExpKey(key, type, options) : IsString2(key) ? FromStringKey(key, type, options) : IsAny(key) ? FromAnyKey(key, type, options) : IsNever(key) ? FromNeverKey(key, type, options) : Never(options);
2571
- }
2572
- function RecordPattern(record) {
2573
- return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0];
2574
- }
2575
- function RecordKey2(type) {
2576
- const pattern = RecordPattern(type);
2577
- return pattern === PatternStringExact ? String2() : pattern === PatternNumberExact ? Number2() : String2({ pattern });
2578
- }
2579
- function RecordValue2(type) {
2580
- return type.patternProperties[RecordPattern(type)];
2581
- }
2582
-
2583
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs
2584
- function FromConstructor2(args, type) {
2585
- type.parameters = FromTypes(args, type.parameters);
2586
- type.returns = FromType(args, type.returns);
2587
- return type;
2588
- }
2589
- function FromFunction2(args, type) {
2590
- type.parameters = FromTypes(args, type.parameters);
2591
- type.returns = FromType(args, type.returns);
2592
- return type;
2593
- }
2594
- function FromIntersect5(args, type) {
2595
- type.allOf = FromTypes(args, type.allOf);
2596
- return type;
2597
- }
2598
- function FromUnion7(args, type) {
2599
- type.anyOf = FromTypes(args, type.anyOf);
2600
- return type;
2601
- }
2602
- function FromTuple4(args, type) {
2603
- if (IsUndefined(type.items))
2604
- return type;
2605
- type.items = FromTypes(args, type.items);
2606
- return type;
2607
- }
2608
- function FromArray5(args, type) {
2609
- type.items = FromType(args, type.items);
2610
- return type;
2611
- }
2612
- function FromAsyncIterator2(args, type) {
2613
- type.items = FromType(args, type.items);
2614
- return type;
2615
- }
2616
- function FromIterator2(args, type) {
2617
- type.items = FromType(args, type.items);
2618
- return type;
2619
- }
2620
- function FromPromise3(args, type) {
2621
- type.item = FromType(args, type.item);
2622
- return type;
2623
- }
2624
- function FromObject2(args, type) {
2625
- const mappedProperties = FromProperties11(args, type.properties);
2626
- return { ...type, ...Object2(mappedProperties) };
2627
- }
2628
- function FromRecord2(args, type) {
2629
- const mappedKey = FromType(args, RecordKey2(type));
2630
- const mappedValue = FromType(args, RecordValue2(type));
2631
- const result = Record(mappedKey, mappedValue);
2632
- return { ...type, ...result };
2633
- }
2634
- function FromArgument(args, argument) {
2635
- return argument.index in args ? args[argument.index] : Unknown();
2636
- }
2637
- function FromProperty2(args, type) {
2638
- const isReadonly = IsReadonly(type);
2639
- const isOptional = IsOptional(type);
2640
- const mapped = FromType(args, type);
2641
- return isReadonly && isOptional ? ReadonlyOptional(mapped) : isReadonly && !isOptional ? Readonly(mapped) : !isReadonly && isOptional ? Optional(mapped) : mapped;
2642
- }
2643
- function FromProperties11(args, properties) {
2644
- return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => {
2645
- return { ...result, [key]: FromProperty2(args, properties[key]) };
2646
- }, {});
2647
- }
2648
- function FromTypes(args, types) {
2649
- return types.map((type) => FromType(args, type));
2650
- }
2651
- function FromType(args, type) {
2652
- return IsConstructor(type) ? FromConstructor2(args, type) : IsFunction2(type) ? FromFunction2(args, type) : IsIntersect(type) ? FromIntersect5(args, type) : IsUnion(type) ? FromUnion7(args, type) : IsTuple(type) ? FromTuple4(args, type) : IsArray3(type) ? FromArray5(args, type) : IsAsyncIterator2(type) ? FromAsyncIterator2(args, type) : IsIterator2(type) ? FromIterator2(args, type) : IsPromise(type) ? FromPromise3(args, type) : IsObject3(type) ? FromObject2(args, type) : IsRecord(type) ? FromRecord2(args, type) : IsArgument(type) ? FromArgument(args, type) : type;
2653
- }
2654
- function Instantiate(type, args) {
2655
- return FromType(args, CloneType(type));
2656
- }
2657
-
2658
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/integer/integer.mjs
2659
- function Integer(options) {
2660
- return CreateType({ [Kind]: "Integer", type: "integer" }, options);
2661
- }
2662
-
2663
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic-from-mapped-key.mjs
2664
- function MappedIntrinsicPropertyKey(K, M, options) {
2665
- return {
2666
- [K]: Intrinsic(Literal(K), M, Clone(options))
2667
- };
2668
- }
2669
- function MappedIntrinsicPropertyKeys(K, M, options) {
2670
- const result = K.reduce((Acc, L) => {
2671
- return { ...Acc, ...MappedIntrinsicPropertyKey(L, M, options) };
2672
- }, {});
2673
- return result;
2674
- }
2675
- function MappedIntrinsicProperties(T, M, options) {
2676
- return MappedIntrinsicPropertyKeys(T["keys"], M, options);
2677
- }
2678
- function IntrinsicFromMappedKey(T, M, options) {
2679
- const P = MappedIntrinsicProperties(T, M, options);
2680
- return MappedResult(P);
2681
- }
2682
-
2683
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs
2684
- function ApplyUncapitalize(value) {
2685
- const [first, rest] = [value.slice(0, 1), value.slice(1)];
2686
- return [first.toLowerCase(), rest].join("");
2687
- }
2688
- function ApplyCapitalize(value) {
2689
- const [first, rest] = [value.slice(0, 1), value.slice(1)];
2690
- return [first.toUpperCase(), rest].join("");
2691
- }
2692
- function ApplyUppercase(value) {
2693
- return value.toUpperCase();
2694
- }
2695
- function ApplyLowercase(value) {
2696
- return value.toLowerCase();
2697
- }
2698
- function FromTemplateLiteral3(schema, mode, options) {
2699
- const expression = TemplateLiteralParseExact(schema.pattern);
2700
- const finite = IsTemplateLiteralExpressionFinite(expression);
2701
- if (!finite)
2702
- return { ...schema, pattern: FromLiteralValue(schema.pattern, mode) };
2703
- const strings = [...TemplateLiteralExpressionGenerate(expression)];
2704
- const literals = strings.map((value) => Literal(value));
2705
- const mapped = FromRest5(literals, mode);
2706
- const union = Union(mapped);
2707
- return TemplateLiteral([union], options);
2708
- }
2709
- function FromLiteralValue(value, mode) {
2710
- return typeof value === "string" ? mode === "Uncapitalize" ? ApplyUncapitalize(value) : mode === "Capitalize" ? ApplyCapitalize(value) : mode === "Uppercase" ? ApplyUppercase(value) : mode === "Lowercase" ? ApplyLowercase(value) : value : value.toString();
2711
- }
2712
- function FromRest5(T, M) {
2713
- return T.map((L) => Intrinsic(L, M));
2714
- }
2715
- function Intrinsic(schema, mode, options = {}) {
2716
- return (
2717
- // Intrinsic-Mapped-Inference
2718
- IsMappedKey(schema) ? IntrinsicFromMappedKey(schema, mode, options) : (
2719
- // Standard-Inference
2720
- IsTemplateLiteral(schema) ? FromTemplateLiteral3(schema, mode, options) : IsUnion(schema) ? Union(FromRest5(schema.anyOf, mode), options) : IsLiteral(schema) ? Literal(FromLiteralValue(schema.const, mode), options) : (
2721
- // Default Type
2722
- CreateType(schema, options)
2723
- )
2724
- )
2725
- );
2726
- }
2727
-
2728
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs
2729
- function Capitalize(T, options = {}) {
2730
- return Intrinsic(T, "Capitalize", options);
2731
- }
2732
-
2733
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intrinsic/lowercase.mjs
2734
- function Lowercase(T, options = {}) {
2735
- return Intrinsic(T, "Lowercase", options);
2736
- }
2737
-
2738
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uncapitalize.mjs
2739
- function Uncapitalize(T, options = {}) {
2740
- return Intrinsic(T, "Uncapitalize", options);
2741
- }
2742
-
2743
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uppercase.mjs
2744
- function Uppercase(T, options = {}) {
2745
- return Intrinsic(T, "Uppercase", options);
2746
- }
2747
-
2748
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-result.mjs
2749
- function FromProperties12(properties, propertyKeys, options) {
2750
- const result = {};
2751
- for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
2752
- result[K2] = Omit(properties[K2], propertyKeys, Clone(options));
2753
- return result;
2754
- }
2755
- function FromMappedResult9(mappedResult, propertyKeys, options) {
2756
- return FromProperties12(mappedResult.properties, propertyKeys, options);
2757
- }
2758
- function OmitFromMappedResult(mappedResult, propertyKeys, options) {
2759
- const properties = FromMappedResult9(mappedResult, propertyKeys, options);
2760
- return MappedResult(properties);
2761
- }
2762
-
2763
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs
2764
- function FromIntersect6(types, propertyKeys) {
2765
- return types.map((type) => OmitResolve(type, propertyKeys));
2766
- }
2767
- function FromUnion8(types, propertyKeys) {
2768
- return types.map((type) => OmitResolve(type, propertyKeys));
2769
- }
2770
- function FromProperty3(properties, key) {
2771
- const { [key]: _, ...R } = properties;
2772
- return R;
2773
- }
2774
- function FromProperties13(properties, propertyKeys) {
2775
- return propertyKeys.reduce((T, K2) => FromProperty3(T, K2), properties);
2776
- }
2777
- function FromObject3(properties, propertyKeys) {
2778
- const options = Discard(properties, [TransformKind, "$id", "required", "properties"]);
2779
- const omittedProperties = FromProperties13(properties["properties"], propertyKeys);
2780
- return Object2(omittedProperties, options);
2781
- }
2782
- function UnionFromPropertyKeys(propertyKeys) {
2783
- const result = propertyKeys.reduce((result2, key) => IsLiteralValue(key) ? [...result2, Literal(key)] : result2, []);
2784
- return Union(result);
2785
- }
2786
- function OmitResolve(properties, propertyKeys) {
2787
- return IsIntersect(properties) ? Intersect(FromIntersect6(properties.allOf, propertyKeys)) : IsUnion(properties) ? Union(FromUnion8(properties.anyOf, propertyKeys)) : IsObject3(properties) ? FromObject3(properties, propertyKeys) : Object2({});
2788
- }
2789
- function Omit(type, key, options) {
2790
- const typeKey = IsArray(key) ? UnionFromPropertyKeys(key) : key;
2791
- const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;
2792
- const isTypeRef = IsRef(type);
2793
- const isKeyRef = IsRef(key);
2794
- return IsMappedResult(type) ? OmitFromMappedResult(type, propertyKeys, options) : IsMappedKey(key) ? OmitFromMappedKey(type, key, options) : isTypeRef && isKeyRef ? Computed("Omit", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed("Omit", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed("Omit", [type, typeKey], options) : CreateType({ ...OmitResolve(type, propertyKeys), ...options });
2795
- }
2796
-
2797
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs
2798
- function FromPropertyKey2(type, key, options) {
2799
- return { [key]: Omit(type, [key], Clone(options)) };
2800
- }
2801
- function FromPropertyKeys2(type, propertyKeys, options) {
2802
- return propertyKeys.reduce((Acc, LK) => {
2803
- return { ...Acc, ...FromPropertyKey2(type, LK, options) };
2804
- }, {});
2805
- }
2806
- function FromMappedKey3(type, mappedKey, options) {
2807
- return FromPropertyKeys2(type, mappedKey.keys, options);
2808
- }
2809
- function OmitFromMappedKey(type, mappedKey, options) {
2810
- const properties = FromMappedKey3(type, mappedKey, options);
2811
- return MappedResult(properties);
2812
- }
2813
-
2814
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-result.mjs
2815
- function FromProperties14(properties, propertyKeys, options) {
2816
- const result = {};
2817
- for (const K2 of globalThis.Object.getOwnPropertyNames(properties))
2818
- result[K2] = Pick(properties[K2], propertyKeys, Clone(options));
2819
- return result;
2820
- }
2821
- function FromMappedResult10(mappedResult, propertyKeys, options) {
2822
- return FromProperties14(mappedResult.properties, propertyKeys, options);
2823
- }
2824
- function PickFromMappedResult(mappedResult, propertyKeys, options) {
2825
- const properties = FromMappedResult10(mappedResult, propertyKeys, options);
2826
- return MappedResult(properties);
2827
- }
2828
-
2829
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs
2830
- function FromIntersect7(types, propertyKeys) {
2831
- return types.map((type) => PickResolve(type, propertyKeys));
2832
- }
2833
- function FromUnion9(types, propertyKeys) {
2834
- return types.map((type) => PickResolve(type, propertyKeys));
2835
- }
2836
- function FromProperties15(properties, propertyKeys) {
2837
- const result = {};
2838
- for (const K2 of propertyKeys)
2839
- if (K2 in properties)
2840
- result[K2] = properties[K2];
2841
- return result;
2842
- }
2843
- function FromObject4(T, K) {
2844
- const options = Discard(T, [TransformKind, "$id", "required", "properties"]);
2845
- const properties = FromProperties15(T["properties"], K);
2846
- return Object2(properties, options);
2847
- }
2848
- function UnionFromPropertyKeys2(propertyKeys) {
2849
- const result = propertyKeys.reduce((result2, key) => IsLiteralValue(key) ? [...result2, Literal(key)] : result2, []);
2850
- return Union(result);
2851
- }
2852
- function PickResolve(properties, propertyKeys) {
2853
- return IsIntersect(properties) ? Intersect(FromIntersect7(properties.allOf, propertyKeys)) : IsUnion(properties) ? Union(FromUnion9(properties.anyOf, propertyKeys)) : IsObject3(properties) ? FromObject4(properties, propertyKeys) : Object2({});
2854
- }
2855
- function Pick(type, key, options) {
2856
- const typeKey = IsArray(key) ? UnionFromPropertyKeys2(key) : key;
2857
- const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;
2858
- const isTypeRef = IsRef(type);
2859
- const isKeyRef = IsRef(key);
2860
- return IsMappedResult(type) ? PickFromMappedResult(type, propertyKeys, options) : IsMappedKey(key) ? PickFromMappedKey(type, key, options) : isTypeRef && isKeyRef ? Computed("Pick", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed("Pick", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed("Pick", [type, typeKey], options) : CreateType({ ...PickResolve(type, propertyKeys), ...options });
2861
- }
2862
-
2863
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs
2864
- function FromPropertyKey3(type, key, options) {
2865
- return {
2866
- [key]: Pick(type, [key], Clone(options))
2867
- };
2868
- }
2869
- function FromPropertyKeys3(type, propertyKeys, options) {
2870
- return propertyKeys.reduce((result, leftKey) => {
2871
- return { ...result, ...FromPropertyKey3(type, leftKey, options) };
2872
- }, {});
2873
- }
2874
- function FromMappedKey4(type, mappedKey, options) {
2875
- return FromPropertyKeys3(type, mappedKey.keys, options);
2876
- }
2877
- function PickFromMappedKey(type, mappedKey, options) {
2878
- const properties = FromMappedKey4(type, mappedKey, options);
2879
- return MappedResult(properties);
2880
- }
2881
-
2882
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/partial/partial.mjs
2883
- function FromComputed3(target, parameters) {
2884
- return Computed("Partial", [Computed(target, parameters)]);
2885
- }
2886
- function FromRef3($ref) {
2887
- return Computed("Partial", [Ref($ref)]);
2888
- }
2889
- function FromProperties16(properties) {
2890
- const partialProperties = {};
2891
- for (const K of globalThis.Object.getOwnPropertyNames(properties))
2892
- partialProperties[K] = Optional(properties[K]);
2893
- return partialProperties;
2894
- }
2895
- function FromObject5(type) {
2896
- const options = Discard(type, [TransformKind, "$id", "required", "properties"]);
2897
- const properties = FromProperties16(type["properties"]);
2898
- return Object2(properties, options);
2899
- }
2900
- function FromRest6(types) {
2901
- return types.map((type) => PartialResolve(type));
2902
- }
2903
- function PartialResolve(type) {
2904
- return (
2905
- // Mappable
2906
- IsComputed(type) ? FromComputed3(type.target, type.parameters) : IsRef(type) ? FromRef3(type.$ref) : IsIntersect(type) ? Intersect(FromRest6(type.allOf)) : IsUnion(type) ? Union(FromRest6(type.anyOf)) : IsObject3(type) ? FromObject5(type) : (
2907
- // Intrinsic
2908
- IsBigInt2(type) ? type : IsBoolean2(type) ? type : IsInteger(type) ? type : IsLiteral(type) ? type : IsNull2(type) ? type : IsNumber3(type) ? type : IsString2(type) ? type : IsSymbol2(type) ? type : IsUndefined3(type) ? type : (
2909
- // Passthrough
2910
- Object2({})
2911
- )
2912
- )
2913
- );
2914
- }
2915
- function Partial(type, options) {
2916
- if (IsMappedResult(type)) {
2917
- return PartialFromMappedResult(type, options);
2918
- } else {
2919
- return CreateType({ ...PartialResolve(type), ...options });
2920
- }
2921
- }
2922
-
2923
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs
2924
- function FromProperties17(K, options) {
2925
- const Acc = {};
2926
- for (const K2 of globalThis.Object.getOwnPropertyNames(K))
2927
- Acc[K2] = Partial(K[K2], Clone(options));
2928
- return Acc;
2929
- }
2930
- function FromMappedResult11(R, options) {
2931
- return FromProperties17(R.properties, options);
2932
- }
2933
- function PartialFromMappedResult(R, options) {
2934
- const P = FromMappedResult11(R, options);
2935
- return MappedResult(P);
2936
- }
2937
-
2938
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/required/required.mjs
2939
- function FromComputed4(target, parameters) {
2940
- return Computed("Required", [Computed(target, parameters)]);
2941
- }
2942
- function FromRef4($ref) {
2943
- return Computed("Required", [Ref($ref)]);
2944
- }
2945
- function FromProperties18(properties) {
2946
- const requiredProperties = {};
2947
- for (const K of globalThis.Object.getOwnPropertyNames(properties))
2948
- requiredProperties[K] = Discard(properties[K], [OptionalKind]);
2949
- return requiredProperties;
2950
- }
2951
- function FromObject6(type) {
2952
- const options = Discard(type, [TransformKind, "$id", "required", "properties"]);
2953
- const properties = FromProperties18(type["properties"]);
2954
- return Object2(properties, options);
2955
- }
2956
- function FromRest7(types) {
2957
- return types.map((type) => RequiredResolve(type));
2958
- }
2959
- function RequiredResolve(type) {
2960
- return (
2961
- // Mappable
2962
- IsComputed(type) ? FromComputed4(type.target, type.parameters) : IsRef(type) ? FromRef4(type.$ref) : IsIntersect(type) ? Intersect(FromRest7(type.allOf)) : IsUnion(type) ? Union(FromRest7(type.anyOf)) : IsObject3(type) ? FromObject6(type) : (
2963
- // Intrinsic
2964
- IsBigInt2(type) ? type : IsBoolean2(type) ? type : IsInteger(type) ? type : IsLiteral(type) ? type : IsNull2(type) ? type : IsNumber3(type) ? type : IsString2(type) ? type : IsSymbol2(type) ? type : IsUndefined3(type) ? type : (
2965
- // Passthrough
2966
- Object2({})
2967
- )
2968
- )
2969
- );
2970
- }
2971
- function Required(type, options) {
2972
- if (IsMappedResult(type)) {
2973
- return RequiredFromMappedResult(type, options);
2974
- } else {
2975
- return CreateType({ ...RequiredResolve(type), ...options });
2976
- }
2977
- }
2978
-
2979
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs
2980
- function FromProperties19(P, options) {
2981
- const Acc = {};
2982
- for (const K2 of globalThis.Object.getOwnPropertyNames(P))
2983
- Acc[K2] = Required(P[K2], options);
2984
- return Acc;
2985
- }
2986
- function FromMappedResult12(R, options) {
2987
- return FromProperties19(R.properties, options);
2988
- }
2989
- function RequiredFromMappedResult(R, options) {
2990
- const P = FromMappedResult12(R, options);
2991
- return MappedResult(P);
2992
- }
2993
-
2994
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs
2995
- function DereferenceParameters(moduleProperties, types) {
2996
- return types.map((type) => {
2997
- return IsRef(type) ? Dereference(moduleProperties, type.$ref) : FromType2(moduleProperties, type);
2998
- });
2999
- }
3000
- function Dereference(moduleProperties, ref) {
3001
- return ref in moduleProperties ? IsRef(moduleProperties[ref]) ? Dereference(moduleProperties, moduleProperties[ref].$ref) : FromType2(moduleProperties, moduleProperties[ref]) : Never();
3002
- }
3003
- function FromAwaited(parameters) {
3004
- return Awaited(parameters[0]);
3005
- }
3006
- function FromIndex(parameters) {
3007
- return Index(parameters[0], parameters[1]);
3008
- }
3009
- function FromKeyOf(parameters) {
3010
- return KeyOf(parameters[0]);
3011
- }
3012
- function FromPartial(parameters) {
3013
- return Partial(parameters[0]);
3014
- }
3015
- function FromOmit(parameters) {
3016
- return Omit(parameters[0], parameters[1]);
3017
- }
3018
- function FromPick(parameters) {
3019
- return Pick(parameters[0], parameters[1]);
3020
- }
3021
- function FromRequired(parameters) {
3022
- return Required(parameters[0]);
3023
- }
3024
- function FromComputed5(moduleProperties, target, parameters) {
3025
- const dereferenced = DereferenceParameters(moduleProperties, parameters);
3026
- return target === "Awaited" ? FromAwaited(dereferenced) : target === "Index" ? FromIndex(dereferenced) : target === "KeyOf" ? FromKeyOf(dereferenced) : target === "Partial" ? FromPartial(dereferenced) : target === "Omit" ? FromOmit(dereferenced) : target === "Pick" ? FromPick(dereferenced) : target === "Required" ? FromRequired(dereferenced) : Never();
3027
- }
3028
- function FromArray6(moduleProperties, type) {
3029
- return Array2(FromType2(moduleProperties, type));
3030
- }
3031
- function FromAsyncIterator3(moduleProperties, type) {
3032
- return AsyncIterator(FromType2(moduleProperties, type));
3033
- }
3034
- function FromConstructor3(moduleProperties, parameters, instanceType) {
3035
- return Constructor(FromTypes2(moduleProperties, parameters), FromType2(moduleProperties, instanceType));
3036
- }
3037
- function FromFunction3(moduleProperties, parameters, returnType) {
3038
- return Function(FromTypes2(moduleProperties, parameters), FromType2(moduleProperties, returnType));
3039
- }
3040
- function FromIntersect8(moduleProperties, types) {
3041
- return Intersect(FromTypes2(moduleProperties, types));
3042
- }
3043
- function FromIterator3(moduleProperties, type) {
3044
- return Iterator(FromType2(moduleProperties, type));
3045
- }
3046
- function FromObject7(moduleProperties, properties) {
3047
- return Object2(globalThis.Object.keys(properties).reduce((result, key) => {
3048
- return { ...result, [key]: FromType2(moduleProperties, properties[key]) };
3049
- }, {}));
3050
- }
3051
- function FromRecord3(moduleProperties, type) {
3052
- const [value, pattern] = [FromType2(moduleProperties, RecordValue2(type)), RecordPattern(type)];
3053
- const result = CloneType(type);
3054
- result.patternProperties[pattern] = value;
3055
- return result;
3056
- }
3057
- function FromTransform(moduleProperties, transform) {
3058
- return IsRef(transform) ? { ...Dereference(moduleProperties, transform.$ref), [TransformKind]: transform[TransformKind] } : transform;
3059
- }
3060
- function FromTuple5(moduleProperties, types) {
3061
- return Tuple(FromTypes2(moduleProperties, types));
3062
- }
3063
- function FromUnion10(moduleProperties, types) {
3064
- return Union(FromTypes2(moduleProperties, types));
3065
- }
3066
- function FromTypes2(moduleProperties, types) {
3067
- return types.map((type) => FromType2(moduleProperties, type));
3068
- }
3069
- function FromType2(moduleProperties, type) {
3070
- return (
3071
- // Modifiers
3072
- IsOptional(type) ? CreateType(FromType2(moduleProperties, Discard(type, [OptionalKind])), type) : IsReadonly(type) ? CreateType(FromType2(moduleProperties, Discard(type, [ReadonlyKind])), type) : (
3073
- // Transform
3074
- IsTransform(type) ? CreateType(FromTransform(moduleProperties, type), type) : (
3075
- // Types
3076
- IsArray3(type) ? CreateType(FromArray6(moduleProperties, type.items), type) : IsAsyncIterator2(type) ? CreateType(FromAsyncIterator3(moduleProperties, type.items), type) : IsComputed(type) ? CreateType(FromComputed5(moduleProperties, type.target, type.parameters)) : IsConstructor(type) ? CreateType(FromConstructor3(moduleProperties, type.parameters, type.returns), type) : IsFunction2(type) ? CreateType(FromFunction3(moduleProperties, type.parameters, type.returns), type) : IsIntersect(type) ? CreateType(FromIntersect8(moduleProperties, type.allOf), type) : IsIterator2(type) ? CreateType(FromIterator3(moduleProperties, type.items), type) : IsObject3(type) ? CreateType(FromObject7(moduleProperties, type.properties), type) : IsRecord(type) ? CreateType(FromRecord3(moduleProperties, type)) : IsTuple(type) ? CreateType(FromTuple5(moduleProperties, type.items || []), type) : IsUnion(type) ? CreateType(FromUnion10(moduleProperties, type.anyOf), type) : type
3077
- )
3078
- )
3079
- );
3080
- }
3081
- function ComputeType(moduleProperties, key) {
3082
- return key in moduleProperties ? FromType2(moduleProperties, moduleProperties[key]) : Never();
3083
- }
3084
- function ComputeModuleProperties(moduleProperties) {
3085
- return globalThis.Object.getOwnPropertyNames(moduleProperties).reduce((result, key) => {
3086
- return { ...result, [key]: ComputeType(moduleProperties, key) };
3087
- }, {});
3088
- }
3089
-
3090
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/module/module.mjs
3091
- var TModule = class {
3092
- constructor($defs) {
3093
- const computed = ComputeModuleProperties($defs);
3094
- const identified = this.WithIdentifiers(computed);
3095
- this.$defs = identified;
3096
- }
3097
- /** `[Json]` Imports a Type by Key. */
3098
- Import(key, options) {
3099
- const $defs = { ...this.$defs, [key]: CreateType(this.$defs[key], options) };
3100
- return CreateType({ [Kind]: "Import", $defs, $ref: key });
3101
- }
3102
- // prettier-ignore
3103
- WithIdentifiers($defs) {
3104
- return globalThis.Object.getOwnPropertyNames($defs).reduce((result, key) => {
3105
- return { ...result, [key]: { ...$defs[key], $id: key } };
3106
- }, {});
3107
- }
3108
- };
3109
- function Module(properties) {
3110
- return new TModule(properties);
3111
- }
3112
-
3113
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/not/not.mjs
3114
- function Not(type, options) {
3115
- return CreateType({ [Kind]: "Not", not: type }, options);
3116
- }
3117
-
3118
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/parameters/parameters.mjs
3119
- function Parameters(schema, options) {
3120
- return IsFunction2(schema) ? Tuple(schema.parameters, options) : Never();
3121
- }
3122
-
3123
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/recursive/recursive.mjs
3124
- var Ordinal = 0;
3125
- function Recursive(callback, options = {}) {
3126
- if (IsUndefined(options.$id))
3127
- options.$id = `T${Ordinal++}`;
3128
- const thisType = CloneType(callback({ [Kind]: "This", $ref: `${options.$id}` }));
3129
- thisType.$id = options.$id;
3130
- return CreateType({ [Hint]: "Recursive", ...thisType }, options);
3131
- }
3132
-
3133
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/regexp/regexp.mjs
3134
- function RegExp2(unresolved, options) {
3135
- const expr = IsString(unresolved) ? new globalThis.RegExp(unresolved) : unresolved;
3136
- return CreateType({ [Kind]: "RegExp", type: "RegExp", source: expr.source, flags: expr.flags }, options);
3137
- }
3138
-
3139
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/rest/rest.mjs
3140
- function RestResolve(T) {
3141
- return IsIntersect(T) ? T.allOf : IsUnion(T) ? T.anyOf : IsTuple(T) ? T.items ?? [] : [];
3142
- }
3143
- function Rest(T) {
3144
- return RestResolve(T);
3145
- }
3146
-
3147
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/return-type/return-type.mjs
3148
- function ReturnType(schema, options) {
3149
- return IsFunction2(schema) ? CreateType(schema.returns, options) : Never(options);
3150
- }
3151
-
3152
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/transform/transform.mjs
3153
- var TransformDecodeBuilder = class {
3154
- constructor(schema) {
3155
- this.schema = schema;
3156
- }
3157
- Decode(decode) {
3158
- return new TransformEncodeBuilder(this.schema, decode);
3159
- }
3160
- };
3161
- var TransformEncodeBuilder = class {
3162
- constructor(schema, decode) {
3163
- this.schema = schema;
3164
- this.decode = decode;
3165
- }
3166
- EncodeTransform(encode, schema) {
3167
- const Encode = (value) => schema[TransformKind].Encode(encode(value));
3168
- const Decode = (value) => this.decode(schema[TransformKind].Decode(value));
3169
- const Codec = { Encode, Decode };
3170
- return { ...schema, [TransformKind]: Codec };
3171
- }
3172
- EncodeSchema(encode, schema) {
3173
- const Codec = { Decode: this.decode, Encode: encode };
3174
- return { ...schema, [TransformKind]: Codec };
3175
- }
3176
- Encode(encode) {
3177
- return IsTransform(this.schema) ? this.EncodeTransform(encode, this.schema) : this.EncodeSchema(encode, this.schema);
3178
- }
3179
- };
3180
- function Transform(schema) {
3181
- return new TransformDecodeBuilder(schema);
3182
- }
3183
-
3184
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/unsafe/unsafe.mjs
3185
- function Unsafe(options = {}) {
3186
- return CreateType({ [Kind]: options[Kind] ?? "Unsafe" }, options);
3187
- }
3188
-
3189
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/void/void.mjs
3190
- function Void(options) {
3191
- return CreateType({ [Kind]: "Void", type: "void" }, options);
3192
- }
3193
-
3194
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/type/type.mjs
3195
- var type_exports2 = {};
3196
- __export(type_exports2, {
3197
- Any: () => Any,
3198
- Argument: () => Argument,
3199
- Array: () => Array2,
3200
- AsyncIterator: () => AsyncIterator,
3201
- Awaited: () => Awaited,
3202
- BigInt: () => BigInt,
3203
- Boolean: () => Boolean,
3204
- Capitalize: () => Capitalize,
3205
- Composite: () => Composite,
3206
- Const: () => Const,
3207
- Constructor: () => Constructor,
3208
- ConstructorParameters: () => ConstructorParameters,
3209
- Date: () => Date2,
3210
- Enum: () => Enum,
3211
- Exclude: () => Exclude,
3212
- Extends: () => Extends,
3213
- Extract: () => Extract,
3214
- Function: () => Function,
3215
- Index: () => Index,
3216
- InstanceType: () => InstanceType,
3217
- Instantiate: () => Instantiate,
3218
- Integer: () => Integer,
3219
- Intersect: () => Intersect,
3220
- Iterator: () => Iterator,
3221
- KeyOf: () => KeyOf,
3222
- Literal: () => Literal,
3223
- Lowercase: () => Lowercase,
3224
- Mapped: () => Mapped,
3225
- Module: () => Module,
3226
- Never: () => Never,
3227
- Not: () => Not,
3228
- Null: () => Null,
3229
- Number: () => Number2,
3230
- Object: () => Object2,
3231
- Omit: () => Omit,
3232
- Optional: () => Optional,
3233
- Parameters: () => Parameters,
3234
- Partial: () => Partial,
3235
- Pick: () => Pick,
3236
- Promise: () => Promise2,
3237
- Readonly: () => Readonly,
3238
- ReadonlyOptional: () => ReadonlyOptional,
3239
- Record: () => Record,
3240
- Recursive: () => Recursive,
3241
- Ref: () => Ref,
3242
- RegExp: () => RegExp2,
3243
- Required: () => Required,
3244
- Rest: () => Rest,
3245
- ReturnType: () => ReturnType,
3246
- String: () => String2,
3247
- Symbol: () => Symbol2,
3248
- TemplateLiteral: () => TemplateLiteral,
3249
- Transform: () => Transform,
3250
- Tuple: () => Tuple,
3251
- Uint8Array: () => Uint8Array2,
3252
- Uncapitalize: () => Uncapitalize,
3253
- Undefined: () => Undefined,
3254
- Union: () => Union,
3255
- Unknown: () => Unknown,
3256
- Unsafe: () => Unsafe,
3257
- Uppercase: () => Uppercase,
3258
- Void: () => Void
3259
- });
3260
-
3261
- // ../../node_modules/.pnpm/@sinclair+typebox@0.34.41/node_modules/@sinclair/typebox/build/esm/type/type/index.mjs
3262
- var Type = type_exports2;
3263
-
3264
- // src/lib/types/schemas.ts
3265
- var SuccessResponseSchema = (dataSchema) => Type.Object(
3266
- {
3267
- success: Type.Literal(true),
3268
- data: dataSchema,
3269
- message: Type.Optional(Type.String())
3270
- }
3271
- );
3272
- var ErrorResponseSchema = Type.Object(
3273
- {
3274
- success: Type.Literal(false),
3275
- error: Type.Object(
3276
- {
3277
- code: Type.String(),
3278
- message: Type.String(),
3279
- details: Type.Optional(Type.Any())
3280
- }
3281
- )
3282
- }
3283
- );
3284
- var ApiResponseSchema = (dataSchema) => Type.Union([
3285
- SuccessResponseSchema(dataSchema),
3286
- ErrorResponseSchema
3287
- ]);
3288
-
3289
- // src/lib/contracts/auth.ts
3290
- var EMAIL_PATTERN = "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
3291
- var PHONE_PATTERN = "^\\+[1-9]\\d{1,14}$";
3292
- var FINGERPRINT_PATTERN = "^[a-f0-9]{64}$";
3293
- var UUID_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
3294
- var BASE64_PATTERN = "^[A-Za-z0-9+/]+=*$";
3295
- var sendVerificationCodeContract = {
3296
- method: "POST",
3297
- path: "/_auth/codes",
3298
- body: Type.Object({
3299
- target: Type.String({
3300
- description: "Email address or phone number in E.164 format"
3301
- }),
3302
- targetType: Type.Union([
3303
- Type.Literal("email"),
3304
- Type.Literal("phone")
3305
- ], {
3306
- description: "Type of target (email or phone)"
3307
- }),
3308
- purpose: Type.Union([
3309
- Type.Literal("registration"),
3310
- Type.Literal("login"),
3311
- Type.Literal("password_reset")
3312
- ], {
3313
- description: "Purpose of verification"
3314
- })
3315
- }),
3316
- response: ApiResponseSchema(
3317
- Type.Object({
3318
- success: Type.Boolean(),
3319
- expiresAt: Type.String({ description: "ISO 8601 expiry time" })
3320
- })
3321
- )
3322
- };
3323
- var verifyCodeContract = {
3324
- method: "POST",
3325
- path: "/_auth/codes/verify",
3326
- body: Type.Object({
3327
- target: Type.String({
3328
- description: "Email address or phone number"
3329
- }),
3330
- targetType: Type.Union([
3331
- Type.Literal("email"),
3332
- Type.Literal("phone")
3333
- ]),
3334
- code: Type.String({
3335
- minLength: 6,
3336
- maxLength: 6,
3337
- pattern: "^[0-9]{6}$",
3338
- description: "6-digit verification code"
3339
- }),
3340
- purpose: Type.Union([
3341
- Type.Literal("registration"),
3342
- Type.Literal("login"),
3343
- Type.Literal("password_reset")
3344
- ])
3345
- }),
3346
- response: ApiResponseSchema(
3347
- Type.Object({
3348
- valid: Type.Boolean(),
3349
- verificationToken: Type.Optional(Type.String({
3350
- description: "Temporary token for completing registration (15min validity)"
3351
- }))
3352
- })
3353
- )
3354
- };
3355
- var checkAccountExistsContract = {
3356
- method: "POST",
3357
- path: "/_auth/exists",
3358
- body: Type.Object(
3359
- {
3360
- email: Type.Optional(Type.String({
3361
- pattern: EMAIL_PATTERN,
3362
- description: "Email address to check"
3363
- })),
3364
- phone: Type.Optional(Type.String({
3365
- pattern: PHONE_PATTERN,
3366
- description: "Phone number in E.164 format (e.g., +821012345678)"
3367
- }))
3368
- },
3369
- {
3370
- minProperties: 1,
3371
- description: "At least one of email or phone must be provided"
3372
- }
3373
- ),
3374
- response: ApiResponseSchema(
3375
- Type.Object(
3376
- {
3377
- exists: Type.Boolean({ description: "Whether the account exists" }),
3378
- identifier: Type.String({ description: "The identifier that was checked" }),
3379
- identifierType: Type.Union([
3380
- Type.Literal("email"),
3381
- Type.Literal("phone")
3382
- ], { description: "Type of identifier checked" })
3383
- }
3384
- )
3385
- )
3386
- };
3387
- var registerContract = {
3388
- method: "POST",
3389
- path: "/_auth/register",
3390
- body: Type.Object({
3391
- email: Type.Optional(Type.String({
3392
- pattern: EMAIL_PATTERN,
3393
- description: "Email address"
3394
- })),
3395
- phone: Type.Optional(Type.String({
3396
- pattern: PHONE_PATTERN,
3397
- description: "Phone number in E.164 format"
3398
- })),
3399
- verificationToken: Type.String({
3400
- description: "Verification token obtained from /verify-code endpoint"
3401
- }),
3402
- password: Type.String({
3403
- minLength: 8,
3404
- description: "User password (minimum 8 characters)"
3405
- }),
3406
- publicKey: Type.String({
3407
- pattern: BASE64_PATTERN,
3408
- description: "Base64 encoded DER public key (SPKI format)"
3409
- }),
3410
- keyId: Type.String({
3411
- pattern: UUID_PATTERN,
3412
- description: "Client-generated UUID v4 key identifier"
3413
- }),
3414
- fingerprint: Type.String({
3415
- pattern: FINGERPRINT_PATTERN,
3416
- description: "SHA-256 fingerprint of public key (64 hex characters)"
3417
- }),
3418
- algorithm: Type.Union([
3419
- Type.Literal("ES256"),
3420
- Type.Literal("RS256")
3421
- ], {
3422
- description: "Signing algorithm (ES256 recommended, RS256 for compatibility)"
3423
- }),
3424
- keySize: Type.Optional(Type.Number({
3425
- description: "Key size in bytes"
3426
- }))
3427
- }, {
3428
- minProperties: 6,
3429
- // email/phone + verificationToken + password + publicKey + keyId + fingerprint
3430
- description: "Email or phone must be provided with verification token"
3431
- }),
3432
- response: ApiResponseSchema(
3433
- Type.Object({
3434
- userId: Type.String(),
3435
- email: Type.Optional(Type.String()),
3436
- phone: Type.Optional(Type.String())
3437
- })
3438
- )
3439
- };
3440
- var loginContract = {
3441
- method: "POST",
3442
- path: "/_auth/login",
3443
- body: Type.Object({
3444
- email: Type.Optional(Type.String({
3445
- pattern: EMAIL_PATTERN,
3446
- description: "Email address"
3447
- })),
3448
- phone: Type.Optional(Type.String({
3449
- pattern: PHONE_PATTERN,
3450
- description: "Phone number in E.164 format"
3451
- })),
3452
- password: Type.String({
3453
- minLength: 1,
3454
- description: "User password"
3455
- }),
3456
- publicKey: Type.String({
3457
- pattern: BASE64_PATTERN,
3458
- description: "Base64 encoded DER public key (SPKI format)"
3459
- }),
3460
- keyId: Type.String({
3461
- pattern: UUID_PATTERN,
3462
- description: "Client-generated UUID v4 key identifier"
3463
- }),
3464
- fingerprint: Type.String({
3465
- pattern: FINGERPRINT_PATTERN,
3466
- description: "SHA-256 fingerprint of public key (64 hex characters)"
3467
- }),
3468
- oldKeyId: Type.Optional(Type.String({
3469
- pattern: UUID_PATTERN,
3470
- description: "Previous key ID to revoke (server-side cleanup)"
3471
- })),
3472
- algorithm: Type.Union([
3473
- Type.Literal("ES256"),
3474
- Type.Literal("RS256")
3475
- ], {
3476
- description: "Signing algorithm (ES256 recommended, RS256 for compatibility)"
3477
- }),
3478
- keySize: Type.Optional(Type.Number({
3479
- description: "Key size in bytes"
3480
- }))
3481
- }, {
3482
- minProperties: 5,
3483
- // email/phone + password + publicKey + keyId + fingerprint
3484
- description: "Email or phone must be provided along with key data"
3485
- }),
3486
- response: ApiResponseSchema(
3487
- Type.Object({
3488
- userId: Type.String(),
3489
- email: Type.Optional(Type.String()),
3490
- phone: Type.Optional(Type.String()),
3491
- passwordChangeRequired: Type.Boolean({
3492
- description: "Whether user must change password before proceeding"
3493
- })
3494
- })
3495
- )
3496
- };
3497
- var logoutContract = {
3498
- method: "POST",
3499
- path: "/_auth/logout",
3500
- body: Type.Object({}),
3501
- response: ApiResponseSchema(
3502
- Type.Object({
3503
- success: Type.Boolean()
3504
- })
3505
- )
3506
- };
3507
- var rotateKeyContract = {
3508
- method: "POST",
3509
- path: "/_auth/keys/rotate",
3510
- body: Type.Object({
3511
- publicKey: Type.String({
3512
- pattern: BASE64_PATTERN,
3513
- description: "Base64 encoded DER public key (SPKI format)"
3514
- }),
3515
- keyId: Type.String({
3516
- pattern: UUID_PATTERN,
3517
- description: "Client-generated UUID v4 key identifier"
3518
- }),
3519
- fingerprint: Type.String({
3520
- pattern: FINGERPRINT_PATTERN,
3521
- description: "SHA-256 fingerprint of public key (64 hex characters)"
3522
- }),
3523
- algorithm: Type.Union([
3524
- Type.Literal("ES256"),
3525
- Type.Literal("RS256")
3526
- ], {
3527
- description: "Signing algorithm (ES256 recommended, RS256 for compatibility)"
3528
- }),
3529
- keySize: Type.Optional(Type.Number({
3530
- description: "Key size in bytes"
3531
- }))
3532
- }),
3533
- response: ApiResponseSchema(
3534
- Type.Object({
3535
- success: Type.Boolean(),
3536
- keyId: Type.String()
3537
- })
3538
- )
3539
- };
3540
- var changePasswordContract = {
3541
- method: "PUT",
3542
- path: "/_auth/password",
3543
- body: Type.Object({
3544
- currentPassword: Type.String({
3545
- minLength: 1,
3546
- description: "Current password for verification"
3547
- }),
3548
- newPassword: Type.String({
3549
- minLength: 8,
3550
- description: "New password (minimum 8 characters)"
3551
- })
3552
- }),
3553
- response: ApiResponseSchema(
3554
- Type.Object({
3555
- success: Type.Boolean({ description: "Whether password was changed successfully" })
3556
- })
3557
- )
3558
- };
3559
- var getMeContract = {
3560
- method: "GET",
3561
- path: "/_auth/me",
3562
- body: Type.Object({}),
3563
- response: ApiResponseSchema(
3564
- Type.Object({
3565
- userId: Type.String({ description: "User ID" }),
3566
- email: Type.Optional(Type.String({ description: "User email address" })),
3567
- phone: Type.Optional(Type.String({ description: "User phone number" })),
3568
- role: Type.Object({
3569
- id: Type.Number({ description: "Role ID" }),
3570
- name: Type.String({ description: "Role name (e.g., user, admin)" }),
3571
- displayName: Type.String({ description: "Display name for UI" }),
3572
- priority: Type.Number({ description: "Role priority level" })
3573
- }, { description: "User role information" }),
3574
- permissions: Type.Array(
3575
- Type.Object({
3576
- id: Type.Number({ description: "Permission ID" }),
3577
- name: Type.String({ description: "Permission name (e.g., user:delete)" }),
3578
- displayName: Type.String({ description: "Display name for UI" }),
3579
- category: Type.Optional(Type.String({ description: "Permission category" }))
3580
- }),
3581
- { description: "List of permissions granted through role" }
3582
- )
3583
- })
3584
- )
3585
- };
3586
-
3587
- // src/lib/contracts/invitation.ts
3588
- var UUID_PATTERN2 = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";
3589
- var EMAIL_PATTERN2 = "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
3590
- var BASE64_PATTERN2 = "^[A-Za-z0-9+/]+=*$";
3591
- var FINGERPRINT_PATTERN2 = "^[a-f0-9]{64}$";
3592
- var getInvitationContract = {
3593
- method: "GET",
3594
- path: "/_auth/invitations/:token",
3595
- params: Type.Object({
3596
- token: Type.String({
3597
- pattern: UUID_PATTERN2,
3598
- description: "Invitation token (UUID v4)"
3599
- })
3600
- }),
3601
- response: ApiResponseSchema(
3602
- Type.Object({
3603
- email: Type.String({
3604
- format: "email",
3605
- description: "Email address being invited"
3606
- }),
3607
- role: Type.String({
3608
- description: 'Role name (e.g., "admin", "user")'
3609
- }),
3610
- roleDisplayName: Type.String({
3611
- description: 'Role display name (e.g., "Administrator")'
3612
- }),
3613
- invitedBy: Type.String({
3614
- format: "email",
3615
- description: "Email of user who sent invitation"
3616
- }),
3617
- expiresAt: Type.String({
3618
- format: "date-time",
3619
- description: "ISO 8601 expiration timestamp"
3620
- }),
3621
- metadata: Type.Optional(Type.Any({
3622
- description: "Custom metadata (welcome message, etc.)"
3623
- }))
3624
- })
3625
- )
3626
- };
3627
- var acceptInvitationContract = {
3628
- method: "POST",
3629
- path: "/_auth/invitations/accept",
3630
- body: Type.Object({
3631
- token: Type.String({
3632
- pattern: UUID_PATTERN2,
3633
- description: "Invitation token"
3634
- }),
3635
- password: Type.String({
3636
- minLength: 8,
3637
- description: "Account password (minimum 8 characters)"
3638
- }),
3639
- publicKey: Type.String({
3640
- pattern: BASE64_PATTERN2,
3641
- description: "Base64 DER encoded public key (SPKI format)"
3642
- }),
3643
- keyId: Type.String({
3644
- pattern: UUID_PATTERN2,
3645
- description: "Unique key identifier (UUID v4)"
3646
- }),
3647
- fingerprint: Type.String({
3648
- pattern: FINGERPRINT_PATTERN2,
3649
- description: "SHA-256 fingerprint of public key (64 hex chars)"
3650
- }),
3651
- algorithm: Type.Union([
3652
- Type.Literal("ES256"),
3653
- Type.Literal("RS256")
3654
- ], {
3655
- description: "Asymmetric signing algorithm"
3656
- })
3657
- }),
3658
- response: ApiResponseSchema(
3659
- Type.Object({
3660
- userId: Type.Number({
3661
- description: "Created user ID"
3662
- }),
3663
- email: Type.String({
3664
- format: "email",
3665
- description: "User email address"
3666
- }),
3667
- role: Type.String({
3668
- description: "Assigned role name"
3669
- })
3670
- })
3671
- )
3672
- };
3673
- var createInvitationContract = {
3674
- method: "POST",
3675
- path: "/_auth/invitations",
3676
- body: Type.Object({
3677
- email: Type.String({
3678
- pattern: EMAIL_PATTERN2,
3679
- description: "Email address to invite"
3680
- }),
3681
- roleId: Type.Number({
3682
- description: "Role ID to assign"
3683
- }),
3684
- expiresInDays: Type.Optional(Type.Number({
3685
- minimum: 1,
3686
- maximum: 30,
3687
- description: "Days until invitation expires (default: 7)"
3688
- })),
3689
- metadata: Type.Optional(Type.Any({
3690
- description: "Custom metadata (welcome message, department, etc.)"
3691
- }))
3692
- }),
3693
- response: ApiResponseSchema(
3694
- Type.Object({
3695
- id: Type.Number(),
3696
- email: Type.String({ format: "email" }),
3697
- token: Type.String({
3698
- description: "Invitation token (send via email)"
3699
- }),
3700
- roleId: Type.Number(),
3701
- expiresAt: Type.String({
3702
- format: "date-time",
3703
- description: "ISO 8601 expiration timestamp"
3704
- }),
3705
- invitationUrl: Type.String({
3706
- description: "Full invitation URL for email"
3707
- })
3708
- })
3709
- )
3710
- };
3711
- var listInvitationsContract = {
3712
- method: "GET",
3713
- path: "/_auth/invitations",
3714
- query: Type.Object({
3715
- status: Type.Optional(Type.Union([
3716
- Type.Literal("pending"),
3717
- Type.Literal("accepted"),
3718
- Type.Literal("expired"),
3719
- Type.Literal("cancelled")
3720
- ], {
3721
- description: "Filter by status"
3722
- })),
3723
- page: Type.Optional(Type.Number({
3724
- minimum: 1,
3725
- description: "Page number (default: 1)"
3726
- })),
3727
- limit: Type.Optional(Type.Number({
3728
- minimum: 1,
3729
- maximum: 100,
3730
- description: "Items per page (default: 20)"
3731
- }))
3732
- }),
3733
- response: ApiResponseSchema(
3734
- Type.Object({
3735
- invitations: Type.Array(Type.Object({
3736
- id: Type.Number(),
3737
- email: Type.String({ format: "email" }),
3738
- status: Type.String(),
3739
- role: Type.Object({
3740
- id: Type.Number(),
3741
- name: Type.String(),
3742
- displayName: Type.String()
3743
- }),
3744
- inviter: Type.Object({
3745
- id: Type.Number(),
3746
- email: Type.String({ format: "email" })
3747
- }),
3748
- createdAt: Type.String({ format: "date-time" }),
3749
- expiresAt: Type.String({ format: "date-time" }),
3750
- acceptedAt: Type.Optional(Type.String({ format: "date-time" })),
3751
- cancelledAt: Type.Optional(Type.String({ format: "date-time" }))
3752
- })),
3753
- total: Type.Number({ description: "Total invitation count" }),
3754
- page: Type.Number({ description: "Current page" }),
3755
- limit: Type.Number({ description: "Items per page" }),
3756
- totalPages: Type.Number({ description: "Total page count" })
3757
- })
3758
- )
3759
- };
3760
- var cancelInvitationContract = {
3761
- method: "POST",
3762
- path: "/_auth/invitations/cancel",
3763
- body: Type.Object({
3764
- id: Type.Number({
3765
- description: "Invitation ID"
3766
- }),
3767
- reason: Type.Optional(Type.String({
3768
- description: "Cancellation reason"
3769
- }))
3770
- }),
3771
- response: ApiResponseSchema(
3772
- Type.Object({
3773
- success: Type.Boolean(),
3774
- cancelledAt: Type.String({
3775
- format: "date-time",
3776
- description: "Cancellation timestamp"
3777
- })
3778
- })
3779
- )
3780
- };
3781
- var resendInvitationContract = {
3782
- method: "POST",
3783
- path: "/_auth/invitations/resend",
3784
- body: Type.Object({
3785
- id: Type.Number({
3786
- description: "Invitation ID"
3787
- }),
3788
- expiresInDays: Type.Optional(Type.Number({
3789
- minimum: 1,
3790
- maximum: 30,
3791
- description: "New expiration period (default: 7)"
3792
- }))
3793
- }),
3794
- response: ApiResponseSchema(
3795
- Type.Object({
3796
- success: Type.Boolean(),
3797
- expiresAt: Type.String({
3798
- format: "date-time",
3799
- description: "New expiration timestamp"
3800
- })
3801
- })
3802
- )
3803
- };
3804
- var deleteInvitationContract = {
3805
- method: "POST",
3806
- path: "/_auth/invitations/delete",
3807
- body: Type.Object({
3808
- id: Type.Number({
3809
- description: "Invitation ID"
3810
- })
3811
- }),
3812
- response: ApiResponseSchema(
3813
- Type.Object({
3814
- success: Type.Boolean()
3815
- })
3816
- )
3817
- };
3818
-
3819
- // src/server/helpers/password.ts
3820
- import bcrypt from "bcrypt";
3821
- var SALT_ROUNDS = parseInt(
3822
- process.env.SPFN_AUTH_BCRYPT_SALT_ROUNDS || // New prefixed version (recommended)
3823
- process.env.BCRYPT_SALT_ROUNDS || // Legacy fallback
3824
- "10",
3825
- 10
3826
- );
3827
- async function hashPassword(password) {
3828
- if (!password || password.length === 0) {
3829
- throw new Error("Password cannot be empty");
3830
- }
3831
- return bcrypt.hash(password, SALT_ROUNDS);
3832
- }
3833
- async function verifyPassword(password, hash) {
3834
- if (!password || password.length === 0) {
3835
- throw new Error("Password cannot be empty");
3836
- }
3837
- if (!hash || hash.length === 0) {
3838
- throw new Error("Hash cannot be empty");
3839
- }
3840
- return bcrypt.compare(password, hash);
3841
- }
3842
-
3843
- // src/server/helpers/jwt.ts
3844
- import jwt from "jsonwebtoken";
3845
- import crypto from "crypto";
3846
- var JWT_SECRET = process.env.SPFN_AUTH_JWT_SECRET || // New prefixed version (recommended)
3847
- process.env.JWT_SECRET || // Legacy fallback
3848
- "dev-secret-key-change-in-production";
3849
- var JWT_EXPIRES_IN = process.env.SPFN_AUTH_JWT_EXPIRES_IN || // New prefixed version (recommended)
3850
- process.env.JWT_EXPIRES_IN || // Legacy fallback
3851
- "7d";
3852
- function verifyKeyFingerprint(publicKeyB64, expectedFingerprint) {
3853
- try {
3854
- const publicKeyDER = Buffer.from(publicKeyB64, "base64");
3855
- const fingerprint = crypto.createHash("sha256").update(publicKeyDER).digest("hex");
3856
- return fingerprint === expectedFingerprint;
3857
- } catch (error) {
3858
- console.error("Failed to verify key fingerprint:", error);
3859
- return false;
3860
- }
3861
- }
3862
-
3863
- // src/server/helpers/verification.ts
3864
- init_verification_codes();
3865
- import jwt2 from "jsonwebtoken";
3866
- import { getDatabase, create } from "@spfn/core/db";
3867
- import { eq, and } from "drizzle-orm";
3868
- function getVerificationTokenSecret() {
3869
- const secret = process.env.SPFN_AUTH_VERIFICATION_TOKEN_SECRET || // New prefixed version (recommended)
3870
- process.env.VERIFICATION_TOKEN_SECRET || // Legacy fallback
3871
- process.env.SPFN_AUTH_JWT_SECRET || // New JWT secret fallback
3872
- process.env.JWT_SECRET;
3873
- if (!secret || secret.length < 32) {
3874
- throw new Error("SPFN_AUTH_VERIFICATION_TOKEN_SECRET must be at least 32 characters long");
3875
- }
3876
- return secret;
3877
- }
3878
- var VERIFICATION_TOKEN_EXPIRY = "15m";
3879
- var VERIFICATION_CODE_EXPIRY_MINUTES = 5;
3880
- var MAX_VERIFICATION_ATTEMPTS = 5;
3881
- function generateVerificationCode() {
3882
- const code = Math.floor(Math.random() * 1e6).toString().padStart(6, "0");
3883
- return code;
3884
- }
3885
- async function storeVerificationCode(target, targetType, code, purpose) {
3886
- const db = getDatabase();
3887
- if (!db) {
3888
- throw new Error("Database not initialized");
3889
- }
3890
- const expiresAt = /* @__PURE__ */ new Date();
3891
- expiresAt.setMinutes(expiresAt.getMinutes() + VERIFICATION_CODE_EXPIRY_MINUTES);
3892
- const record = await create(verificationCodes, {
3893
- target,
3894
- targetType,
3895
- code,
3896
- purpose,
3897
- expiresAt,
3898
- attempts: "0"
3899
- });
3900
- return record;
3901
- }
3902
- async function validateVerificationCode(target, targetType, code, purpose) {
3903
- const db = getDatabase();
3904
- if (!db) {
3905
- throw new Error("Database not initialized");
3906
- }
3907
- const records = await db.select().from(verificationCodes).where(
3908
- and(
3909
- eq(verificationCodes.target, target),
3910
- eq(verificationCodes.targetType, targetType),
3911
- eq(verificationCodes.code, code),
3912
- eq(verificationCodes.purpose, purpose)
3913
- )
3914
- ).limit(1);
3915
- if (records.length === 0) {
3916
- return { valid: false, error: "Invalid verification code" };
3917
- }
3918
- const record = records[0];
3919
- if (record.usedAt) {
3920
- return { valid: false, error: "Verification code already used" };
3921
- }
3922
- if (/* @__PURE__ */ new Date() > new Date(record.expiresAt)) {
3923
- return { valid: false, error: "Verification code expired" };
3924
- }
3925
- const attempts = parseInt(record.attempts, 10);
3926
- if (attempts >= MAX_VERIFICATION_ATTEMPTS) {
3927
- return { valid: false, error: "Too many attempts, please request a new code" };
3928
- }
3929
- await db.update(verificationCodes).set({ attempts: (attempts + 1).toString() }).where(eq(verificationCodes.id, record.id));
3930
- return { valid: true, codeId: record.id };
3931
- }
3932
- async function markCodeAsUsed(codeId) {
3933
- const db = getDatabase();
3934
- if (!db) {
3935
- throw new Error("Database not initialized");
3936
- }
3937
- await db.update(verificationCodes).set({ usedAt: /* @__PURE__ */ new Date() }).where(eq(verificationCodes.id, codeId));
3938
- }
3939
- function createVerificationToken(payload) {
3940
- const secret = getVerificationTokenSecret();
3941
- return jwt2.sign(payload, secret, {
3942
- expiresIn: VERIFICATION_TOKEN_EXPIRY,
3943
- issuer: "spfn-auth",
3944
- audience: "spfn-client"
3945
- });
3946
- }
3947
- function validateVerificationToken(token) {
3948
- try {
3949
- const secret = getVerificationTokenSecret();
3950
- const decoded = jwt2.verify(token, secret, {
3951
- issuer: "spfn-auth",
3952
- audience: "spfn-client"
3953
- });
3954
- if (typeof decoded === "object" && decoded !== null && "target" in decoded && "targetType" in decoded && "purpose" in decoded && "codeId" in decoded) {
3955
- return decoded;
3956
- }
3957
- return null;
3958
- } catch (error) {
3959
- console.error("[validateVerificationToken] Error:", error);
3960
- return null;
3961
- }
3962
- }
3963
- async function sendVerificationEmail(email, code, purpose) {
3964
- console.log(`[VERIFICATION EMAIL] To: ${email}, Code: ${code}, Purpose: ${purpose}`);
3965
- }
3966
- async function sendVerificationSMS(phone, code, purpose) {
3967
- console.log(`[VERIFICATION SMS] To: ${phone}, Code: ${code}, Purpose: ${purpose}`);
3968
- }
3969
-
3970
- // src/server/helpers/context.ts
3971
- function getAuth(c) {
3972
- if ("raw" in c && c.raw) {
3973
- return c.raw.get("auth");
3974
- }
3975
- return c.get("auth");
3976
- }
3977
- function getUser(c) {
3978
- return getAuth(c).user;
3979
- }
3980
-
3981
- // src/server/services/auth.service.ts
3982
- init_entities();
3983
- import { findOne as findOne2, create as create3 } from "@spfn/core/db";
3984
- import { ValidationError as ValidationError2 } from "@spfn/core/errors";
3985
-
3986
- // src/server/errors/auth-errors.ts
3987
- import {
3988
- ValidationError,
3989
- UnauthorizedError,
3990
- ForbiddenError,
3991
- ConflictError
3992
- } from "@spfn/core/errors";
3993
- var InvalidCredentialsError = class extends UnauthorizedError {
3994
- constructor(message = "Invalid credentials") {
3995
- super(message);
3996
- this.name = "InvalidCredentialsError";
3997
- }
3998
- };
3999
- var AccountDisabledError = class extends ForbiddenError {
4000
- constructor(status = "disabled") {
4001
- super(`Account is ${status}`, { details: { status } });
4002
- this.name = "AccountDisabledError";
4003
- }
4004
- };
4005
- var AccountAlreadyExistsError = class extends ConflictError {
4006
- constructor(identifier, identifierType) {
4007
- super("Account already exists", { details: { identifier, identifierType } });
4008
- this.name = "AccountAlreadyExistsError";
4009
- }
4010
- };
4011
- var InvalidVerificationCodeError = class extends ValidationError {
4012
- constructor(reason = "Invalid verification code") {
4013
- super(reason);
4014
- this.name = "InvalidVerificationCodeError";
4015
- }
4016
- };
4017
- var InvalidVerificationTokenError = class extends ValidationError {
4018
- constructor(message = "Invalid or expired verification token") {
4019
- super(message);
4020
- this.name = "InvalidVerificationTokenError";
4021
- }
4022
- };
4023
- var InvalidKeyFingerprintError = class extends ValidationError {
4024
- constructor(message = "Invalid key fingerprint") {
4025
- super(message);
4026
- this.name = "InvalidKeyFingerprintError";
4027
- }
4028
- };
4029
- var VerificationTokenPurposeMismatchError = class extends ValidationError {
4030
- constructor(expected, actual) {
4031
- super(`Verification token is for ${actual}, but ${expected} was expected`, { details: { expected, actual } });
4032
- this.name = "VerificationTokenPurposeMismatchError";
4033
- }
4034
- };
4035
- var VerificationTokenTargetMismatchError = class extends ValidationError {
4036
- constructor() {
4037
- super("Verification token does not match provided email/phone");
4038
- this.name = "VerificationTokenTargetMismatchError";
4039
- }
4040
- };
4041
-
4042
- // src/server/services/key.service.ts
4043
- init_entities();
4044
- import { create as create2, getDatabase as getDatabase2 } from "@spfn/core/db";
4045
- import { eq as eq2, and as and2 } from "drizzle-orm";
4046
- function getKeyExpiryDate() {
4047
- const expiresAt = /* @__PURE__ */ new Date();
4048
- expiresAt.setDate(expiresAt.getDate() + 90);
4049
- return expiresAt;
4050
- }
4051
- async function registerPublicKeyService(params) {
4052
- const { userId, keyId, publicKey, fingerprint, algorithm = "ES256" } = params;
4053
- const isValidFingerprint = verifyKeyFingerprint(publicKey, fingerprint);
4054
- if (!isValidFingerprint) {
4055
- throw new InvalidKeyFingerprintError();
4056
- }
4057
- await create2(userPublicKeys, {
4058
- userId,
4059
- keyId,
4060
- publicKey,
4061
- algorithm,
4062
- fingerprint,
4063
- isActive: true,
4064
- createdAt: /* @__PURE__ */ new Date(),
4065
- expiresAt: getKeyExpiryDate()
4066
- });
4067
- }
4068
- async function rotateKeyService(params) {
4069
- const { userId, oldKeyId, newKeyId, newPublicKey, fingerprint, algorithm = "ES256" } = params;
4070
- const isValidFingerprint = verifyKeyFingerprint(newPublicKey, fingerprint);
4071
- if (!isValidFingerprint) {
4072
- throw new InvalidKeyFingerprintError();
4073
- }
4074
- const db = getDatabase2();
4075
- await db.update(userPublicKeys).set({
4076
- isActive: false,
4077
- revokedAt: /* @__PURE__ */ new Date(),
4078
- revokedReason: "Replaced by key rotation"
4079
- }).where(
4080
- and2(
4081
- eq2(userPublicKeys.keyId, oldKeyId),
4082
- eq2(userPublicKeys.userId, userId)
4083
- )
4084
- );
4085
- await create2(userPublicKeys, {
4086
- userId,
4087
- keyId: newKeyId,
4088
- publicKey: newPublicKey,
4089
- algorithm,
4090
- fingerprint,
4091
- isActive: true,
4092
- createdAt: /* @__PURE__ */ new Date(),
4093
- expiresAt: getKeyExpiryDate()
4094
- });
4095
- return {
4096
- success: true,
4097
- keyId: newKeyId
4098
- };
4099
- }
4100
- async function revokeKeyService(params) {
4101
- const { userId, keyId, reason } = params;
4102
- const db = getDatabase2();
4103
- await db.update(userPublicKeys).set({
4104
- isActive: false,
4105
- revokedAt: /* @__PURE__ */ new Date(),
4106
- revokedReason: reason
4107
- }).where(
4108
- and2(
4109
- eq2(userPublicKeys.keyId, keyId),
4110
- eq2(userPublicKeys.userId, userId)
4111
- )
4112
- );
4113
- }
4114
-
4115
- // src/server/services/user.service.ts
4116
- init_entities();
4117
- import { findOne, updateOne } from "@spfn/core/db";
4118
- async function updateLastLoginService(userId) {
4119
- await updateOne(users, { id: userId }, {
4120
- lastLoginAt: /* @__PURE__ */ new Date()
4121
- });
4122
- }
4123
-
4124
- // src/server/services/auth.service.ts
4125
- async function checkAccountExistsService(params) {
4126
- const { email, phone } = params;
4127
- let identifier;
4128
- let identifierType;
4129
- let user;
4130
- if (email) {
4131
- identifier = email;
4132
- identifierType = "email";
4133
- user = await findOne2(users, { email });
4134
- } else if (phone) {
4135
- identifier = phone;
4136
- identifierType = "phone";
4137
- user = await findOne2(users, { phone });
4138
- } else {
4139
- throw new ValidationError2("Either email or phone must be provided");
4140
- }
4141
- return {
4142
- exists: !!user,
4143
- identifier,
4144
- identifierType
4145
- };
4146
- }
4147
- async function registerService(params) {
4148
- const { email, phone, verificationToken, password, publicKey, keyId, fingerprint, algorithm } = params;
4149
- const tokenPayload = validateVerificationToken(verificationToken);
4150
- if (!tokenPayload) {
4151
- throw new InvalidVerificationTokenError();
4152
- }
4153
- if (tokenPayload.purpose !== "registration") {
4154
- throw new VerificationTokenPurposeMismatchError("registration", tokenPayload.purpose);
4155
- }
4156
- const providedTarget = email || phone;
4157
- if (tokenPayload.target !== providedTarget) {
4158
- throw new VerificationTokenTargetMismatchError();
4159
- }
4160
- const providedTargetType = email ? "email" : "phone";
4161
- if (tokenPayload.targetType !== providedTargetType) {
4162
- throw new VerificationTokenTargetMismatchError();
4163
- }
4164
- let existingUser;
4165
- if (email) {
4166
- existingUser = await findOne2(users, { email });
4167
- } else if (phone) {
4168
- existingUser = await findOne2(users, { phone });
4169
- } else {
4170
- throw new ValidationError2("Either email or phone must be provided");
4171
- }
4172
- if (existingUser) {
4173
- const identifierType = email ? "email" : "phone";
4174
- throw new AccountAlreadyExistsError(email || phone, identifierType);
4175
- }
4176
- const passwordHash = await hashPassword(password);
4177
- const { getRoleByName: getRoleByName2 } = await Promise.resolve().then(() => (init_role_service(), role_service_exports));
4178
- const userRole = await getRoleByName2("user");
4179
- if (!userRole) {
4180
- throw new Error("Default user role not found. Run initializeAuth() first.");
4181
- }
4182
- const newUser = await create3(users, {
4183
- email: email || null,
4184
- phone: phone || null,
4185
- passwordHash,
4186
- passwordChangeRequired: false,
4187
- roleId: userRole.id,
4188
- status: "active",
4189
- createdAt: /* @__PURE__ */ new Date(),
4190
- updatedAt: /* @__PURE__ */ new Date()
4191
- });
4192
- await registerPublicKeyService({
4193
- userId: newUser.id,
4194
- keyId,
4195
- publicKey,
4196
- fingerprint,
4197
- algorithm
4198
- });
4199
- return {
4200
- userId: String(newUser.id),
4201
- email: newUser.email || void 0,
4202
- phone: newUser.phone || void 0
4203
- };
4204
- }
4205
- async function loginService(params) {
4206
- const { email, phone, password, publicKey, keyId, fingerprint, oldKeyId, algorithm } = params;
4207
- let user;
4208
- if (email) {
4209
- user = await findOne2(users, { email });
4210
- } else if (phone) {
4211
- user = await findOne2(users, { phone });
4212
- } else {
4213
- throw new ValidationError2("Either email or phone must be provided");
4214
- }
4215
- if (!user || !user.passwordHash) {
4216
- throw new InvalidCredentialsError();
4217
- }
4218
- console.log("user", user);
4219
- console.log("\uD328\uC2A4\uC6CC\uB4DC: ", password);
4220
- const isValid = await verifyPassword(password, user.passwordHash);
4221
- if (!isValid) {
4222
- throw new InvalidCredentialsError();
4223
- }
4224
- if (user.status !== "active") {
4225
- throw new AccountDisabledError(user.status);
4226
- }
4227
- if (oldKeyId) {
4228
- await revokeKeyService({
4229
- userId: user.id,
4230
- keyId: oldKeyId,
4231
- reason: "Replaced by new key on login"
4232
- });
4233
- }
4234
- await registerPublicKeyService({
4235
- userId: user.id,
4236
- keyId,
4237
- publicKey,
4238
- fingerprint,
4239
- algorithm
4240
- });
4241
- await updateLastLoginService(user.id);
4242
- return {
4243
- userId: String(user.id),
4244
- email: user.email || void 0,
4245
- phone: user.phone || void 0,
4246
- passwordChangeRequired: user.passwordChangeRequired
4247
- };
4248
- }
4249
- async function logoutService(params) {
4250
- const { userId, keyId } = params;
4251
- await revokeKeyService({
4252
- userId,
4253
- keyId,
4254
- reason: "Revoked by logout"
4255
- });
4256
- }
4257
- async function changePasswordService(params) {
4258
- const { userId, currentPassword, newPassword, passwordHash: providedHash } = params;
4259
- let passwordHash;
4260
- if (providedHash) {
4261
- passwordHash = providedHash;
4262
- } else {
4263
- const user = await findOne2(users, { id: userId });
4264
- if (!user) {
4265
- throw new ValidationError2("User not found");
4266
- }
4267
- passwordHash = user.passwordHash;
4268
- }
4269
- if (!passwordHash) {
4270
- throw new ValidationError2("No password set for this account");
4271
- }
4272
- const isValid = await verifyPassword(currentPassword, passwordHash);
4273
- if (!isValid) {
4274
- throw new InvalidCredentialsError("Current password is incorrect");
4275
- }
4276
- const newPasswordHash = await hashPassword(newPassword);
4277
- const { updateOne: updateOne2 } = await import("@spfn/core/db");
4278
- await updateOne2(users, { id: userId }, {
4279
- passwordHash: newPasswordHash,
4280
- passwordChangeRequired: false,
4281
- updatedAt: /* @__PURE__ */ new Date()
4282
- });
4283
- }
4284
-
4285
- // src/server/services/verification.service.ts
4286
- async function sendVerificationCodeService(params) {
4287
- const { target, targetType, purpose } = params;
4288
- const code = generateVerificationCode();
4289
- const codeRecord = await storeVerificationCode(target, targetType, code, purpose);
4290
- if (targetType === "email") {
4291
- await sendVerificationEmail(target, code, purpose);
4292
- } else {
4293
- await sendVerificationSMS(target, code, purpose);
4294
- }
4295
- return {
4296
- success: true,
4297
- expiresAt: codeRecord.expiresAt.toISOString()
4298
- };
4299
- }
4300
- async function verifyCodeService(params) {
4301
- const { target, targetType, code, purpose } = params;
4302
- const validation = await validateVerificationCode(target, targetType, code, purpose);
4303
- if (!validation.valid) {
4304
- throw new InvalidVerificationCodeError(validation.error || "Invalid verification code");
4305
- }
4306
- await markCodeAsUsed(validation.codeId);
4307
- const verificationToken = createVerificationToken({
4308
- target,
4309
- targetType,
4310
- purpose,
4311
- codeId: validation.codeId
4312
- });
4313
- return {
4314
- valid: true,
4315
- verificationToken
4316
- };
4317
- }
4318
-
4319
- // src/server/services/me.service.ts
4320
- init_entities();
4321
- import { getDatabase as getDatabase4 } from "@spfn/core/db";
4322
- import { eq as eq4, and as and4 } from "drizzle-orm";
4323
- async function getMeService(userId) {
4324
- const db = getDatabase4();
4325
- if (!db) {
4326
- throw new Error("[Auth] Database not initialized");
4327
- }
4328
- const userIdNum = typeof userId === "string" ? Number(userId) : Number(userId);
4329
- const [userWithRole] = await db.select({
4330
- userId: users.id,
4331
- email: users.email,
4332
- phone: users.phone,
4333
- roleId: roles.id,
4334
- roleName: roles.name,
4335
- roleDisplayName: roles.displayName,
4336
- rolePriority: roles.priority
4337
- }).from(users).innerJoin(roles, eq4(users.roleId, roles.id)).where(eq4(users.id, userIdNum)).limit(1);
4338
- if (!userWithRole) {
4339
- throw new Error("[Auth] User not found");
4340
- }
4341
- const rolePerms = await db.select({
4342
- id: permissions.id,
4343
- name: permissions.name,
4344
- displayName: permissions.displayName,
4345
- category: permissions.category
4346
- }).from(rolePermissions).innerJoin(permissions, eq4(rolePermissions.permissionId, permissions.id)).where(
4347
- and4(
4348
- eq4(rolePermissions.roleId, userWithRole.roleId),
4349
- eq4(permissions.isActive, true)
4350
- )
4351
- );
4352
- return {
4353
- userId: userWithRole.userId.toString(),
4354
- email: userWithRole.email ?? void 0,
4355
- phone: userWithRole.phone ?? void 0,
4356
- role: {
4357
- id: userWithRole.roleId,
4358
- name: userWithRole.roleName,
4359
- displayName: userWithRole.roleDisplayName,
4360
- priority: userWithRole.rolePriority
4361
- },
4362
- permissions: rolePerms.map((perm) => ({
4363
- id: perm.id,
4364
- name: perm.name,
4365
- displayName: perm.displayName,
4366
- category: perm.category ?? void 0
4367
- }))
4368
- };
4369
- }
4370
-
4371
- // src/server/services/rbac.service.ts
4372
- init_entities();
4373
- import { getDatabase as getDatabase5 } from "@spfn/core/db";
4374
- import { logger } from "@spfn/core/logger";
4375
- import { eq as eq5, and as and5, inArray } from "drizzle-orm";
4376
- var authLogger = logger.child("@spfn/auth");
4377
-
4378
- // src/server/services/permission.service.ts
4379
- init_entities();
4380
- import { getDatabase as getDatabase6 } from "@spfn/core/db";
4381
- import { eq as eq6, and as and6 } from "drizzle-orm";
4382
-
4383
- // src/server/services/index.ts
4384
- init_role_service();
4385
-
4386
- // src/server/services/invitation.service.ts
4387
- init_entities();
4388
- import { getDatabase as getDatabase7 } from "@spfn/core/db";
4389
- import { eq as eq7, and as and7, lt, desc, sql as sql2 } from "drizzle-orm";
4390
-
4391
- // src/server/routes/auth/index.ts
4392
- var app = createApp();
4393
- app.bind(checkAccountExistsContract, async (c) => {
4394
- const body = await c.data();
4395
- const result = await checkAccountExistsService(body);
4396
- return c.success(result);
4397
- });
4398
- app.bind(sendVerificationCodeContract, async (c) => {
4399
- const body = await c.data();
4400
- const result = await sendVerificationCodeService(body);
4401
- return c.success(result);
4402
- });
4403
- app.bind(verifyCodeContract, async (c) => {
4404
- const body = await c.data();
4405
- const result = await verifyCodeService(body);
4406
- return c.success(result);
4407
- });
4408
- app.bind(registerContract, async (c) => {
4409
- const body = await c.data();
4410
- const result = await registerService(body);
4411
- return c.success(result);
4412
- });
4413
- app.bind(loginContract, async (c) => {
4414
- const body = await c.data();
4415
- const result = await loginService(body);
4416
- return c.success(result);
4417
- });
4418
- app.bind(logoutContract, async (c) => {
4419
- const auth = getAuth(c);
4420
- if (!auth) {
4421
- return c.success({ success: true });
4422
- }
4423
- const { keyId, userId } = auth;
4424
- await logoutService({ userId: Number(userId), keyId });
4425
- return c.success({ success: true });
4426
- });
4427
- app.bind(rotateKeyContract, async (c) => {
4428
- const body = await c.data();
4429
- const { keyId: oldKeyId, userId } = getAuth(c);
4430
- const result = await rotateKeyService({
4431
- userId: Number(userId),
4432
- oldKeyId,
4433
- newKeyId: body.keyId,
4434
- newPublicKey: body.publicKey,
4435
- fingerprint: body.fingerprint,
4436
- algorithm: body.algorithm
4437
- });
4438
- return c.success(result);
4439
- });
4440
- app.bind(changePasswordContract, async (c) => {
4441
- const body = await c.data();
4442
- const user = getUser(c);
4443
- await changePasswordService({
4444
- userId: user.id,
4445
- currentPassword: body.currentPassword,
4446
- newPassword: body.newPassword,
4447
- passwordHash: user.passwordHash || void 0
4448
- });
4449
- return c.success({ success: true });
4450
- });
4451
- app.bind(getMeContract, async (c) => {
4452
- const { userId } = getAuth(c);
4453
- const result = await getMeService(userId);
4454
- return c.success(result);
4455
- });
4456
- var auth_default = app;
4457
- export {
4458
- auth_default as default
4459
- };
4460
- //# sourceMappingURL=index.js.map