@vrplatform/kysely 1.3.45-391 → 1.3.45-39248566836

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 (122) hide show
  1. package/build/.data.tar +2 -2
  2. package/build/main/camel-case/index.d.ts +4 -4
  3. package/build/main/camel-case/index.js +2 -1
  4. package/build/main/camel-case/index.js.map +1 -1
  5. package/build/main/connect-handoff.d.ts +12 -0
  6. package/build/main/connect-handoff.js +73 -0
  7. package/build/main/connect-handoff.js.map +1 -0
  8. package/build/main/control-plane/index.d.ts +19 -1
  9. package/build/main/control-plane/index.js +10 -0
  10. package/build/main/control-plane/index.js.map +1 -1
  11. package/build/main/index.d.ts +39 -2
  12. package/build/main/index.js +323 -58
  13. package/build/main/index.js.map +1 -1
  14. package/build/main/isomorphic.d.ts +1 -1
  15. package/build/main/isomorphic.js +3 -1
  16. package/build/main/isomorphic.js.map +1 -1
  17. package/build/main/local/generate.js +4 -3
  18. package/build/main/local/generate.js.map +1 -1
  19. package/build/main/local/index.js +3 -0
  20. package/build/main/local/index.js.map +1 -1
  21. package/build/main/migration-source.d.ts +4 -0
  22. package/build/main/migration-source.js +45 -0
  23. package/build/main/migration-source.js.map +1 -0
  24. package/build/main/pganalyze-comment-plugin/comment-transformer.js +3 -1
  25. package/build/main/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
  26. package/build/main/query/listing/status.js +6 -2
  27. package/build/main/query/listing/status.js.map +1 -1
  28. package/build/main/query/tenant/status.d.ts +1 -6
  29. package/build/main/query/tenant/status.js +4 -12
  30. package/build/main/query/tenant/status.js.map +1 -1
  31. package/build/main/regional.d.ts +1 -0
  32. package/build/main/regional.js +1 -0
  33. package/build/main/regional.js.map +1 -1
  34. package/build/main/test/index.js +4 -3
  35. package/build/main/test/index.js.map +1 -1
  36. package/build/main/v1.generated.d.ts +358 -19
  37. package/build/main/v1.generated.js.map +1 -1
  38. package/build/migrations-v2/0000000000033-plaid-connect-session-telemetry.ts +31 -0
  39. package/build/migrations-v2/0000000000049-queued-journal-operation-failures.ts +60 -0
  40. package/build/migrations-v2/0000000000050-connection-oauth-state.ts +43 -0
  41. package/build/migrations-v2/0000000000051-owner-statement-email-delivery.ts +134 -0
  42. package/build/migrations-v2/0000000000052-fee-journal-lock-skip-operations.ts +59 -0
  43. package/build/migrations-v2/0000000000053-fee-journal-lock-skip-null-attempt.ts +44 -0
  44. package/build/migrations-v2/0000000000054-journal-refresh-issue-codes.ts +16 -0
  45. package/build/migrations-v2/0000000000055-tenant-billing-subscription.ts +8 -0
  46. package/build/migrations-v2/0000000000056-journal-operation-failure-precedence.ts +306 -0
  47. package/build/migrations-v2/0000000000057-journal-invalidation-failure-code.ts +28 -0
  48. package/build/migrations-v2/0000000000058-journal-invalidation-locked-failure.ts +16 -0
  49. package/build/migrations-v2/0000000000059-billing-active-listing-cross-region-partner.ts +135 -0
  50. package/build/migrations-v2/0000000000060-accounting-integrity-change-driven.ts +99 -0
  51. package/build/migrations-v2/0000000000061-tenant-pending-onboarding-status.ts +37 -0
  52. package/build/migrations-v2/0000000000062-statement-payout-operations.ts +16 -0
  53. package/build/migrations-v2/0000000000063-missing-account-assignments-issue-code.ts +13 -0
  54. package/build/migrations-v2/0000000000064-journal-invalidation-source-lookup-index.ts +26 -0
  55. package/build/migrations-v2/0000000000065-hasura-connection-event-credentials.ts +42 -0
  56. package/build/migrations-v2/0000000000066-recurring-fee-listing-subscription-match-by.ts +51 -0
  57. package/build/migrations-v2/0000000000067-connection-credential-metadata.ts +60 -0
  58. package/build/migrations-v2/0000000000068-connection-credential-version.ts +34 -0
  59. package/build/migrations-v2/0000000000069-owner-statement-contact-email-delivery.ts +84 -0
  60. package/build/migrations-v2/0000000000070-payment-writer-compatibility.ts +69 -0
  61. package/build/migrations-v2/0000000000071-payments.ts +532 -0
  62. package/build/migrations-v2/0000000000072-journal-entry-payment-index.ts +21 -0
  63. package/build/migrations-v2/0000000000073-batch-invalidation-operation-registration.ts +74 -0
  64. package/build/migrations-v2/0000000000074-owner-statement-email-history.ts +34 -0
  65. package/build/migrations-v2/0000000000075-tenant-deletion-lookup-indexes.ts +46 -0
  66. package/build/migrations-v2/0000000000076-tenant-onboarding-not-null.ts +23 -0
  67. package/build/migrations-v2/0000000000077-payment-writer-statement-attachment.ts +92 -0
  68. package/build/migrations-v2/0000000000078-trigger-timeout-indexes.ts +44 -0
  69. package/build/migrations-v2/0000000000079-core-change-tenant-statistics.ts +26 -0
  70. package/build/migrations-v2/0000000000080-drop-legacy-tracking-event.ts +60 -0
  71. package/build/migrations-v2/0000000000081-recurring-fee-planner-operation-status.ts +35 -0
  72. package/build/migrations-v2/0000000000082-reservation-search-trigram-indexes.ts +54 -0
  73. package/build/migrations-v2/0000000000083-journal-entry-deposit-lookup-index.ts +31 -0
  74. package/build/migrations-v2/0000000000084-journal-entry-reservation-revenue-indexes.ts +39 -0
  75. package/build/migrations-v2/0000000000085-owner-statement-link-email-template.ts +23 -0
  76. package/build/migrations-v2/0000000000086-contact-payment-setup.ts +72 -0
  77. package/build/migrations-v2/0000000000087-address-delete-fk-indexes.ts +30 -0
  78. package/build/migrations-v2/0000000000088-owner-statement-email-switch.ts +76 -0
  79. package/build/migrations-v2/0000000000089-contact-bank-details-requested-at.ts +21 -0
  80. package/build/migrations-v2/0000000000090-contact-bank-account-api-key.ts +22 -0
  81. package/build/migrations-v2/0000000000091-contact-bank-details-request.ts +78 -0
  82. package/build/migrations-v2/0000000000092-payment-provider-reference.ts +22 -0
  83. package/build/migrations-v2/0000000000093-payment-reversal-offline-undo.ts +18 -0
  84. package/build/migrations-v2/0000000000094-reservation-status-checkout-index.ts +37 -0
  85. package/build/migrations-v2/0000000000095-payment-batches.ts +196 -0
  86. package/build/module/camel-case/index.d.ts +4 -4
  87. package/build/module/camel-case/index.js +3 -2
  88. package/build/module/camel-case/index.js.map +1 -1
  89. package/build/module/connect-handoff.d.ts +12 -0
  90. package/build/module/connect-handoff.js +70 -0
  91. package/build/module/connect-handoff.js.map +1 -0
  92. package/build/module/control-plane/index.d.ts +19 -1
  93. package/build/module/control-plane/index.js +9 -0
  94. package/build/module/control-plane/index.js.map +1 -1
  95. package/build/module/index.d.ts +39 -2
  96. package/build/module/index.js +322 -58
  97. package/build/module/index.js.map +1 -1
  98. package/build/module/isomorphic.d.ts +1 -1
  99. package/build/module/isomorphic.js +1 -1
  100. package/build/module/isomorphic.js.map +1 -1
  101. package/build/module/local/generate.js +4 -3
  102. package/build/module/local/generate.js.map +1 -1
  103. package/build/module/local/index.js +3 -0
  104. package/build/module/local/index.js.map +1 -1
  105. package/build/module/migration-source.d.ts +4 -0
  106. package/build/module/migration-source.js +42 -0
  107. package/build/module/migration-source.js.map +1 -0
  108. package/build/module/pganalyze-comment-plugin/comment-transformer.js +3 -1
  109. package/build/module/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
  110. package/build/module/query/listing/status.js +6 -2
  111. package/build/module/query/listing/status.js.map +1 -1
  112. package/build/module/query/tenant/status.d.ts +1 -6
  113. package/build/module/query/tenant/status.js +4 -11
  114. package/build/module/query/tenant/status.js.map +1 -1
  115. package/build/module/regional.d.ts +1 -0
  116. package/build/module/regional.js +1 -0
  117. package/build/module/regional.js.map +1 -1
  118. package/build/module/test/index.js +4 -3
  119. package/build/module/test/index.js.map +1 -1
  120. package/build/module/v1.generated.d.ts +358 -19
  121. package/build/module/v1.generated.js.map +1 -1
  122. package/package.json +8 -6
@@ -0,0 +1,30 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ export async function up(db: Kysely<unknown>): Promise<void> {
5
+ await sql`set local lock_timeout = '5s'`.execute(db);
6
+ await sql`set local statement_timeout = '10min'`.execute(db);
7
+ // Each address delete probes these referencing columns, including global users.
8
+ await sql`
9
+ create index if not exists user_address_id_idx on public."user" (address_id)
10
+ where address_id is not null
11
+ `.execute(db);
12
+ await sql`
13
+ create index if not exists owner_address_id_idx on public.owner (address_id)
14
+ where address_id is not null
15
+ `.execute(db);
16
+ await sql`
17
+ create index if not exists tenant_billing_address_id_idx on public.tenant (billing_address_id)
18
+ where billing_address_id is not null
19
+ `.execute(db);
20
+ }
21
+
22
+ export async function down(db: Kysely<unknown>): Promise<void> {
23
+ await sql`set local lock_timeout = '5s'`.execute(db);
24
+ await sql`set local statement_timeout = '60s'`.execute(db);
25
+ await sql`drop index if exists public.tenant_billing_address_id_idx`.execute(
26
+ db
27
+ );
28
+ await sql`drop index if exists public.owner_address_id_idx`.execute(db);
29
+ await sql`drop index if exists public.user_address_id_idx`.execute(db);
30
+ }
@@ -0,0 +1,76 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // VRT-766: every team emails owner statements to owner contact addresses.
5
+ // - statement_email_enabled is the team's switch per owner. Null follows the
6
+ // default: on while the owner has an active portal login, off otherwise.
7
+ // - Owners whose portal logins all turned statement emails off stay opted
8
+ // out once the portal user email no longer reaches them.
9
+ // - Teams keep their saved statement email text in the link email. The
10
+ // preview line told owners to log in, so it takes the no-login default.
11
+ // Code that predates the switch ignores the column, and only teams with the
12
+ // email links flag read the opt-outs and link templates.
13
+ export async function up(db: Kysely<unknown>): Promise<void> {
14
+ await sql`set local lock_timeout = '5s'`.execute(db);
15
+ await sql`set local statement_timeout = '60s'`.execute(db);
16
+
17
+ await sql`
18
+ alter table accounting.contact
19
+ add column if not exists statement_email_enabled boolean
20
+ `.execute(db);
21
+
22
+ await sql`
23
+ update accounting.contact contact
24
+ set statement_email_unsubscribed_at = now()
25
+ where contact.type = 'owner'
26
+ and contact.statement_email_unsubscribed_at is null
27
+ and exists (
28
+ select 1
29
+ from public.owner_user_access access
30
+ join public.tenant_user tenant_user
31
+ on tenant_user.user_id = access.user_id
32
+ and tenant_user.tenant_id = contact.tenant_id
33
+ and tenant_user.role = 'owner'
34
+ and tenant_user.status = 'active'
35
+ where access.contact_id = contact.id
36
+ and access.role = 'admin'
37
+ )
38
+ and not exists (
39
+ select 1
40
+ from public.owner_user_access access
41
+ join public.tenant_user tenant_user
42
+ on tenant_user.user_id = access.user_id
43
+ and tenant_user.tenant_id = contact.tenant_id
44
+ and tenant_user.role = 'owner'
45
+ and tenant_user.status = 'active'
46
+ where access.contact_id = contact.id
47
+ and access.role = 'admin'
48
+ and not coalesce(tenant_user.notification_preferences, '[]'::jsonb)
49
+ ? 'owner-statements.published.disabled'
50
+ )
51
+ `.execute(db);
52
+
53
+ await sql`
54
+ insert into public.email_template (tenant_id, type, data_json)
55
+ select
56
+ template.tenant_id,
57
+ 'ownerStatementLink_owner',
58
+ template.data_json || jsonb_build_object(
59
+ 'shortDescription',
60
+ 'Your owner statement is ready. Open it with one click, no login needed.'
61
+ )
62
+ from public.email_template template
63
+ join public.tenant tenant on tenant.id = template.tenant_id
64
+ where template.type = 'ownerStatement_owner'
65
+ and tenant.storage_realm = 'vrtrust'
66
+ on conflict (tenant_id, type) do nothing
67
+ `.execute(db);
68
+ }
69
+
70
+ // Opt-outs and copied templates are owner and team data by now, so they stay.
71
+ export async function down(db: Kysely<unknown>): Promise<void> {
72
+ await sql`
73
+ alter table accounting.contact
74
+ drop column if exists statement_email_enabled
75
+ `.execute(db);
76
+ }
@@ -0,0 +1,21 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // PRO-19485/PRO-19486: when the team last emailed an owner or vendor a
5
+ // request for bank details. Expand only; code that predates it ignores it.
6
+ export async function up(db: Kysely<unknown>): Promise<void> {
7
+ await sql`set local lock_timeout = '5s'`.execute(db);
8
+ await sql`set local statement_timeout = '60s'`.execute(db);
9
+
10
+ await sql`
11
+ alter table accounting.contact
12
+ add column if not exists bank_details_requested_at timestamptz
13
+ `.execute(db);
14
+ }
15
+
16
+ export async function down(db: Kysely<unknown>): Promise<void> {
17
+ await sql`
18
+ alter table accounting.contact
19
+ drop column if exists bank_details_requested_at
20
+ `.execute(db);
21
+ }
@@ -0,0 +1,22 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // PRO-19531: the API key that last changed a bank account when no user did.
5
+ // API keys live in the control plane, so there is no foreign key. Expand
6
+ // only; code that predates it ignores the column.
7
+ export async function up(db: Kysely<unknown>): Promise<void> {
8
+ await sql`set local lock_timeout = '5s'`.execute(db);
9
+ await sql`set local statement_timeout = '60s'`.execute(db);
10
+
11
+ await sql`
12
+ alter table accounting.contact_bank_account
13
+ add column if not exists updated_by_api_token_id uuid
14
+ `.execute(db);
15
+ }
16
+
17
+ export async function down(db: Kysely<unknown>): Promise<void> {
18
+ await sql`
19
+ alter table accounting.contact_bank_account
20
+ drop column if exists updated_by_api_token_id
21
+ `.execute(db);
22
+ }
@@ -0,0 +1,78 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // PRO-19485/PRO-19486: one row per bank details request email, so the team
5
+ // sees whether it went out, when its link expires, and when a vendor opened
6
+ // it. accounting.contact.bank_details_requested_at stays the time of the
7
+ // latest request. Expand only; code that predates it ignores the table.
8
+ export async function up(db: Kysely<unknown>): Promise<void> {
9
+ await sql`set local lock_timeout = '5s'`.execute(db);
10
+ await sql`set local statement_timeout = '60s'`.execute(db);
11
+
12
+ await sql`
13
+ create type accounting.bank_details_request_delivery as enum (
14
+ 'queued', 'sent', 'failed', 'skipped'
15
+ )
16
+ `.execute(db);
17
+ await sql`
18
+ create table accounting.contact_bank_details_request (
19
+ id uuid primary key default gen_random_uuid(),
20
+ tenant_id uuid not null references public.tenant (id) on delete restrict,
21
+ contact_id uuid not null references accounting.contact (id) on delete cascade,
22
+ requested_at timestamptz not null,
23
+ requested_by_user_id uuid null references public.user (id) on delete set null,
24
+ delivery accounting.bank_details_request_delivery not null default 'queued',
25
+ recipient_email text null,
26
+ sent_at timestamptz null,
27
+ link_expires_at timestamptz null,
28
+ opened_at timestamptz null,
29
+ created_at timestamptz not null default now(),
30
+ updated_at timestamptz not null default now()
31
+ )
32
+ `.execute(db);
33
+ await sql`
34
+ create index contact_bank_details_request_contact_idx
35
+ on accounting.contact_bank_details_request (contact_id, requested_at desc)
36
+ `.execute(db);
37
+ await sql`
38
+ create index contact_bank_details_request_tenant_id_idx
39
+ on accounting.contact_bank_details_request (tenant_id)
40
+ `.execute(db);
41
+ // Requests sent before this table existed: vendor links lasted 14 days;
42
+ // owner links are treated as not expiring.
43
+ await sql`
44
+ insert into accounting.contact_bank_details_request
45
+ (tenant_id, contact_id, requested_at, delivery, sent_at, link_expires_at)
46
+ select
47
+ contact.tenant_id,
48
+ contact.id,
49
+ contact.bank_details_requested_at,
50
+ 'sent',
51
+ contact.bank_details_requested_at,
52
+ case
53
+ when contact.type = 'vendor'
54
+ then contact.bank_details_requested_at + interval '14 days'
55
+ end
56
+ from accounting.contact contact
57
+ where contact.bank_details_requested_at is not null
58
+ `.execute(db);
59
+ await sql`
60
+ do $$
61
+ begin
62
+ if exists (select 1 from pg_roles where rolname = 'application') then
63
+ grant select, insert, update, delete
64
+ on accounting.contact_bank_details_request to application;
65
+ end if;
66
+ end;
67
+ $$
68
+ `.execute(db);
69
+ }
70
+
71
+ export async function down(db: Kysely<unknown>): Promise<void> {
72
+ await sql`drop table if exists accounting.contact_bank_details_request`.execute(
73
+ db
74
+ );
75
+ await sql`drop type if exists accounting.bank_details_request_delivery`.execute(
76
+ db
77
+ );
78
+ }
@@ -0,0 +1,22 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // PRO-19507: Ramp's customer-friendly payment id (PAY#), assigned after submit.
5
+ // Expand only; code that predates it ignores it. Not an instruction column, so
6
+ // the immutability trigger of migration 0071 lets it be set later.
7
+ export async function up(db: Kysely<unknown>): Promise<void> {
8
+ await sql`set local lock_timeout = '5s'`.execute(db);
9
+ await sql`set local statement_timeout = '60s'`.execute(db);
10
+
11
+ await sql`
12
+ alter table accounting.payment
13
+ add column if not exists provider_reference text
14
+ `.execute(db);
15
+ }
16
+
17
+ export async function down(db: Kysely<unknown>): Promise<void> {
18
+ await sql`
19
+ alter table accounting.payment
20
+ drop column if exists provider_reference
21
+ `.execute(db);
22
+ }
@@ -0,0 +1,18 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // PRO-19526: Mark as unpaid and a changed paid date or account undo an offline payment by
5
+ // removing its journal rows instead of posting a reversing entry. Expand only; older code
6
+ // never writes the new value.
7
+ export async function up(db: Kysely<unknown>): Promise<void> {
8
+ await sql`set local lock_timeout = '5s'`.execute(db);
9
+ await sql`set local statement_timeout = '60s'`.execute(db);
10
+
11
+ await sql`
12
+ alter type accounting.payment_reversal_kind add value if not exists 'offlineUndo'
13
+ `.execute(db);
14
+ }
15
+
16
+ export async function down(_db: Kysely<unknown>): Promise<void> {
17
+ // PostgreSQL enum values cannot be removed safely without rebuilding the type.
18
+ }
@@ -0,0 +1,37 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // GET /reservations counts by status and stay overlap (`dateField=intersection`)
5
+ // without a listing. The only index that holds both dates leads with listing_id,
6
+ // so Postgres skip-scanned it once per listing: 6.4 s for one US team. On large
7
+ // databases run scripts/ben-2/pro-19581-create-reservation-index.ts first: it
8
+ // builds the index concurrently, and this migration then skips it.
9
+ export async function up(db: Kysely<unknown>): Promise<void> {
10
+ await sql`set local lock_timeout = '5s'`.execute(db);
11
+ await sql`set local statement_timeout = '30min'`.execute(db);
12
+ // A failed concurrent build leaves an invalid index that `if not exists`
13
+ // would keep, so drop it first.
14
+ const invalid = await sql<{ invalid: boolean }>`
15
+ select not (i.indisvalid and i.indisready) as invalid
16
+ from pg_index as i
17
+ inner join pg_class as index_class on index_class.oid = i.indexrelid
18
+ where index_class.relname = 'reservation_tenant_status_effective_check_out_idx'
19
+ `.execute(db);
20
+ if (invalid.rows[0]?.invalid) {
21
+ await sql`
22
+ drop index public.reservation_tenant_status_effective_check_out_idx
23
+ `.execute(db);
24
+ }
25
+ await sql`
26
+ create index if not exists reservation_tenant_status_effective_check_out_idx
27
+ on public.reservation (tenant_id, status, effective_check_out, effective_check_in)
28
+ `.execute(db);
29
+ }
30
+
31
+ export async function down(db: Kysely<unknown>): Promise<void> {
32
+ await sql`set local lock_timeout = '5s'`.execute(db);
33
+ await sql`set local statement_timeout = '60s'`.execute(db);
34
+ await sql`
35
+ drop index if exists public.reservation_tenant_status_effective_check_out_idx
36
+ `.execute(db);
37
+ }
@@ -0,0 +1,196 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // P-PRO-983: Nacha files and printed checks. Expand only; no existing code reads or writes
5
+ // these tables. Funding bank numbers and Nacha entry snapshots hold full account numbers, so
6
+ // they live in their own tables that account reads, copies and exports never select.
7
+ export async function up(db: Kysely<unknown>): Promise<void> {
8
+ await sql`set local lock_timeout = '5s'`.execute(db);
9
+ await sql`set local statement_timeout = '60s'`.execute(db);
10
+
11
+ await sql`
12
+ create type accounting.nacha_bank_profile as enum (
13
+ 'generic', 'hancockWhitney', 'bmo', 'regions'
14
+ )
15
+ `.execute(db);
16
+ await sql`
17
+ create type accounting.nacha_sec_code as enum ('PPD', 'CCD')
18
+ `.execute(db);
19
+ await sql`
20
+ create type accounting.check_print_mode as enum ('plainPaper', 'preprinted')
21
+ `.execute(db);
22
+ await sql`
23
+ create type accounting.check_format as enum ('voucher', 'standard')
24
+ `.execute(db);
25
+ await sql`
26
+ create type accounting.payment_batch_type as enum ('nacha', 'check')
27
+ `.execute(db);
28
+
29
+ await sql`
30
+ create table accounting.account_payment_file_setting (
31
+ account_id uuid primary key references accounting.account (id) on delete cascade,
32
+ tenant_id uuid not null references public.tenant (id) on delete restrict,
33
+ bank_name text null check (bank_name is null or length(bank_name) between 1 and 100),
34
+ routing_number text null check (routing_number ~ '^[0-9]{9}$'),
35
+ account_number text null check (account_number ~ '^[0-9]{4,17}$'),
36
+ account_kind accounting.bank_account_kind null,
37
+ company_name text null
38
+ check (company_name is null or length(company_name) between 1 and 100),
39
+ company_address jsonb null
40
+ check (company_address is null or jsonb_typeof(company_address) = 'object'),
41
+ nacha_enabled boolean not null default false,
42
+ nacha_bank_profile accounting.nacha_bank_profile null,
43
+ nacha_immediate_destination text null
44
+ check (nacha_immediate_destination ~ '^[0-9]{9}$'),
45
+ nacha_immediate_destination_name text null
46
+ check (nacha_immediate_destination_name is null
47
+ or length(nacha_immediate_destination_name) between 1 and 23),
48
+ nacha_immediate_origin text null
49
+ check (nacha_immediate_origin ~ '^[0-9A-Za-z ]{1,10}$'),
50
+ nacha_immediate_origin_name text null
51
+ check (nacha_immediate_origin_name is null
52
+ or length(nacha_immediate_origin_name) between 1 and 23),
53
+ nacha_company_id text null
54
+ check (nacha_company_id ~ '^[0-9A-Za-z ]{1,10}$'),
55
+ nacha_company_name text null
56
+ check (nacha_company_name is null or length(nacha_company_name) between 1 and 16),
57
+ nacha_entry_description text null
58
+ check (nacha_entry_description is null
59
+ or length(nacha_entry_description) between 1 and 10),
60
+ nacha_discretionary_data text null
61
+ check (nacha_discretionary_data is null
62
+ or length(nacha_discretionary_data) between 1 and 20),
63
+ nacha_offset_entry boolean not null default false,
64
+ nacha_accept_canadian boolean not null default false,
65
+ nacha_test_file_at timestamptz null,
66
+ nacha_test_file_valid boolean null,
67
+ check_enabled boolean not null default false,
68
+ check_print_mode accounting.check_print_mode null,
69
+ check_format accounting.check_format null,
70
+ check_next_number integer null check (check_next_number between 1 and 99999999),
71
+ check_offset_x integer not null default 0 check (check_offset_x between -100 and 100),
72
+ check_offset_y integer not null default 0 check (check_offset_y between -100 and 100),
73
+ updated_by_user_id uuid null references public.user (id) on delete set null,
74
+ created_at timestamptz not null default now(),
75
+ updated_at timestamptz not null default now(),
76
+ check (num_nonnulls(nacha_test_file_at, nacha_test_file_valid) in (0, 2))
77
+ )
78
+ `.execute(db);
79
+ await sql`
80
+ create index account_payment_file_setting_tenant_id_idx
81
+ on accounting.account_payment_file_setting (tenant_id)
82
+ `.execute(db);
83
+
84
+ await sql`
85
+ create table accounting.payment_batch (
86
+ id uuid primary key default gen_random_uuid(),
87
+ tenant_id uuid not null references public.tenant (id) on delete restrict,
88
+ type accounting.payment_batch_type not null,
89
+ account_id uuid not null references accounting.account (id) on delete restrict,
90
+ currency text not null references public.currency (name),
91
+ effective_date date not null,
92
+ settings jsonb not null check (jsonb_typeof(settings) = 'object'),
93
+ file_content text null,
94
+ file_updated_at timestamptz null,
95
+ created_by_user_id uuid null references public.user (id) on delete set null,
96
+ idempotency_key text not null check (length(idempotency_key) between 1 and 200),
97
+ voided_at timestamptz null,
98
+ created_at timestamptz not null default now(),
99
+ updated_at timestamptz not null default now(),
100
+ unique (tenant_id, idempotency_key),
101
+ check ((type = 'nacha') = (file_content is not null))
102
+ )
103
+ `.execute(db);
104
+ await sql`
105
+ create index payment_batch_tenant_created_idx
106
+ on accounting.payment_batch (tenant_id, created_at desc)
107
+ `.execute(db);
108
+ await sql`
109
+ create index payment_batch_account_idx
110
+ on accounting.payment_batch (tenant_id, account_id)
111
+ `.execute(db);
112
+
113
+ await sql`
114
+ create table accounting.payment_batch_item (
115
+ id uuid primary key default gen_random_uuid(),
116
+ tenant_id uuid not null references public.tenant (id) on delete restrict,
117
+ batch_id uuid not null references accounting.payment_batch (id) on delete restrict,
118
+ account_id uuid not null references accounting.account (id) on delete restrict,
119
+ contact_id uuid not null references accounting.contact (id) on delete restrict,
120
+ amount integer not null check (amount > 0),
121
+ payee_name text not null check (length(payee_name) between 1 and 200),
122
+ payee_address jsonb null
123
+ check (payee_address is null or jsonb_typeof(payee_address) = 'object'),
124
+ memo text null check (memo is null or length(memo) <= 200),
125
+ stub jsonb not null check (jsonb_typeof(stub) = 'array'),
126
+ check_number integer null check (check_number between 1 and 99999999),
127
+ sec_code accounting.nacha_sec_code null,
128
+ routing_number text null check (routing_number ~ '^[0-9]{9}$'),
129
+ account_number text null check (account_number ~ '^[0-9]{4,17}$'),
130
+ account_kind accounting.bank_account_kind null,
131
+ trace_number text null check (trace_number ~ '^[0-9]{15}$'),
132
+ voided_at timestamptz null,
133
+ created_at timestamptz not null default now(),
134
+ check (
135
+ num_nonnulls(sec_code, routing_number, account_number, account_kind) in (0, 4)
136
+ ),
137
+ check (check_number is null or sec_code is null)
138
+ )
139
+ `.execute(db);
140
+ // Voided check numbers keep their row, so a number is never printed twice.
141
+ await sql`
142
+ create unique index payment_batch_item_check_number_idx
143
+ on accounting.payment_batch_item (tenant_id, account_id, check_number)
144
+ where check_number is not null
145
+ `.execute(db);
146
+ await sql`
147
+ create index payment_batch_item_batch_idx
148
+ on accounting.payment_batch_item (tenant_id, batch_id)
149
+ `.execute(db);
150
+ await sql`
151
+ create index payment_batch_item_contact_idx
152
+ on accounting.payment_batch_item (tenant_id, contact_id)
153
+ `.execute(db);
154
+
155
+ await sql`
156
+ create table accounting.payment_batch_payment (
157
+ payment_id uuid primary key references accounting.payment (id) on delete restrict,
158
+ tenant_id uuid not null references public.tenant (id) on delete restrict,
159
+ item_id uuid not null references accounting.payment_batch_item (id) on delete restrict,
160
+ created_at timestamptz not null default now()
161
+ )
162
+ `.execute(db);
163
+ await sql`
164
+ create index payment_batch_payment_item_idx
165
+ on accounting.payment_batch_payment (tenant_id, item_id)
166
+ `.execute(db);
167
+
168
+ await sql`
169
+ do $$
170
+ begin
171
+ if exists (select 1 from pg_roles where rolname = 'application') then
172
+ grant select, insert, update, delete on
173
+ accounting.account_payment_file_setting,
174
+ accounting.payment_batch,
175
+ accounting.payment_batch_item,
176
+ accounting.payment_batch_payment
177
+ to application;
178
+ end if;
179
+ end;
180
+ $$
181
+ `.execute(db);
182
+ }
183
+
184
+ export async function down(db: Kysely<unknown>): Promise<void> {
185
+ await sql`drop table if exists accounting.payment_batch_payment`.execute(db);
186
+ await sql`drop table if exists accounting.payment_batch_item`.execute(db);
187
+ await sql`drop table if exists accounting.payment_batch`.execute(db);
188
+ await sql`drop table if exists accounting.account_payment_file_setting`.execute(
189
+ db
190
+ );
191
+ await sql`drop type if exists accounting.payment_batch_type`.execute(db);
192
+ await sql`drop type if exists accounting.check_format`.execute(db);
193
+ await sql`drop type if exists accounting.check_print_mode`.execute(db);
194
+ await sql`drop type if exists accounting.nacha_sec_code`.execute(db);
195
+ await sql`drop type if exists accounting.nacha_bank_profile`.execute(db);
196
+ }
@@ -1,8 +1,8 @@
1
- import { CamelCasePlugin, type SelectQueryNode } from 'kysely';
1
+ import { CamelCasePlugin, type PluginTransformQueryArgs, type PluginTransformResultArgs, SelectQueryNode, type UnknownRow } from 'kysely';
2
2
  export declare class CustomCasePlugin extends CamelCasePlugin {
3
3
  constructor();
4
- transformResult(args: any): Promise<import("kysely").QueryResult<import("kysely").UnknownRow>>;
5
- transformQuery(args: any): import("kysely").RootOperationNode;
4
+ transformResult(args: PluginTransformResultArgs): Promise<import("kysely").QueryResult<UnknownRow>>;
5
+ transformQuery(args: PluginTransformQueryArgs): import("kysely").RootOperationNode;
6
6
  verifyAlias(node: SelectQueryNode): void;
7
- protected mapRow(row: any): any;
7
+ protected mapRow(row: UnknownRow): Record<string, any>;
8
8
  }
@@ -1,4 +1,4 @@
1
- import { CamelCasePlugin, } from 'kysely';
1
+ import { CamelCasePlugin, SelectQueryNode, } from 'kysely';
2
2
  import { KyselyError } from '../error';
3
3
  export class CustomCasePlugin extends CamelCasePlugin {
4
4
  // _excludedColumns: Record<string, boolean> = {};
@@ -11,7 +11,8 @@ export class CustomCasePlugin extends CamelCasePlugin {
11
11
  return super.transformResult(args);
12
12
  }
13
13
  transformQuery(args) {
14
- this.verifyAlias(args.node);
14
+ if (SelectQueryNode.is(args.node))
15
+ this.verifyAlias(args.node);
15
16
  return super.transformQuery(args);
16
17
  }
17
18
  verifyAlias(node) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["camel-case/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,eAAe,GAIhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAEvC,MAAM,OAAO,gBAAiB,SAAQ,eAAe;IACnD,kDAAkD;IA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B,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,GAAG;YAAE,OAAO,GAAG,CAAC;QAEhD,MAAM,MAAM,GAAwB,EAAE,CAAC;QACvC,8GAA8G;QAC9G,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACnC,IAAI,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;YACrB,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;YACpC,iEAAiE;YACjE,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;gBACzB,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC;YAC7C,CAAC;YACD,MAAM,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;QACzB,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import {\n type AliasNode,\n CamelCasePlugin,\n type IdentifierNode,\n type RawNode,\n type SelectQueryNode,\n} from 'kysely';\nimport { KyselyError } from '../error';\n\nexport class CustomCasePlugin extends CamelCasePlugin {\n // _excludedColumns: Record<string, boolean> = {};\n constructor() {\n super({\n maintainNestedObjectKeys: true,\n });\n }\n\n transformResult(args) {\n return super.transformResult(args);\n }\n\n transformQuery(args) {\n this.verifyAlias(args.node);\n return super.transformQuery(args);\n }\n\n verifyAlias(node: SelectQueryNode) {\n if (!node?.selections) return;\n\n for (const x of node.selections ?? []) {\n const selection = x.selection as AliasNode;\n if (!selection.alias) continue;\n const alias = selection.alias as IdentifierNode;\n\n // alias can be a raw node (jsonArrayFrom)\n if (selection.node.kind === 'RawNode') {\n const rawNode = selection.node as RawNode;\n for (const x of rawNode.parameters ?? []) {\n if (x.kind === 'SelectQueryNode') {\n const selectQueryNode = x as SelectQueryNode;\n this.verifyAlias(selectQueryNode);\n }\n }\n }\n\n if (!alias.name.includes('_')) continue;\n\n throw new KyselyError('Alias contains underscore', { name: alias.name });\n }\n }\n\n protected mapRow(row) {\n if (typeof row !== 'object' || !row) return row;\n\n const newRow: Record<string, any> = {};\n // we camel case on first layer, and nested ONLY if in an array (jsonArrayFrom), NOT if it's an object (jsonb)\n for (const key of Object.keys(row)) {\n let value = row[key];\n const newKey = super.camelCase(key);\n // array CAN be non object, so we need to check the first element\n if (Array.isArray(value)) {\n value = value.map((it) => this.mapRow(it));\n }\n newRow[newKey] = value;\n }\n return newRow;\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["camel-case/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,eAAe,EAKf,eAAe,GAEhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAEvC,MAAM,OAAO,gBAAiB,SAAQ,eAAe;IACnD,kDAAkD;IAClD;QACE,KAAK,CAAC;YACJ,wBAAwB,EAAE,IAAI;SAC/B,CAAC,CAAC;IACL,CAAC;IAED,eAAe,CAAC,IAA+B;QAC7C,OAAO,KAAK,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;IAED,cAAc,CAAC,IAA8B;QAC3C,IAAI,eAAe,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;YAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/D,OAAO,KAAK,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,WAAW,CAAC,IAAqB;QAC/B,IAAI,CAAC,IAAI,EAAE,UAAU;YAAE,OAAO;QAE9B,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;YACtC,MAAM,SAAS,GAAG,CAAC,CAAC,SAAsB,CAAC;YAC3C,IAAI,CAAC,SAAS,CAAC,KAAK;gBAAE,SAAS;YAC/B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AAG,KAAK,CAAC;QACzB,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["import {\n type AliasNode,\n CamelCasePlugin,\n type IdentifierNode,\n type PluginTransformQueryArgs,\n type PluginTransformResultArgs,\n type RawNode,\n SelectQueryNode,\n type UnknownRow,\n} from 'kysely';\nimport { KyselyError } from '../error';\n\nexport class CustomCasePlugin extends CamelCasePlugin {\n // _excludedColumns: Record<string, boolean> = {};\n constructor() {\n super({\n maintainNestedObjectKeys: true,\n });\n }\n\n transformResult(args: PluginTransformResultArgs) {\n return super.transformResult(args);\n }\n\n transformQuery(args: PluginTransformQueryArgs) {\n if (SelectQueryNode.is(args.node)) this.verifyAlias(args.node);\n return super.transformQuery(args);\n }\n\n verifyAlias(node: SelectQueryNode) {\n if (!node?.selections) return;\n\n for (const x of node.selections ?? []) {\n const selection = x.selection as AliasNode;\n if (!selection.alias) continue;\n const alias = selection.alias as IdentifierNode;\n\n // alias can be a raw node (jsonArrayFrom)\n if (selection.node.kind === 'RawNode') {\n const rawNode = selection.node as RawNode;\n for (const x of rawNode.parameters ?? []) {\n if (x.kind === 'SelectQueryNode') {\n const selectQueryNode = x as SelectQueryNode;\n this.verifyAlias(selectQueryNode);\n }\n }\n }\n\n if (!alias.name.includes('_')) continue;\n\n throw new KyselyError('Alias contains underscore', { name: alias.name });\n }\n }\n\n protected mapRow(row: UnknownRow) {\n if (typeof row !== 'object' || !row) return row;\n\n const newRow: Record<string, any> = {};\n // we camel case on first layer, and nested ONLY if in an array (jsonArrayFrom), NOT if it's an object (jsonb)\n for (const key of Object.keys(row)) {\n let value = row[key];\n const newKey = super.camelCase(key);\n // array CAN be non object, so we need to check the first element\n if (Array.isArray(value)) {\n value = value.map((it) => this.mapRow(it));\n }\n newRow[newKey] = value;\n }\n return newRow;\n }\n}\n"]}
@@ -0,0 +1,12 @@
1
+ import type { Kysely } from './index';
2
+ import type { JsonObject } from './v1.generated';
3
+ /**
4
+ * Passes secrets between the API and Trigger.dev tasks through the tenant's
5
+ * database, so connect credentials never enter Trigger.dev payloads or outputs.
6
+ * Rows expire after one hour, the lifetime of a reused connect run. Reads do not
7
+ * consume the row: a retried or reused run must still find it.
8
+ */
9
+ export declare function useConnectHandoff(kysely: Kysely, tenantId: string): {
10
+ put(appId: string, value: JsonObject): Promise<string>;
11
+ get(ref: string, appId: string): Promise<JsonObject | undefined>;
12
+ };
@@ -0,0 +1,70 @@
1
+ import { sql } from 'kysely';
2
+ // Rows never belong to a user, so no authenticated user can claim one through
3
+ // the OAuth state flow that shares the table.
4
+ const handoffUserId = '00000000-0000-0000-0000-000000000000';
5
+ const handoffRefPattern = /^handoff_[A-Za-z0-9_-]{22}$/;
6
+ async function hashRef(ref) {
7
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(ref));
8
+ return [...new Uint8Array(digest)]
9
+ .map((byte) => byte.toString(16).padStart(2, '0'))
10
+ .join('');
11
+ }
12
+ /**
13
+ * Passes secrets between the API and Trigger.dev tasks through the tenant's
14
+ * database, so connect credentials never enter Trigger.dev payloads or outputs.
15
+ * Rows expire after one hour, the lifetime of a reused connect run. Reads do not
16
+ * consume the row: a retried or reused run must still find it.
17
+ */
18
+ export function useConnectHandoff(kysely, tenantId) {
19
+ return {
20
+ async put(appId, value) {
21
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
22
+ const ref = `handoff_${btoa(String.fromCharCode(...bytes))
23
+ .replaceAll('+', '-')
24
+ .replaceAll('/', '_')
25
+ .replaceAll('=', '')}`;
26
+ await kysely
27
+ .deleteFrom('public.connectionOauthState')
28
+ .where('stateHash', 'in', kysely
29
+ .selectFrom('public.connectionOauthState')
30
+ .select('stateHash')
31
+ .where('expiresAt', '<=', sql `clock_timestamp()`)
32
+ .orderBy('expiresAt')
33
+ .limit(100)
34
+ .forUpdate()
35
+ .skipLocked())
36
+ .execute();
37
+ // Transient authentication coordination is excluded from business audit:
38
+ // references, setup parameters and credentials must never be audited.
39
+ await kysely
40
+ .insertInto('public.connectionOauthState')
41
+ .values({
42
+ stateHash: await hashRef(ref),
43
+ tenantId,
44
+ userId: handoffUserId,
45
+ appId,
46
+ connectionId: null,
47
+ params: value,
48
+ redirectUri: '',
49
+ expiresAt: sql `clock_timestamp() + interval '1 hour'`,
50
+ })
51
+ .execute();
52
+ return ref;
53
+ },
54
+ async get(ref, appId) {
55
+ if (!handoffRefPattern.test(ref))
56
+ return undefined;
57
+ const row = await kysely
58
+ .selectFrom('public.connectionOauthState')
59
+ .select('params')
60
+ .where('stateHash', '=', await hashRef(ref))
61
+ .where('tenantId', '=', tenantId)
62
+ .where('appId', '=', appId)
63
+ .where('userId', '=', handoffUserId)
64
+ .where('expiresAt', '>', sql `clock_timestamp()`)
65
+ .executeTakeFirst();
66
+ return row?.params;
67
+ },
68
+ };
69
+ }
70
+ //# sourceMappingURL=connect-handoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect-handoff.js","sourceRoot":"src/","sources":["connect-handoff.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAI7B,8EAA8E;AAC9E,8CAA8C;AAC9C,MAAM,aAAa,GAAG,sCAAsC,CAAC;AAC7D,MAAM,iBAAiB,GAAG,6BAA6B,CAAC;AAExD,KAAK,UAAU,OAAO,CAAC,GAAW;IAChC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CACvC,SAAS,EACT,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAC9B,CAAC;IACF,OAAO,CAAC,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;SAC/B,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SACjD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,MAAM,U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AiB,CAAC,IAAI,CAAC,GAAG,CAAC;gBAAE,OAAO,SAAS,CAAC;YACnD,MAAM,GAAG,GAAG,MAAM,MAAM;iBACrB,UAAU,CAAC,6BAA6B,CAAC;iBACzC,MAAM,CAAC,QAAQ,CAAC;iBAChB,KAAK,CAAC,WAAW,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC;iBAC3C,KAAK,CAAC,UAAU,EAAE,GAAG,EAAE,QAAQ,CAAC;iBAChC,KAAK,CAAC,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC;iBAC1B,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,aAAa,CAAC;iBACnC,KAAK,CAAC,WAAW,EAAE,GAAG,EAAE,GAAG,CAAQ,mBAAmB,CAAC;iBACvD,gBAAgB,EAAE,CAAC;YACtB,OAAO,GAAG,EAAE,MAAM,CAAC;QACrB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { sql } from 'kysely';\nimport type { Kysely } from './index';\nimport type { JsonObject } from './v1.generated';\n\n// Rows never belong to a user, so no authenticated user can claim one through\n// the OAuth state flow that shares the table.\nconst handoffUserId = '00000000-0000-0000-0000-000000000000';\nconst handoffRefPattern = /^handoff_[A-Za-z0-9_-]{22}$/;\n\nasync function hashRef(ref: string) {\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(ref)\n );\n return [...new Uint8Array(digest)]\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Passes secrets between the API and Trigger.dev tasks through the tenant's\n * database, so connect credentials never enter Trigger.dev payloads or outputs.\n * Rows expire after one hour, the lifetime of a reused connect run. Reads do not\n * consume the row: a retried or reused run must still find it.\n */\nexport function useConnectHandoff(kysely: Kysely, tenantId: string) {\n return {\n async put(appId: string, value: JsonObject) {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n const ref = `handoff_${btoa(String.fromCharCode(...bytes))\n .replaceAll('+', '-')\n .replaceAll('/', '_')\n .replaceAll('=', '')}`;\n await kysely\n .deleteFrom('public.connectionOauthState')\n .where(\n 'stateHash',\n 'in',\n kysely\n .selectFrom('public.connectionOauthState')\n .select('stateHash')\n .where('expiresAt', '<=', sql<string>`clock_timestamp()`)\n .orderBy('expiresAt')\n .limit(100)\n .forUpdate()\n .skipLocked()\n )\n .execute();\n // Transient authentication coordination is excluded from business audit:\n // references, setup parameters and credentials must never be audited.\n await kysely\n .insertInto('public.connectionOauthState')\n .values({\n stateHash: await hashRef(ref),\n tenantId,\n userId: handoffUserId,\n appId,\n connectionId: null,\n params: value,\n redirectUri: '',\n expiresAt: sql`clock_timestamp() + interval '1 hour'`,\n })\n .execute();\n return ref;\n },\n async get(ref: string, appId: string) {\n if (!handoffRefPattern.test(ref)) return undefined;\n const row = await kysely\n .selectFrom('public.connectionOauthState')\n .select('params')\n .where('stateHash', '=', await hashRef(ref))\n .where('tenantId', '=', tenantId)\n .where('appId', '=', appId)\n .where('userId', '=', handoffUserId)\n .where('expiresAt', '>', sql<string>`clock_timestamp()`)\n .executeTakeFirst();\n return row?.params;\n },\n };\n}\n"]}