@vrplatform/kysely 1.3.41 → 1.3.45-stage.4321

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 (98) hide show
  1. package/build/main/camel-case/index.js.map +1 -1
  2. package/build/main/control-plane/index.d.ts +142 -0
  3. package/build/main/control-plane/index.js +3 -0
  4. package/build/main/control-plane/index.js.map +1 -0
  5. package/build/main/error.js.map +1 -1
  6. package/build/main/index.d.ts +5 -3
  7. package/build/main/index.js +7 -9
  8. package/build/main/index.js.map +1 -1
  9. package/build/main/isomorphic.js +2 -2
  10. package/build/main/isomorphic.js.map +1 -1
  11. package/build/main/local/digest.js.map +1 -1
  12. package/build/main/local/generate.js.map +1 -1
  13. package/build/main/local/index.js.map +1 -1
  14. package/build/main/local/prune-pulled-schema.js.map +1 -1
  15. package/build/main/pganalyze-comment-plugin/comment-transformer.js +0 -1
  16. package/build/main/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
  17. package/build/main/pganalyze-comment-plugin/index.js +16 -3
  18. package/build/main/pganalyze-comment-plugin/index.js.map +1 -1
  19. package/build/main/plugins.js.map +1 -1
  20. package/build/main/query/listing/status.d.ts +4 -4
  21. package/build/main/query/listing/status.js +2 -1
  22. package/build/main/query/listing/status.js.map +1 -1
  23. package/build/main/regional.d.ts +34 -0
  24. package/build/main/regional.js +145 -0
  25. package/build/main/regional.js.map +1 -0
  26. package/build/main/test/index.js.map +1 -1
  27. package/build/main/transaction.js.map +1 -1
  28. package/build/main/v1.generated.d.ts +19 -1
  29. package/build/main/v1.generated.js.map +1 -1
  30. package/build/migrations/0000000000001-init.ts +5 -0
  31. package/build/migrations/0000000000009-drop-store-schema.ts +14 -0
  32. package/build/migrations/0000000000010-bank-rules.ts +190 -0
  33. package/build/migrations/0000000000011-bank-rule-line-adjustments.ts +65 -0
  34. package/build/migrations/0000000000012-bank-rule-conditions.ts +45 -0
  35. package/build/migrations/0000000000013-bank-rule-name-unique.ts +15 -0
  36. package/build/migrations/0000000000014-bank-rule-drop-legacy-conditions.ts +41 -0
  37. package/build/migrations/0000000000015-booking-channel-logo-dev-provider.ts +70 -0
  38. package/build/migrations/0000000000016-owner-statement-draft-status.ts +22 -0
  39. package/build/migrations/0000000000017-tenant-migration-markers.ts +18 -0
  40. package/build/migrations/0000000000018-security-deposits-payable-category.ts +63 -0
  41. package/build/migrations/0000000000019-tenant-app-settings.ts +76 -0
  42. package/build/migrations/0000000000020-operating-opening-trial-balance.ts +36 -0
  43. package/build/migrations/0000000000021-audit-foreign-key-indexes.ts +77 -0
  44. package/build/migrations/0000000000022-opening-trial-balance-combined-columns.ts +30 -0
  45. package/build/migrations/0000000000023-journal-entry-currency-mismatch-reason.ts +14 -0
  46. package/build/migrations/0000000000024-listing-parent.ts +37 -0
  47. package/build/migrations/0000000000025-journal-entry-parent-listing.ts +26 -0
  48. package/build/migrations/0000000000026-booking-channel-logo-slots.ts +89 -0
  49. package/build/migrations/0000000000027-list-browse-performance-indexes.ts +52 -0
  50. package/build/migrations/0000000000028-flow-setting-status-jsonb.ts +20 -0
  51. package/build/migrations/0000000000029-tenant-slug.ts +328 -0
  52. package/build/migrations/0000000000030-pms-accounting-windows.ts +50 -0
  53. package/build/migrations/0000000000031-owner-statement-projection-listing-revision.ts +20 -0
  54. package/build/migrations/0000000000032-flow-event-listening.ts +28 -0
  55. package/build/migrations/0000000000033-opening-trial-balance-transaction.ts +272 -0
  56. package/build/migrations/0000000000034-historic-general-ledger.ts +24 -0
  57. package/build/migrations/0000000000035-tenant-regional-placement.ts +37 -0
  58. package/build/migrations/0000000000036-control-plane-projection-events.ts +43 -0
  59. package/build/migrations/0000000000037-tenant-guide-onboarding.ts +21 -0
  60. package/build/migrations/0000000000038-tracking-event-analytics-sink.ts +31 -0
  61. package/build/migrations/0000000000039-crunchy-region.ts +86 -0
  62. package/build/migrations/0000000000040-hostaway-region.ts +72 -0
  63. package/build/migrations/0000000000041-audit-tenant-fk.ts +66 -0
  64. package/build/migrations/0000000000042-ramp-staging-connect-params.ts +35 -0
  65. package/build/migrations/0000000000043-gl-pms-accounting-window-guard.ts +125 -0
  66. package/build/migrations/0000000000044-tenant-cross-region-fks.ts +45 -0
  67. package/build/migrations/0000000000045-cloudflare-region-env.ts +100 -0
  68. package/build/migrations/0000000000046-control-plane-outbox-alias.ts +46 -0
  69. package/build/migrations/0000000000047-ramp-contact-last-4-digits.ts +16 -0
  70. package/build/module/camel-case/index.js.map +1 -1
  71. package/build/module/control-plane/index.d.ts +142 -0
  72. package/build/module/control-plane/index.js +2 -0
  73. package/build/module/control-plane/index.js.map +1 -0
  74. package/build/module/error.js.map +1 -1
  75. package/build/module/index.d.ts +5 -3
  76. package/build/module/index.js +7 -9
  77. package/build/module/index.js.map +1 -1
  78. package/build/module/isomorphic.js.map +1 -1
  79. package/build/module/local/digest.js.map +1 -1
  80. package/build/module/local/generate.js.map +1 -1
  81. package/build/module/local/index.js.map +1 -1
  82. package/build/module/local/prune-pulled-schema.js.map +1 -1
  83. package/build/module/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
  84. package/build/module/pganalyze-comment-plugin/index.js.map +1 -1
  85. package/build/module/plugins.js.map +1 -1
  86. package/build/module/query/listing/status.d.ts +4 -4
  87. package/build/module/query/listing/status.js +2 -1
  88. package/build/module/query/listing/status.js.map +1 -1
  89. package/build/module/regional.d.ts +34 -0
  90. package/build/module/regional.js +103 -0
  91. package/build/module/regional.js.map +1 -0
  92. package/build/module/test/index.js.map +1 -1
  93. package/build/module/transaction.js.map +1 -1
  94. package/build/module/v1.generated.d.ts +19 -1
  95. package/build/module/v1.generated.js.map +1 -1
  96. package/package.json +13 -4
  97. package/build/main/tsconfig.main.tsbuildinfo +0 -1
  98. package/build/module/tsconfig.esm.tsbuildinfo +0 -1
@@ -0,0 +1,125 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ export async function up(db: Kysely<any>): Promise<void> {
5
+ await sql`
6
+ create or replace function public.assert_gl_pms_accounting_window_for_tenant(
7
+ check_tenant_id uuid
8
+ )
9
+ returns void
10
+ language plpgsql
11
+ as $$
12
+ begin
13
+ if check_tenant_id is null then
14
+ return;
15
+ end if;
16
+
17
+ if exists (
18
+ select 1
19
+ from public.tenant as tenant
20
+ where tenant.id = check_tenant_id
21
+ and tenant.is_general_ledger is true
22
+ and exists (
23
+ select 1
24
+ from public.connection as connection
25
+ inner join public.app as app on app.id = connection.app_id
26
+ where connection.tenant_id = check_tenant_id
27
+ and connection.status = 'active'
28
+ and connection.accounting_start_at is null
29
+ and app.category = 'propertyManagementSystem'
30
+ )
31
+ and not exists (
32
+ select 1
33
+ from public.connection as connection
34
+ inner join public.app as app on app.id = connection.app_id
35
+ where connection.tenant_id = check_tenant_id
36
+ and connection.status = 'active'
37
+ and connection.accounting_start_at is not null
38
+ and connection.accounting_end_at is null
39
+ and app.category = 'propertyManagementSystem'
40
+ )
41
+ ) then
42
+ raise exception
43
+ 'Active GL PMS connection is missing accountingStartAt without an open PMS accounting source'
44
+ using errcode = '23514';
45
+ end if;
46
+ end;
47
+ $$;
48
+ `.execute(db);
49
+
50
+ await sql`
51
+ create or replace function public.assert_gl_pms_accounting_window_connection_trigger()
52
+ returns trigger
53
+ language plpgsql
54
+ as $$
55
+ begin
56
+ if tg_op = 'DELETE' then
57
+ perform public.assert_gl_pms_accounting_window_for_tenant(old.tenant_id);
58
+ return null;
59
+ end if;
60
+
61
+ if tg_op = 'UPDATE' and new.tenant_id is distinct from old.tenant_id then
62
+ perform public.assert_gl_pms_accounting_window_for_tenant(old.tenant_id);
63
+ end if;
64
+
65
+ perform public.assert_gl_pms_accounting_window_for_tenant(new.tenant_id);
66
+ return null;
67
+ end;
68
+ $$;
69
+ `.execute(db);
70
+
71
+ await sql`
72
+ create or replace function public.assert_gl_pms_accounting_window_tenant_trigger()
73
+ returns trigger
74
+ language plpgsql
75
+ as $$
76
+ begin
77
+ if new.is_general_ledger is true then
78
+ perform public.assert_gl_pms_accounting_window_for_tenant(new.id);
79
+ end if;
80
+
81
+ return null;
82
+ end;
83
+ $$;
84
+ `.execute(db);
85
+
86
+ await sql`
87
+ create constraint trigger connection_gl_pms_accounting_window_guard
88
+ after insert or update or delete on public.connection
89
+ deferrable initially deferred
90
+ for each row
91
+ execute function public.assert_gl_pms_accounting_window_connection_trigger();
92
+ `.execute(db);
93
+
94
+ await sql`
95
+ create constraint trigger tenant_gl_pms_accounting_window_guard
96
+ after insert or update on public.tenant
97
+ deferrable initially deferred
98
+ for each row
99
+ execute function public.assert_gl_pms_accounting_window_tenant_trigger();
100
+ `.execute(db);
101
+ }
102
+
103
+ export async function down(db: Kysely<any>): Promise<void> {
104
+ await sql`
105
+ drop trigger if exists tenant_gl_pms_accounting_window_guard
106
+ on public.tenant;
107
+ `.execute(db);
108
+
109
+ await sql`
110
+ drop trigger if exists connection_gl_pms_accounting_window_guard
111
+ on public.connection;
112
+ `.execute(db);
113
+
114
+ await sql`
115
+ drop function if exists public.assert_gl_pms_accounting_window_tenant_trigger();
116
+ `.execute(db);
117
+
118
+ await sql`
119
+ drop function if exists public.assert_gl_pms_accounting_window_connection_trigger();
120
+ `.execute(db);
121
+
122
+ await sql`
123
+ drop function if exists public.assert_gl_pms_accounting_window_for_tenant(uuid);
124
+ `.execute(db);
125
+ }
@@ -0,0 +1,45 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ // Tenant-to-tenant references (partner, billing partner, chart-of-accounts
5
+ // source) are cross-region: a partner homed in one cell manages tenants in
6
+ // another, so these self-referential FKs cannot hold within a single regional
7
+ // database. The control plane holds the authoritative tenant graph; the
8
+ // regional columns keep the ids as plain references. Drop the FKs.
9
+ export async function up(db: Kysely<any>): Promise<void> {
10
+ await sql`
11
+ alter table public.tenant
12
+ drop constraint if exists tenant_partner_id_fkey;
13
+ `.execute(db);
14
+ await sql`
15
+ alter table public.tenant
16
+ drop constraint if exists tenant_billing_partner_id_fkey;
17
+ `.execute(db);
18
+ await sql`
19
+ alter table public.tenant
20
+ drop constraint if exists tenant_chart_of_account_tenant_id_fkey;
21
+ `.execute(db);
22
+ }
23
+
24
+ export async function down(db: Kysely<any>): Promise<void> {
25
+ // NOT VALID: cross-region references may already exist; only future writes
26
+ // are constrained again.
27
+ await sql`
28
+ alter table public.tenant
29
+ add constraint tenant_partner_id_fkey
30
+ foreign key (partner_id) references public.tenant(id)
31
+ on update restrict on delete restrict not valid;
32
+ `.execute(db);
33
+ await sql`
34
+ alter table public.tenant
35
+ add constraint tenant_billing_partner_id_fkey
36
+ foreign key (billing_partner_id) references public.tenant(id)
37
+ on update restrict on delete restrict not valid;
38
+ `.execute(db);
39
+ await sql`
40
+ alter table public.tenant
41
+ add constraint tenant_chart_of_account_tenant_id_fkey
42
+ foreign key (chart_of_account_tenant_id) references public.tenant(id)
43
+ on update restrict on delete restrict not valid;
44
+ `.execute(db);
45
+ }
@@ -0,0 +1,100 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ const regionalApiEnvKeys = sql`array[
5
+ 'staging-ap',
6
+ 'staging-crunchy',
7
+ 'staging-eu',
8
+ 'staging-hostaway',
9
+ 'staging-us',
10
+ 'production-ap',
11
+ 'production-crunchy',
12
+ 'production-eu',
13
+ 'production-hostaway',
14
+ 'production-us'
15
+ ]::text[]`;
16
+
17
+ export async function up(db: Kysely<any>): Promise<void> {
18
+ await sql`
19
+ do $$
20
+ begin
21
+ if exists (
22
+ select 1
23
+ from public.app
24
+ cross join lateral jsonb_each(
25
+ coalesce(authentication -> 'defaultConnectParamsByApiEnv', '{}'::jsonb)
26
+ ) as env(key, value)
27
+ where env.key = any(${regionalApiEnvKeys})
28
+ and not (
29
+ coalesce(authentication -> 'defaultConnectParamsByApiEnv', '{}'::jsonb)
30
+ ? split_part(env.key, '-', 1)
31
+ )
32
+ group by public.app.id, split_part(env.key, '-', 1)
33
+ having count(distinct env.value::text) > 1
34
+ ) then
35
+ raise exception
36
+ 'Regional defaultConnectParamsByApiEnv values disagree; add staging/production explicitly before removing regional keys';
37
+ end if;
38
+ end $$;
39
+ `.execute(db);
40
+
41
+ await sql`
42
+ with base_values as (
43
+ select
44
+ public.app.id,
45
+ split_part(env.key, '-', 1) as base_env,
46
+ min(env.value::text)::jsonb as params
47
+ from public.app
48
+ cross join lateral jsonb_each(
49
+ coalesce(authentication -> 'defaultConnectParamsByApiEnv', '{}'::jsonb)
50
+ ) as env(key, value)
51
+ where env.key = any(${regionalApiEnvKeys})
52
+ and not (
53
+ coalesce(authentication -> 'defaultConnectParamsByApiEnv', '{}'::jsonb)
54
+ ? split_part(env.key, '-', 1)
55
+ )
56
+ group by public.app.id, split_part(env.key, '-', 1)
57
+ ),
58
+ per_app as (
59
+ select id, jsonb_object_agg(base_env, params) as params_by_env
60
+ from base_values
61
+ group by id
62
+ )
63
+ update public.app
64
+ set authentication = jsonb_set(
65
+ coalesce(authentication, '{}'::jsonb),
66
+ '{defaultConnectParamsByApiEnv}',
67
+ coalesce(authentication -> 'defaultConnectParamsByApiEnv', '{}'::jsonb)
68
+ || per_app.params_by_env,
69
+ true
70
+ )
71
+ from per_app
72
+ where public.app.id = per_app.id;
73
+ `.execute(db);
74
+
75
+ await sql`
76
+ update public.app
77
+ set authentication = jsonb_set(
78
+ coalesce(authentication, '{}'::jsonb),
79
+ '{defaultConnectParamsByApiEnv}',
80
+ coalesce(authentication -> 'defaultConnectParamsByApiEnv', '{}'::jsonb)
81
+ - 'staging-ap'
82
+ - 'staging-crunchy'
83
+ - 'staging-eu'
84
+ - 'staging-hostaway'
85
+ - 'staging-us'
86
+ - 'production-ap'
87
+ - 'production-crunchy'
88
+ - 'production-eu'
89
+ - 'production-hostaway'
90
+ - 'production-us',
91
+ true
92
+ )
93
+ where coalesce(authentication -> 'defaultConnectParamsByApiEnv', '{}'::jsonb)
94
+ ?| ${regionalApiEnvKeys};
95
+ `.execute(db);
96
+ }
97
+
98
+ export async function down(db: Kysely<any>): Promise<void> {
99
+ await sql`select 1`.execute(db);
100
+ }
@@ -0,0 +1,46 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ export async function up(db: Kysely<any>): Promise<void> {
5
+ await sql`
6
+ create table if not exists public.control_plane_outbox (
7
+ id uuid primary key default gen_random_uuid(),
8
+ aggregate_type text not null,
9
+ aggregate_id text not null,
10
+ event_type text not null,
11
+ event_version integer not null,
12
+ data_region text,
13
+ payload jsonb not null default jsonb_build_object(),
14
+ created_at timestamptz not null default now(),
15
+ published_at timestamptz,
16
+ attempts integer not null default 0,
17
+ last_error text,
18
+ constraint control_plane_outbox_region_check
19
+ check (
20
+ data_region is null
21
+ or data_region in ('ap', 'crunchy', 'eu', 'hostaway', 'us')
22
+ ),
23
+ constraint control_plane_outbox_event_version_check
24
+ check (event_version > 0),
25
+ constraint control_plane_outbox_aggregate_version_key
26
+ unique (aggregate_type, aggregate_id, event_version)
27
+ );
28
+ `.execute(db);
29
+
30
+ await sql`
31
+ create index if not exists control_plane_outbox_pending_idx
32
+ on public.control_plane_outbox (created_at, id)
33
+ where published_at is null;
34
+ `.execute(db);
35
+
36
+ await sql`
37
+ create index if not exists control_plane_outbox_aggregate_idx
38
+ on public.control_plane_outbox (aggregate_type, aggregate_id, created_at);
39
+ `.execute(db);
40
+ }
41
+
42
+ export async function down(db: Kysely<any>): Promise<void> {
43
+ await sql`
44
+ drop table if exists public.control_plane_outbox;
45
+ `.execute(db);
46
+ }
@@ -0,0 +1,16 @@
1
+ import type { Kysely } from 'kysely';
2
+ import { sql } from 'kysely';
3
+
4
+ export async function up(db: Kysely<any>): Promise<void> {
5
+ await sql`
6
+ alter table accounting.contact
7
+ add column ramp_last4_digits text;
8
+ `.execute(db);
9
+ }
10
+
11
+ export async function down(db: Kysely<any>): Promise<void> {
12
+ await sql`
13
+ alter table accounting.contact
14
+ drop column if exists ramp_last4_digits;
15
+ `.execute(db);
16
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["camel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CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;gBAAE,SAAS;YAExC,MAAM,IAAI,WAAW,CAAC,SAAS,KAAK,CAAC,IAAI,sBAAsB,CAAC,CAAC;QACnE,CAAC;IAAA,CACF;IAES,MAAM,CAAC,GAAG,EAAE;QACpB,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;IAAA,CACf;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 ${alias.name} contains underscore`);\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,GAIhB,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,IAAI;QAClB,OAAO,KAAK,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;IAED,cAAc,CAAC,IAAI;QACjB,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,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,CA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AC,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 ${alias.name} contains underscore`);\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"]}
@@ -0,0 +1,142 @@
1
+ import type { ColumnType, Kysely as K } from 'kysely';
2
+ export type Generated<T> = T extends ColumnType<infer S, infer I, infer U> ? ColumnType<S, I | undefined, U> : ColumnType<T, T | undefined, T>;
3
+ export type Json = JsonValue;
4
+ export type JsonArray = JsonValue[];
5
+ export type JsonObject = {
6
+ [x: string]: JsonValue | undefined;
7
+ };
8
+ export type JsonPrimitive = boolean | number | string | null;
9
+ export type JsonValue = JsonArray | JsonObject | JsonPrimitive;
10
+ export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;
11
+ export interface ControlPlaneApp {
12
+ authentication: Generated<Json>;
13
+ category: string | null;
14
+ color: string | null;
15
+ createdAt: Generated<Timestamp>;
16
+ icon: string | null;
17
+ iconRound: string | null;
18
+ id: Generated<string>;
19
+ info: Json | null;
20
+ name: string;
21
+ type: string;
22
+ version: Generated<number>;
23
+ }
24
+ export interface ControlPlaneBookingChannel {
25
+ channelRef: string | null;
26
+ color: string | null;
27
+ createdAt: Generated<Timestamp>;
28
+ icon: string | null;
29
+ iconProvider: string | null;
30
+ id: Generated<string>;
31
+ lastGenerateRun: Timestamp | null;
32
+ logo: string | null;
33
+ logoProvider: string | null;
34
+ selectedBookingChannelIconCandidateId: string | null;
35
+ selectedBookingChannelLogoCandidateId: string | null;
36
+ uniqueRef: string;
37
+ updatedAt: Generated<Timestamp>;
38
+ }
39
+ export interface ControlPlaneCurrency {
40
+ name: string;
41
+ }
42
+ export interface ControlPlaneConnectionRoute {
43
+ connectionId: string;
44
+ createdAt: Generated<Timestamp>;
45
+ tenantId: string;
46
+ updatedAt: Generated<Timestamp>;
47
+ }
48
+ export interface ControlPlaneFeature {
49
+ createdAt: Generated<Timestamp>;
50
+ description: string | null;
51
+ id: Generated<string>;
52
+ issueUrl: string | null;
53
+ requiredApprovals: Generated<Json | null>;
54
+ status: Generated<string | null>;
55
+ tenantId: string | null;
56
+ title: string;
57
+ updatedAt: Generated<Timestamp>;
58
+ url: string | null;
59
+ }
60
+ export interface ControlPlaneFeatureEnabledTeam {
61
+ createdAt: Generated<Timestamp>;
62
+ featureId: string;
63
+ id: Generated<string>;
64
+ status: Generated<string | null>;
65
+ tenantId: string;
66
+ updatedAt: Generated<Timestamp>;
67
+ }
68
+ export interface ControlPlaneOutbox {
69
+ aggregateId: string;
70
+ aggregateType: string;
71
+ attempts: Generated<number>;
72
+ createdAt: Generated<Timestamp>;
73
+ dataRegion: string | null;
74
+ eventType: string;
75
+ eventVersion: number;
76
+ id: Generated<string>;
77
+ lastError: string | null;
78
+ payload: Generated<Json>;
79
+ publishedAt: Timestamp | null;
80
+ }
81
+ export interface ControlPlaneTenant {
82
+ billingPlan: string | null;
83
+ createdAt: Generated<Timestamp>;
84
+ dataRegion: Generated<string>;
85
+ id: Generated<string>;
86
+ name: string;
87
+ partnerId: string | null;
88
+ slug: string;
89
+ status: Generated<string | null>;
90
+ storageRealm: Generated<string>;
91
+ type: Generated<string | null>;
92
+ updatedAt: Generated<Timestamp | null>;
93
+ }
94
+ export interface ControlPlaneTenantUser {
95
+ createdAt: Generated<Timestamp | null>;
96
+ id: Generated<string>;
97
+ lastInvitedAt: Timestamp | null;
98
+ role: Generated<string | null>;
99
+ status: Generated<string | null>;
100
+ tenantId: string;
101
+ updatedAt: Generated<Timestamp | null>;
102
+ userId: string;
103
+ }
104
+ export interface ControlPlaneToken {
105
+ createdAt: Generated<Timestamp>;
106
+ expiresAt: Timestamp | null;
107
+ id: Generated<string>;
108
+ nanoId: Generated<string>;
109
+ payload: Generated<Json>;
110
+ tenantId: string | null;
111
+ type: string | null;
112
+ userId: string | null;
113
+ }
114
+ export interface ControlPlaneUser {
115
+ clerkId: string | null;
116
+ createdAt: Generated<Timestamp | null>;
117
+ email: string | null;
118
+ firstName: string | null;
119
+ id: Generated<string>;
120
+ isAdmin: Generated<boolean>;
121
+ lastName: string | null;
122
+ name: string | null;
123
+ partnerId: string | null;
124
+ status: Generated<string | null>;
125
+ sub: string | null;
126
+ type: Generated<string | null>;
127
+ updatedAt: Generated<Timestamp | null>;
128
+ }
129
+ export interface ControlPlaneDB {
130
+ 'public.app': ControlPlaneApp;
131
+ 'public.bookingChannel': ControlPlaneBookingChannel;
132
+ 'public.connectionRoute': ControlPlaneConnectionRoute;
133
+ 'public.currency': ControlPlaneCurrency;
134
+ 'public.feature': ControlPlaneFeature;
135
+ 'public.featureEnabledTeam': ControlPlaneFeatureEnabledTeam;
136
+ 'public.controlPlaneOutbox': ControlPlaneOutbox;
137
+ 'public.tenant': ControlPlaneTenant;
138
+ 'public.tenantUser': ControlPlaneTenantUser;
139
+ 'public.token': ControlPlaneToken;
140
+ 'public.user': ControlPlaneUser;
141
+ }
142
+ export type ControlPlaneKysely = K<ControlPlaneDB>;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["control-plane/index.ts"],"names":[],"mappings":"","sourcesContent":["import type { ColumnType, Kysely as K } from 'kysely';\n\nexport type Generated<T> =\n T extends ColumnType<infer S, infer I, infer U>\n ? ColumnType<S, I | undefined, U>\n : ColumnType<T, T | undefined, T>;\n\nexport type Json = JsonValue;\n\nexport type JsonArray = JsonValue[];\n\nexport type JsonObject = {\n [x: string]: JsonValue | undefined;\n};\n\nexport type JsonPrimitive = boolean | number | string | null;\n\nexport type JsonValue = JsonArray | JsonObject | JsonPrimitive;\n\nexport type Timestamp = ColumnType<Date | string, Date | string, Date | string>;\n\nexport interface ControlPlaneApp {\n authentication: Generated<Json>;\n category: string | null;\n color: string | null;\n createdAt: Generated<Timestamp>;\n icon: string | null;\n iconRound: string | null;\n id: Generated<string>;\n info: Json | null;\n name: string;\n type: string;\n version: Generated<number>;\n}\n\nexport interface ControlPlaneBookingChannel {\n channelRef: string | null;\n color: string | null;\n createdAt: Generated<Timestamp>;\n icon: string | null;\n iconProvider: string | null;\n id: Generated<string>;\n lastGenerateRun: Timestamp | null;\n logo: string | null;\n logoProvider: string | null;\n selectedBookingChannelIconCandidateId: string | null;\n selectedBookingChannelLogoCandidateId: string | null;\n uniqueRef: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneCurrency {\n name: string;\n}\n\nexport interface ControlPlaneConnectionRoute {\n connectionId: string;\n createdAt: Generated<Timestamp>;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneFeature {\n createdAt: Generated<Timestamp>;\n description: string | null;\n id: Generated<string>;\n issueUrl: string | null;\n requiredApprovals: Generated<Json | null>;\n status: Generated<string | null>;\n tenantId: string | null;\n title: string;\n updatedAt: Generated<Timestamp>;\n url: string | null;\n}\n\nexport interface ControlPlaneFeatureEnabledTeam {\n createdAt: Generated<Timestamp>;\n featureId: string;\n id: Generated<string>;\n status: Generated<string | null>;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneOutbox {\n aggregateId: string;\n aggregateType: string;\n attempts: Generated<number>;\n createdAt: Generated<Timestamp>;\n dataRegion: string | null;\n eventType: string;\n eventVersion: number;\n id: Generated<string>;\n lastError: string | null;\n payload: Generated<Json>;\n publishedAt: Timestamp | null;\n}\n\nexport interface ControlPlaneTenant {\n billingPlan: string | null;\n createdAt: Generated<Timestamp>;\n dataRegion: Generated<string>;\n id: Generated<string>;\n name: string;\n partnerId: string | null;\n slug: string;\n status: Generated<string | null>;\n storageRealm: Generated<string>;\n type: Generated<string | null>;\n updatedAt: Generated<Timestamp | null>;\n}\n\nexport interface ControlPlaneTenantUser {\n createdAt: Generated<Timestamp | null>;\n id: Generated<string>;\n lastInvitedAt: Timestamp | null;\n role: Generated<string | null>;\n status: Generated<string | null>;\n tenantId: string;\n updatedAt: Generated<Timestamp | null>;\n userId: string;\n}\n\nexport interface ControlPlaneToken {\n createdAt: Generated<Timestamp>;\n expiresAt: Timestamp | null;\n id: Generated<string>;\n nanoId: Generated<string>;\n payload: Generated<Json>;\n tenantId: string | null;\n type: string | null;\n userId: string | null;\n}\n\nexport interface ControlPlaneUser {\n clerkId: string | null;\n createdAt: Generated<Timestamp | null>;\n email: string | null;\n firstName: string | null;\n id: Generated<string>;\n isAdmin: Generated<boolean>;\n lastName: string | null;\n name: string | null;\n partnerId: string | null;\n status: Generated<string | null>;\n sub: string | null;\n type: Generated<string | null>;\n updatedAt: Generated<Timestamp | null>;\n}\n\nexport interface ControlPlaneDB {\n 'public.app': ControlPlaneApp;\n 'public.bookingChannel': ControlPlaneBookingChannel;\n 'public.connectionRoute': ControlPlaneConnectionRoute;\n 'public.currency': ControlPlaneCurrency;\n 'public.feature': ControlPlaneFeature;\n 'public.featureEnabledTeam': ControlPlaneFeatureEnabledTeam;\n 'public.controlPlaneOutbox': ControlPlaneOutbox;\n 'public.tenant': ControlPlaneTenant;\n 'public.tenantUser': ControlPlaneTenantUser;\n 'public.token': ControlPlaneToken;\n 'public.user': ControlPlaneUser;\n}\n\nexport type ControlPlaneKysely = K<ControlPlaneDB>;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","sourceRoot":"src/","sources":["error.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,YAAY,OAAe,EAAE;QAC3B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAAA,CAC3B;CACF","sourcesContent":["export class KyselyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'KyselyError';\n }\n}\n"]}
1
+ {"version":3,"file":"error.js","sourceRoot":"src/","sources":["error.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,WAAY,SAAQ,KAAK;IACpC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF","sourcesContent":["export class KyselyError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'KyselyError';\n }\n}\n"]}
@@ -1,9 +1,10 @@
1
1
  import type { Kysely as K, LogConfig } from 'kysely';
2
- import { type Sql } from 'postgres';
2
+ import postgres, { type Sql } from 'postgres';
3
3
  export type { Insertable, LogEvent } from 'kysely';
4
4
  export * from './error';
5
5
  export * from './isomorphic';
6
6
  export * from './query';
7
+ export * from './regional';
7
8
  export * from './transaction';
8
9
  import type { DB } from './v1.generated';
9
10
  type KyselyOpts = {
@@ -12,6 +13,7 @@ type KyselyOpts = {
12
13
  };
13
14
  type PgOpt = {
14
15
  forceDisableSSL?: boolean;
16
+ probe?: false;
15
17
  retries?: false | number;
16
18
  };
17
19
  export type Kysely = K<DB>;
@@ -20,12 +22,12 @@ export type Postgres = Sql;
20
22
  * @deprecated This method is deprecated in favor of the useAsyncKysely method.
21
23
  */
22
24
  export declare function useKysely(postgres: Sql, options?: KyselyOpts): K<DB>;
23
- export declare function useAsyncPostgres(connectionString: string, opt?: PgOpt): Promise<Sql<{}>>;
25
+ export declare function useAsyncPostgres(connectionString: string, opt?: PgOpt): Promise<postgres.Sql<{}>>;
24
26
  export declare function useAsyncKysely(connectionString: string, opt?: PgOpt & KyselyOpts): Promise<K<DB>>;
25
27
  /**
26
28
  * @deprecated This method is deprecated in favor of the useAsyncKysely method.
27
29
  */
28
- export declare function usePostgres(connectionString?: string, opt?: Pick<PgOpt, 'forceDisableSSL'>): Sql<{}>;
30
+ export declare function usePostgres(connectionString?: string, opt?: Pick<PgOpt, 'forceDisableSSL'>): postgres.Sql<{}>;
29
31
  export declare function forceCloseAllPostgres(timeoutMs?: number): Promise<void>;
30
32
  export declare class DatabaseError extends Error {
31
33
  constructor(message: string, cause: any);
@@ -6,6 +6,7 @@ import { getKysely } from './plugins';
6
6
  export * from './error';
7
7
  export * from './isomorphic';
8
8
  export * from './query';
9
+ export * from './regional';
9
10
  export * from './transaction';
10
11
  import { parseDuration } from '@vrplatform/utils';
11
12
  const retryableMessages = ['CONNECTION_CLOSED'];
@@ -50,7 +51,7 @@ export function useKysely(postgres, options) {
50
51
  let _connections = [];
51
52
  export async function useAsyncPostgres(connectionString, opt) {
52
53
  const delayMs = 2500;
53
- const retries = opt?.retries === false ? 0 : opt?.retries || 3;
54
+ const retries = opt?.probe === false ? 1 : opt?.retries === false ? 0 : opt?.retries || 3;
54
55
  const ssl = opt?.forceDisableSSL !== true;
55
56
  const url = new URL(connectionString);
56
57
  console.debug(`Creating Postgres connection with ${retries} retries and ssl=${ssl} and port=${url.port}`);
@@ -67,15 +68,12 @@ export async function useAsyncPostgres(connectionString, opt) {
67
68
  connect_timeout: 10,
68
69
  idle_timeout: 60,
69
70
  });
70
- await sql `select 1`;
71
- try {
72
- // connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off
73
- await sql `set statement_timeout to '30s';`;
74
- await sql `set lock_timeout to '10s';`;
75
- }
76
- catch (e) {
77
- console.warn('Failed to set statement timeout, continuing', e);
71
+ if (opt?.probe !== false) {
72
+ await sql `select 1`;
78
73
  }
74
+ // statement_timeout/lock_timeout are role-level settings on the cluster
75
+ // (ALTER ROLE application SET ...) so they cover every pooled
76
+ // connection; per-session SETs here only ever applied to one of them
79
77
  _connections.push(sql);
80
78
  return sql;
81
79
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAE9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,QAAsB,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGtC,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,eAAe,CAAC;AAE9B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAalD,MAAM,iBAAiB,GAAG,CAAC,mBAAmB,CAAC,CAAC;AAIhD;;GAEG;AACH,MAAM,UAAU,SAAS,CAAC,QAAa,EAAE,OAAoB,EAAE;IAC7D,OAAO,CAAC,KAAK,CAAC,0BAA0B,CAAC,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AAe,KAAK,IAAI,CAAC;IAC1C,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;IACtC,OAAO,CAAC,KAAK,CACX,8CAA8C,GAAG,aAAa,GAAG,CAAC,IAAI,EAAE,CACzE,CAAC;IACF,MAAM,EAAE,GAAG,QAAQ,CAAC,gBAAgB,EAAE;QACpC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK;KAC7B,CAAC,CAAC;IACH,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACtB,OAAO,EAAE,CAAC;AAAA,CACX;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI,EAAE;IAC5D,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,CAAC,GAAG,CACT,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACtB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CACtD,CACF;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AAAA,CACnB;AAED,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU,EAAE;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAAA,CACpB;CACF","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport type { Kysely as K, LogConfig } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './query';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n retries?: false | number;\n};\n\nconst retryableMessages = ['CONNECTION_CLOSED'];\n\nexport type Kysely = K<DB>;\nexport type Postgres = Sql;\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function useKysely(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const kysely = getKysely(\n new PostgresJSDialect({\n postgres,\n onReserveConnection: async (connection) => {\n const executeQuery = connection.executeQuery.bind(connection);\n connection.executeQuery = (arg) =>\n backOff(async () => await executeQuery(arg), {\n numOfAttempts: 3,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (retryableMessages.some((m) => message?.includes(m))) {\n return true;\n }\n return false;\n },\n });\n },\n }),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await Promise.race([\n postgres.end({ timeout: 5000 }).catch(() => undefined),\n new Promise((res) => setTimeout(res, 6000)),\n ]);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const retries = opt?.retries === false ? 0 : opt?.retries || 3;\n const ssl = opt?.forceDisableSSL !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with ${retries} retries and ssl=${ssl} and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n // connect_timeout: 10\n // idle_timeout: 10\n // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\n connect_timeout: 10,\n idle_timeout: 60,\n });\n\n await sql`select 1`;\n try {\n // connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off\n await sql`set statement_timeout to '30s';`;\n await sql`set lock_timeout to '10s';`;\n } catch (e) {\n console.warn('Failed to set statement timeout, continuing', e);\n }\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new KyselyError('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\n}\n\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function usePostgres(\n connectionString?: string,\n opt?: Pick<PgOpt, 'forceDisableSSL'>\n) {\n if (!connectionString) throw new KyselyError('No connection string');\n const ssl = opt?.forceDisableSSL !== true;\n const url = new URL(connectionString);\n console.debug(\n `Creating sync Postgres connection with ssl=${ssl} and port=${url.port}`\n );\n const pg = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n });\n _connections.push(pg);\n return pg;\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,C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AAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AACpB,CAAC;AAED,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU;QACrC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport type { Kysely as K, LogConfig } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './query';\nexport * from './regional';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n probe?: false;\n retries?: false | number;\n};\n\nconst retryableMessages = ['CONNECTION_CLOSED'];\n\nexport type Kysely = K<DB>;\nexport type Postgres = Sql;\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function useKysely(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const kysely = getKysely(\n new PostgresJSDialect({\n postgres,\n onReserveConnection: async (connection) => {\n const executeQuery = connection.executeQuery.bind(connection);\n connection.executeQuery = (arg) =>\n backOff(async () => await executeQuery(arg), {\n numOfAttempts: 3,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (retryableMessages.some((m) => message?.includes(m))) {\n return true;\n }\n return false;\n },\n });\n },\n }),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await Promise.race([\n postgres.end({ timeout: 5000 }).catch(() => undefined),\n new Promise((res) => setTimeout(res, 6000)),\n ]);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const retries =\n opt?.probe === false ? 1 : opt?.retries === false ? 0 : opt?.retries || 3;\n const ssl = opt?.forceDisableSSL !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with ${retries} retries and ssl=${ssl} and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n // connect_timeout: 10\n // idle_timeout: 10\n // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\n connect_timeout: 10,\n idle_timeout: 60,\n });\n\n if (opt?.probe !== false) {\n await sql`select 1`;\n }\n // statement_timeout/lock_timeout are role-level settings on the cluster\n // (ALTER ROLE application SET ...) so they cover every pooled\n // connection; per-session SETs here only ever applied to one of them\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new KyselyError('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\n}\n\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function usePostgres(\n connectionString?: string,\n opt?: Pick<PgOpt, 'forceDisableSSL'>\n) {\n if (!connectionString) throw new KyselyError('No connection string');\n const ssl = opt?.forceDisableSSL !== true;\n const url = new URL(connectionString);\n console.debug(\n `Creating sync Postgres connection with ssl=${ssl} and port=${url.port}`\n );\n const pg = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n });\n _connections.push(pg);\n return pg;\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,cAAc,gBAAgB,CAAC;AAM/B,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAI7B,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU,EAAE;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAAA,CACpB;CACF","sourcesContent":["import type {\n ControlledTransaction as CT,\n Kysely as K,\n Transaction as T,\n} from 'kysely';\n\nexport type {\n ColumnType,\n Expression,\n ExpressionBuilder,\n ExpressionOrFactory,\n Generated,\n Insertable,\n JSONColumnType,\n KyselyPlugin,\n Nullable,\n OperandExpression,\n PluginTransformQueryArgs,\n PluginTransformResultArgs,\n QueryResult,\n RootOperationNode,\n Selectable,\n SelectQueryBuilder,\n SqlBool,\n UnknownRow,\n Updateable,\n} from 'kysely';\nexport { jsonArrayFrom } from 'kysely/helpers/postgres';\nexport * from './v1.generated';\n\nimport type { DB } from './v1.generated';\n\nexport type Transaction = T<DB>;\nexport type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;\nexport { sql } from 'kysely';\n\nexport type Kysely = K<DB>;\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n"]}
1
+ {"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,cAAc,gBAAgB,CAAC;AAM/B,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC;AAI7B,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe,EAAE,KAAU;QACrC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF","sourcesContent":["import type {\n ControlledTransaction as CT,\n Kysely as K,\n Transaction as T,\n} from 'kysely';\n\nexport type {\n ColumnType,\n Expression,\n ExpressionBuilder,\n ExpressionOrFactory,\n Generated,\n Insertable,\n JSONColumnType,\n KyselyPlugin,\n Nullable,\n OperandExpression,\n PluginTransformQueryArgs,\n PluginTransformResultArgs,\n QueryResult,\n RootOperationNode,\n Selectable,\n SelectQueryBuilder,\n SqlBool,\n UnknownRow,\n Updateable,\n} from 'kysely';\nexport { jsonArrayFrom } from 'kysely/helpers/postgres';\nexport * from './v1.generated';\n\nimport type { DB } from './v1.generated';\n\nexport type Transaction = T<DB>;\nexport type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;\nexport { sql } from 'kysely';\n\nexport type Kysely = K<DB>;\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n"]}