@codemem/core 0.40.2 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/api-types.d.ts +17 -0
  2. package/dist/api-types.d.ts.map +1 -1
  3. package/dist/claude-hooks.d.ts +12 -4
  4. package/dist/claude-hooks.d.ts.map +1 -1
  5. package/dist/codex-hooks.d.ts +7 -3
  6. package/dist/codex-hooks.d.ts.map +1 -1
  7. package/dist/coordinator-actions.d.ts.map +1 -1
  8. package/dist/coordinator-api-SeLosPIq.js +3102 -0
  9. package/dist/coordinator-api-SeLosPIq.js.map +1 -0
  10. package/dist/coordinator-api.d.ts.map +1 -1
  11. package/dist/coordinator-runtime.d.ts.map +1 -1
  12. package/dist/db.d.ts +9 -3
  13. package/dist/db.d.ts.map +1 -1
  14. package/dist/device-identity-binding.d.ts +50 -0
  15. package/dist/device-identity-binding.d.ts.map +1 -0
  16. package/dist/device-identity-inventory.d.ts +72 -0
  17. package/dist/device-identity-inventory.d.ts.map +1 -0
  18. package/dist/hook-transcript.d.ts +25 -0
  19. package/dist/hook-transcript.d.ts.map +1 -0
  20. package/dist/identity-target.d.ts +16 -0
  21. package/dist/identity-target.d.ts.map +1 -0
  22. package/dist/index.d.ts +27 -11
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +24492 -4337
  25. package/dist/index.js.map +1 -1
  26. package/dist/internal/cloudflare-coordinator.js +159 -159
  27. package/dist/operational-status.d.ts +36 -0
  28. package/dist/operational-status.d.ts.map +1 -0
  29. package/dist/policy-team-device-eligibility.d.ts +51 -0
  30. package/dist/policy-team-device-eligibility.d.ts.map +1 -0
  31. package/dist/project-invite-identity.d.ts +2 -0
  32. package/dist/project-invite-identity.d.ts.map +1 -1
  33. package/dist/project-share-intent.d.ts +16 -0
  34. package/dist/project-share-intent.d.ts.map +1 -0
  35. package/dist/prompt-transport.d.ts +36 -0
  36. package/dist/prompt-transport.d.ts.map +1 -0
  37. package/dist/raw-event-flush.d.ts +1 -0
  38. package/dist/raw-event-flush.d.ts.map +1 -1
  39. package/dist/raw-event-ingest.d.ts +19 -0
  40. package/dist/raw-event-ingest.d.ts.map +1 -0
  41. package/dist/raw-event-sweeper.d.ts +6 -1
  42. package/dist/raw-event-sweeper.d.ts.map +1 -1
  43. package/dist/recipient-policy-edges.d.ts.map +1 -1
  44. package/dist/recipient-policy-intent.d.ts.map +1 -1
  45. package/dist/recipient-policy-onboarding.d.ts +3 -1
  46. package/dist/recipient-policy-onboarding.d.ts.map +1 -1
  47. package/dist/recipient-policy-reconciliation.d.ts +10 -1
  48. package/dist/recipient-policy-reconciliation.d.ts.map +1 -1
  49. package/dist/release-discovery.d.ts +47 -0
  50. package/dist/release-discovery.d.ts.map +1 -0
  51. package/dist/schema-bootstrap.d.ts +9 -0
  52. package/dist/schema-bootstrap.d.ts.map +1 -1
  53. package/dist/schema.d.ts +1625 -344
  54. package/dist/schema.d.ts.map +1 -1
  55. package/dist/scope-membership-cache.d.ts +2 -0
  56. package/dist/scope-membership-cache.d.ts.map +1 -1
  57. package/dist/share-operation.d.ts +4 -15
  58. package/dist/share-operation.d.ts.map +1 -1
  59. package/dist/store.d.ts +2 -1
  60. package/dist/store.d.ts.map +1 -1
  61. package/dist/sync-auth.d.ts +65 -2
  62. package/dist/sync-auth.d.ts.map +1 -1
  63. package/dist/sync-bootstrap-constants.d.ts +7 -0
  64. package/dist/sync-bootstrap-constants.d.ts.map +1 -0
  65. package/dist/sync-bootstrap.d.ts +4 -11
  66. package/dist/sync-bootstrap.d.ts.map +1 -1
  67. package/dist/sync-daemon.d.ts +2 -2
  68. package/dist/sync-daemon.d.ts.map +1 -1
  69. package/dist/sync-http-client.d.ts +1 -0
  70. package/dist/sync-http-client.d.ts.map +1 -1
  71. package/dist/sync-identity.d.ts +10 -2
  72. package/dist/sync-identity.d.ts.map +1 -1
  73. package/dist/sync-pass.d.ts +1 -0
  74. package/dist/sync-pass.d.ts.map +1 -1
  75. package/dist/sync-replication.d.ts.map +1 -1
  76. package/dist/sync-scope-protocol.d.ts +1 -3
  77. package/dist/sync-scope-protocol.d.ts.map +1 -1
  78. package/dist/test-schema.generated.d.ts +1 -1
  79. package/dist/test-schema.generated.d.ts.map +1 -1
  80. package/dist/viewer-probe.d.ts +50 -0
  81. package/dist/viewer-probe.d.ts.map +1 -0
  82. package/package.json +1 -1
  83. package/dist/coordinator-api-CvU8oTg1.js +0 -21107
  84. package/dist/coordinator-api-CvU8oTg1.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coordinator-api-SeLosPIq.js","names":["#matchResult","#validatedData","#getDecodedParam","#getAllDecodedParams","#getParamValue","#cachedBody","#rawRequest","#executionCtx","#notFoundHandler","#path","#matchResult","#req","#res","#preparedHeaders","#renderer","#layout","#status","#var","#newResponse","Hono","#path","#addRoute","#notFoundHandler","#clone","#dispatch","#handleError","Node","#index","#children","#varIndex","Node","#root","#context","#middleware","#routes","#buildMatcher","#routers","#routes","#children","#methods","#patterns","#order","#params","#pushHandlerSets","#node","HonoBase"],"sources":["../src/coordinator-membership-effects.ts","../src/coordinator-store-contract.ts","../src/project-invite-identity.ts","../src/recipient-reviewed-intent.ts","../src/sync-fingerprint.ts","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/compose.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/request/constants.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/utils/body.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/utils/url.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/request.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/utils/html.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/context.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/utils/constants.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/hono-base.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router/reg-exp-router/matcher.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router/reg-exp-router/node.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router/reg-exp-router/trie.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router/reg-exp-router/router.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router/smart-router/router.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router/trie-router/node.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/router/trie-router/router.js","../../../node_modules/.pnpm/hono@4.12.26/node_modules/hono/dist/hono.js","../src/coordinator-invites.ts","../src/project-invite-acceptance.ts","../src/scope-resolution.ts","../src/project-share-intent.ts","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/clock.js","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/TokenBucket.js","../../../node_modules/.pnpm/limiter@3.0.0/node_modules/limiter/dist/esm/RateLimiter.js","../src/request-rate-limit.ts","../src/scope-membership-semantics.ts","../src/sync-auth-constants.ts","../src/coordinator-api.ts"],"sourcesContent":["import type {\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScopeMembership,\n} from \"./coordinator-store-contract.js\";\n\nexport const SCOPE_MEMBERSHIP_EFFECT_CONFLICT = \"scope_membership_effect_conflict\";\n\nexport type CoordinatorMembershipErrorCode =\n\t| \"device_not_enrolled\"\n\t| \"scope_group_mismatch\"\n\t| \"scope_inactive\"\n\t| \"scope_not_found\";\n\nconst MEMBERSHIP_ERROR_MESSAGES: Record<CoordinatorMembershipErrorCode, string> = {\n\tdevice_not_enrolled: \"device must be enrolled and enabled in the scope group.\",\n\tscope_group_mismatch: \"membership groupId must match the scope groupId.\",\n\tscope_inactive: \"scope is not active.\",\n\tscope_not_found: \"scopeId must reference an existing scope.\",\n};\n\nexport class CoordinatorMembershipError extends Error {\n\treadonly code: CoordinatorMembershipErrorCode;\n\n\tconstructor(code: CoordinatorMembershipErrorCode) {\n\t\tsuper(MEMBERSHIP_ERROR_MESSAGES[code]);\n\t\tthis.name = \"CoordinatorMembershipError\";\n\t\tthis.code = code;\n\t}\n}\n\nexport interface CoordinatorMembershipEffectReceipt {\n\teffect_id: string;\n\taction: \"grant\" | \"revoke\";\n\trequest_json: string;\n\toutcome_applied: number;\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string | null;\n\tstatus: string | null;\n\tmembership_epoch: number | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmanifest_hash: string | null;\n\tsigned_manifest_json: string | null;\n\tupdated_at: string | null;\n\tcreated_at: string;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst normalized = value?.trim();\n\treturn normalized ? normalized : null;\n}\n\nexport function normalizeMembershipEffectId(value: string): string {\n\tconst effectId = clean(value);\n\tif (!effectId) throw new Error(\"effectId is required.\");\n\tif (effectId.length > 512 || /[\\p{Cc}\\p{Cf}]/u.test(effectId)) {\n\t\tthrow new Error(\"effectId is invalid.\");\n\t}\n\treturn effectId;\n}\n\nexport function grantMembershipEffectRequestJson(\n\topts: CoordinatorGrantScopeMembershipInput,\n): string {\n\treturn JSON.stringify({\n\t\tscopeId: clean(opts.scopeId),\n\t\tdeviceId: clean(opts.deviceId),\n\t\trole: clean(opts.role),\n\t\tmembershipEpoch: opts.membershipEpoch ?? null,\n\t\tcoordinatorId: clean(opts.coordinatorId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmanifestIssuerDeviceId: clean(opts.manifestIssuerDeviceId),\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t});\n}\n\nexport function revokeMembershipEffectRequestJson(\n\topts: CoordinatorRevokeScopeMembershipInput,\n): string {\n\treturn JSON.stringify({\n\t\tscopeId: clean(opts.scopeId),\n\t\tdeviceId: clean(opts.deviceId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmembershipEpoch: opts.membershipEpoch ?? null,\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t});\n}\n\nexport function assertMatchingMembershipEffectReceipt(\n\treceipt: CoordinatorMembershipEffectReceipt,\n\taction: CoordinatorMembershipEffectReceipt[\"action\"],\n\trequestJson: string,\n): void {\n\tif (receipt.action !== action || receipt.request_json !== requestJson) {\n\t\tthrow new Error(SCOPE_MEMBERSHIP_EFFECT_CONFLICT);\n\t}\n}\n\nexport function membershipFromEffectReceipt(\n\treceipt: CoordinatorMembershipEffectReceipt,\n): CoordinatorScopeMembership {\n\tif (\n\t\treceipt.action !== \"grant\" ||\n\t\treceipt.outcome_applied !== 1 ||\n\t\treceipt.role == null ||\n\t\treceipt.status == null ||\n\t\treceipt.membership_epoch == null ||\n\t\treceipt.updated_at == null\n\t) {\n\t\tthrow new Error(\"scope_membership_effect_receipt_invalid\");\n\t}\n\treturn {\n\t\tscope_id: receipt.scope_id,\n\t\tdevice_id: receipt.device_id,\n\t\trole: receipt.role,\n\t\tstatus: receipt.status,\n\t\tmembership_epoch: receipt.membership_epoch,\n\t\tcoordinator_id: receipt.coordinator_id,\n\t\tgroup_id: receipt.group_id,\n\t\tmanifest_issuer_device_id: receipt.manifest_issuer_device_id,\n\t\tmanifest_hash: receipt.manifest_hash,\n\t\tsigned_manifest_json: receipt.signed_manifest_json,\n\t\tupdated_at: receipt.updated_at,\n\t};\n}\n","import type { RecipientReviewedIntentV1 } from \"./recipient-reviewed-intent.js\";\n\n/**\n * Normalize a caller-supplied invite expiry to a canonical UTC ISO-8601\n * (`...Z`) string. Invite lookups filter with a SQL `expires_at > ?` string\n * comparison against `new Date().toISOString()`, which is only correct when\n * stored values share that exact format — a `+00:00` offset or date-only value\n * would compare wrong. Shared by both coordinator store implementations.\n */\nexport function normalizeInviteExpiresAt(value: string): string {\n\tconst trimmed = value.trim();\n\tconst parsed = new Date(trimmed);\n\tif (!trimmed || Number.isNaN(parsed.getTime())) {\n\t\tthrow new Error(\"expiresAt must be a valid date.\");\n\t}\n\treturn parsed.toISOString();\n}\n\nexport interface CoordinatorGroup {\n\tgroup_id: string;\n\tdisplay_name: string | null;\n\tarchived_at: string | null;\n\tcreated_at: string;\n}\n\nexport interface CoordinatorEnrollment {\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tidentity_id: string | null;\n\tdisplay_name: string | null;\n\tenabled: number;\n\tcreated_at: string;\n\t/** Authenticated presence expiry for this exact group/device enrollment. */\n\tpresence_expires_at?: string;\n\t/** Token-free capabilities from the same authenticated presence record. */\n\tpresence_capabilities?: Record<string, unknown>;\n}\n\nexport interface CoordinatorInvite {\n\tinvite_id: string;\n\tgroup_id: string;\n\ttoken: string;\n\tpolicy: string;\n\texpires_at: string;\n\tcreated_at: string;\n\tcreated_by: string | null;\n\tteam_name_snapshot: string | null;\n\trevoked_at: string | null;\n\t/** Null/absent identifies a legacy enrollment invite, which grants no project intent by itself. */\n\toperation_id?: string | null;\n\t/** Digest reference only; the reviewed project set remains server-owned operation state. */\n\treviewed_project_set_digest?: string | null;\n\ttoken_digest?: string | null;\n\tinviter_actor_id?: string | null;\n\tinviter_display_name?: string | null;\n\tinviter_device_id?: string | null;\n\tpending_person_id?: string | null;\n\tproject_summaries_json?: string | null;\n\tproject_intent_json?: string | null;\n\tconsumed_at?: string | null;\n\tbound_device_id?: string | null;\n\tbound_public_key?: string | null;\n\tbound_fingerprint?: string | null;\n\trecipient_actor_id?: string | null;\n\trecipient_display_name?: string | null;\n\trecipient_device_display_name?: string | null;\n\ttrust_state?: string | null;\n\tbootstrap_grant_id?: string | null;\n\t/** Explicit lifecycle kind. Null is retained only for pre-migration rows. */\n\tinvite_kind?: CoordinatorInviteKind | null;\n\t/** Policy Team identifier for team-member invitations; never a coordinator group grant. */\n\tpolicy_team_id?: string | null;\n\t/** Identity fixed by an add-device invitation. */\n\ttarget_identity_id?: string | null;\n\t/** Opaque Identity minted by the coordinator for a Team-member invitation. */\n\tassigned_identity_id?: string | null;\n\t/** Digest of the server-owned preview reviewed before invitation creation. */\n\treviewed_preview_digest?: string | null;\n\t/** Canonical JSON for the inviter-reviewed access intent. */\n\treviewed_intent_json?: string | null;\n}\n\nexport type CoordinatorInviteKind =\n\t| \"legacy_enrollment\"\n\t| \"project_share\"\n\t| \"team_member\"\n\t| \"add_device\";\n\nexport type CoordinatorRecipientInviteKind = Extract<\n\tCoordinatorInviteKind,\n\t\"team_member\" | \"add_device\"\n>;\n\nconst COORDINATOR_ASSIGNED_IDENTITY_PATTERN = /^identity:[A-Za-z0-9_-]{18,24}$/u;\n\nexport function isCoordinatorAssignedIdentityId(value: unknown): value is string {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\tvalue === value.trim() &&\n\t\tCOORDINATOR_ASSIGNED_IDENTITY_PATTERN.test(value)\n\t);\n}\n\nexport function recipientInviteAuthoritativeIdentityId(value: {\n\tkind: CoordinatorRecipientInviteKind;\n\tassigned_identity_id?: unknown;\n\ttarget_identity_id?: unknown;\n}): string {\n\treturn String(\n\t\tvalue.kind === \"team_member\"\n\t\t\t? (value.assigned_identity_id ?? \"\")\n\t\t\t: (value.target_identity_id ?? \"\"),\n\t).trim();\n}\n\nexport interface CoordinatorProjectInviteSummary {\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nexport interface CoordinatorProjectInviteAcceptance {\n\tstatus: \"accepted\" | \"existing\";\n\tinvite: CoordinatorInvite;\n\tenrollment: CoordinatorEnrollment;\n\tseed_enrollment: CoordinatorEnrollment | null;\n\tbootstrap_grant: CoordinatorBootstrapGrant | null;\n}\n\nexport type CoordinatorRecipientInviteInspection =\n\t| {\n\t\t\tkind: \"team_member\";\n\t\t\tinvite: CoordinatorInvite;\n\t\t\tpolicy_team_id: string;\n\t\t\tassigned_identity_id: string;\n\t\t\treviewed_preview_digest: string;\n\t\t\treviewed_intent?: RecipientReviewedIntentV1;\n\t\t\tbound: boolean;\n\t }\n\t| {\n\t\t\tkind: \"add_device\";\n\t\t\tinvite: CoordinatorInvite;\n\t\t\ttarget_identity_id: string;\n\t\t\treviewed_preview_digest: string;\n\t\t\treviewed_intent?: RecipientReviewedIntentV1;\n\t\t\tbound: boolean;\n\t };\n\nexport interface CoordinatorRecipientInviteAcceptance {\n\tstatus: \"accepted\" | \"existing\";\n\tinvite: CoordinatorInvite;\n\treviewed_intent?: RecipientReviewedIntentV1;\n\tbootstrap_grant?: CoordinatorBootstrapGrant | null;\n}\n\nexport interface CoordinatorJoinRequest {\n\trequest_id: string;\n\tgroup_id: string;\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tdisplay_name: string | null;\n\ttoken: string;\n\tstatus: string;\n\tcreated_at: string;\n\treviewed_at: string | null;\n\treviewed_by: string | null;\n}\n\nexport interface CoordinatorJoinRequestReviewResult extends CoordinatorJoinRequest {\n\t_no_transition?: boolean;\n\tbootstrap_grant?: CoordinatorBootstrapGrant | null;\n}\n\nexport interface CoordinatorReviewJoinRequestBootstrapGrantInput {\n\tseedDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n}\n\nexport interface CoordinatorPresenceRecord {\n\tgroup_id: string;\n\tdevice_id: string;\n\taddresses: string[];\n\texpires_at: string;\n}\n\nexport interface CoordinatorPeerRecord {\n\tdevice_id: string;\n\tpublic_key: string;\n\tfingerprint: string;\n\tdisplay_name: string | null;\n\taddresses: string[];\n\tlast_seen_at: string | null;\n\texpires_at: string | null;\n\tstale: boolean;\n\tcapabilities: Record<string, unknown>;\n}\n\nexport interface CoordinatorReciprocalApproval {\n\trequest_id: string;\n\tgroup_id: string;\n\trequesting_device_id: string;\n\trequested_device_id: string;\n\tstatus: string;\n\tcreated_at: string;\n\tresolved_at: string | null;\n}\n\nexport interface CoordinatorBootstrapGrant {\n\tgrant_id: string;\n\tgroup_id: string;\n\tseed_device_id: string;\n\tworker_device_id: string;\n\texpires_at: string;\n\tcreated_at: string;\n\tcreated_by: string | null;\n\trevoked_at: string | null;\n}\n\nexport interface CoordinatorScope {\n\tscope_id: string;\n\tlabel: string;\n\tkind: string;\n\tauthority_type: string;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmembership_epoch: number;\n\tmanifest_hash: string | null;\n\tstatus: string;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\nexport interface CoordinatorScopeMembership {\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string;\n\tstatus: string;\n\tmembership_epoch: number;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tmanifest_issuer_device_id: string | null;\n\tmanifest_hash: string | null;\n\tsigned_manifest_json: string | null;\n\tupdated_at: string;\n}\n\nexport type CoordinatorScopeMembershipAuditAction = \"grant\" | \"revoke\";\n\nexport interface CoordinatorScopeMembershipAuditEvent {\n\tevent_id: number;\n\teffect_id: string | null;\n\taction: CoordinatorScopeMembershipAuditAction;\n\tscope_id: string;\n\tdevice_id: string;\n\trole: string | null;\n\tstatus: string;\n\tmembership_epoch: number;\n\tprevious_role: string | null;\n\tprevious_status: string | null;\n\tprevious_membership_epoch: number | null;\n\tcoordinator_id: string | null;\n\tgroup_id: string | null;\n\tactor_type: string | null;\n\tactor_id: string | null;\n\tmanifest_hash: string | null;\n\tcreated_at: string;\n}\n\nexport interface CoordinatorEnrollDeviceInput {\n\tdeviceId: string;\n\tfingerprint: string;\n\tpublicKey: string;\n\tdisplayName?: string | null;\n\t/** Null or omitted means the enrollment has no authoritative issuance binding. */\n\tidentityId?: string | null;\n}\n\nexport interface CoordinatorCreateInviteInput {\n\tgroupId: string;\n\tpolicy: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n\toperationId?: string | null;\n\treviewedProjectSetDigest?: string | null;\n\tinviterActorId?: string | null;\n\tinviterDisplayName?: string | null;\n\tinviterDeviceId?: string | null;\n\tpendingPersonId?: string | null;\n\tprojectSummaries?: CoordinatorProjectInviteSummary[] | null;\n\tprojectIntent?: Array<CoordinatorProjectInviteSummary & { canonical_identity: string }> | null;\n\tinviteKind?: CoordinatorInviteKind | null;\n\tpolicyTeamId?: string | null;\n\ttargetIdentityId?: string | null;\n\treviewedPreviewDigest?: string | null;\n\treviewedIntent?: unknown;\n}\n\nexport interface CoordinatorConsumeProjectInviteInput {\n\ttoken: string;\n\toperationId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\trecipientActorId: string;\n\trecipientDisplayName: string;\n\tdeviceDisplayName: string;\n\t/** Runtime-authoritative timestamp used for expiry, binding, and grant creation. */\n\tnow: string;\n}\n\nexport interface CoordinatorInspectRecipientInviteInput {\n\ttoken: string;\n\tnow: string;\n}\n\nexport interface CoordinatorConsumeRecipientInviteInput {\n\ttoken: string;\n\tinviteKind: CoordinatorRecipientInviteKind;\n\tidentityId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\trecipientDisplayName?: string | null;\n\tdeviceDisplayName?: string | null;\n\t/** Runtime-authoritative timestamp used for expiry and binding. */\n\tnow: string;\n}\n\nexport interface CoordinatorCreateJoinRequestInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tpublicKey: string;\n\tfingerprint: string;\n\tdisplayName?: string | null;\n\ttoken: string;\n}\n\nexport interface CoordinatorReviewJoinRequestInput {\n\trequestId: string;\n\tapproved: boolean;\n\treviewedBy?: string | null;\n\tbootstrapGrant?: CoordinatorReviewJoinRequestBootstrapGrantInput | null;\n}\n\nexport interface CoordinatorUpsertPresenceInput {\n\tgroupId: string;\n\tdeviceId: string;\n\taddresses: string[];\n\tttlS: number;\n\tcapabilities?: Record<string, unknown> | null;\n}\n\nexport interface CoordinatorCreateReciprocalApprovalInput {\n\tgroupId: string;\n\trequestingDeviceId: string;\n\trequestedDeviceId: string;\n}\n\nexport interface CoordinatorCreateBootstrapGrantInput {\n\tgroupId: string;\n\tseedDeviceId: string;\n\tworkerDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy?: string | null;\n}\n\nexport interface CoordinatorCreateScopeInput {\n\tscopeId: string;\n\tlabel: string;\n\tkind?: string | null;\n\tauthorityType?: string | null;\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tstatus?: string | null;\n}\n\nexport interface CoordinatorUpdateScopeInput {\n\t/** Internal sharing-domain identifier (`scope_id`). */\n\tscopeId: string;\n\t/** User-facing Sharing domain label. Omitted fields keep existing metadata. */\n\tlabel?: string | null;\n\tkind?: string | null;\n\tauthorityType?: string | null;\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tstatus?: string | null;\n}\n\nexport interface CoordinatorListScopesInput {\n\tcoordinatorId?: string | null;\n\tgroupId?: string | null;\n\tstatus?: string | null;\n\tincludeInactive?: boolean;\n}\n\nexport interface CoordinatorGrantScopeMembershipInput {\n\teffectId: string;\n\tscopeId: string;\n\tdeviceId: string;\n\trole?: string | null;\n\tmembershipEpoch?: number | null;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tcoordinatorId?: string | null;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tgroupId?: string | null;\n\tmanifestIssuerDeviceId?: string | null;\n\tmanifestHash?: string | null;\n\tsignedManifestJson?: string | null;\n\tactorType?: string | null;\n\tactorId?: string | null;\n}\n\nexport interface CoordinatorRevokeScopeMembershipInput {\n\teffectId: string;\n\tscopeId: string;\n\tdeviceId: string;\n\t/** Optional assertion; persisted authority is derived from the referenced scope. */\n\tgroupId?: string | null;\n\tmembershipEpoch?: number | null;\n\tmanifestHash?: string | null;\n\tsignedManifestJson?: string | null;\n\tactorType?: string | null;\n\tactorId?: string | null;\n}\n\nexport interface CoordinatorListScopeMembershipAuditInput {\n\tscopeId: string;\n\tdeviceId?: string | null;\n\tlimit?: number | null;\n}\n\nexport interface CoordinatorListReciprocalApprovalsInput {\n\tgroupId: string;\n\tdeviceId: string;\n\tdirection: \"incoming\" | \"outgoing\";\n\tstatus?: string;\n}\n\nexport interface CoordinatorStore {\n\tclose(): Promise<void>;\n\tcreateGroup(groupId: string, displayName?: string | null): Promise<void>;\n\tgetGroup(groupId: string): Promise<CoordinatorGroup | null>;\n\tlistGroups(includeArchived?: boolean): Promise<CoordinatorGroup[]>;\n\trenameGroup(groupId: string, displayName: string): Promise<boolean>;\n\tarchiveGroup(groupId: string, archivedAt?: string): Promise<boolean>;\n\tunarchiveGroup(groupId: string): Promise<boolean>;\n\tenrollDevice(groupId: string, opts: CoordinatorEnrollDeviceInput): Promise<void>;\n\tlistEnrolledDevices(groupId: string, includeDisabled?: boolean): Promise<CoordinatorEnrollment[]>;\n\tgetEnrollment(\n\t\tgroupId: string,\n\t\tdeviceId: string,\n\t\tincludeDisabled?: boolean,\n\t): Promise<CoordinatorEnrollment | null>;\n\trenameDevice(groupId: string, deviceId: string, displayName: string): Promise<boolean>;\n\tsetDeviceEnabled(groupId: string, deviceId: string, enabled: boolean): Promise<boolean>;\n\tremoveDevice(groupId: string, deviceId: string): Promise<boolean>;\n\trecordNonce(deviceId: string, nonce: string, createdAt: string): Promise<boolean>;\n\tcleanupNonces(cutoff: string): Promise<void>;\n\tcreateInvite(opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite>;\n\tgetInviteByToken(token: string): Promise<CoordinatorInvite | null>;\n\tgetInviteByTokenForInspection(token: string): Promise<CoordinatorInvite | null>;\n\tinspectRecipientInvite(\n\t\topts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null>;\n\tconsumeProjectInvite(\n\t\topts: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance>;\n\tconsumeRecipientInvite(\n\t\topts: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance>;\n\tlistInvites(groupId: string): Promise<CoordinatorInvite[]>;\n\tcreateJoinRequest(opts: CoordinatorCreateJoinRequestInput): Promise<CoordinatorJoinRequest>;\n\tlistJoinRequests(groupId: string, status?: string): Promise<CoordinatorJoinRequest[]>;\n\treviewJoinRequest(\n\t\topts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null>;\n\tcreateReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval>;\n\tcreateBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant>;\n\tcreateScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope>;\n\tupdateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null>;\n\tlistScopes(opts?: CoordinatorListScopesInput): Promise<CoordinatorScope[]>;\n\tgrantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership>;\n\trevokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean>;\n\tlistScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked?: boolean,\n\t): Promise<CoordinatorScopeMembership[]>;\n\tlistScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]>;\n\tgetBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null>;\n\tlistBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]>;\n\trevokeBootstrapGrant(grantId: string, revokedAt?: string): Promise<boolean>;\n\tlistReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]>;\n\tupsertPresence(opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord>;\n\tlistGroupPeers(groupId: string, requestingDeviceId: string): Promise<CoordinatorPeerRecord[]>;\n}\n\nexport interface CoordinatorBootstrapGrantVerification {\n\tgrant: CoordinatorBootstrapGrant;\n\tworker_enrollment: CoordinatorEnrollment;\n}\n","const MAX_IDENTITY_DISPLAY_LENGTH = 120;\n// Keep machine-shaped cases synchronized with ui/src/lib/identity-presentation.ts.\nconst UUID_NAME = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu;\nconst MACHINE_PREFIX_NAME = /^(?:actor|device|identity|local):\\S+$/iu;\nconst MACHINE_SLUG_NAME = /^(?:actor|device|identity)[_-][a-z0-9][a-z0-9._:-]{4,}$/iu;\nconst PENDING_PERSON_NAME = /^pending[_-]\\S+$/iu;\nconst HEX_HOSTNAME = /^[a-f0-9]{12,64}$/iu;\n\nexport interface ProjectInviteSummary {\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nexport function normalizeIdentityDisplayName(value: string, field: string): string {\n\tif ([...value].some((character) => /[\\p{Cc}\\p{Cf}]/u.test(character))) {\n\t\tthrow new Error(`${field}_invalid`);\n\t}\n\tconst normalized = value.replace(/\\s+/gu, \" \").trim();\n\tif (!normalized) throw new Error(`${field}_required`);\n\tif ([...normalized].length > MAX_IDENTITY_DISPLAY_LENGTH) {\n\t\tthrow new Error(`${field}_too_long`);\n\t}\n\treturn normalized;\n}\n\nexport function isHumanPresentationName(value: unknown): boolean {\n\tif (typeof value !== \"string\") return false;\n\tlet normalized: string;\n\ttry {\n\t\tnormalized = normalizeIdentityDisplayName(value, \"display_name\");\n\t} catch {\n\t\treturn false;\n\t}\n\treturn ![\n\t\tUUID_NAME,\n\t\tMACHINE_PREFIX_NAME,\n\t\tMACHINE_SLUG_NAME,\n\t\tPENDING_PERSON_NAME,\n\t\tHEX_HOSTNAME,\n\t].some((pattern) => pattern.test(normalized));\n}\n\nexport function normalizeHumanPresentationName(value: string, field: string): string {\n\tconst normalized = normalizeIdentityDisplayName(value, field);\n\tif (!isHumanPresentationName(normalized)) throw new Error(`${field}_invalid`);\n\treturn normalized;\n}\n\nexport function normalizeDeviceNameHint(value: string | null | undefined): string | null {\n\tconst raw = String(value ?? \"\").replace(/\\.local$/iu, \"\");\n\tif (!raw.trim()) return null;\n\treturn normalizeIdentityDisplayName(raw.replace(/[-_]+/gu, \" \"), \"device_display_name\");\n}\n\nexport function friendlyDeviceName(input: {\n\texplicitName?: string | null;\n\tosName?: string | null;\n\tcoordinatorName?: string | null;\n\tfallbackSeed?: string | null;\n}): string {\n\tfor (const candidate of [input.explicitName, input.osName, input.coordinatorName]) {\n\t\tconst raw = String(candidate ?? \"\")\n\t\t\t.replace(/\\.local$/iu, \"\")\n\t\t\t.trim();\n\t\t// Classify before separator normalization so UUIDs and machine slugs cannot\n\t\t// be disguised as human labels by replacing hyphens or underscores.\n\t\tif (!raw || !isHumanPresentationName(raw)) continue;\n\t\ttry {\n\t\t\tconst normalized = normalizeDeviceNameHint(candidate);\n\t\t\tif (normalized && isHumanPresentationName(normalized)) return normalized;\n\t\t} catch {\n\t\t\t// Unusable automatic hints must degrade to the generated fallback.\n\t\t}\n\t}\n\tconst seed = String(input.fallbackSeed ?? \"\")\n\t\t.replace(/[^a-z0-9]/giu, \"\")\n\t\t.slice(0, 6);\n\treturn seed ? `Codemem device ${seed}` : \"Codemem device\";\n}\n\nexport function normalizeProjectInviteSummaries(value: unknown): ProjectInviteSummary[] {\n\tif (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n\t\tthrow new Error(\"project_summaries_invalid\");\n\t}\n\treturn value.map((item) => {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(\"project_summaries_invalid\");\n\t\t}\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (\n\t\t\t!Number.isSafeInteger(record.existing_memory_count) ||\n\t\t\tNumber(record.existing_memory_count) < 0\n\t\t) {\n\t\t\tthrow new Error(\"project_summaries_invalid\");\n\t\t}\n\t\treturn {\n\t\t\tdisplay_name: normalizeIdentityDisplayName(String(record.display_name ?? \"\"), \"project_name\"),\n\t\t\texisting_memory_count: Number(record.existing_memory_count),\n\t\t};\n\t});\n}\n","import { normalizeIdentityDisplayName } from \"./project-invite-identity.js\";\n\nexport const RECIPIENT_REVIEWED_INTENT_VERSION = 1 as const;\n\nexport type RecipientReviewedIntentProjectSourceV1 =\n\t| { kind: \"direct\" }\n\t| { kind: \"team\"; teamId: string; displayName: string };\n\nexport interface RecipientReviewedIntentProjectV1 {\n\tcanonicalProjectIdentity: string;\n\tdisplayName: string;\n\texistingMemoryCount: number;\n\tfutureMemoriesShared: true;\n\tsources: RecipientReviewedIntentProjectSourceV1[];\n}\n\nexport interface RecipientReviewedIntentExcludedProjectV1 {\n\tcanonicalProjectIdentity: string;\n\tdisplayName: string;\n\texistingMemoryCount: number;\n}\n\ninterface RecipientReviewedIntentBaseV1 {\n\tversion: 1;\n\tprojects: RecipientReviewedIntentProjectV1[];\n\texcludedProjects: RecipientReviewedIntentExcludedProjectV1[];\n}\n\nexport type RecipientReviewedIntentV1 =\n\t| (RecipientReviewedIntentBaseV1 & {\n\t\t\tjourney: \"team\";\n\t\t\tteam: { teamId: string; displayName: string; futureProjectsInherit: true };\n\t })\n\t| (RecipientReviewedIntentBaseV1 & {\n\t\t\tjourney: \"add_device\";\n\t\t\ttargetIdentity: { identityId: string; displayName: string };\n\t });\n\nexport type RecipientReviewedIntentTargetV1 =\n\t| { kind: \"team_member\"; policyTeamId: string }\n\t| { kind: \"add_device\"; targetIdentityId: string };\n\nexport class RecipientReviewedIntentError extends Error {\n\treadonly code: \"recipient_reviewed_intent_invalid\" | \"recipient_invite_intent_mismatch\";\n\n\tconstructor(code: RecipientReviewedIntentError[\"code\"]) {\n\t\tsuper(code);\n\t\tthis.name = \"RecipientReviewedIntentError\";\n\t\tthis.code = code;\n\t}\n}\n\nconst CONTROL_CHARACTER = /[\\p{Cc}\\p{Cf}]/u;\nconst MAX_PROJECTS = 100;\nconst MAX_CANONICAL_BYTES = 64 * 1024;\n\nfunction invalid(): never {\n\tthrow new RecipientReviewedIntentError(\"recipient_reviewed_intent_invalid\");\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) invalid();\n\treturn value as Record<string, unknown>;\n}\n\nfunction assertKeys(value: Record<string, unknown>, keys: readonly string[]): void {\n\tif (Object.keys(value).some((key) => !keys.includes(key))) invalid();\n}\n\nfunction strictText(value: unknown, maxLength: number): string {\n\tif (\n\t\ttypeof value !== \"string\" ||\n\t\t!value ||\n\t\tvalue !== value.trim() ||\n\t\tvalue.length > maxLength ||\n\t\tCONTROL_CHARACTER.test(value)\n\t) {\n\t\tinvalid();\n\t}\n\treturn value;\n}\n\nfunction displayName(value: unknown): string {\n\tif (typeof value !== \"string\" || CONTROL_CHARACTER.test(value)) invalid();\n\tconst normalized = value.trim().replace(/\\s+/gu, \" \");\n\tif (!normalized || normalized.length > 256) invalid();\n\treturn normalized;\n}\n\nfunction identityDisplayName(value: unknown): string {\n\tif (typeof value !== \"string\") invalid();\n\ttry {\n\t\treturn normalizeIdentityDisplayName(value, \"identity_display_name\");\n\t} catch {\n\t\treturn invalid();\n\t}\n}\n\nfunction memoryCount(value: unknown): number {\n\tif (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) invalid();\n\treturn value;\n}\n\nfunction compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction sourceKey(source: RecipientReviewedIntentProjectSourceV1): string {\n\treturn source.kind === \"direct\" ? \"direct\" : `team\\u0000${source.teamId}`;\n}\n\nfunction normalizeSource(value: unknown): RecipientReviewedIntentProjectSourceV1 {\n\tconst input = record(value);\n\tif (input.kind === \"direct\") {\n\t\tassertKeys(input, [\"kind\"]);\n\t\treturn { kind: \"direct\" };\n\t}\n\tif (input.kind !== \"team\") invalid();\n\tassertKeys(input, [\"kind\", \"teamId\", \"displayName\"]);\n\treturn {\n\t\tkind: \"team\",\n\t\tteamId: strictText(input.teamId, 256),\n\t\tdisplayName: displayName(input.displayName),\n\t};\n}\n\nfunction normalizeProject(value: unknown): RecipientReviewedIntentProjectV1 {\n\tconst input = record(value);\n\tassertKeys(input, [\n\t\t\"canonicalProjectIdentity\",\n\t\t\"displayName\",\n\t\t\"existingMemoryCount\",\n\t\t\"futureMemoriesShared\",\n\t\t\"sources\",\n\t]);\n\tif (\n\t\tinput.futureMemoriesShared !== true ||\n\t\t!Array.isArray(input.sources) ||\n\t\t!input.sources.length\n\t) {\n\t\tinvalid();\n\t}\n\tconst sources = input.sources\n\t\t.map(normalizeSource)\n\t\t.toSorted((left, right) => compareText(sourceKey(left), sourceKey(right)));\n\tif (new Set(sources.map(sourceKey)).size !== sources.length) invalid();\n\treturn {\n\t\tcanonicalProjectIdentity: strictText(input.canonicalProjectIdentity, 512),\n\t\tdisplayName: displayName(input.displayName),\n\t\texistingMemoryCount: memoryCount(input.existingMemoryCount),\n\t\tfutureMemoriesShared: true,\n\t\tsources,\n\t};\n}\n\nfunction normalizeExcludedProject(value: unknown): RecipientReviewedIntentExcludedProjectV1 {\n\tconst input = record(value);\n\tassertKeys(input, [\"canonicalProjectIdentity\", \"displayName\", \"existingMemoryCount\"]);\n\treturn {\n\t\tcanonicalProjectIdentity: strictText(input.canonicalProjectIdentity, 512),\n\t\tdisplayName: displayName(input.displayName),\n\t\texistingMemoryCount: memoryCount(input.existingMemoryCount),\n\t};\n}\n\nfunction normalizeProjectLists(\n\tinput: Record<string, unknown>,\n): Pick<RecipientReviewedIntentBaseV1, \"projects\" | \"excludedProjects\"> {\n\tif (\n\t\t!Array.isArray(input.projects) ||\n\t\t!Array.isArray(input.excludedProjects) ||\n\t\tinput.projects.length > MAX_PROJECTS\n\t) {\n\t\tinvalid();\n\t}\n\tconst projects = input.projects\n\t\t.map(normalizeProject)\n\t\t.toSorted((left, right) =>\n\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity),\n\t\t);\n\tconst excludedProjects = input.excludedProjects\n\t\t.map(normalizeExcludedProject)\n\t\t.toSorted((left, right) =>\n\t\t\tcompareText(left.canonicalProjectIdentity, right.canonicalProjectIdentity),\n\t\t);\n\tconst includedIds = projects.map((project) => project.canonicalProjectIdentity);\n\tconst excludedIds = excludedProjects.map((project) => project.canonicalProjectIdentity);\n\tif (\n\t\tnew Set(includedIds).size !== includedIds.length ||\n\t\tnew Set(excludedIds).size !== excludedIds.length ||\n\t\texcludedIds.some((projectId) => includedIds.includes(projectId))\n\t) {\n\t\tinvalid();\n\t}\n\treturn { projects, excludedProjects };\n}\n\nfunction assertTarget(\n\tintent: RecipientReviewedIntentV1,\n\ttarget: RecipientReviewedIntentTargetV1,\n): void {\n\tconst matches =\n\t\t(intent.journey === \"team\" &&\n\t\t\ttarget.kind === \"team_member\" &&\n\t\t\tintent.team.teamId === target.policyTeamId) ||\n\t\t(intent.journey === \"add_device\" &&\n\t\t\ttarget.kind === \"add_device\" &&\n\t\t\tintent.targetIdentity.identityId === target.targetIdentityId);\n\tif (!matches) throw new RecipientReviewedIntentError(\"recipient_invite_intent_mismatch\");\n}\n\nexport function normalizeRecipientReviewedIntent(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): RecipientReviewedIntentV1 {\n\tconst input = record(value);\n\tif (input.version !== RECIPIENT_REVIEWED_INTENT_VERSION) invalid();\n\tconst projectLists = normalizeProjectLists(input);\n\tlet intent: RecipientReviewedIntentV1;\n\tif (input.journey === \"team\") {\n\t\tassertKeys(input, [\"version\", \"journey\", \"team\", \"projects\", \"excludedProjects\"]);\n\t\tconst team = record(input.team);\n\t\tassertKeys(team, [\"teamId\", \"displayName\", \"futureProjectsInherit\"]);\n\t\tif (team.futureProjectsInherit !== true) invalid();\n\t\tintent = {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tteam: {\n\t\t\t\tteamId: strictText(team.teamId, 256),\n\t\t\t\tdisplayName: displayName(team.displayName),\n\t\t\t\tfutureProjectsInherit: true,\n\t\t\t},\n\t\t\t...projectLists,\n\t\t};\n\t} else if (input.journey === \"add_device\") {\n\t\tassertKeys(input, [\"version\", \"journey\", \"targetIdentity\", \"projects\", \"excludedProjects\"]);\n\t\tconst identity = record(input.targetIdentity);\n\t\tassertKeys(identity, [\"identityId\", \"displayName\"]);\n\t\tintent = {\n\t\t\tversion: 1,\n\t\t\tjourney: \"add_device\",\n\t\t\ttargetIdentity: {\n\t\t\t\tidentityId: strictText(identity.identityId, 256),\n\t\t\t\tdisplayName: identityDisplayName(identity.displayName),\n\t\t\t},\n\t\t\t...projectLists,\n\t\t};\n\t} else {\n\t\tinvalid();\n\t}\n\tif (target) assertTarget(intent, target);\n\tif (new TextEncoder().encode(canonicalJson(intent)).byteLength > MAX_CANONICAL_BYTES) invalid();\n\treturn intent;\n}\n\nfunction canonicalJson(value: unknown): string {\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n\tif (value && typeof value === \"object\") {\n\t\treturn `{${Object.entries(value as Record<string, unknown>)\n\t\t\t.toSorted(([left], [right]) => compareText(left, right))\n\t\t\t.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`)\n\t\t\t.join(\",\")}}`;\n\t}\n\treturn JSON.stringify(value) ?? \"null\";\n}\n\nexport function canonicalRecipientReviewedIntentJson(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): string {\n\treturn canonicalJson(normalizeRecipientReviewedIntent(value, target));\n}\n\nexport async function recipientReviewedIntentDigest(\n\tvalue: unknown,\n\ttarget?: RecipientReviewedIntentTargetV1,\n): Promise<string> {\n\tconst canonical = canonicalRecipientReviewedIntentJson(value, target);\n\tconst bytes = new TextEncoder().encode(`recipient-reviewed-intent-v1\\n${canonical}`);\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", bytes);\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function verifyRecipientReviewedIntent(\n\tvalue: unknown,\n\toptions: { target: RecipientReviewedIntentTargetV1; digest: string },\n): Promise<RecipientReviewedIntentV1> {\n\tconst normalized = normalizeRecipientReviewedIntent(value, options.target);\n\tif ((await recipientReviewedIntentDigest(normalized)) !== options.digest) {\n\t\tthrow new RecipientReviewedIntentError(\"recipient_invite_intent_mismatch\");\n\t}\n\treturn normalized;\n}\n\nexport async function parseStoredRecipientReviewedIntent(\n\tjson: string | null | undefined,\n\toptions: { target: RecipientReviewedIntentTargetV1; digest: string },\n): Promise<RecipientReviewedIntentV1> {\n\tif (!json) throw new Error(\"recipient_invite_review_unavailable\");\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(json);\n\t} catch {\n\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t}\n\ttry {\n\t\tconst normalized = normalizeRecipientReviewedIntent(parsed, options.target);\n\t\tif (canonicalJson(normalized) !== json) {\n\t\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t\t}\n\t\treturn await verifyRecipientReviewedIntent(normalized, options);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tif (error instanceof Error && error.message === \"recipient_invite_review_unavailable\") {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t}\n}\n","import { createHash } from \"node:crypto\";\n\n/** SHA-256 hex digest of a public key string. */\nexport function fingerprintPublicKey(publicKey: string): string {\n\treturn createHash(\"sha256\").update(publicKey, \"utf-8\").digest(\"hex\");\n}\n","// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n","// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n","// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n","// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return value.indexOf(\"%\") !== -1 ? tryDecode(value, decodeURIComponent_) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI\n};\n","// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from \"./utils/url.js\";\nvar tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.#getParamValue(paramKey);\n return param && /\\%/.test(param) ? tryDecodeURIComponent(param) : param;\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = /\\%/.test(value) ? tryDecodeURIComponent(value) : value;\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * `.bytes()` parses the request body as a `Uint8Array`.\n *\n * @see {@link https://hono.dev/docs/api/request#bytes}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.bytes()\n * })\n * ```\n */\n bytes() {\n return this.#cachedBody(\"arrayBuffer\").then((buffer) => new Uint8Array(buffer));\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n const requestInit = {\n body: await req[cacheKey](),\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers: req.header(),\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \"&quot;\";\n break;\n case 39:\n escape = \"&#39;\";\n break;\n case 38:\n escape = \"&amp;\";\n break;\n case 60:\n escape = \"&lt;\";\n break;\n case 62:\n escape = \"&gt;\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * <html>\n * <body>\n * <p>{content}</p>\n * </body>\n * </html>\n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();\n if (typeof arg === \"object\" && \"headers\" in arg) {\n const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);\n for (const [key, value] of argHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, { status, headers: responseHeaders });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n","// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n","// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n","// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler, r.basePath);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = this.getPath(request).slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler, baseRoutePath) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = {\n basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,\n path,\n method,\n handler\n };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} Env - env Object\n * @param {ExecutionContext} - context of execution\n * @returns {Response | Promise<Response>} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n","// src/router/reg-exp-router/matcher.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nvar emptyParam = [];\nfunction match(method, path) {\n const matchers = this.buildAllMatchers();\n const match2 = ((method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match3 = path2.match(matcher[0]);\n if (!match3) {\n return [[], emptyParam];\n }\n const index = match3.indexOf(\"\", 1);\n return [matcher[1][index], match3];\n });\n this.match = match2;\n return match2(method, path);\n}\nexport {\n emptyParam,\n match\n};\n","// src/router/reg-exp-router/node.ts\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = /* @__PURE__ */ Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class _Node {\n #index;\n #varIndex;\n #children = /* @__PURE__ */ Object.create(null);\n insert(tokens, index, paramMap, context, pathErrorCheckOnly) {\n if (tokens.length === 0) {\n if (this.#index !== void 0) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n this.#index = index;\n return;\n }\n const [token, ...restTokens] = tokens;\n const pattern = token === \"*\" ? restTokens.length === 0 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let node;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n if (regexpStr === \".*\") {\n throw PATH_ERROR;\n }\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n node = this.#children[regexpStr];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[regexpStr] = new _Node();\n if (name !== \"\") {\n node.#varIndex = context.varIndex++;\n }\n }\n if (!pathErrorCheckOnly && name !== \"\") {\n paramMap.push([name, node.#varIndex]);\n }\n } else {\n node = this.#children[token];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[token] = new _Node();\n }\n }\n node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.#children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.#children[k];\n return (typeof c.#varIndex === \"number\" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + c.buildRegExpStr();\n });\n if (typeof this.#index === \"number\") {\n strList.unshift(`#${this.#index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n Node,\n PATH_ERROR\n};\n","// src/router/reg-exp-router/trie.ts\nimport { Node } from \"./node.js\";\nvar Trie = class {\n #context = { varIndex: 0 };\n #root = new Node();\n insert(path, index, pathErrorCheckOnly) {\n const paramAssoc = [];\n const groups = [];\n for (let i = 0; ; ) {\n let replaced = false;\n path = path.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = path.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);\n return paramAssoc;\n }\n buildRegExp() {\n let regexp = this.#root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (handlerIndex !== void 0) {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (paramIndex !== void 0) {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n","// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport { PATH_ERROR } from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];\nvar wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n path === \"*\" ? \"\" : `^${path.replace(\n /\\/\\*$|([.\\\\+*[^\\]$()])/g,\n (_, metaChar) => metaChar ? `\\\\${metaChar}` : \"(?:|/.*)\"\n )}$`\n );\n}\nfunction clearWildcardRegExpCache() {\n wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\n}\nfunction buildMatcherFromPreprocessedRoutes(routes) {\n const trie = new Trie();\n const handlerData = [];\n if (routes.length === 0) {\n return nullMatcher;\n }\n const routesWithStaticPathFlag = routes.map(\n (route) => [!/\\*|\\/:/.test(route[0]), ...route]\n ).sort(\n ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length\n );\n const staticMap = /* @__PURE__ */ Object.create(null);\n for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {\n const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];\n if (pathErrorCheckOnly) {\n staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];\n } else {\n j++;\n }\n let paramAssoc;\n try {\n paramAssoc = trie.insert(path, j, pathErrorCheckOnly);\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n if (pathErrorCheckOnly) {\n continue;\n }\n handlerData[j] = handlers.map(([h, paramCount]) => {\n const paramIndexMap = /* @__PURE__ */ Object.create(null);\n paramCount -= 1;\n for (; paramCount >= 0; paramCount--) {\n const [key, value] = paramAssoc[paramCount];\n paramIndexMap[key] = value;\n }\n return [h, paramIndexMap];\n });\n }\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (let i = 0, len = handlerData.length; i < len; i++) {\n for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {\n const map = handlerData[i][j]?.[1];\n if (!map) {\n continue;\n }\n const keys = Object.keys(map);\n for (let k = 0, len3 = keys.length; k < len3; k++) {\n map[keys[k]] = paramReplacementMap[map[keys[k]]];\n }\n }\n }\n const handlerMap = [];\n for (const i in indexReplacementMap) {\n handlerMap[i] = handlerData[indexReplacementMap[i]];\n }\n return [regexp, handlerMap, staticMap];\n}\nfunction findMiddleware(middleware, path) {\n if (!middleware) {\n return void 0;\n }\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n #middleware;\n #routes;\n constructor() {\n this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n }\n add(method, path, handler) {\n const middleware = this.#middleware;\n const routes = this.#routes;\n if (!middleware || !routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n ;\n [middleware, routes].forEach((handlerMap) => {\n handlerMap[method] = /* @__PURE__ */ Object.create(null);\n Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n });\n });\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const paramCount = (path.match(/\\/:/g) || []).length;\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n if (method === METHOD_NAME_ALL) {\n Object.keys(middleware).forEach((m) => {\n middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n });\n } else {\n middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n Object.keys(middleware).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(middleware[m]).forEach((p) => {\n re.test(p) && middleware[m][p].push([handler, paramCount]);\n });\n }\n });\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(routes[m]).forEach(\n (p) => re.test(p) && routes[m][p].push([handler, paramCount])\n );\n }\n });\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (let i = 0, len = paths.length; i < len; i++) {\n const path2 = paths[i];\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n routes[m][path2] ||= [\n ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []\n ];\n routes[m][path2].push([handler, paramCount - len + i + 1]);\n }\n });\n }\n }\n match = match;\n buildAllMatchers() {\n const matchers = /* @__PURE__ */ Object.create(null);\n Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {\n matchers[method] ||= this.#buildMatcher(method);\n });\n this.#middleware = this.#routes = void 0;\n clearWildcardRegExpCache();\n return matchers;\n }\n #buildMatcher(method) {\n const routes = [];\n let hasOwnRoute = method === METHOD_NAME_ALL;\n [this.#middleware, this.#routes].forEach((r) => {\n const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];\n if (ownRoute.length !== 0) {\n hasOwnRoute ||= true;\n routes.push(...ownRoute);\n } else if (method !== METHOD_NAME_ALL) {\n routes.push(\n ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])\n );\n }\n });\n if (!hasOwnRoute) {\n return null;\n } else {\n return buildMatcherFromPreprocessedRoutes(routes);\n }\n }\n};\nexport {\n RegExpRouter\n};\n","// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n #routers = [];\n #routes = [];\n constructor(init) {\n this.#routers = init.routers;\n }\n add(method, path, handler) {\n if (!this.#routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.#routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.#routes) {\n throw new Error(\"Fatal error\");\n }\n const routers = this.#routers;\n const routes = this.#routes;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {\n router.add(...routes[i2]);\n }\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.#routers = [router];\n this.#routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.#routes || this.#routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.#routers[0];\n }\n};\nexport {\n SmartRouter\n};\n","// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nvar emptyParams = /* @__PURE__ */ Object.create(null);\nvar hasChildren = (children) => {\n for (const _ in children) {\n return true;\n }\n return false;\n};\nvar Node = class _Node {\n #methods;\n #children;\n #patterns;\n #order = 0;\n #params = emptyParams;\n constructor(method, handler, children) {\n this.#children = children || /* @__PURE__ */ Object.create(null);\n this.#methods = [];\n if (method && handler) {\n const m = /* @__PURE__ */ Object.create(null);\n m[method] = { handler, possibleKeys: [], score: 0 };\n this.#methods = [m];\n }\n this.#patterns = [];\n }\n insert(method, path, handler) {\n this.#order = ++this.#order;\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = [];\n for (let i = 0, len = parts.length; i < len; i++) {\n const p = parts[i];\n const nextP = parts[i + 1];\n const pattern = getPattern(p, nextP);\n const key = Array.isArray(pattern) ? pattern[0] : p;\n if (key in curNode.#children) {\n curNode = curNode.#children[key];\n if (pattern) {\n possibleKeys.push(pattern[1]);\n }\n continue;\n }\n curNode.#children[key] = new _Node();\n if (pattern) {\n curNode.#patterns.push(pattern);\n possibleKeys.push(pattern[1]);\n }\n curNode = curNode.#children[key];\n }\n curNode.#methods.push({\n [method]: {\n handler,\n possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),\n score: this.#order\n }\n });\n return curNode;\n }\n #pushHandlerSets(handlerSets, node, method, nodeParams, params) {\n for (let i = 0, len = node.#methods.length; i < len; i++) {\n const m = node.#methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n const processedSet = {};\n if (handlerSet !== void 0) {\n handlerSet.params = /* @__PURE__ */ Object.create(null);\n handlerSets.push(handlerSet);\n if (nodeParams !== emptyParams || params && params !== emptyParams) {\n for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {\n const key = handlerSet.possibleKeys[i2];\n const processed = processedSet[handlerSet.score];\n handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];\n processedSet[handlerSet.score] = true;\n }\n }\n }\n }\n }\n search(method, path) {\n const handlerSets = [];\n this.#params = emptyParams;\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n const curNodesQueue = [];\n const len = parts.length;\n let partOffsets = null;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.#children[part];\n if (nextNode) {\n nextNode.#params = node.#params;\n if (isLast) {\n if (nextNode.#children[\"*\"]) {\n this.#pushHandlerSets(handlerSets, nextNode.#children[\"*\"], method, node.#params);\n }\n this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {\n const pattern = node.#patterns[k];\n const params = node.#params === emptyParams ? {} : { ...node.#params };\n if (pattern === \"*\") {\n const astNode = node.#children[\"*\"];\n if (astNode) {\n this.#pushHandlerSets(handlerSets, astNode, method, node.#params);\n astNode.#params = params;\n tempNodes.push(astNode);\n }\n continue;\n }\n const [key, name, matcher] = pattern;\n if (!part && !(matcher instanceof RegExp)) {\n continue;\n }\n const child = node.#children[key];\n if (matcher instanceof RegExp) {\n if (partOffsets === null) {\n partOffsets = new Array(len);\n let offset = path[0] === \"/\" ? 1 : 0;\n for (let p = 0; p < len; p++) {\n partOffsets[p] = offset;\n offset += parts[p].length + 1;\n }\n }\n const restPathString = path.substring(partOffsets[i]);\n const m = matcher.exec(restPathString);\n if (m) {\n params[name] = m[0];\n this.#pushHandlerSets(handlerSets, child, method, node.#params, params);\n if (hasChildren(child.#children)) {\n child.#params = params;\n const componentCount = m[0].match(/\\//)?.length ?? 0;\n const targetCurNodes = curNodesQueue[componentCount] ||= [];\n targetCurNodes.push(child);\n }\n continue;\n }\n }\n if (matcher === true || matcher.test(part)) {\n params[name] = part;\n if (isLast) {\n this.#pushHandlerSets(handlerSets, child, method, params, node.#params);\n if (child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n params,\n node.#params\n );\n }\n } else {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n const shifted = curNodesQueue.shift();\n curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;\n }\n if (handlerSets.length > 1) {\n handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n }\n return [handlerSets.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n","// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n #node;\n constructor() {\n this.#node = new Node();\n }\n add(method, path, handler) {\n const results = checkOptionalParameter(path);\n if (results) {\n for (let i = 0, len = results.length; i < len; i++) {\n this.#node.insert(method, results[i], handler);\n }\n return;\n }\n this.#node.insert(method, path, handler);\n }\n match(method, path) {\n return this.#node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n","// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n /**\n * Creates an instance of the Hono class.\n *\n * @param options - Optional configuration options for the Hono instance.\n */\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n","/**\n * Invite link encoding/decoding for the coordinator join flow.\n *\n * Ported from codemem/coordinator_invites.py.\n */\n\nexport interface InvitePayload {\n\tv: number;\n\tkind: \"coordinator_team_invite\" | \"team_member\" | \"add_device\" | string;\n\tcoordinator_url: string;\n\tgroup_id: string;\n\tpolicy: string;\n\ttoken: string;\n\texpires_at: string;\n\tteam_name: string | null;\n\t/** Present only for project-first invites. All values are display-only; access intent stays coordinator-owned. */\n\toperation_id?: string;\n\tinviter_name?: string | null;\n\tinviter_device_id?: string;\n\tproject_summaries?: Array<{ display_name: string; existing_memory_count: number }>;\n\t/** Policy metadata for recipient-aware invites. It is preview-only and never grants scope access. */\n\tpolicy_team_id?: string;\n\ttarget_identity_id?: string;\n\tassigned_identity_id?: string;\n\treviewed_preview_digest?: string;\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) binary += String.fromCharCode(byte);\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(base64: string): Uint8Array {\n\tconst binary = atob(base64);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let index = 0; index < binary.length; index += 1) {\n\t\tbytes[index] = binary.charCodeAt(index);\n\t}\n\treturn bytes;\n}\n\nfunction toBase64Url(base64: string): string {\n\treturn base64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(value: string): string {\n\tconst padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\treturn padded + \"=\".repeat((4 - (padded.length % 4)) % 4);\n}\n\n/** Encode an invite payload as a compact base64url string (no padding). */\nexport function encodeInvitePayload(payload: InvitePayload): string {\n\tconst json = JSON.stringify(payload);\n\tconst bytes = new TextEncoder().encode(json);\n\treturn toBase64Url(bytesToBase64(bytes));\n}\n\n/** Decode a base64url invite payload string back to an InvitePayload. */\nexport function decodeInvitePayload(value: string): InvitePayload {\n\tconst json = new TextDecoder().decode(base64ToBytes(fromBase64Url(value)));\n\tconst data: unknown = JSON.parse(json);\n\tif (typeof data !== \"object\" || data === null) {\n\t\tthrow new Error(\"invalid invite payload\");\n\t}\n\treturn data as InvitePayload;\n}\n\n/** Build a `codemem://join?invite=...` link from an encoded payload. */\nexport function inviteLink(encodedPayload: string): string {\n\treturn `codemem://join?invite=${encodeURIComponent(encodedPayload)}`;\n}\n\n/**\n * Extract the raw encoded payload from either a `codemem://` link or a raw value.\n *\n * Throws if a `codemem://` link is provided but has no `invite` query parameter.\n */\nexport function extractInvitePayload(value: string): string {\n\tconst raw = value.trim();\n\tif (raw.startsWith(\"codemem://\")) {\n\t\tconst url = new URL(raw);\n\t\tconst invite = url.searchParams.get(\"invite\") ?? \"\";\n\t\tif (!invite) {\n\t\t\tthrow new Error(\"invite payload missing from link\");\n\t\t}\n\t\treturn invite;\n\t}\n\treturn raw;\n}\n","export const PROJECT_INVITE_PENDING_STATUS = \"pending_setup\" as const;\n\nexport const PROJECT_SYNC_ENABLEMENT_FAILED = \"project_sync_enablement_failed\" as const;\n\nexport const PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL =\n\t\"Invitation was accepted, but sync could not be enabled. Make the codemem config writable, then retry.\";\n\nexport class ProjectSyncEnablementError extends Error {\n\treadonly code = PROJECT_SYNC_ENABLEMENT_FAILED;\n\treadonly detail = PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL;\n\n\tconstructor(options?: ErrorOptions) {\n\t\tsuper(PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL, options);\n\t\tthis.name = \"ProjectSyncEnablementError\";\n\t}\n}\n\nexport function isProjectSyncEnablementError(error: unknown): error is ProjectSyncEnablementError {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\terror.code === PROJECT_SYNC_ENABLEMENT_FAILED &&\n\t\t\"detail\" in error &&\n\t\terror.detail === PROJECT_SYNC_ENABLEMENT_FAILURE_DETAIL\n\t);\n}\n","import { createHash } from \"node:crypto\";\nimport { resolve } from \"node:path\";\nimport type { Database } from \"better-sqlite3\";\n\nexport const LOCAL_DEFAULT_SCOPE_ID = \"local-default\";\n\n/**\n * Scope id used by the conservative migration backfill for legacy shared\n * memories that cannot yet be assigned to a concrete team/org scope. Single\n * source of truth: filters.ts and scope-backfill.ts re-import this so the\n * read-visibility predicate and the backfill agree on one literal.\n */\nexport const LEGACY_SHARED_REVIEW_SCOPE_ID = \"legacy-shared-review\";\n\n/**\n * Upper bound on how many scope ids we will inline into the index-eligible\n * `scope_id IN (...)` fast path (one bound parameter each). Kept well under\n * SQLite's compiled `SQLITE_MAX_VARIABLE_NUMBER` so a device with an\n * unrealistically large visible set falls back to the fixed-param EXISTS\n * predicate instead of throwing \"too many SQL variables\" at prepare time.\n */\nexport const MAX_SCOPE_IN_PARAMS = 500;\n\nexport type WorkspaceIdentitySource =\n\t| \"git_remote\"\n\t| \"git_remote_branch\"\n\t| \"cwd\"\n\t| \"workspace_id\"\n\t| \"unmapped\";\n\nexport interface WorkspaceIdentityInput {\n\tgitRemote?: string | null;\n\tgitBranch?: string | null;\n\tcwd?: string | null;\n\tworkspaceId?: string | null;\n\tproject?: string | null;\n\tbranchScoped?: boolean;\n}\n\nexport interface CanonicalWorkspaceIdentity {\n\tvalue: string;\n\tsource: WorkspaceIdentitySource;\n\tdisplayProject: string | null;\n}\n\nexport interface ScopeMapping {\n\tid?: number | null;\n\tworkspace_identity?: string | null;\n\tproject_pattern: string;\n\tscope_id: string;\n\tpriority?: number | null;\n\tupdated_at?: string | null;\n\tsource?: string | null;\n}\n\nexport type ScopeResolutionReason =\n\t| \"explicit_override\"\n\t| \"exact_mapping\"\n\t| \"pattern_mapping\"\n\t| \"local_default\";\n\nexport interface ScopeResolution {\n\tscopeId: string;\n\treason: ScopeResolutionReason;\n\tworkspaceIdentity: CanonicalWorkspaceIdentity;\n\tmapping: ScopeMapping | null;\n\tmatchedPattern: string | null;\n}\n\nexport interface ResolveProjectScopeInput extends WorkspaceIdentityInput {\n\texplicitScopeId?: string | null;\n\tmappings?: ScopeMapping[];\n\tlocalDefaultScopeId?: string;\n}\n\ninterface MappingCandidate {\n\tmapping: ScopeMapping;\n\tspecificity: number;\n\tmatchedPattern: string | null;\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nfunction normalizeSlash(value: string): string {\n\tconst normalized = value.trim().replaceAll(\"\\\\\", \"/\").replace(/\\/+$/, \"\");\n\treturn normalized || value.trim();\n}\n\nfunction normalizeCwd(cwd: string): string {\n\t// Callers should pass an already-realpathed session cwd when symlink\n\t// resolution matters; this pure helper only normalizes path syntax.\n\treturn normalizeSlash(resolve(cwd));\n}\n\nfunction normalizeMappingIdentity(value: string | null | undefined): string | null {\n\tconst cleaned = clean(value);\n\treturn cleaned ? normalizeSlash(cleaned) : null;\n}\n\nfunction unmappedIdentity(input: WorkspaceIdentityInput): string {\n\tconst seed = [input.cwd, input.project, input.workspaceId]\n\t\t.map((value) => clean(value))\n\t\t.find((value): value is string => value != null);\n\tconst digest = createHash(\"sha256\")\n\t\t.update(seed ?? \"unknown\", \"utf8\")\n\t\t.digest(\"hex\");\n\treturn `unmapped:${digest}`;\n}\n\nexport function canonicalWorkspaceIdentity(\n\tinput: WorkspaceIdentityInput,\n): CanonicalWorkspaceIdentity {\n\tconst gitRemote = clean(input.gitRemote);\n\tconst gitBranch = clean(input.gitBranch);\n\tconst cwd = clean(input.cwd);\n\tconst workspaceId = clean(input.workspaceId);\n\tconst project = clean(input.project);\n\n\tif (gitRemote) {\n\t\tconst normalizedRemote = normalizeSlash(gitRemote);\n\t\tif (input.branchScoped && gitBranch) {\n\t\t\treturn {\n\t\t\t\tvalue: `${normalizedRemote}:${gitBranch}`,\n\t\t\t\tsource: \"git_remote_branch\",\n\t\t\t\tdisplayProject: project,\n\t\t\t};\n\t\t}\n\t\treturn { value: normalizedRemote, source: \"git_remote\", displayProject: project };\n\t}\n\n\tif (cwd) {\n\t\treturn { value: normalizeCwd(cwd), source: \"cwd\", displayProject: project };\n\t}\n\n\tif (workspaceId) {\n\t\treturn { value: normalizeSlash(workspaceId), source: \"workspace_id\", displayProject: project };\n\t}\n\n\treturn { value: unmappedIdentity(input), source: \"unmapped\", displayProject: project };\n}\n\nfunction isBasenameOnlyPattern(pattern: string): boolean {\n\treturn !/[\\\\/:]/.test(pattern);\n}\n\nfunction escapeRegex(value: string): string {\n\treturn value.replace(/[|\\\\{}()[\\]^$+?.*]/g, \"\\\\$&\");\n}\n\nfunction patternSpecificity(pattern: string): number {\n\treturn pattern.replace(/[*?]/g, \"\").length;\n}\n\nfunction matchesPattern(identity: string, pattern: string): boolean {\n\tconst normalizedPattern = normalizeSlash(pattern);\n\tif (!normalizedPattern || isBasenameOnlyPattern(normalizedPattern)) return false;\n\tif (!/[*?]/.test(normalizedPattern)) return identity === normalizedPattern;\n\tconst regex = new RegExp(\n\t\t`^${escapeRegex(normalizedPattern).replaceAll(\"\\\\*\", \".*\").replaceAll(\"\\\\?\", \".\")}$`,\n\t);\n\treturn regex.test(identity);\n}\n\nfunction candidatePriority(candidate: MappingCandidate): number {\n\treturn candidate.mapping.priority ?? 0;\n}\n\nfunction candidateUpdatedAt(candidate: MappingCandidate): number {\n\tconst updatedAt = clean(candidate.mapping.updated_at);\n\tif (!updatedAt) return 0;\n\tconst time = Date.parse(updatedAt);\n\treturn Number.isFinite(time) ? time : 0;\n}\n\nfunction compareCandidates(a: MappingCandidate, b: MappingCandidate): number {\n\treturn (\n\t\tcandidatePriority(b) - candidatePriority(a) ||\n\t\tb.specificity - a.specificity ||\n\t\tcandidateUpdatedAt(b) - candidateUpdatedAt(a) ||\n\t\t(b.mapping.id ?? 0) - (a.mapping.id ?? 0) ||\n\t\ta.mapping.scope_id.localeCompare(b.mapping.scope_id)\n\t);\n}\n\nfunction bestCandidate(candidates: MappingCandidate[]): MappingCandidate | null {\n\treturn candidates.toSorted(compareCandidates)[0] ?? null;\n}\n\nexport function resolveProjectScope(input: ResolveProjectScopeInput): ScopeResolution {\n\tconst workspaceIdentity = canonicalWorkspaceIdentity(input);\n\tconst explicitScopeId = clean(input.explicitScopeId);\n\tif (explicitScopeId) {\n\t\treturn {\n\t\t\tscopeId: explicitScopeId,\n\t\t\treason: \"explicit_override\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: null,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\tif (workspaceIdentity.source === \"unmapped\") {\n\t\treturn {\n\t\t\tscopeId: input.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\t\treason: \"local_default\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: null,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\n\tconst mappings = input.mappings ?? [];\n\tconst exact = bestCandidate(\n\t\tmappings\n\t\t\t.filter(\n\t\t\t\t(mapping) =>\n\t\t\t\t\tnormalizeMappingIdentity(mapping.workspace_identity) === workspaceIdentity.value,\n\t\t\t)\n\t\t\t.map((mapping) => ({\n\t\t\t\tmapping,\n\t\t\t\tmatchedPattern: null,\n\t\t\t\tspecificity: workspaceIdentity.value.length,\n\t\t\t})),\n\t);\n\tif (exact) {\n\t\treturn {\n\t\t\tscopeId: exact.mapping.scope_id,\n\t\t\treason: \"exact_mapping\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: exact.mapping,\n\t\t\tmatchedPattern: null,\n\t\t};\n\t}\n\n\tconst pattern = bestCandidate(\n\t\tmappings.flatMap((mapping): MappingCandidate[] => {\n\t\t\tif (clean(mapping.workspace_identity)) return [];\n\t\t\tconst projectPattern = clean(mapping.project_pattern);\n\t\t\tif (!projectPattern || !matchesPattern(workspaceIdentity.value, projectPattern)) return [];\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tmapping,\n\t\t\t\t\tmatchedPattern: normalizeSlash(projectPattern),\n\t\t\t\t\tspecificity: patternSpecificity(projectPattern),\n\t\t\t\t},\n\t\t\t];\n\t\t}),\n\t);\n\tif (pattern) {\n\t\treturn {\n\t\t\tscopeId: pattern.mapping.scope_id,\n\t\t\treason: \"pattern_mapping\",\n\t\t\tworkspaceIdentity,\n\t\t\tmapping: pattern.mapping,\n\t\t\tmatchedPattern: pattern.matchedPattern,\n\t\t};\n\t}\n\n\treturn {\n\t\tscopeId: input.localDefaultScopeId ?? LOCAL_DEFAULT_SCOPE_ID,\n\t\treason: \"local_default\",\n\t\tworkspaceIdentity,\n\t\tmapping: null,\n\t\tmatchedPattern: null,\n\t};\n}\n\n/**\n * Resolve, once per request, the full set of scope_ids that `deviceId` may read.\n *\n * This is the index-eligible equivalent of the per-row EXISTS predicate in\n * `addScopeVisibilityFilter`'s fallback branch (filters.ts): instead of\n * evaluating the replication_scopes / scope_memberships subqueries for every\n * candidate row, we compute the visible set up front and let the SQL filter use\n * a plain `scope_id IN (...)`. The membership predicate (active membership with\n * `membership_epoch >= scope.membership_epoch`) is preserved exactly.\n *\n * Lives in this leaf module (it imports nothing from filters/search/store/\n * vectors) so all three OwnershipFilterContext builders can share it without an\n * import cycle.\n *\n * NULL scope_ids are skipped here — a NULL scope_id is handled by the filter's\n * dedicated `IS NULL` branch, not by membership in this set.\n */\nexport function resolveVisibleScopeIds(db: Database, deviceId: string): string[] {\n\tconst visible = new Set<string>([\"\", LOCAL_DEFAULT_SCOPE_ID, LEGACY_SHARED_REVIEW_SCOPE_ID]);\n\tconst localScopes = db\n\t\t.prepare(\n\t\t\t`SELECT scope_id\n\t\t\t FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'local'`,\n\t\t)\n\t\t.all() as Array<{ scope_id: string | null }>;\n\tfor (const row of localScopes) {\n\t\tif (row.scope_id != null) visible.add(row.scope_id);\n\t}\n\tconst memberScopes = db\n\t\t.prepare(\n\t\t\t`SELECT sm.scope_id AS scope_id\n\t\t\t FROM scope_memberships sm\n\t\t\t JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\t WHERE sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch`,\n\t\t)\n\t\t.all(deviceId) as Array<{ scope_id: string | null }>;\n\tfor (const row of memberScopes) {\n\t\tif (row.scope_id != null) visible.add(row.scope_id);\n\t}\n\treturn [...visible];\n}\n","import { createHash } from \"node:crypto\";\nimport { normalizeIdentityDisplayName } from \"./project-invite-identity.js\";\nimport { canonicalWorkspaceIdentity } from \"./scope-resolution.js\";\n\nexport const SHARE_HISTORY_POLICY = \"existing_and_future\" as const;\n\nexport interface ShareProjectIntent {\n\tcanonicalIdentity: string;\n\tdisplayName: string;\n\tidentitySource: string;\n\texistingMemoryCount: number;\n}\n\nexport interface AcceptedProjectIntent {\n\tcanonical_identity: string;\n\tdisplay_name: string;\n\texisting_memory_count: number;\n}\n\nfunction digest(value: unknown): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\");\n}\n\nexport function shareProjectSetDigest(projects: ShareProjectIntent[]): string {\n\tconst reviewedProjects = projects\n\t\t.map((project) => ({\n\t\t\tcanonicalIdentity: project.canonicalIdentity,\n\t\t\texistingMemoryCount: project.existingMemoryCount,\n\t\t}))\n\t\t.toSorted((left, right) => left.canonicalIdentity.localeCompare(right.canonicalIdentity));\n\treturn digest({ v: 1, historyPolicy: SHARE_HISTORY_POLICY, projects: reviewedProjects });\n}\n\nexport function acceptedProjectIntentDigest(projects: AcceptedProjectIntent[]): string {\n\treturn shareProjectSetDigest(\n\t\tprojects.map((project) => ({\n\t\t\tcanonicalIdentity: project.canonical_identity,\n\t\t\tdisplayName: project.display_name,\n\t\t\tidentitySource: \"coordinator_acceptance\",\n\t\t\texistingMemoryCount: project.existing_memory_count,\n\t\t})),\n\t);\n}\n\nexport function parseAcceptedProjectIntent(value: unknown): AcceptedProjectIntent[] {\n\tif (!Array.isArray(value) || value.length === 0 || value.length > 100) {\n\t\tthrow new Error(\"operation_intent_invalid\");\n\t}\n\tconst projects = value.map((item) => {\n\t\tif (!item || typeof item !== \"object\" || Array.isArray(item)) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst record = item as Record<string, unknown>;\n\t\tif (typeof record.canonical_identity !== \"string\" || typeof record.display_name !== \"string\") {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst canonicalIdentityRaw = record.canonical_identity;\n\t\tconst canonicalIdentity = canonicalIdentityRaw.trim();\n\t\tconst displayNameRaw = record.display_name;\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeIdentityDisplayName(displayNameRaw, \"project_name\");\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst count = record.existing_memory_count;\n\t\tconst canonicalIdentityRoundTrip = canonicalWorkspaceIdentity({\n\t\t\tgitRemote: canonicalIdentity,\n\t\t}).value;\n\t\tif (\n\t\t\t!canonicalIdentity ||\n\t\t\tcanonicalIdentity !== canonicalIdentityRaw ||\n\t\t\tcanonicalIdentity.length > 2048 ||\n\t\t\tcanonicalIdentity.startsWith(\"unmapped:\") ||\n\t\t\tcanonicalIdentityRoundTrip !== canonicalIdentity ||\n\t\t\tdisplayName !== displayNameRaw ||\n\t\t\t!Number.isSafeInteger(count) ||\n\t\t\tNumber(count) < 0 ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(canonicalIdentity) ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(displayName)\n\t\t) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\treturn {\n\t\t\tcanonical_identity: canonicalIdentity,\n\t\t\tdisplay_name: displayName,\n\t\t\texisting_memory_count: Number(count),\n\t\t};\n\t});\n\tif (new Set(projects.map((project) => project.canonical_identity)).size !== projects.length) {\n\t\tthrow new Error(\"operation_intent_invalid\");\n\t}\n\treturn projects.toSorted((left, right) =>\n\t\tleft.canonical_identity.localeCompare(right.canonical_identity),\n\t);\n}\n","// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nfunction hrtime(previousTimestamp) {\n const clocktime = performance.now() * 1e-3;\n let seconds = Math.floor(clocktime);\n let nanoseconds = Math.floor((clocktime % 1) * 1e9);\n if (previousTimestamp != undefined) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds < 0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [seconds, nanoseconds];\n}\n// The current timestamp in whole milliseconds\nexport function getMilliseconds() {\n const [seconds, nanoseconds] = hrtime();\n return seconds * 1e3 + Math.floor(nanoseconds / 1e6);\n}\n// Wait for a specified number of milliseconds before fulfilling the returned promise.\nexport function wait(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n//# sourceMappingURL=clock.js.map","import { getMilliseconds, wait } from \"./clock.js\";\n/**\n * A hierarchical token bucket for rate limiting. See\n * http://en.wikipedia.org/wiki/Token_bucket for more information.\n *\n * @param options\n * @param options.bucketSize Maximum number of tokens to hold in the bucket.\n * Also known as the burst rate.\n * @param options.tokensPerInterval Number of tokens to drip into the bucket\n * over the course of one interval.\n * @param options.interval The interval length in milliseconds, or as\n * one of the following strings: 'second', 'minute', 'hour', day'.\n * @param options.parentBucket Optional. A token bucket that will act as\n * the parent of this bucket.\n */\nexport class TokenBucket {\n bucketSize;\n tokensPerInterval;\n interval;\n parentBucket;\n content;\n lastDrip;\n constructor({ bucketSize, tokensPerInterval, interval, parentBucket }) {\n this.bucketSize = bucketSize;\n this.tokensPerInterval = tokensPerInterval;\n if (typeof interval === \"string\") {\n switch (interval) {\n case \"sec\":\n case \"second\":\n this.interval = 1000;\n break;\n case \"min\":\n case \"minute\":\n this.interval = 1000 * 60;\n break;\n case \"hr\":\n case \"hour\":\n this.interval = 1000 * 60 * 60;\n break;\n case \"day\":\n this.interval = 1000 * 60 * 60 * 24;\n break;\n default:\n throw new Error(\"Invalid interval \" + interval);\n }\n }\n else {\n this.interval = interval;\n }\n this.parentBucket = parentBucket;\n this.content = 0;\n this.lastDrip = getMilliseconds();\n }\n /**\n * Remove the requested number of tokens. If the bucket (and any parent\n * buckets) contains enough tokens this will happen immediately. Otherwise,\n * the removal will happen when enough tokens become available.\n * @param count The number of tokens to remove.\n * @returns A promise for the remainingTokens count.\n */\n async removeTokens(count) {\n // Is this an infinite size bucket?\n if (this.bucketSize === 0) {\n return Number.POSITIVE_INFINITY;\n }\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds bucket size ${this.bucketSize}`);\n }\n // Drip new tokens into this bucket\n this.drip();\n const comeBackLater = async () => {\n // How long do we need to wait to make up the difference in tokens?\n const waitMs = Math.ceil((count - this.content) * (this.interval / this.tokensPerInterval));\n await wait(waitMs);\n return this.removeTokens(count);\n };\n // If we don't have enough tokens in this bucket, come back later\n if (count > this.content)\n return comeBackLater();\n if (this.parentBucket != undefined) {\n // Remove the requested from the parent bucket first\n const remainingTokens = await this.parentBucket.removeTokens(count);\n // Check that we still have enough tokens in this bucket\n if (count > this.content)\n return comeBackLater();\n // Tokens were removed from the parent bucket, now remove them from\n // this bucket. Note that we look at the current bucket and parent\n // bucket's remaining tokens and return the smaller of the two values\n this.content -= count;\n return Math.min(remainingTokens, this.content);\n }\n else {\n // Remove the requested tokens from this bucket\n this.content -= count;\n return this.content;\n }\n }\n /**\n * Attempt to remove the requested number of tokens and return immediately.\n * If the bucket (and any parent buckets) contains enough tokens this will\n * return true, otherwise false is returned.\n * @param {Number} count The number of tokens to remove.\n * @param {Boolean} True if the tokens were successfully removed, otherwise\n * false.\n */\n tryRemoveTokens(count) {\n // Is this an infinite size bucket?\n if (!this.bucketSize)\n return true;\n // Make sure the bucket can hold the requested number of tokens\n if (count > this.bucketSize)\n return false;\n // Drip new tokens into this bucket\n this.drip();\n // If we don't have enough tokens in this bucket, return false\n if (count > this.content)\n return false;\n // Try to remove the requested tokens from the parent bucket\n if (this.parentBucket && !this.parentBucket.tryRemoveTokens(count))\n return false;\n // Remove the requested tokens from this bucket and return\n this.content -= count;\n return true;\n }\n /**\n * Add any new tokens to the bucket since the last drip.\n * @returns {Boolean} True if new tokens were added, otherwise false.\n */\n drip() {\n if (this.tokensPerInterval === 0) {\n const prevContent = this.content;\n this.content = this.bucketSize;\n return this.content > prevContent;\n }\n const now = getMilliseconds();\n const deltaMS = Math.max(now - this.lastDrip, 0);\n this.lastDrip = now;\n const dripAmount = deltaMS * (this.tokensPerInterval / this.interval);\n const prevContent = this.content;\n this.content = Math.min(this.content + dripAmount, this.bucketSize);\n return Math.floor(this.content) > Math.floor(prevContent);\n }\n}\n//# sourceMappingURL=TokenBucket.js.map","import { TokenBucket } from \"./TokenBucket.js\";\nimport { getMilliseconds, wait } from \"./clock.js\";\n/**\n * A generic rate limiter. Underneath the hood, this uses a token bucket plus\n * an additional check to limit how many tokens we can remove each interval.\n *\n * @param options\n * @param options.tokensPerInterval Maximum number of tokens that can be\n * removed at any given moment and over the course of one interval.\n * @param options.interval The interval length in milliseconds, or as\n * one of the following strings: 'second', 'minute', 'hour', day'.\n * @param options.fireImmediately Whether or not the promise will resolve\n * immediately when rate limiting is in effect (default is false).\n */\nexport class RateLimiter {\n tokenBucket;\n curIntervalStart;\n tokensThisInterval;\n fireImmediately;\n constructor({ tokensPerInterval, interval, fireImmediately }) {\n this.tokenBucket = new TokenBucket({\n bucketSize: tokensPerInterval,\n tokensPerInterval,\n interval,\n });\n // Fill the token bucket to start\n this.tokenBucket.content = tokensPerInterval;\n this.curIntervalStart = getMilliseconds();\n this.tokensThisInterval = 0;\n this.fireImmediately = fireImmediately ?? false;\n }\n /**\n * Remove the requested number of tokens. If the rate limiter contains enough\n * tokens and we haven't spent too many tokens in this interval already, this\n * will happen immediately. Otherwise, the removal will happen when enough\n * tokens become available.\n * @param count The number of tokens to remove.\n * @returns A promise for the remainingTokens count.\n */\n async removeTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize) {\n throw new Error(`Requested tokens ${count} exceeds maximum tokens per interval ${this.tokenBucket.bucketSize}`);\n }\n const now = getMilliseconds();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, wait until the\n // next interval\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval) {\n if (this.fireImmediately) {\n return -1;\n }\n else {\n const waitMs = Math.ceil(this.curIntervalStart + this.tokenBucket.interval - now);\n await wait(waitMs);\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n }\n // Remove the requested number of tokens from the token bucket\n const remainingTokens = await this.tokenBucket.removeTokens(count);\n this.tokensThisInterval += count;\n return remainingTokens;\n }\n /**\n * Attempt to remove the requested number of tokens and return immediately.\n * If the bucket (and any parent buckets) contains enough tokens and we\n * haven't spent too many tokens in this interval already, this will return\n * true. Otherwise, false is returned.\n * @param {Number} count The number of tokens to remove.\n * @param {Boolean} True if the tokens were successfully removed, otherwise\n * false.\n */\n tryRemoveTokens(count) {\n // Make sure the request isn't for more than we can handle\n if (count > this.tokenBucket.bucketSize)\n return false;\n const now = getMilliseconds();\n // Advance the current interval and reset the current interval token count\n // if needed\n if (now < this.curIntervalStart || now - this.curIntervalStart >= this.tokenBucket.interval) {\n this.curIntervalStart = now;\n this.tokensThisInterval = 0;\n }\n // If we don't have enough tokens left in this interval, return false\n if (count > this.tokenBucket.tokensPerInterval - this.tokensThisInterval)\n return false;\n // Try to remove the requested number of tokens from the token bucket\n const removed = this.tokenBucket.tryRemoveTokens(count);\n if (removed) {\n this.tokensThisInterval += count;\n }\n return removed;\n }\n /**\n * Returns the number of tokens remaining in the TokenBucket.\n * @returns {Number} The number of tokens remaining.\n */\n getTokensRemaining() {\n this.tokenBucket.drip();\n return this.tokenBucket.content;\n }\n}\n//# sourceMappingURL=RateLimiter.js.map","import { RateLimiter } from \"limiter\";\n\nexport interface InMemoryRequestRateLimiter {\n\tcheck(key: string, limit: number): { allowed: boolean; retryAfterS: number };\n}\n\nexport interface CreateInMemoryRequestRateLimiterOptions {\n\twindowMs?: number;\n\tnow?: () => number;\n}\n\n/**\n * Best-effort, per-isolate request rate limiter.\n *\n * Buckets live in a module-local Map, so on Cloudflare Workers the limits are\n * enforced per isolate, not fleet-wide: the effective ceiling is multiplied by\n * the number of live isolates and resets whenever an isolate is evicted. This\n * is acceptable as a coarse abuse brake but is NOT a hard global limit. The\n * unauthenticated /v1/join surface is the most exposed to this gap. Real\n * fleet-wide enforcement needs a shared counter backed by a Durable Object or\n * D1/KV.\n */\nexport function createInMemoryRequestRateLimiter(\n\toptions: CreateInMemoryRequestRateLimiterOptions = {},\n): InMemoryRequestRateLimiter {\n\tconst windowMs = Math.max(1000, Math.trunc(options.windowMs ?? 60_000));\n\tconst now = options.now ?? (() => Date.now());\n\tconst buckets = new Map<string, { limiter: RateLimiter; lastUsedAt: number }>();\n\tlet checks = 0;\n\n\tfunction estimatedRetryAfterS(limit: number): number {\n\t\treturn Math.max(1, Math.ceil(windowMs / Math.max(1, limit) / 1000));\n\t}\n\n\tfunction cleanupExpiredBuckets(currentNow: number): void {\n\t\tif (buckets.size < 64 || checks % 64 !== 0) return;\n\t\tconst staleBefore = currentNow - windowMs * 10;\n\t\tfor (const [key, bucket] of buckets) {\n\t\t\tif (bucket.lastUsedAt < staleBefore) buckets.delete(key);\n\t\t}\n\t}\n\n\treturn {\n\t\tcheck(key: string, limit: number) {\n\t\t\tconst safeLimit = Math.max(1, Math.trunc(limit));\n\t\t\tchecks += 1;\n\t\t\tconst currentNow = now();\n\t\t\tcleanupExpiredBuckets(currentNow);\n\t\t\tconst bucketKey = `${safeLimit}:${key}`;\n\t\t\tlet bucket = buckets.get(bucketKey);\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = {\n\t\t\t\t\tlimiter: new RateLimiter({\n\t\t\t\t\t\ttokensPerInterval: safeLimit,\n\t\t\t\t\t\tinterval: windowMs,\n\t\t\t\t\t\tfireImmediately: true,\n\t\t\t\t\t}),\n\t\t\t\t\tlastUsedAt: currentNow,\n\t\t\t\t};\n\t\t\t\tbuckets.set(bucketKey, bucket);\n\t\t\t}\n\t\t\tbucket.lastUsedAt = currentNow;\n\t\t\tif (bucket.limiter.tryRemoveTokens(1)) {\n\t\t\t\treturn { allowed: true, retryAfterS: 0 };\n\t\t\t}\n\t\t\treturn { allowed: false, retryAfterS: estimatedRetryAfterS(safeLimit) };\n\t\t},\n\t};\n}\n","export const SCOPE_MEMBERSHIP_REVOCATION_LIMITATION =\n\t\"Revocation blocks future sync for this Space. It does not remove data already copied to the revoked device; offline devices, backups, copied databases, malicious peers, or old versions may retain data.\";\n\nexport interface ScopeMembershipRevocationNotice {\n\tscope_id: string;\n\tdevice_id: string;\n\tmembership_epoch: number | null;\n\tprevents_future_sync: true;\n\tdeletes_already_copied_data: false;\n\tmessage: string;\n}\n\nexport interface ScopeMembershipEpochStatus {\n\tmembership_epoch: number | null;\n\trequired_epoch: number | null;\n\tstale: boolean;\n\treason: \"current\" | \"stale_epoch\" | \"unknown_epoch\";\n}\n\nexport function scopeMembershipEpochStatus(input: {\n\tmembershipEpoch?: number | null;\n\trequiredEpoch?: number | null;\n}): ScopeMembershipEpochStatus {\n\tconst membershipEpoch = Number.isFinite(input.membershipEpoch)\n\t\t? Number(input.membershipEpoch)\n\t\t: null;\n\tconst requiredEpoch = Number.isFinite(input.requiredEpoch) ? Number(input.requiredEpoch) : null;\n\tif (membershipEpoch == null || requiredEpoch == null) {\n\t\treturn {\n\t\t\tmembership_epoch: membershipEpoch,\n\t\t\trequired_epoch: requiredEpoch,\n\t\t\tstale: false,\n\t\t\treason: \"unknown_epoch\",\n\t\t};\n\t}\n\treturn {\n\t\tmembership_epoch: membershipEpoch,\n\t\trequired_epoch: requiredEpoch,\n\t\tstale: membershipEpoch < requiredEpoch,\n\t\treason: membershipEpoch < requiredEpoch ? \"stale_epoch\" : \"current\",\n\t};\n}\n\nexport function explainScopeMembershipRevocation(input: {\n\tscopeId: string;\n\tdeviceId: string;\n\tmembershipEpoch?: number | null;\n}): ScopeMembershipRevocationNotice {\n\treturn {\n\t\tscope_id: input.scopeId,\n\t\tdevice_id: input.deviceId,\n\t\tmembership_epoch: Number.isFinite(input.membershipEpoch) ? Number(input.membershipEpoch) : null,\n\t\tprevents_future_sync: true,\n\t\tdeletes_already_copied_data: false,\n\t\tmessage: SCOPE_MEMBERSHIP_REVOCATION_LIMITATION,\n\t};\n}\n","export const DEFAULT_TIME_WINDOW_S = 300;\n","/**\n * Coordinator API — Hono-based HTTP server for the coordinator relay.\n *\n * Manages device enrollment, presence, invites, and join requests.\n * Ported from codemem/coordinator_api.py.\n */\n\nimport type { Context } from \"hono\";\nimport { Hono } from \"hono\";\nimport type { InvitePayload } from \"./coordinator-invites.js\";\nimport { encodeInvitePayload, inviteLink } from \"./coordinator-invites.js\";\nimport {\n\tCoordinatorMembershipError,\n\tSCOPE_MEMBERSHIP_EFFECT_CONFLICT,\n} from \"./coordinator-membership-effects.js\";\nimport type {\n\tCoordinatorBootstrapGrantVerification,\n\tCoordinatorEnrollment,\n\tCoordinatorInviteKind,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tCoordinatorStore,\n} from \"./coordinator-store-contract.js\";\nimport { PROJECT_INVITE_PENDING_STATUS } from \"./project-invite-acceptance.js\";\nimport {\n\tnormalizeHumanPresentationName,\n\tnormalizeProjectInviteSummaries,\n} from \"./project-invite-identity.js\";\nimport { acceptedProjectIntentDigest, parseAcceptedProjectIntent } from \"./project-share-intent.js\";\nimport {\n\tRecipientReviewedIntentError,\n\ttype RecipientReviewedIntentV1,\n\tverifyRecipientReviewedIntent,\n} from \"./recipient-reviewed-intent.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\nimport { explainScopeMembershipRevocation } from \"./scope-membership-semantics.js\";\nimport { DEFAULT_TIME_WINDOW_S } from \"./sync-auth-constants.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst MAX_BODY_BYTES = 64 * 1024;\nconst ADMIN_HEADER = \"X-Codemem-Coordinator-Admin\";\nconst ADMIN_ACTOR_HEADER = \"X-Codemem-Coordinator-Admin-Actor\";\nconst DEFAULT_COORDINATOR_READ_LIMIT = 120;\nconst DEFAULT_COORDINATOR_MUTATION_LIMIT = 30;\n\nexport interface CoordinatorRequestRateLimitOptions {\n\tlimiter?: InMemoryRequestRateLimiter;\n\treadLimit?: number;\n\tmutationLimit?: number;\n\tunauthenticatedReadLimit?: number;\n\tunauthenticatedMutationLimit?: number;\n}\n\nexport interface CoordinatorRuntimeDeps {\n\tadminSecret(): string | null;\n\tnow(): string;\n}\n\nexport interface CreateCoordinatorAppOptions {\n\tstoreFactory: () => CoordinatorStore;\n\truntime: CoordinatorRuntimeDeps;\n\trequestVerifier: CoordinatorRequestVerifier;\n\trequestRateLimit?: CoordinatorRequestRateLimitOptions;\n}\n\nexport interface CoordinatorVerifyRequestInput {\n\tmethod: string;\n\tpathWithQuery: string;\n\tbodyBytes: Uint8Array;\n\ttimestamp: string;\n\tnonce: string;\n\tsignature: string;\n\tpublicKey: string;\n\tdeviceId: string;\n}\n\nexport type CoordinatorRequestVerifier = (\n\tinput: CoordinatorVerifyRequestInput,\n) => Promise<boolean> | boolean;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction authorizeAdmin(\n\theaderValue: string | null | undefined,\n\truntime: CoordinatorRuntimeDeps,\n): { ok: boolean; error: string } {\n\tconst expected = runtime.adminSecret();\n\tif (!expected) return { ok: false, error: \"admin_not_configured\" };\n\tconst provided = (headerValue ?? \"\").trim();\n\tif (!provided) return { ok: false, error: \"missing_admin_header\" };\n\tif (provided !== expected) return { ok: false, error: \"invalid_admin_secret\" };\n\treturn { ok: true, error: \"ok\" };\n}\n\n/** Extract path + query string from a full URL for signature verification. */\nfunction pathWithQuery(url: string): string {\n\tconst parsed = new URL(url);\n\treturn parsed.search ? `${parsed.pathname}${parsed.search}` : parsed.pathname;\n}\n\nasync function recordNonce(\n\tstore: CoordinatorStore,\n\tdeviceId: string,\n\tnonce: string,\n\tcreatedAt: string,\n): Promise<boolean> {\n\treturn await store.recordNonce(deviceId, nonce, createdAt);\n}\n\nasync function cleanupNonces(store: CoordinatorStore, cutoff: string): Promise<void> {\n\tawait store.cleanupNonces(cutoff);\n}\n\ninterface AuthResult {\n\tok: boolean;\n\terror: string;\n\tenrollment: CoordinatorEnrollment | null;\n}\n\nasync function authorizeRequest(\n\tstore: CoordinatorStore,\n\truntime: CoordinatorRuntimeDeps,\n\trequestVerifier: CoordinatorRequestVerifier,\n\topts: {\n\t\tmethod: string;\n\t\turl: string;\n\t\tgroupId: string;\n\t\tbody: Uint8Array;\n\t\tdeviceId: string | null;\n\t\tsignature: string | null;\n\t\ttimestamp: string | null;\n\t\tnonce: string | null;\n\t},\n): Promise<AuthResult> {\n\tconst { deviceId, signature, timestamp, nonce } = opts;\n\tif (!deviceId || !signature || !timestamp || !nonce) {\n\t\treturn { ok: false, error: \"missing_headers\", enrollment: null };\n\t}\n\n\tconst enrollment = await store.getEnrollment(opts.groupId, deviceId, true);\n\tif (!enrollment) {\n\t\treturn { ok: false, error: \"unknown_device\", enrollment: null };\n\t}\n\tif (enrollment.enabled !== 1) {\n\t\treturn { ok: false, error: \"device_disabled\", enrollment: null };\n\t}\n\tconst group = await store.getGroup(opts.groupId);\n\tif (!group) {\n\t\treturn { ok: false, error: \"group_not_found\", enrollment: null };\n\t}\n\tif (group.archived_at) {\n\t\treturn { ok: false, error: \"group_archived\", enrollment: null };\n\t}\n\n\tlet valid: boolean;\n\ttry {\n\t\tvalid = await requestVerifier({\n\t\t\tmethod: opts.method,\n\t\t\tpathWithQuery: pathWithQuery(opts.url),\n\t\t\tbodyBytes: opts.body,\n\t\t\ttimestamp,\n\t\t\tnonce,\n\t\t\tsignature,\n\t\t\tpublicKey: String(enrollment.public_key),\n\t\t\tdeviceId,\n\t\t});\n\t} catch {\n\t\treturn { ok: false, error: \"signature_verification_error\", enrollment: null };\n\t}\n\n\tif (!valid) {\n\t\treturn { ok: false, error: \"invalid_signature\", enrollment: null };\n\t}\n\n\tconst createdAt = runtime.now();\n\tif (!(await recordNonce(store, deviceId, nonce, createdAt))) {\n\t\treturn { ok: false, error: \"nonce_replay\", enrollment: null };\n\t}\n\n\t// Clock-source note: the nonce timestamp/cutoff below is driven by the\n\t// injected runtime.now(), while the request freshness window is enforced\n\t// inside requestVerifier using real Date.now() (see the worker's\n\t// request-verifier). In production both are wall-clock so they agree. Under\n\t// an injected/frozen clock they can diverge; the freshness check is not\n\t// reachable from runtime.now(), so tests that freeze runtime.now() must keep\n\t// timestamps within DEFAULT_TIME_WINDOW_S of real time for the verifier to\n\t// accept them. Unifying the two would require threading the clock into the\n\t// verifier signature across the core/worker boundary.\n\tconst cutoff = new Date(\n\t\tnew Date(createdAt).getTime() - DEFAULT_TIME_WINDOW_S * 2 * 1000,\n\t).toISOString();\n\tawait cleanupNonces(store, cutoff);\n\n\treturn { ok: true, error: \"ok\", enrollment };\n}\n\nfunction authErrorStatus(error: string): 401 | 403 | 409 {\n\tif (error === \"device_disabled\") return 403;\n\tif (error === \"group_archived\") return 409;\n\treturn 401;\n}\n\n// ---------------------------------------------------------------------------\n// App factory\n// ---------------------------------------------------------------------------\n\nexport function createCoordinatorApp(\n\topts?: CreateCoordinatorAppOptions,\n): InstanceType<typeof Hono> {\n\tif (!opts?.storeFactory || !opts.runtime || !opts.requestVerifier) {\n\t\tthrow new Error(\"createCoordinatorApp requires storeFactory, runtime, and requestVerifier.\");\n\t}\n\tconst runtime = opts.runtime;\n\tconst createStore = opts.storeFactory;\n\tconst requestVerifier = opts.requestVerifier;\n\tconst requestRateLimit = opts.requestRateLimit ?? {};\n\tconst rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();\n\tconst readLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.readLimit ?? DEFAULT_COORDINATOR_READ_LIMIT),\n\t);\n\tconst mutationLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.mutationLimit ?? DEFAULT_COORDINATOR_MUTATION_LIMIT),\n\t);\n\tconst unauthenticatedReadLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit)),\n\t);\n\tconst unauthenticatedMutationLimit = Math.max(\n\t\t1,\n\t\tMath.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)),\n\t);\n\tconst app = new Hono();\n\tconst textDecoder = new TextDecoder();\n\n\tfunction rateLimitedResponse(c: Context, key: string, authenticated: boolean) {\n\t\tconst isRead = c.req.method === \"GET\" || c.req.method === \"HEAD\" || c.req.method === \"OPTIONS\";\n\t\tconst result = rateLimiter.check(\n\t\t\t`${c.req.method}:${authenticated ? \"auth\" : \"anon\"}:${key}`,\n\t\t\tauthenticated\n\t\t\t\t? isRead\n\t\t\t\t\t? readLimit\n\t\t\t\t\t: mutationLimit\n\t\t\t\t: isRead\n\t\t\t\t\t? unauthenticatedReadLimit\n\t\t\t\t\t: unauthenticatedMutationLimit,\n\t\t);\n\t\tif (result.allowed) return null;\n\t\tc.header(\"Retry-After\", String(result.retryAfterS));\n\t\treturn c.json({ error: \"rate_limited\", retry_after_s: result.retryAfterS }, 429);\n\t}\n\n\tasync function readRequestBytes(c: Context): Promise<Uint8Array | null> {\n\t\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"\", 10);\n\t\tif (Number.isFinite(contentLength) && contentLength > MAX_BODY_BYTES) {\n\t\t\treturn null;\n\t\t}\n\t\tconst stream = c.req.raw.body;\n\t\tif (!stream) return new Uint8Array();\n\t\tconst reader = stream.getReader();\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tif (!value) continue;\n\t\t\t\ttotal += value.byteLength;\n\t\t\t\tif (total > MAX_BODY_BYTES) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tchunks.push(value);\n\t\t\t}\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t\tconst combined = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tcombined.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn combined;\n\t}\n\n\tfunction parseJsonObject(raw: Uint8Array): Record<string, unknown> | null {\n\t\ttry {\n\t\t\tconst data: unknown = JSON.parse(textDecoder.decode(raw));\n\t\t\tif (typeof data !== \"object\" || data === null || Array.isArray(data)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn data as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tfunction optionalString(data: Record<string, unknown>, key: string): string | null {\n\t\tconst value = data[key];\n\t\tif (value == null) return null;\n\t\treturn String(value).trim() || null;\n\t}\n\n\tfunction optionalHeaderString(value: string | null | undefined): string | null {\n\t\treturn value?.trim() || null;\n\t}\n\n\tfunction optionalNumber(data: Record<string, unknown>, key: string): number | null {\n\t\tconst value = data[key];\n\t\tif (value == null || value === \"\") return null;\n\t\tif (typeof value !== \"number\" && typeof value !== \"string\") return Number.NaN;\n\t\tif (typeof value === \"string\") {\n\t\t\tconst trimmed = value.trim();\n\t\t\tif (!trimmed) return Number.NaN;\n\t\t\tconst number = Number(trimmed);\n\t\t\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n\t\t}\n\t\tconst number = value;\n\t\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n\t}\n\n\tfunction queryFlag(value: string | undefined | null): boolean {\n\t\treturn [\"1\", \"true\", \"yes\"].includes(\n\t\t\tString(value ?? \"\")\n\t\t\t\t.trim()\n\t\t\t\t.toLowerCase(),\n\t\t);\n\t}\n\n\tfunction storedProjectIntent(value: string | null | undefined) {\n\t\ttry {\n\t\t\treturn parseAcceptedProjectIntent(JSON.parse(value ?? \"\"));\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t}\n\n\tfunction buildAcceptedProjectIntent(invite: {\n\t\toperation_id?: string | null;\n\t\treviewed_project_set_digest?: string | null;\n\t\tproject_intent_json?: string | null;\n\t}) {\n\t\tconst operationId = String(invite.operation_id ?? \"\").trim();\n\t\tconst reviewedProjectSetDigest = String(invite.reviewed_project_set_digest ?? \"\").trim();\n\t\tif (\n\t\t\t!/^share_[a-f0-9]{40}$/u.test(operationId) ||\n\t\t\t!/^[a-f0-9]{64}$/u.test(reviewedProjectSetDigest)\n\t\t) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\tconst projects = storedProjectIntent(invite.project_intent_json);\n\t\tconst computedDigest = acceptedProjectIntentDigest(projects);\n\t\tif (computedDigest !== reviewedProjectSetDigest) {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t\treturn {\n\t\t\toperation_id: operationId,\n\t\t\treviewed_project_set_digest: reviewedProjectSetDigest,\n\t\t\tprojects,\n\t\t};\n\t}\n\n\tfunction storedProjectSummaries(\n\t\tvalue: string | null | undefined,\n\t): ReturnType<typeof normalizeProjectInviteSummaries> {\n\t\ttry {\n\t\t\treturn normalizeProjectInviteSummaries(JSON.parse(value ?? \"\"));\n\t\t} catch {\n\t\t\tthrow new Error(\"operation_intent_invalid\");\n\t\t}\n\t}\n\n\tasync function requireActiveAdminGroup(store: CoordinatorStore, groupId: string, c: Context) {\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst group = await store.getGroup(groupId);\n\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\t\treturn null;\n\t}\n\n\tasync function findAdminScope(\n\t\tstore: CoordinatorStore,\n\t\tgroupId: string,\n\t\tscopeId: string,\n\t\tc: Context,\n\t): Promise<{ scope: CoordinatorScope | null; response: Response | null }> {\n\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\tif (groupError) return { scope: null, response: groupError };\n\t\tif (!scopeId) return { scope: null, response: c.json({ error: \"scope_id_required\" }, 400) };\n\t\tconst matching = await store.listScopes({ groupId, includeInactive: true });\n\t\tconst scope = matching.find((item) => item.scope_id === scopeId) ?? null;\n\t\tif (!scope) return { scope: null, response: c.json({ error: \"scope_not_found\" }, 404) };\n\t\treturn { scope, response: null };\n\t}\n\n\tasync function authorizeGroupMember(store: CoordinatorStore, groupId: string, c: Context) {\n\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\tmethod: c.req.method,\n\t\t\turl: c.req.url,\n\t\t\tgroupId,\n\t\t\tbody: new Uint8Array(0),\n\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t});\n\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\treturn {\n\t\t\t\tauth,\n\t\t\t\tresponse:\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error)),\n\t\t\t};\n\t\t}\n\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\treturn { auth, response: limited };\n\t}\n\n\tfunction activeCurrentMembership(\n\t\tmembership: CoordinatorScopeMembership,\n\t\tscope: CoordinatorScope,\n\t): boolean {\n\t\treturn membership.status === \"active\" && membership.membership_epoch >= scope.membership_epoch;\n\t}\n\n\tasync function requesterAuthorizedForScope(\n\t\tstore: CoordinatorStore,\n\t\tscope: CoordinatorScope,\n\t\tdeviceId: string,\n\t): Promise<boolean> {\n\t\tconst memberships = await store.listScopeMemberships(scope.scope_id, false);\n\t\treturn memberships.some(\n\t\t\t(membership) =>\n\t\t\t\tmembership.device_id === deviceId && activeCurrentMembership(membership, scope),\n\t\t);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/presence — upsert device presence (authenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/presence\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"body_too_large\" }, 413);\n\t\t}\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\treturn c.json({ error: auth.error }, authErrorStatus(auth.error));\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tif (data.fingerprint && String(data.fingerprint) !== String(auth.enrollment.fingerprint)) {\n\t\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 401);\n\t\t\t}\n\n\t\t\tconst rawAddresses = data.addresses ?? [];\n\t\t\tif (!Array.isArray(rawAddresses) || !rawAddresses.every((item) => typeof item === \"string\")) {\n\t\t\t\treturn c.json({ error: \"addresses_must_be_list_of_strings\" }, 400);\n\t\t\t}\n\n\t\t\tlet ttlS: number;\n\t\t\ttry {\n\t\t\t\tttlS = Math.max(1, Number.parseInt(String(data.ttl_s ?? 180), 10));\n\t\t\t\tif (Number.isNaN(ttlS)) {\n\t\t\t\t\treturn c.json({ error: \"ttl_s_must_be_int\" }, 400);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"ttl_s_must_be_int\" }, 400);\n\t\t\t}\n\n\t\t\tconst response = await store.upsertPresence({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId: String(auth.enrollment.device_id),\n\t\t\t\taddresses: rawAddresses as string[],\n\t\t\t\tttlS,\n\t\t\t\tcapabilities:\n\t\t\t\t\ttypeof data.capabilities === \"object\" &&\n\t\t\t\t\tdata.capabilities !== null &&\n\t\t\t\t\t!Array.isArray(data.capabilities)\n\t\t\t\t\t\t? (data.capabilities as Record<string, unknown>)\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\n\t\t\treturn c.json({ ok: true, ...response });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/peers — list group peers (authenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/peers\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\tconst limited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\tif (limited) return limited;\n\t\t\t\treturn c.json({ error: auth.error }, authErrorStatus(auth.error));\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tconst items = await store.listGroupPeers(groupId, String(auth.enrollment.device_id));\n\t\t\treturn c.json({ items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/scopes — list syncable scopes for the authenticated group member\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/scopes\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst { auth, response } = await authorizeGroupMember(store, groupId, c);\n\t\t\tif (response) return response;\n\t\t\tif (!auth.enrollment) return c.json({ error: \"unknown_device\" }, 401);\n\t\t\tconst scopes = await store.listScopes({ groupId, includeInactive: false });\n\t\t\tconst items: CoordinatorScope[] = [];\n\t\t\tfor (const scope of scopes) {\n\t\t\t\tif (scope.status !== \"active\") continue;\n\t\t\t\tif (await requesterAuthorizedForScope(store, scope, String(auth.enrollment.device_id))) {\n\t\t\t\t\titems.push(scope);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn c.json({ items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/scopes/:scope_id/members — list members of an authorized scope\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/scopes/:scope_id/members\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst { auth, response } = await authorizeGroupMember(store, groupId, c);\n\t\t\tif (response) return response;\n\t\t\tif (!auth.enrollment) return c.json({ error: \"unknown_device\" }, 401);\n\t\t\tconst scopes = await store.listScopes({ groupId, includeInactive: false });\n\t\t\tconst scope = scopes.find((item) => item.scope_id === scopeId) ?? null;\n\t\t\tif (scope?.status !== \"active\") return c.json({ error: \"scope_not_found\" }, 404);\n\t\t\tconst memberships = await store.listScopeMemberships(scopeId, false);\n\t\t\tconst requesterAuthorized = memberships.some(\n\t\t\t\t(membership) =>\n\t\t\t\t\tmembership.device_id === String(auth.enrollment?.device_id) &&\n\t\t\t\t\tactiveCurrentMembership(membership, scope),\n\t\t\t);\n\t\t\tif (!requesterAuthorized) return c.json({ error: \"scope_not_authorized\" }, 403);\n\t\t\treturn c.json({\n\t\t\t\titems: memberships.filter((membership) => activeCurrentMembership(membership, scope)),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// GET /v1/reciprocal-approvals — list pending local approval state\n\t// -----------------------------------------------------------------------\n\n\tapp.get(\"/v1/reciprocal-approvals\", async (c) => {\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tconst direction = (c.req.query(\"direction\") ?? \"incoming\").trim();\n\t\tconst status = (c.req.query(\"status\") ?? \"pending\").trim() || \"pending\";\n\t\tif (!groupId) {\n\t\t\treturn c.json({ error: \"group_id_required\" }, 400);\n\t\t}\n\t\tif (![\"incoming\", \"outgoing\"].includes(direction)) {\n\t\t\treturn c.json({ error: \"direction_must_be_incoming_or_outgoing\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tconst items = await store.listReciprocalApprovals({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId: String(auth.enrollment.device_id),\n\t\t\t\tdirection: direction as \"incoming\" | \"outgoing\",\n\t\t\t\tstatus,\n\t\t\t});\n\t\t\treturn c.json({ items });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/reciprocal-approvals — register a local trust action\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/reciprocal-approvals\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"body_too_large\" }, 413);\n\t\t}\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst requestedDeviceId = String(data.requested_device_id ?? \"\").trim();\n\t\tif (!groupId || !requestedDeviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_requested_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tif (requestedDeviceId === String(auth.enrollment.device_id)) {\n\t\t\t\treturn c.json({ error: \"requested_device_must_differ\" }, 400);\n\t\t\t}\n\t\t\tconst targetEnrollment = await store.getEnrollment(groupId, requestedDeviceId);\n\t\t\tif (!targetEnrollment) {\n\t\t\t\treturn c.json({ error: \"requested_device_not_found\" }, 404);\n\t\t\t}\n\t\t\tconst request = await store.createReciprocalApproval({\n\t\t\t\tgroupId,\n\t\t\t\trequestingDeviceId: String(auth.enrollment.device_id),\n\t\t\t\trequestedDeviceId,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, request });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/invites/add-device — create an Identity-owned device invite\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/invites/add-device\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst allowedFields = new Set([\n\t\t\t\"group_id\",\n\t\t\t\"expires_at\",\n\t\t\t\"reviewed_preview_digest\",\n\t\t\t\"reviewed_intent\",\n\t\t]);\n\t\tif (Object.keys(data).some((key) => !allowedFields.has(key))) {\n\t\t\treturn c.json({ error: \"unexpected_add_device_invite_fields\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst expiresAt = String(data.expires_at ?? \"\").trim();\n\t\tconst reviewedPreviewDigest = String(data.reviewed_preview_digest ?? \"\").trim();\n\t\tif (!groupId || !expiresAt) {\n\t\t\treturn c.json({ error: \"group_id_and_expires_at_required\" }, 400);\n\t\t}\n\t\tif (Number.isNaN(new Date(expiresAt).getTime())) {\n\t\t\treturn c.json({ error: \"invalid_expires_at\" }, 400);\n\t\t}\n\t\tif (!/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\t\treturn c.json({ error: \"reviewed_preview_digest_invalid\" }, 400);\n\t\t}\n\t\tif (data.reviewed_intent == null) {\n\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: raw,\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\n\t\t\tconst targetIdentityId = auth.enrollment.identity_id;\n\t\t\tif (\n\t\t\t\t!targetIdentityId ||\n\t\t\t\ttargetIdentityId !== targetIdentityId.trim() ||\n\t\t\t\ttargetIdentityId.length > 256 ||\n\t\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(targetIdentityId)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"identity_binding_required\" }, 403);\n\t\t\t}\n\n\t\t\tlet reviewedIntent: RecipientReviewedIntentV1;\n\t\t\ttry {\n\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(data.reviewed_intent, {\n\t\t\t\t\ttarget: { kind: \"add_device\", targetIdentityId },\n\t\t\t\t\tdigest: reviewedPreviewDigest,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\n\t\t\tconst invite = await store.createInvite({\n\t\t\t\tgroupId,\n\t\t\t\tpolicy: \"auto_admit\",\n\t\t\t\texpiresAt,\n\t\t\t\tcreatedBy: targetIdentityId,\n\t\t\t\tinviterDeviceId: String(auth.enrollment.device_id),\n\t\t\t\tinviteKind: \"add_device\",\n\t\t\t\ttargetIdentityId,\n\t\t\t\treviewedPreviewDigest,\n\t\t\t\treviewedIntent,\n\t\t\t});\n\t\t\tconst payload: InvitePayload = {\n\t\t\t\tv: 1,\n\t\t\t\tkind: \"add_device\",\n\t\t\t\tcoordinator_url: new URL(c.req.url).origin,\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t\ttoken: String(invite.token ?? \"\"),\n\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\tteam_name: (invite.team_name_snapshot as string) ?? null,\n\t\t\t\ttarget_identity_id: invite.target_identity_id ?? undefined,\n\t\t\t\tinviter_device_id: invite.inviter_device_id ?? undefined,\n\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t};\n\t\t\tconst encoded = encodeInvitePayload(payload);\n\t\t\tconst { token: _token, ...inviteWithoutToken } = invite;\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tinvite: inviteWithoutToken,\n\t\t\t\tpayload,\n\t\t\t\tencoded,\n\t\t\t\tlink: inviteLink(encoded),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// Admin routes\n\t// -----------------------------------------------------------------------\n\n\t// POST /v1/admin/devices — enroll a device\n\tapp.post(\"/v1/admin/devices\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst fingerprint = String(data.fingerprint ?? \"\").trim();\n\t\tconst publicKey = String(data.public_key ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\n\t\tif (!groupId || !deviceId || !fingerprint || !publicKey) {\n\t\t\treturn c.json({ error: \"group_id_device_id_fingerprint_public_key_required\" }, 400);\n\t\t}\n\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tawait store.createGroup(groupId);\n\t\t\tawait store.enrollDevice(groupId, {\n\t\t\t\tdeviceId,\n\t\t\t\tfingerprint,\n\t\t\t\tpublicKey,\n\t\t\t\tdisplayName,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\n\t\treturn c.json({ ok: true });\n\t});\n\n\t// GET /v1/admin/groups — list coordinator groups\n\tapp.get(\"/v1/admin/groups\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst includeArchived = [\"1\", \"true\", \"yes\"].includes(\n\t\t\t(c.req.query(\"include_archived\") ?? \"0\").trim().toLowerCase(),\n\t\t);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listGroups(includeArchived) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tawait store.createGroup(groupId, displayName);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/rename\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim();\n\t\tif (!groupId || !displayName) {\n\t\t\treturn c.json({ error: \"group_id_and_display_name_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.renameGroup(groupId, displayName);\n\t\t\tif (!ok) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/archive\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.archiveGroup(groupId, runtime.now());\n\t\t\tif (!ok) return c.json({ error: \"group_not_found_or_already_archived\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/groups/unarchive\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.unarchiveGroup(groupId);\n\t\t\tif (!ok) return c.json({ error: \"group_not_found_or_not_archived\" }, 404);\n\t\t\treturn c.json({ ok: true, group: await store.getGroup(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/groups/:group_id/scopes — list Sharing domains for a group\n\tapp.get(\"/v1/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\t\tif (groupError) return groupError;\n\t\t\tconst includeInactive = queryFlag(c.req.query(\"include_inactive\"));\n\t\t\treturn c.json({\n\t\t\t\titems: await store.listScopes({ groupId, includeInactive }),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes — create a Sharing domain\n\tapp.post(\"/v1/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = optionalString(data, \"scope_id\");\n\t\tconst label = optionalString(data, \"label\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!scopeId || !label) return c.json({ error: \"scope_id_and_label_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst groupError = await requireActiveAdminGroup(store, groupId, c);\n\t\t\tif (groupError) return groupError;\n\t\t\tconst scope = await store.createScope({\n\t\t\t\tscopeId,\n\t\t\t\tlabel,\n\t\t\t\tkind: optionalString(data, \"kind\"),\n\t\t\t\tauthorityType: optionalString(data, \"authority_type\"),\n\t\t\t\tcoordinatorId: optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tstatus: optionalString(data, \"status\"),\n\t\t\t});\n\t\t\treturn c.json({ ok: true, scope }, 201);\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// PATCH /v1/admin/groups/:group_id/scopes/:scope_id — update Sharing domain metadata\n\tapp.patch(\"/v1/admin/groups/:group_id/scopes/:scope_id\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!scopeId) return c.json({ error: \"scope_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst scope = await store.updateScope({\n\t\t\t\tscopeId,\n\t\t\t\tlabel: data.label === undefined ? undefined : optionalString(data, \"label\"),\n\t\t\t\tkind: data.kind === undefined ? undefined : optionalString(data, \"kind\"),\n\t\t\t\tauthorityType:\n\t\t\t\t\tdata.authority_type === undefined ? undefined : optionalString(data, \"authority_type\"),\n\t\t\t\tcoordinatorId:\n\t\t\t\t\tdata.coordinator_id === undefined ? undefined : optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId:\n\t\t\t\t\tdata.manifest_issuer_device_id === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash:\n\t\t\t\t\tdata.manifest_hash === undefined ? undefined : optionalString(data, \"manifest_hash\"),\n\t\t\t\tstatus: data.status === undefined ? undefined : optionalString(data, \"status\"),\n\t\t\t});\n\t\t\tif (!scope) return c.json({ error: \"scope_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, scope });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/groups/:group_id/scopes/:scope_id/members — list explicit grants\n\tapp.get(\"/v1/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\treturn c.json({\n\t\t\t\titems: await store.listScopeMemberships(scopeId, queryFlag(c.req.query(\"include_revoked\"))),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes/:scope_id/members — grant device access\n\tapp.post(\"/v1/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst effectId = optionalString(data, \"effect_id\");\n\t\tconst deviceId = optionalString(data, \"device_id\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!effectId) return c.json({ error: \"effect_id_required\" }, 400);\n\t\tif (!deviceId) return c.json({ error: \"device_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst membership = await store.grantScopeMembership({\n\t\t\t\teffectId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\trole: optionalString(data, \"role\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tcoordinatorId: optionalString(data, \"coordinator_id\"),\n\t\t\t\tgroupId,\n\t\t\t\tmanifestIssuerDeviceId: optionalString(data, \"manifest_issuer_device_id\"),\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tsignedManifestJson: optionalString(data, \"signed_manifest_json\"),\n\t\t\t\tactorType: \"admin\",\n\t\t\t\tactorId: optionalHeaderString(c.req.header(ADMIN_ACTOR_HEADER)),\n\t\t\t});\n\t\t\treturn c.json({ ok: true, membership }, 201);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (\n\t\t\t\terror instanceof CoordinatorMembershipError &&\n\t\t\t\t(error.code === \"scope_not_found\" || error.code === \"scope_group_mismatch\")\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t}\n\t\t\tif (error instanceof CoordinatorMembershipError && error.code === \"device_not_enrolled\") {\n\t\t\t\treturn c.json({ error: \"device_not_enrolled_for_scope_group\" }, 404);\n\t\t\t}\n\t\t\tconst scopeInactive =\n\t\t\t\terror instanceof CoordinatorMembershipError && error.code === \"scope_inactive\";\n\t\t\treturn c.json(\n\t\t\t\t{ error: scopeInactive ? \"scope_not_active\" : message },\n\t\t\t\tmessage === SCOPE_MEMBERSHIP_EFFECT_CONFLICT || scopeInactive ? 409 : 400,\n\t\t\t);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\n\tapp.post(\"/v1/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = raw.byteLength > 0 ? parseJsonObject(raw) : {};\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tconst effectId = optionalString(data, \"effect_id\");\n\t\tconst membershipEpoch = optionalNumber(data, \"membership_epoch\");\n\t\tif (!effectId) return c.json({ error: \"effect_id_required\" }, 400);\n\t\tif (!deviceId) return c.json({ error: \"device_id_required\" }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch_must_be_number\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst lookup = await findAdminScope(store, groupId, scopeId, c);\n\t\t\tif (lookup.response) return lookup.response;\n\t\t\tconst ok = await store.revokeScopeMembership({\n\t\t\t\teffectId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\tgroupId,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalString(data, \"manifest_hash\"),\n\t\t\t\tsignedManifestJson: optionalString(data, \"signed_manifest_json\"),\n\t\t\t\tactorType: \"admin\",\n\t\t\t\tactorId: optionalHeaderString(c.req.header(ADMIN_ACTOR_HEADER)),\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"membership_not_found\" }, 404);\n\t\t\tlet revokedMembership: CoordinatorScopeMembership | undefined;\n\t\t\ttry {\n\t\t\t\trevokedMembership = (await store.listScopeMemberships(scopeId, true)).find(\n\t\t\t\t\t(membership) => membership.device_id === deviceId,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\trevokedMembership = undefined;\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tscope_id: scopeId,\n\t\t\t\tdevice_id: deviceId,\n\t\t\t\trevocation: explainScopeMembershipRevocation({\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembershipEpoch: revokedMembership?.membership_epoch ?? membershipEpoch,\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tif (error instanceof CoordinatorMembershipError && error.code === \"scope_group_mismatch\") {\n\t\t\t\treturn c.json({ error: \"scope_not_found\" }, 404);\n\t\t\t}\n\t\t\treturn c.json({ error: message }, message === SCOPE_MEMBERSHIP_EFFECT_CONFLICT ? 409 : 400);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/devices — list enrolled devices\n\tapp.get(\"/v1/admin/devices\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst includeDisabled = [\"1\", \"true\", \"yes\"].includes(\n\t\t\t(c.req.query(\"include_disabled\") ?? \"0\").trim().toLowerCase(),\n\t\t);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listEnrolledDevices(groupId, includeDisabled) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/rename\n\tapp.post(\"/v1/admin/devices/rename\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\t\tif (!displayName) {\n\t\t\treturn c.json({ error: \"display_name_required\" }, 400);\n\t\t}\n\t\tlet normalizedDisplayName: string;\n\t\ttry {\n\t\t\tnormalizedDisplayName = normalizeHumanPresentationName(displayName, \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.renameDevice(groupId, deviceId, normalizedDisplayName);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\tconst device = await store.getEnrollment(groupId, deviceId);\n\t\t\treturn c.json({ ok: true, device });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/disable\n\tapp.post(\"/v1/admin/devices/disable\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.setDeviceEnabled(groupId, deviceId, false);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/enable\n\tapp.post(\"/v1/admin/devices/enable\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.setDeviceEnabled(groupId, deviceId, true);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/devices/remove\n\tapp.post(\"/v1/admin/devices/remove\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\n\t\tif (!groupId || !deviceId) {\n\t\t\treturn c.json({ error: \"group_id_and_device_id_required\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.removeDevice(groupId, deviceId);\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/invites — create an invite\n\tapp.post(\"/v1/admin/invites\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst groupId = String(data.group_id ?? \"\").trim();\n\t\tconst policy = String(data.policy ?? \"auto_admit\").trim();\n\t\tconst expiresAt = String(data.expires_at ?? \"\").trim();\n\t\tconst createdBy = String(data.created_by ?? \"\").trim() || null;\n\t\tconst operationId = String(data.operation_id ?? \"\").trim() || null;\n\t\tconst reviewedProjectSetDigest = String(data.reviewed_project_set_digest ?? \"\").trim() || null;\n\t\tconst inviterActorId = String(data.inviter_actor_id ?? \"\").trim() || null;\n\t\tconst inviterDisplayName = String(data.inviter_display_name ?? \"\").trim() || null;\n\t\tconst inviterDeviceId = String(data.inviter_device_id ?? \"\").trim() || null;\n\t\tconst pendingPersonId = String(data.pending_person_id ?? \"\").trim() || null;\n\t\tconst requestedInviteKind = String(data.invite_kind ?? data.kind ?? \"\").trim();\n\t\tconst policyTeamId = String(data.policy_team_id ?? \"\").trim() || null;\n\t\tconst targetIdentityId = String(data.target_identity_id ?? \"\").trim() || null;\n\t\tconst reviewedPreviewDigest = String(data.reviewed_preview_digest ?? \"\").trim() || null;\n\t\tlet reviewedIntent: RecipientReviewedIntentV1 | undefined;\n\t\tlet projectSummaries: ReturnType<typeof normalizeProjectInviteSummaries> | null = null;\n\t\tlet projectIntent: Array<{\n\t\t\tcanonical_identity: string;\n\t\t\tdisplay_name: string;\n\t\t\texisting_memory_count: number;\n\t\t}> | null = null;\n\n\t\tif (!groupId || ![\"auto_admit\", \"approval_required\"].includes(policy) || !expiresAt) {\n\t\t\treturn c.json({ error: \"group_id_policy_and_expires_at_required\" }, 400);\n\t\t}\n\t\tif (Object.hasOwn(data, \"assigned_identity_id\")) {\n\t\t\treturn c.json({ error: \"assigned_identity_id_forbidden\" }, 400);\n\t\t}\n\t\t// Validate the date at the boundary so store.createInvite's\n\t\t// normalizeInviteExpiresAt throw can't escape as an unhandled 500.\n\t\tif (Number.isNaN(new Date(expiresAt).getTime())) {\n\t\t\treturn c.json({ error: \"invalid_expires_at\" }, 400);\n\t\t}\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\treturn c.json({ error: \"operation_intent_reference_incomplete\" }, 400);\n\t\t}\n\t\tconst inviteKind = (requestedInviteKind ||\n\t\t\t(operationId ? \"project_share\" : \"legacy_enrollment\")) as CoordinatorInviteKind;\n\t\tif (\n\t\t\t!([\"legacy_enrollment\", \"project_share\", \"team_member\", \"add_device\"] as const).includes(\n\t\t\t\tinviteKind,\n\t\t\t)\n\t\t) {\n\t\t\treturn c.json({ error: \"invite_kind_invalid\" }, 400);\n\t\t}\n\t\tif (inviteKind === \"project_share\" ? !operationId : Boolean(operationId)) {\n\t\t\treturn c.json({ error: \"invite_kind_intent_mismatch\" }, 400);\n\t\t}\n\t\tif (reviewedPreviewDigest && !/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\t\treturn c.json({ error: \"reviewed_preview_digest_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t(inviteKind === \"team_member\" &&\n\t\t\t\t(!policyTeamId || !reviewedPreviewDigest || Boolean(targetIdentityId))) ||\n\t\t\t(inviteKind === \"add_device\" &&\n\t\t\t\t(!targetIdentityId || !reviewedPreviewDigest || Boolean(policyTeamId))) ||\n\t\t\t(![\"team_member\", \"add_device\"].includes(inviteKind) &&\n\t\t\t\tBoolean(policyTeamId || targetIdentityId || reviewedPreviewDigest))\n\t\t) {\n\t\t\treturn c.json({ error: \"recipient_invite_metadata_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t[policyTeamId, targetIdentityId]\n\t\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t\t.some((value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value))\n\t\t) {\n\t\t\treturn c.json({ error: \"recipient_invite_identifier_invalid\" }, 400);\n\t\t}\n\t\tif (inviteKind === \"team_member\" || inviteKind === \"add_device\") {\n\t\t\tif (data.reviewed_intent == null) {\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(data.reviewed_intent, {\n\t\t\t\t\ttarget:\n\t\t\t\t\t\tinviteKind === \"team_member\"\n\t\t\t\t\t\t\t? { kind: \"team_member\", policyTeamId: String(policyTeamId) }\n\t\t\t\t\t\t\t: { kind: \"add_device\", targetIdentityId: String(targetIdentityId) },\n\t\t\t\t\tdigest: String(reviewedPreviewDigest),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof RecipientReviewedIntentError &&\n\t\t\t\t\terror.code === \"recipient_invite_intent_mismatch\"\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: error.code }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 400);\n\t\t\t}\n\t\t} else if (data.reviewed_intent != null) {\n\t\t\treturn c.json({ error: \"recipient_invite_metadata_invalid\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t(operationId && !/^share_[a-f0-9]{40}$/u.test(operationId)) ||\n\t\t\t(reviewedProjectSetDigest && !/^[a-f0-9]{64}$/u.test(reviewedProjectSetDigest))\n\t\t) {\n\t\t\treturn c.json({ error: \"operation_intent_reference_invalid\" }, 400);\n\t\t}\n\t\tif (operationId) {\n\t\t\tif (!inviterActorId || !inviterDisplayName || !inviterDeviceId || !pendingPersonId) {\n\t\t\t\treturn c.json({ error: \"project_invite_identity_context_required\" }, 400);\n\t\t\t}\n\t\t\tif (\n\t\t\t\t[inviterActorId, inviterDeviceId, pendingPersonId].some(\n\t\t\t\t\t(value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value),\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"project_invite_identity_context_invalid\" }, 400);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tnormalizeHumanPresentationName(inviterDisplayName, \"inviter_display_name\");\n\t\t\t\tprojectSummaries = normalizeProjectInviteSummaries(data.project_summaries);\n\t\t\t\tif (\n\t\t\t\t\t!Array.isArray(data.project_intent) ||\n\t\t\t\t\tdata.project_intent.length !== projectSummaries.length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t}\n\t\t\t\tprojectIntent = data.project_intent.map((item, index) => {\n\t\t\t\t\tlet parsed: ReturnType<typeof parseAcceptedProjectIntent>[number] | undefined;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tparsed = parseAcceptedProjectIntent([item])[0];\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\tconst summary = projectSummaries?.[index];\n\t\t\t\t\tif (\n\t\t\t\t\t\t!parsed ||\n\t\t\t\t\t\t!summary ||\n\t\t\t\t\t\tparsed.display_name !== summary.display_name ||\n\t\t\t\t\t\tparsed.existing_memory_count !== summary.existing_memory_count\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\treturn parsed;\n\t\t\t\t});\n\t\t\t\tif (\n\t\t\t\t\tnew Set(projectIntent.map((item) => item.canonical_identity)).size !==\n\t\t\t\t\tprojectIntent.length\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"project_intent_invalid\");\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_invalid\" },\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst group = await store.getGroup(groupId);\n\t\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\n\t\t\tconst invite = await store.createInvite({\n\t\t\t\tgroupId,\n\t\t\t\tpolicy,\n\t\t\t\texpiresAt,\n\t\t\t\tcreatedBy,\n\t\t\t\toperationId,\n\t\t\t\treviewedProjectSetDigest,\n\t\t\t\tinviterActorId,\n\t\t\t\tinviterDisplayName,\n\t\t\t\tinviterDeviceId,\n\t\t\t\tpendingPersonId,\n\t\t\t\tprojectSummaries,\n\t\t\t\tprojectIntent,\n\t\t\t\tinviteKind,\n\t\t\t\tpolicyTeamId,\n\t\t\t\ttargetIdentityId,\n\t\t\t\treviewedPreviewDigest,\n\t\t\t\treviewedIntent,\n\t\t\t});\n\n\t\t\tconst payload: InvitePayload = {\n\t\t\t\tv: 1,\n\t\t\t\tkind:\n\t\t\t\t\tinvite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\"\n\t\t\t\t\t\t? invite.invite_kind\n\t\t\t\t\t\t: \"coordinator_team_invite\",\n\t\t\t\tcoordinator_url: String(data.coordinator_url ?? \"\").trim(),\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t\ttoken: String(invite.token ?? \"\"),\n\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\tteam_name: (invite.team_name_snapshot as string) ?? null,\n\t\t\t\t...(invite.operation_id\n\t\t\t\t\t? {\n\t\t\t\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\t\t\t\tinviter_name: invite.inviter_display_name ?? null,\n\t\t\t\t\t\t\tproject_summaries: projectSummaries ?? [],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(invite.invite_kind === \"team_member\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpolicy_team_id: invite.policy_team_id ?? undefined,\n\t\t\t\t\t\t\tassigned_identity_id: invite.assigned_identity_id ?? undefined,\n\t\t\t\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(invite.invite_kind === \"add_device\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttarget_identity_id: invite.target_identity_id ?? undefined,\n\t\t\t\t\t\t\tinviter_device_id: invite.inviter_device_id ?? undefined,\n\t\t\t\t\t\t\treviewed_preview_digest: invite.reviewed_preview_digest ?? undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\t\t\tconst encoded = encodeInvitePayload(payload);\n\n\t\t\t// Omit token from the returned invite object (matches Python)\n\t\t\tconst { token: _token, ...inviteWithoutToken } = invite;\n\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tinvite: inviteWithoutToken,\n\t\t\t\tpayload,\n\t\t\t\tencoded,\n\t\t\t\tlink: inviteLink(encoded),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"invite_operation_intent_conflict\") {\n\t\t\t\treturn c.json({ error: \"invite_operation_intent_conflict\" }, 409);\n\t\t\t}\n\t\t\tif (error instanceof Error && error.message === \"invite_already_bound\") {\n\t\t\t\treturn c.json({ error: \"invite_already_bound\" }, 409);\n\t\t\t}\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/invites/inspect\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\t\tconst token = String(data.token ?? \"\").trim();\n\t\tif (!token) return c.json({ error: \"invite_invalid\" }, 404);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByTokenForInspection(token);\n\t\t\tif (!invite || invite.revoked_at) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\tif (invite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst inspection = await store.inspectRecipientInvite({ token, now: runtime.now() });\n\t\t\t\t\tif (!inspection) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\tinspection.kind === \"team_member\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tkind: inspection.kind,\n\t\t\t\t\t\t\t\t\tpolicy_team_id: inspection.policy_team_id,\n\t\t\t\t\t\t\t\t\tassigned_identity_id: inspection.assigned_identity_id,\n\t\t\t\t\t\t\t\t\treviewed_preview_digest: inspection.reviewed_preview_digest,\n\t\t\t\t\t\t\t\t\treviewed_intent: inspection.reviewed_intent,\n\t\t\t\t\t\t\t\t\tbound: inspection.bound,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\t\tkind: inspection.kind,\n\t\t\t\t\t\t\t\t\ttarget_identity_id: inspection.target_identity_id,\n\t\t\t\t\t\t\t\t\treviewed_preview_digest: inspection.reviewed_preview_digest,\n\t\t\t\t\t\t\t\t\treviewed_intent: inspection.reviewed_intent,\n\t\t\t\t\t\t\t\t\tbound: inspection.bound,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\t\t\t\t\tconst status = code === \"invite_expired\" ? 410 : code === \"invite_invalid\" ? 404 : 409;\n\t\t\t\t\treturn c.json({ error: code }, status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst projectInvite = Boolean(invite.operation_id || invite.reviewed_project_set_digest);\n\t\t\tif (\n\t\t\t\tnew Date(invite.expires_at) <= new Date(runtime.now()) &&\n\t\t\t\t(!projectInvite || !invite.consumed_at)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"invite_expired\" }, 410);\n\t\t\t}\n\t\t\tif (!invite.operation_id) {\n\t\t\t\treturn c.json({ kind: \"legacy_team_invite\", team_name: invite.team_name_snapshot });\n\t\t\t}\n\t\t\tif (!invite.project_intent_json || !invite.project_summaries_json) {\n\t\t\t\treturn c.json({ error: \"invite_invalid\" }, 404);\n\t\t\t}\n\t\t\tlet projects: ReturnType<typeof normalizeProjectInviteSummaries>;\n\t\t\ttry {\n\t\t\t\tprojects = storedProjectSummaries(invite.project_summaries_json);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"invite_invalid\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tkind: \"project_share_invite\",\n\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\tinviter_name: invite.inviter_display_name,\n\t\t\t\tteam_name: invite.team_name_snapshot,\n\t\t\t\tprojects,\n\t\t\t\tbound: Boolean(invite.consumed_at),\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// GET /v1/admin/invites — list invites\n\tapp.get(\"/v1/admin/invites\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst rows = (await store.listInvites(groupId)).map(\n\t\t\t\t({ token: _token, ...inviteWithoutToken }) => inviteWithoutToken,\n\t\t\t);\n\t\t\treturn c.json({ items: rows });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/project-invites/:operationId\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok) return c.json({ error: adminAuth.error }, 401);\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!operationId || !groupId)\n\t\t\treturn c.json({ error: \"operation_id_and_group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = (await store.listInvites(groupId)).find(\n\t\t\t\t(item) => item.operation_id === operationId,\n\t\t\t);\n\t\t\tif (!invite) return c.json({ error: \"operation_not_found\" }, 404);\n\t\t\tlet projects: ReturnType<typeof storedProjectIntent>;\n\t\t\ttry {\n\t\t\t\tprojects = storedProjectIntent(invite.project_intent_json);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"operation_intent_invalid\" }, 409);\n\t\t\t}\n\t\t\tlet inviteLinkValue: string | null = null;\n\t\t\tif (\n\t\t\t\t!invite.consumed_at &&\n\t\t\t\t!invite.revoked_at &&\n\t\t\t\tnew Date(invite.expires_at) > new Date(runtime.now()) &&\n\t\t\t\tinvite.token &&\n\t\t\t\t!invite.token.startsWith(\"consumed:\")\n\t\t\t) {\n\t\t\t\tconst summaries = projects.map((project) => ({\n\t\t\t\t\tdisplay_name: String(project.display_name ?? \"\"),\n\t\t\t\t\texisting_memory_count: Number(project.existing_memory_count ?? 0),\n\t\t\t\t}));\n\t\t\t\tconst payload: InvitePayload = {\n\t\t\t\t\tv: 1,\n\t\t\t\t\tkind: \"coordinator_team_invite\",\n\t\t\t\t\tcoordinator_url: new URL(c.req.url).origin,\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t\ttoken: invite.token,\n\t\t\t\t\texpires_at: invite.expires_at,\n\t\t\t\t\tteam_name: invite.team_name_snapshot,\n\t\t\t\t\toperation_id: operationId,\n\t\t\t\t\tinviter_name: invite.inviter_display_name ?? null,\n\t\t\t\t\tproject_summaries: summaries,\n\t\t\t\t};\n\t\t\t\tinviteLinkValue = inviteLink(encodeInvitePayload(payload));\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\toperation_id: invite.operation_id,\n\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\treviewed_project_set_digest: invite.reviewed_project_set_digest,\n\t\t\t\tstate: invite.consumed_at ? \"accepted\" : \"waiting_for_acceptance\",\n\t\t\t\tpending_person_id: invite.pending_person_id,\n\t\t\t\trecipient_actor_id: invite.recipient_actor_id,\n\t\t\t\trecipient_display_name: invite.recipient_display_name,\n\t\t\t\trecipient_device_id: invite.bound_device_id,\n\t\t\t\trecipient_device_display_name: invite.recipient_device_display_name,\n\t\t\t\trecipient_public_key: invite.bound_public_key,\n\t\t\t\trecipient_fingerprint: invite.bound_fingerprint,\n\t\t\t\tconsumed_at: invite.consumed_at,\n\t\t\t\tbootstrap_grant_id: invite.bootstrap_grant_id,\n\t\t\t\ttrust_state: invite.trust_state,\n\t\t\t\tprojects,\n\t\t\t\tinvite_link: inviteLinkValue,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/bootstrap-grants/:grantId\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst grantId = String(c.req.param(\"grantId\") ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst grant = await store.getBootstrapGrant(grantId);\n\t\t\tif (!grant) return c.json({ error: \"grant_not_found\" }, 404);\n\t\t\tconst workerEnrollment = await store.getEnrollment(grant.group_id, grant.worker_device_id);\n\t\t\tif (!workerEnrollment) return c.json({ error: \"worker_enrollment_not_found\" }, 404);\n\t\t\tconst payload: CoordinatorBootstrapGrantVerification = {\n\t\t\t\tgrant,\n\t\t\t\tworker_enrollment: workerEnrollment,\n\t\t\t};\n\t\t\treturn c.json(payload);\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/bootstrap-grants/:grantId\", async (c) => {\n\t\tconst grantId = String(c.req.param(\"grantId\") ?? \"\").trim();\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!grantId || !groupId) return c.json({ error: \"grant_id_and_group_id_required\" }, 400);\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst auth = await authorizeRequest(store, runtime, requestVerifier, {\n\t\t\t\tmethod: c.req.method,\n\t\t\t\turl: c.req.url,\n\t\t\t\tgroupId,\n\t\t\t\tbody: new Uint8Array(0),\n\t\t\t\tdeviceId: c.req.header(\"X-Opencode-Device\") ?? null,\n\t\t\t\tsignature: c.req.header(\"X-Opencode-Signature\") ?? null,\n\t\t\t\ttimestamp: c.req.header(\"X-Opencode-Timestamp\") ?? null,\n\t\t\t\tnonce: c.req.header(\"X-Opencode-Nonce\") ?? null,\n\t\t\t});\n\t\t\tif (!auth.ok || !auth.enrollment) {\n\t\t\t\treturn (\n\t\t\t\t\trateLimitedResponse(c, c.req.path, false) ??\n\t\t\t\t\tc.json({ error: auth.error }, authErrorStatus(auth.error))\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, String(auth.enrollment.device_id), true);\n\t\t\tif (limited) return limited;\n\t\t\tconst grant = await store.getBootstrapGrant(grantId);\n\t\t\tif (\n\t\t\t\t!grant ||\n\t\t\t\tgrant.group_id !== groupId ||\n\t\t\t\tgrant.seed_device_id !== String(auth.enrollment.device_id)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"grant_not_found\" }, 404);\n\t\t\t}\n\t\t\tconst workerEnrollment = await store.getEnrollment(groupId, grant.worker_device_id);\n\t\t\tif (!workerEnrollment) return c.json({ error: \"worker_enrollment_not_found\" }, 404);\n\t\t\treturn c.json({ grant, worker_enrollment: workerEnrollment });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.get(\"/v1/admin/bootstrap-grants\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listBootstrapGrants(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\tapp.post(\"/v1/admin/bootstrap-grants/revoke\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) return c.json({ error: \"invalid_json\" }, 400);\n\n\t\tconst grantId = String(data.grant_id ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst ok = await store.revokeBootstrapGrant(grantId, runtime.now());\n\t\t\tif (!ok) return c.json({ error: \"grant_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, grant_id: grantId });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// POST /v1/admin/join-requests/approve\n\tapp.post(\"/v1/admin/join-requests/approve\", async (c) => {\n\t\treturn handleJoinRequestReview(c, true, { createStore, runtime, rateLimitedResponse });\n\t});\n\n\t// POST /v1/admin/join-requests/deny\n\tapp.post(\"/v1/admin/join-requests/deny\", async (c) => {\n\t\treturn handleJoinRequestReview(c, false, { createStore, runtime, rateLimitedResponse });\n\t});\n\n\t// GET /v1/admin/join-requests — list join requests\n\tapp.get(\"/v1/admin/join-requests\", async (c) => {\n\t\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), runtime);\n\t\tif (!adminAuth.ok)\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401);\n\t\tconst limited = rateLimitedResponse(c, \"admin\", true);\n\t\tif (limited) return limited;\n\n\t\tconst groupId = (c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\treturn c.json({ items: await store.listJoinRequests(groupId) });\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\t// -----------------------------------------------------------------------\n\t// POST /v1/join — join via invite token (unauthenticated)\n\t// -----------------------------------------------------------------------\n\n\tapp.post(\"/v1/join\", async (c) => {\n\t\tconst raw = await readRequestBytes(c);\n\t\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\t\tconst data = parseJsonObject(raw);\n\t\tif (!data) {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst token = String(data.token ?? \"\").trim();\n\t\tconst deviceId = String(data.device_id ?? \"\").trim();\n\t\tconst fingerprint = String(data.fingerprint ?? \"\").trim();\n\t\tconst publicKey = String(data.public_key ?? \"\").trim();\n\t\tconst displayName = String(data.display_name ?? \"\").trim() || null;\n\t\tconst operationId = String(data.operation_id ?? \"\").trim();\n\t\tconst recipientActorId = String(data.recipient_actor_id ?? \"\").trim();\n\t\tconst recipientDisplayName = String(data.recipient_display_name ?? \"\").trim();\n\t\tconst deviceDisplayName = String(data.device_display_name ?? \"\").trim();\n\n\t\tif (!token || !deviceId || !fingerprint || !publicKey) {\n\t\t\treturn c.json({ error: \"token_device_id_fingerprint_public_key_required\" }, 400);\n\t\t}\n\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t}\n\n\t\tconst store = createStore();\n\t\ttry {\n\t\t\tconst invite = await store.getInviteByTokenForInspection(token);\n\t\t\tif (!invite) return c.json({ error: \"invite_invalid\" }, 404);\n\t\t\tconst projectInvite = Boolean(invite.operation_id || invite.reviewed_project_set_digest);\n\t\t\tconst recipientInvite =\n\t\t\t\tinvite.invite_kind === \"team_member\" || invite.invite_kind === \"add_device\";\n\t\t\tif (invite.revoked_at) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: projectInvite || recipientInvite ? \"invite_invalid\" : \"revoked_token\" },\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!invite.consumed_at && new Date(invite.expires_at) <= new Date(runtime.now())) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: projectInvite || recipientInvite ? \"invite_expired\" : \"expired_token\" },\n\t\t\t\t\t410,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (recipientInvite) {\n\t\t\t\tconst allowedRecipientAcceptanceFields = new Set([\n\t\t\t\t\t\"token\",\n\t\t\t\t\t\"invite_kind\",\n\t\t\t\t\t\"kind\",\n\t\t\t\t\t\"identity_id\",\n\t\t\t\t\t\"device_id\",\n\t\t\t\t\t\"public_key\",\n\t\t\t\t\t\"fingerprint\",\n\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\"device_display_name\",\n\t\t\t\t]);\n\t\t\t\tif (Object.keys(data).some((key) => !allowedRecipientAcceptanceFields.has(key))) {\n\t\t\t\t\treturn c.json({ error: \"unexpected_recipient_invite_fields\" }, 400);\n\t\t\t\t}\n\t\t\t\tconst requestedKind = String(data.invite_kind ?? data.kind ?? \"\").trim();\n\t\t\t\tconst identityId = String(data.identity_id ?? \"\").trim();\n\t\t\t\tif (!identityId || requestedKind !== invite.invite_kind) {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_binding_required\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (identityId.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(identityId)) {\n\t\t\t\t\treturn c.json({ error: \"identity_id_invalid\" }, 400);\n\t\t\t\t}\n\t\t\t\tlet normalizedRecipientDisplayName: string | null = null;\n\t\t\t\tlet normalizedDeviceDisplayName: string | null = null;\n\t\t\t\ttry {\n\t\t\t\t\tif (data.recipient_display_name != null) {\n\t\t\t\t\t\tif (typeof data.recipient_display_name !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\"recipient_display_name_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnormalizedRecipientDisplayName = normalizeHumanPresentationName(\n\t\t\t\t\t\t\tdata.recipient_display_name,\n\t\t\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (data.device_display_name != null) {\n\t\t\t\t\t\tif (typeof data.device_display_name !== \"string\") {\n\t\t\t\t\t\t\tthrow new Error(\"device_display_name_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnormalizedDeviceDisplayName = normalizeHumanPresentationName(\n\t\t\t\t\t\t\tdata.device_display_name,\n\t\t\t\t\t\t\t\"device_display_name\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror: error instanceof Error ? error.message : \"recipient_invite_identity_invalid\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tinvite.invite_kind === \"add_device\" &&\n\t\t\t\t\tString(invite.inviter_device_id ?? \"\").trim() === deviceId\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: \"add_device_invite_self_acceptance_forbidden\" }, 409);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst acceptance = await store.consumeRecipientInvite({\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tinviteKind: invite.invite_kind as \"team_member\" | \"add_device\",\n\t\t\t\t\t\tidentityId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tpublicKey,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\trecipientDisplayName: normalizedRecipientDisplayName,\n\t\t\t\t\t\tdeviceDisplayName: normalizedDeviceDisplayName,\n\t\t\t\t\t\tnow: runtime.now(),\n\t\t\t\t\t});\n\t\t\t\t\treturn c.json({\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tstatus: acceptance.status,\n\t\t\t\t\t\tkind: acceptance.invite.invite_kind,\n\t\t\t\t\t\tgroup_id: acceptance.invite.group_id,\n\t\t\t\t\t\tidentity_id: acceptance.invite.recipient_actor_id,\n\t\t\t\t\t\tpolicy_team_id: acceptance.invite.policy_team_id ?? null,\n\t\t\t\t\t\ttarget_identity_id: acceptance.invite.target_identity_id ?? null,\n\t\t\t\t\t\tassigned_identity_id: acceptance.invite.assigned_identity_id ?? null,\n\t\t\t\t\t\tbootstrap_grant_id: acceptance.bootstrap_grant?.grant_id ?? null,\n\t\t\t\t\t\tinviter_device: acceptance.bootstrap_grant\n\t\t\t\t\t\t\t? await store.getEnrollment(\n\t\t\t\t\t\t\t\t\tacceptance.invite.group_id,\n\t\t\t\t\t\t\t\t\tacceptance.bootstrap_grant.seed_device_id,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\treviewed_preview_digest: acceptance.invite.reviewed_preview_digest,\n\t\t\t\t\t\treviewed_intent: acceptance.reviewed_intent,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\t\t\t\t\tconst status = code === \"invite_expired\" ? 410 : code === \"invite_invalid\" ? 404 : 409;\n\t\t\t\t\treturn c.json({ error: code }, status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (invite.operation_id || invite.reviewed_project_set_digest) {\n\t\t\t\tconst allowedProjectAcceptanceFields = new Set([\n\t\t\t\t\t\"token\",\n\t\t\t\t\t\"operation_id\",\n\t\t\t\t\t\"device_id\",\n\t\t\t\t\t\"public_key\",\n\t\t\t\t\t\"fingerprint\",\n\t\t\t\t\t\"display_name\",\n\t\t\t\t\t\"recipient_actor_id\",\n\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t\"device_display_name\",\n\t\t\t\t]);\n\t\t\t\tif (Object.keys(data).some((key) => !allowedProjectAcceptanceFields.has(key))) {\n\t\t\t\t\treturn c.json({ error: \"unexpected_project_invite_fields\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (!operationId || !recipientActorId || !recipientDisplayName || !deviceDisplayName) {\n\t\t\t\t\treturn c.json({ error: \"project_invite_identity_required\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (String(invite.inviter_device_id ?? \"\").trim() === deviceId) {\n\t\t\t\t\treturn c.json({ error: \"project_invite_self_acceptance_forbidden\" }, 409);\n\t\t\t\t}\n\t\t\t\tif (recipientActorId.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(recipientActorId)) {\n\t\t\t\t\treturn c.json({ error: \"recipient_actor_id_invalid\" }, 400);\n\t\t\t\t}\n\t\t\t\tlet normalizedRecipientName: string;\n\t\t\t\tlet normalizedDeviceName: string;\n\t\t\t\ttry {\n\t\t\t\t\tnormalizedRecipientName = normalizeHumanPresentationName(\n\t\t\t\t\t\trecipientDisplayName,\n\t\t\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\t);\n\t\t\t\t\tnormalizedDeviceName = normalizeHumanPresentationName(\n\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\t\"device_display_name\",\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_identity_invalid\" },\n\t\t\t\t\t\t400,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlet acceptedIntent: ReturnType<typeof buildAcceptedProjectIntent>;\n\t\t\t\ttry {\n\t\t\t\t\tacceptedIntent = buildAcceptedProjectIntent(invite);\n\t\t\t\t} catch {\n\t\t\t\t\treturn c.json({ error: \"operation_intent_invalid\" }, 409);\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst acceptance = await store.consumeProjectInvite({\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\toperationId,\n\t\t\t\t\t\tdeviceId,\n\t\t\t\t\t\tpublicKey,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\trecipientActorId,\n\t\t\t\t\t\trecipientDisplayName: normalizedRecipientName,\n\t\t\t\t\t\tdeviceDisplayName: normalizedDeviceName,\n\t\t\t\t\t\tnow: runtime.now(),\n\t\t\t\t\t});\n\t\t\t\t\treturn c.json({\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tstatus: PROJECT_INVITE_PENDING_STATUS,\n\t\t\t\t\t\tgroup_id: acceptance.invite.group_id,\n\t\t\t\t\t\toperation_id: acceptance.invite.operation_id,\n\t\t\t\t\t\ttrust_state: acceptance.invite.trust_state,\n\t\t\t\t\t\tbootstrap_grant_id: acceptance.bootstrap_grant?.grant_id ?? null,\n\t\t\t\t\t\tinviter_device: acceptance.seed_enrollment\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tdevice_id: acceptance.seed_enrollment.device_id,\n\t\t\t\t\t\t\t\t\tpublic_key: acceptance.seed_enrollment.public_key,\n\t\t\t\t\t\t\t\t\tfingerprint: acceptance.seed_enrollment.fingerprint,\n\t\t\t\t\t\t\t\t\tdisplay_name: acceptance.seed_enrollment.display_name,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\taccepted_project_intent: acceptedIntent,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst code = error instanceof Error ? error.message : \"invite_invalid\";\n\t\t\t\t\tconst status = code === \"invite_expired\" ? 410 : code === \"invite_invalid\" ? 404 : 409;\n\t\t\t\t\treturn c.json({ error: code }, status);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst projectAcceptanceFields = [\n\t\t\t\t\"operation_id\",\n\t\t\t\t\"recipient_actor_id\",\n\t\t\t\t\"recipient_display_name\",\n\t\t\t\t\"device_display_name\",\n\t\t\t];\n\t\t\tif (projectAcceptanceFields.some((field) => Object.hasOwn(data, field))) {\n\t\t\t\treturn c.json({ error: \"unexpected_project_invite_fields\" }, 400);\n\t\t\t}\n\t\t\tconst group = await store.getGroup(String(invite.group_id));\n\t\t\tif (!group) return c.json({ error: \"group_not_found\" }, 404);\n\t\t\tif (group.archived_at) return c.json({ error: \"group_archived\" }, 409);\n\n\t\t\tconst inviteGroupId = String(invite.group_id);\n\t\t\tconst existing = await store.getEnrollment(inviteGroupId, deviceId);\n\t\t\tif (existing) {\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tstatus: \"already_enrolled\",\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst invitePolicy = String(invite.policy);\n\t\t\tif (![\"auto_admit\", \"approval_required\"].includes(invitePolicy)) {\n\t\t\t\treturn c.json({ error: `unknown invite policy: ${invitePolicy}` }, 400);\n\t\t\t}\n\n\t\t\tif (invitePolicy === \"approval_required\") {\n\t\t\t\tconst request = await store.createJoinRequest({\n\t\t\t\t\tgroupId: inviteGroupId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tpublicKey,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\tdisplayName,\n\t\t\t\t\ttoken,\n\t\t\t\t});\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tstatus: \"pending\",\n\t\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\t\tpolicy: invite.policy,\n\t\t\t\t\trequest_id: request.request_id,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tawait store.enrollDevice(inviteGroupId, {\n\t\t\t\tdeviceId,\n\t\t\t\tfingerprint,\n\t\t\t\tpublicKey,\n\t\t\t\tdisplayName,\n\t\t\t});\n\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tstatus: \"enrolled\",\n\t\t\t\tgroup_id: invite.group_id,\n\t\t\t\tpolicy: invite.policy,\n\t\t\t});\n\t\t} finally {\n\t\t\tawait store.close();\n\t\t}\n\t});\n\n\treturn app;\n}\n\n// ---------------------------------------------------------------------------\n// Shared handler for approve/deny\n// ---------------------------------------------------------------------------\n\nasync function handleJoinRequestReview(\n\tc: Context,\n\tapproved: boolean,\n\tdeps: {\n\t\tcreateStore: () => CoordinatorStore;\n\t\truntime: CoordinatorRuntimeDeps;\n\t\trateLimitedResponse: (c: Context, key: string, authenticated: boolean) => Response | null;\n\t},\n) {\n\tconst adminAuth = authorizeAdmin(c.req.header(ADMIN_HEADER), deps.runtime);\n\tif (!adminAuth.ok)\n\t\treturn (\n\t\t\tdeps.rateLimitedResponse(c, c.req.path, false) ?? c.json({ error: adminAuth.error }, 401)\n\t\t);\n\tconst limited = deps.rateLimitedResponse(c, \"admin\", true);\n\tif (limited) return limited;\n\n\tconst raw = await (async () => {\n\t\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"\", 10);\n\t\tif (Number.isFinite(contentLength) && contentLength > MAX_BODY_BYTES) {\n\t\t\treturn null;\n\t\t}\n\t\tconst stream = c.req.raw.body;\n\t\tif (!stream) return new Uint8Array();\n\t\tconst reader = stream.getReader();\n\t\tconst chunks: Uint8Array[] = [];\n\t\tlet total = 0;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tif (!value) continue;\n\t\t\t\ttotal += value.byteLength;\n\t\t\t\tif (total > MAX_BODY_BYTES) {\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tchunks.push(value);\n\t\t\t}\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t\tconst combined = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tcombined.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\treturn combined;\n\t})();\n\tif (raw == null) return c.json({ error: \"body_too_large\" }, 413);\n\n\tlet data: Record<string, unknown> | null;\n\ttry {\n\t\tconst textDecoder = new TextDecoder();\n\t\tconst parsed: unknown = JSON.parse(textDecoder.decode(raw));\n\t\tdata =\n\t\t\ttypeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n\t\t\t\t? (parsed as Record<string, unknown>)\n\t\t\t\t: null;\n\t} catch {\n\t\tdata = null;\n\t}\n\tif (!data) {\n\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t}\n\n\tconst requestId = String(data.request_id ?? \"\").trim();\n\tconst reviewedBy = String(data.reviewed_by ?? \"\").trim() || null;\n\tconst bootstrapGrantSeedDeviceId = String(data.bootstrap_grant_seed_device_id ?? \"\").trim();\n\tconst bootstrapGrantExpiresAt = String(data.bootstrap_grant_expires_at ?? \"\").trim();\n\n\tif (!requestId) return c.json({ error: \"request_id_required\" }, 400);\n\tconst bootstrapGrantFields = [bootstrapGrantSeedDeviceId, bootstrapGrantExpiresAt].filter(\n\t\tBoolean,\n\t).length;\n\tif (bootstrapGrantFields > 0 && bootstrapGrantFields < 2) {\n\t\treturn c.json(\n\t\t\t{ error: \"bootstrap_grant_seed_device_id_and_expires_at_required_together\" },\n\t\t\t400,\n\t\t);\n\t}\n\n\tconst store = deps.createStore();\n\ttry {\n\t\tconst request = await store.reviewJoinRequest({\n\t\t\trequestId,\n\t\t\tapproved,\n\t\t\treviewedBy,\n\t\t\tbootstrapGrant:\n\t\t\t\tapproved && bootstrapGrantSeedDeviceId && bootstrapGrantExpiresAt\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tseedDeviceId: bootstrapGrantSeedDeviceId,\n\t\t\t\t\t\t\texpiresAt: bootstrapGrantExpiresAt,\n\t\t\t\t\t\t\tcreatedBy: reviewedBy,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null,\n\t\t});\n\n\t\tif (!request) return c.json({ error: \"request_not_found\" }, 404);\n\n\t\tif (request._no_transition) {\n\t\t\treturn c.json({ error: \"request_not_pending\", status: request.status }, 409);\n\t\t}\n\n\t\treturn c.json({ ok: true, request });\n\t} finally {\n\t\tawait store.close();\n\t}\n}\n"],"x_google_ignoreList":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,27,28,29],"mappings":";;;AAMA,IAAa,IAAmC,oCAQ1C,IAA4E;CACjF,qBAAqB;CACrB,sBAAsB;CACtB,gBAAgB;CAChB,iBAAiB;AAClB,GAEa,IAAb,cAAgD,MAAM;CACrD;CAEA,YAAY,GAAsC;EAGjD,AAFA,MAAM,EAA0B,EAAK,GACrC,KAAK,OAAO,8BACZ,KAAK,OAAO;CACb;AACD;AAqBA,SAAS,EAAM,GAAiD;CAE/D,OADmB,GAAO,KAAK,KACE;AAClC;AAEA,SAAgB,EAA4B,GAAuB;CAClE,IAAM,IAAW,EAAM,CAAK;CAC5B,IAAI,CAAC,GAAU,MAAU,MAAM,uBAAuB;CACtD,IAAI,EAAS,SAAS,OAAO,kBAAkB,KAAK,CAAQ,GAC3D,MAAU,MAAM,sBAAsB;CAEvC,OAAO;AACR;AAEA,SAAgB,EACf,GACS;CACT,OAAO,KAAK,UAAU;EACrB,SAAS,EAAM,EAAK,OAAO;EAC3B,UAAU,EAAM,EAAK,QAAQ;EAC7B,MAAM,EAAM,EAAK,IAAI;EACrB,iBAAiB,EAAK,mBAAmB;EACzC,eAAe,EAAM,EAAK,aAAa;EACvC,SAAS,EAAM,EAAK,OAAO;EAC3B,wBAAwB,EAAM,EAAK,sBAAsB;EACzD,cAAc,EAAM,EAAK,YAAY;EACrC,oBAAoB,EAAM,EAAK,kBAAkB;EACjD,WAAW,EAAM,EAAK,SAAS;EAC/B,SAAS,EAAM,EAAK,OAAO;CAC5B,CAAC;AACF;AAEA,SAAgB,EACf,GACS;CACT,OAAO,KAAK,UAAU;EACrB,SAAS,EAAM,EAAK,OAAO;EAC3B,UAAU,EAAM,EAAK,QAAQ;EAC7B,SAAS,EAAM,EAAK,OAAO;EAC3B,iBAAiB,EAAK,mBAAmB;E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