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