@remit/backend 0.0.89 → 0.0.91

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.
@@ -0,0 +1,384 @@
1
+ import type {
2
+ CalendarResponse,
3
+ CreateCalendarInput,
4
+ UpdateCalendarInput,
5
+ } from "@remit/api-openapi-types";
6
+ import {
7
+ DEFAULT_CALENDAR_URL_SEGMENT,
8
+ isResolvableZone,
9
+ provisionDefaultCalendar,
10
+ putCalendarObject,
11
+ } from "@remit/calendar-service";
12
+ import type {
13
+ CalendarCollectionItem,
14
+ ICalendarCollectionRepository,
15
+ ICalendarEventIndexRepository,
16
+ ICalendarObjectRepository,
17
+ ICalendarUnitOfWork,
18
+ UpdateCalendarCollectionInput,
19
+ } from "@remit/data-ports";
20
+ import { normalizeCalendarUrlSegment } from "@remit/data-ports/id";
21
+ import { CalendarSource } from "@remit/domain-enums";
22
+ import type { APIGatewayProxyEvent } from "aws-lambda";
23
+ import { getAccountConfigIdFromEvent } from "../auth.js";
24
+ import type { RemitClient } from "../service/data-client.js";
25
+ import { getClient } from "../service/data-client.js";
26
+ import type {
27
+ CalendarDetailOperationIds,
28
+ CalendarOperationIds,
29
+ OperationHandler,
30
+ } from "../types.js";
31
+
32
+ /** The calendar store, as the handlers reach it. */
33
+ export interface CalendarDeps {
34
+ calendarCollection: ICalendarCollectionRepository;
35
+ calendarObject: ICalendarObjectRepository;
36
+ calendarEventIndex: ICalendarEventIndexRepository;
37
+ calendarUnitOfWork: ICalendarUnitOfWork;
38
+ }
39
+
40
+ /** Why a calendar request was refused, in a form a client can branch on. */
41
+ export interface CalendarRefusal {
42
+ code: string;
43
+ message: string;
44
+ }
45
+
46
+ /**
47
+ * A refusal is a value here, not a throw. Every one of these is something the
48
+ * caller sent — a window that runs backwards, a segment already taken, a
49
+ * RECURRENCE-ID naming no occurrence — so it is an ordinary outcome of the
50
+ * request rather than a fault of the server's.
51
+ */
52
+ export type CalendarOutcome<T> =
53
+ | { ok: true; value: T }
54
+ | { ok: false; error: CalendarRefusal };
55
+
56
+ export const refuseCalendar = <T>(
57
+ code: string,
58
+ message: string,
59
+ ): CalendarOutcome<T> => ({ ok: false, error: { code, message } });
60
+
61
+ export const badRequest = (error: CalendarRefusal) => ({
62
+ statusCode: 400,
63
+ body: error,
64
+ });
65
+
66
+ export const notFound = (message: string) => ({
67
+ statusCode: 404,
68
+ body: { code: "NotFound", message },
69
+ });
70
+
71
+ export const preconditionFailed = (message: string) => ({
72
+ statusCode: 412,
73
+ body: { code: "EtagMismatch", message },
74
+ });
75
+
76
+ /** The calendar half of the client, named so a handler takes only what it uses. */
77
+ export const calendarDepsOf = (client: RemitClient): CalendarDeps => ({
78
+ calendarCollection: client.calendarCollection,
79
+ calendarObject: client.calendarObject,
80
+ calendarEventIndex: client.calendarEventIndex,
81
+ calendarUnitOfWork: client.calendarUnitOfWork,
82
+ });
83
+
84
+ const toCalendarResponse = (
85
+ item: CalendarCollectionItem,
86
+ ): CalendarResponse => ({
87
+ calendarId: item.calendarId,
88
+ accountConfigId: item.accountConfigId,
89
+ urlSegment: item.urlSegment,
90
+ displayName: item.displayName,
91
+ color: item.color,
92
+ componentSet: item.componentSet,
93
+ source: item.source,
94
+ timezone: item.timezone,
95
+ syncSequence: item.syncSequence,
96
+ createdAt: item.createdAt,
97
+ updatedAt: item.updatedAt,
98
+ });
99
+
100
+ /**
101
+ * Every collection the account config holds, provisioning the default one when
102
+ * it holds none.
103
+ *
104
+ * Safe to race with itself: `calendarId` is derived from the account config and
105
+ * the URL segment, so two first reads arriving together write the same row
106
+ * rather than two, and the loser's write is a no-op instead of a second
107
+ * calendar nobody asked for.
108
+ */
109
+ export const listCalendarsFor = async (
110
+ deps: CalendarDeps,
111
+ accountConfigId: string,
112
+ ): Promise<CalendarCollectionItem[]> => {
113
+ const existing =
114
+ await deps.calendarCollection.listByAccountConfig(accountConfigId);
115
+ if (existing.length > 0) return existing;
116
+
117
+ await provisionDefaultCalendar(deps.calendarUnitOfWork, accountConfigId);
118
+ return deps.calendarCollection.listByAccountConfig(accountConfigId);
119
+ };
120
+
121
+ /** One of the caller's collections, or a refusal naming the one they asked for. */
122
+ export const findCalendarFor = async (
123
+ deps: CalendarDeps,
124
+ accountConfigId: string,
125
+ calendarId: string,
126
+ ): Promise<CalendarOutcome<CalendarCollectionItem>> => {
127
+ const collections =
128
+ await deps.calendarCollection.listByAccountConfig(accountConfigId);
129
+ const found = collections.find(
130
+ (collection) => collection.calendarId === calendarId,
131
+ );
132
+ if (!found) {
133
+ return refuseCalendar(
134
+ "NotFound",
135
+ `no calendar ${calendarId} on this account`,
136
+ );
137
+ }
138
+ return { ok: true, value: found };
139
+ };
140
+
141
+ /**
142
+ * A collection's timezone is what every floating time in it is read in, so a
143
+ * name this server cannot resolve is not a cosmetic setting — it silently moves
144
+ * every all-day and unzoned event in the calendar. A Windows zone name, which
145
+ * is what a client that has not normalised its input sends, is refused here
146
+ * rather than stored and quietly read as UTC.
147
+ */
148
+ export const readCollectionTimezone = (
149
+ timezone: string | undefined,
150
+ ): CalendarOutcome<string> => {
151
+ if (timezone === undefined || timezone === "") return { ok: true, value: "" };
152
+ if (!isResolvableZone(timezone)) {
153
+ return refuseCalendar(
154
+ "UnknownTimeZone",
155
+ `"${timezone}" is not a time zone this server can resolve — use an IANA name such as "Europe/Amsterdam"`,
156
+ );
157
+ }
158
+ return { ok: true, value: timezone };
159
+ };
160
+
161
+ export const createCalendarFor = async (
162
+ deps: CalendarDeps,
163
+ accountConfigId: string,
164
+ input: CreateCalendarInput,
165
+ ): Promise<CalendarOutcome<CalendarCollectionItem>> => {
166
+ const urlSegment = normalizeCalendarUrlSegment(input.urlSegment);
167
+ if (urlSegment === "") {
168
+ return refuseCalendar(
169
+ "InvalidUrlSegment",
170
+ "a calendar needs a url segment to be addressed by",
171
+ );
172
+ }
173
+
174
+ const timezone = readCollectionTimezone(input.timezone);
175
+ if (!timezone.ok) return timezone;
176
+
177
+ // The write decides, not a prior read: two creates of one segment arriving
178
+ // together would both find it free, and the loser would silently be handed
179
+ // the winner's calendar to write into.
180
+ const created = await deps.calendarUnitOfWork.transaction((repos) =>
181
+ repos.calendarCollection.createExclusive({
182
+ accountConfigId,
183
+ urlSegment,
184
+ displayName: input.displayName,
185
+ color: input.color,
186
+ timezone: timezone.value,
187
+ source: CalendarSource.UserCreated,
188
+ }),
189
+ );
190
+ if (!created) {
191
+ return refuseCalendar(
192
+ "UrlSegmentTaken",
193
+ `"${urlSegment}" already addresses a calendar on this account — pick another`,
194
+ );
195
+ }
196
+ return { ok: true, value: created };
197
+ };
198
+
199
+ /**
200
+ * Removes a collection with everything in it, in one unit.
201
+ *
202
+ * The default collection stays: it is where an accepted invitation and a first
203
+ * event land, and an account config with no calendar has nowhere to put one.
204
+ */
205
+ export const deleteCalendarFor = async (
206
+ deps: CalendarDeps,
207
+ accountConfigId: string,
208
+ calendarId: string,
209
+ ): Promise<CalendarOutcome<null>> => {
210
+ const collection = await findCalendarFor(deps, accountConfigId, calendarId);
211
+ if (!collection.ok) return collection;
212
+ if (collection.value.source === CalendarSource.Default) {
213
+ return refuseCalendar(
214
+ "DefaultCalendarUndeletable",
215
+ `"${DEFAULT_CALENDAR_URL_SEGMENT}" is the calendar this account files events into and cannot be removed`,
216
+ );
217
+ }
218
+
219
+ await deps.calendarUnitOfWork.transaction(async (repos) => {
220
+ const objects = await repos.calendarObject.listByCalendar(calendarId);
221
+ for (const object of objects) {
222
+ await repos.calendarEventIndex.deleteForObject(
223
+ calendarId,
224
+ object.calendarObjectId,
225
+ );
226
+ await repos.calendarObject.delete(calendarId, object.calendarObjectId);
227
+ }
228
+ await repos.calendarCollection.delete(accountConfigId, calendarId);
229
+ });
230
+ return { ok: true, value: null };
231
+ };
232
+
233
+ /**
234
+ * Reduce a PATCH body to the fields a collection update may set. `urlSegment`
235
+ * is deliberately absent: it is the collection's identity and the path a client
236
+ * has bookmarked, so moving it is making a different calendar.
237
+ */
238
+ export const pickCalendarUpdate = (
239
+ body: Partial<UpdateCalendarInput>,
240
+ ): UpdateCalendarCollectionInput => {
241
+ const patch: UpdateCalendarCollectionInput = {};
242
+ if (Object.hasOwn(body, "displayName")) patch.displayName = body.displayName;
243
+ if (Object.hasOwn(body, "color")) patch.color = body.color;
244
+ if (Object.hasOwn(body, "timezone")) patch.timezone = body.timezone;
245
+ return patch;
246
+ };
247
+
248
+ /**
249
+ * Applies a collection patch, rewriting what the collection's timezone decides.
250
+ *
251
+ * The timezone is not a label. Every floating and all-day time in the
252
+ * collection is read in it, so changing it moves every occurrence row those
253
+ * resources produced — and a row left at the old zone is an event drawn hours
254
+ * from where the calendar now says it is. Each resource is therefore written
255
+ * again from its own stored bytes, which re-projects and re-expands it and
256
+ * bumps the collection's sequence so a syncing client sees the change. The
257
+ * whole set is one unit: a half-converted calendar is worse than either zone.
258
+ */
259
+ export const updateCalendarFor = async (
260
+ deps: CalendarDeps,
261
+ accountConfigId: string,
262
+ calendarId: string,
263
+ body: Partial<UpdateCalendarInput>,
264
+ ): Promise<CalendarOutcome<CalendarCollectionItem>> => {
265
+ const current = await findCalendarFor(deps, accountConfigId, calendarId);
266
+ if (!current.ok) return current;
267
+
268
+ const patch = pickCalendarUpdate(body);
269
+ if (patch.timezone !== undefined) {
270
+ const timezone = readCollectionTimezone(patch.timezone);
271
+ if (!timezone.ok) return timezone;
272
+ patch.timezone = timezone.value;
273
+ }
274
+ const rezone =
275
+ patch.timezone !== undefined && patch.timezone !== current.value.timezone;
276
+
277
+ const updated = await deps.calendarUnitOfWork.transaction(async (repos) => {
278
+ const collection = await repos.calendarCollection.update(
279
+ accountConfigId,
280
+ calendarId,
281
+ patch,
282
+ );
283
+ if (!rezone) return collection;
284
+
285
+ const objects = await repos.calendarObject.listByCalendar(calendarId);
286
+ for (const object of objects) {
287
+ const rewritten = await putCalendarObject(deps.calendarUnitOfWork, {
288
+ accountConfigId,
289
+ calendarId,
290
+ resourceName: object.resourceName,
291
+ icalData: object.icalData,
292
+ });
293
+ if (!rewritten.ok) {
294
+ throw new Error(
295
+ `stored calendar object ${object.calendarObjectId} was refused on re-expansion: ${rewritten.error.code}`,
296
+ );
297
+ }
298
+ }
299
+ return repos.calendarCollection.get(accountConfigId, calendarId);
300
+ });
301
+ return { ok: true, value: updated };
302
+ };
303
+
304
+ export const CalendarOperations: Record<
305
+ CalendarOperationIds,
306
+ OperationHandler<CalendarOperationIds>
307
+ > = {
308
+ CalendarOperations_listCalendars: async (_context, ...args: unknown[]) => {
309
+ const event = args[0] as APIGatewayProxyEvent;
310
+ const accountConfigId = getAccountConfigIdFromEvent(event);
311
+ const deps = calendarDepsOf(await getClient());
312
+ const items = await listCalendarsFor(deps, accountConfigId);
313
+ return { items: items.map(toCalendarResponse) };
314
+ },
315
+
316
+ CalendarOperations_createCalendar: async (context, ...args: unknown[]) => {
317
+ const event = args[0] as APIGatewayProxyEvent;
318
+ const accountConfigId = getAccountConfigIdFromEvent(event);
319
+ const input = context.request.requestBody as CreateCalendarInput;
320
+ const deps = calendarDepsOf(await getClient());
321
+
322
+ const created = await createCalendarFor(deps, accountConfigId, input);
323
+ if (!created.ok) return badRequest(created.error);
324
+ return toCalendarResponse(created.value);
325
+ },
326
+ };
327
+
328
+ export const CalendarDetailOperations: Record<
329
+ CalendarDetailOperationIds,
330
+ OperationHandler<CalendarDetailOperationIds>
331
+ > = {
332
+ CalendarDetailOperations_getCalendar: async (context, ...args: unknown[]) => {
333
+ const event = args[0] as APIGatewayProxyEvent;
334
+ const accountConfigId = getAccountConfigIdFromEvent(event);
335
+ const { calendarId } = context.request.params as { calendarId: string };
336
+ const deps = calendarDepsOf(await getClient());
337
+
338
+ const found = await findCalendarFor(deps, accountConfigId, calendarId);
339
+ if (!found.ok) return notFound(found.error.message);
340
+ return toCalendarResponse(found.value);
341
+ },
342
+
343
+ CalendarDetailOperations_updateCalendar: async (
344
+ context,
345
+ ...args: unknown[]
346
+ ) => {
347
+ const event = args[0] as APIGatewayProxyEvent;
348
+ const accountConfigId = getAccountConfigIdFromEvent(event);
349
+ const { calendarId } = context.request.params as { calendarId: string };
350
+ const body = context.request.requestBody as Partial<UpdateCalendarInput>;
351
+ const deps = calendarDepsOf(await getClient());
352
+
353
+ const updated = await updateCalendarFor(
354
+ deps,
355
+ accountConfigId,
356
+ calendarId,
357
+ body,
358
+ );
359
+ if (!updated.ok) {
360
+ return updated.error.code === "NotFound"
361
+ ? notFound(updated.error.message)
362
+ : badRequest(updated.error);
363
+ }
364
+ return toCalendarResponse(updated.value);
365
+ },
366
+
367
+ CalendarDetailOperations_deleteCalendar: async (
368
+ context,
369
+ ...args: unknown[]
370
+ ) => {
371
+ const event = args[0] as APIGatewayProxyEvent;
372
+ const accountConfigId = getAccountConfigIdFromEvent(event);
373
+ const { calendarId } = context.request.params as { calendarId: string };
374
+ const deps = calendarDepsOf(await getClient());
375
+
376
+ const removed = await deleteCalendarFor(deps, accountConfigId, calendarId);
377
+ if (!removed.ok) {
378
+ return removed.error.code === "NotFound"
379
+ ? notFound(removed.error.message)
380
+ : badRequest(removed.error);
381
+ }
382
+ return { statusCode: 204 };
383
+ },
384
+ };
@@ -2,16 +2,23 @@ import type { SQSClient } from "@aws-sdk/client-sqs";
2
2
  import type {
3
3
  AccountConfigResponse,
4
4
  ConfigDescriptionResponse,
5
+ ConfigImportReport,
5
6
  } from "@remit/api-openapi-types";
6
7
  import type { ReaderConfigDocument } from "@remit/config-format";
7
- import { readConfigForExport } from "@remit/config-transfer";
8
+ import {
9
+ importConfig,
10
+ pendingImportOf,
11
+ readConfigForExport,
12
+ } from "@remit/config-transfer";
8
13
  import type { AccountConfigItem, MailboxItem } from "@remit/data-ports";
9
- import { NotFoundError } from "@remit/data-ports/errors";
14
+ import { ConfigNotEmptyError, NotFoundError } from "@remit/data-ports/errors";
15
+ import type { CanonicalMailboxRoleValue } from "@remit/data-ports/folder-role";
10
16
  import { logger } from "@remit/logger-lambda";
11
17
  import type { APIGatewayProxyEvent } from "aws-lambda";
12
18
  import { env } from "expect-env";
13
19
  import type { Context } from "openapi-backend";
14
20
  import { getAccountConfigIdFromEvent, getSubFromEvent } from "../auth.js";
21
+ import { embedAnchorText } from "../service/config-import.js";
15
22
  import { getClient } from "../service/data-client.js";
16
23
  import { exportIdentity } from "../service/export-identity.js";
17
24
  import { fireAndForget } from "../service/fire-and-forget.js";
@@ -30,6 +37,7 @@ import {
30
37
  import {
31
38
  groupFolderAppointmentsByAccount,
32
39
  resolveFolderAppointments,
40
+ writeFolderRoleAppointment,
33
41
  } from "./folder-role-appointments.js";
34
42
 
35
43
  type StructuredLog = (fields: Record<string, unknown>, message: string) => void;
@@ -204,8 +212,15 @@ export const ConfigOperations: Record<
204
212
  activeAccounts.map((acc) => acc.accountId),
205
213
  );
206
214
 
215
+ // An import that named folders IMAP had not produced yet rides the config
216
+ // read rather than a route of its own, so nothing has to poll for it.
217
+ const pendingImport = pendingImportOf(
218
+ await client.configImport.listByAccountConfig(accountConfigId),
219
+ );
220
+
207
221
  return {
208
222
  accountConfig: toAccountConfigResponse(accountConfig),
223
+ ...(pendingImport ? { pendingImport } : {}),
209
224
  accounts: activeAccounts.map((acc) =>
210
225
  toAccountResponse(
211
226
  acc,
@@ -234,4 +249,59 @@ export const ConfigOperations: Record<
234
249
  );
235
250
  return { schemaVersion: document.schemaVersion, document };
236
251
  },
252
+
253
+ ConfigOperations_importConfig: async (
254
+ context: Context,
255
+ ...args: unknown[]
256
+ ): Promise<ConfigImportReport> => {
257
+ const event = args[0] as APIGatewayProxyEvent;
258
+ const accountConfigId = getAccountConfigIdFromEvent(event);
259
+ const body = (context.request.requestBody ?? {}) as {
260
+ mode?: "validate" | "apply";
261
+ onExisting?: "abort" | "merge";
262
+ document?: unknown;
263
+ };
264
+ const client = await getClient();
265
+
266
+ const outcome = await importConfig(
267
+ {
268
+ repositories: client,
269
+ // Passed through as-is, undefined included: a backend with no
270
+ // cross-entity transaction writes without one, and the report words
271
+ // what survived a failure from whether this is here.
272
+ transaction: client.writeSet,
273
+ appointFolderRole: (
274
+ configId,
275
+ accountId,
276
+ role,
277
+ mailboxId,
278
+ lastKnownPath,
279
+ ) =>
280
+ writeFolderRoleAppointment(
281
+ client.accountSetting,
282
+ configId,
283
+ accountId,
284
+ role as CanonicalMailboxRoleValue,
285
+ mailboxId,
286
+ lastKnownPath,
287
+ ),
288
+ embedAnchor: embedAnchorText,
289
+ },
290
+ {
291
+ accountConfigId,
292
+ userId: getSubFromEvent(event) ?? accountConfigId,
293
+ document: body.document,
294
+ mode: body.mode ?? "validate",
295
+ onExisting: body.onExisting ?? "abort",
296
+ },
297
+ );
298
+
299
+ if (outcome.outcome === "conflict") {
300
+ throw new ConfigNotEmptyError(
301
+ outcome.conflict.message,
302
+ outcome.conflict.details,
303
+ );
304
+ }
305
+ return outcome.report;
306
+ },
237
307
  };
@@ -3,10 +3,11 @@ import type {
3
3
  FilterResponse,
4
4
  UpdateFilterInput as UpdateFilterRequestBody,
5
5
  } from "@remit/api-openapi-types";
6
- import type {
7
- FilterItem,
8
- IFilterAnchorTransaction,
9
- UpdateFilterInput,
6
+ import {
7
+ deriveFilterTtl,
8
+ type FilterItem,
9
+ type IFilterAnchorTransaction,
10
+ type UpdateFilterInput,
10
11
  } from "@remit/data-ports";
11
12
  import { BadRequestError } from "@remit/data-ports/errors";
12
13
  import { FilterScope, FilterState } from "@remit/domain-enums";
@@ -41,24 +42,6 @@ export interface FilterCrudDeps {
41
42
  ): Promise<AnchorPayload | null>;
42
43
  }
43
44
 
44
- /**
45
- * Epoch-seconds `ttl` derived from `expiresAt`, set only for a `Temporary`
46
- * filter (RFC 034 Decision 1.3). A `Standing` filter never carries `ttl` — the
47
- * reserved table-wide TTL attribute must stay absent, or the row would be swept
48
- * (Decision 1.4).
49
- */
50
- export const deriveFilterTtl = (
51
- scope: string,
52
- expiresAt: string | undefined,
53
- ): number | undefined => {
54
- if (scope !== FilterScope.Temporary || !expiresAt) return undefined;
55
- const ms = new Date(expiresAt).getTime();
56
- if (Number.isNaN(ms)) {
57
- throw new BadRequestError(`Invalid expiresAt: ${expiresAt}`);
58
- }
59
- return Math.floor(ms / 1000);
60
- };
61
-
62
45
  /**
63
46
  * Reduce a PATCH body to the fields a filter update may set (RFC 034, reader
64
47
  * #266). Preserves absence: a key not present in the body is not present in
@@ -2,6 +2,12 @@ import type { OperationHandler, OperationIds } from "../types.js";
2
2
  import { AccountDetailOperations, AccountOperations } from "./account.js";
3
3
  import { MicrosoftOAuthOperations } from "./account-oauth.js";
4
4
  import { AddressDetailOperations, AddressOperations } from "./address.js";
5
+ import { CalendarDetailOperations, CalendarOperations } from "./calendar.js";
6
+ import {
7
+ CalendarEventDetailOperations,
8
+ CalendarEventOperations,
9
+ CalendarFreeBusyOperations,
10
+ } from "./calendar-event.js";
5
11
  import { ConfigOperations } from "./config.js";
6
12
  import { FilterDetailOperations, FilterOperations } from "./filter.js";
7
13
  import { FolderRoleOperations } from "./folder-role.js";
@@ -42,6 +48,11 @@ export const handlers: Record<OperationIds, OperationHandler<any>> = {
42
48
  ...LabelDetailOperations,
43
49
  ...OrganizeOperations,
44
50
  ...OrganizeJobDetailOperations,
51
+ ...CalendarOperations,
52
+ ...CalendarDetailOperations,
53
+ ...CalendarEventOperations,
54
+ ...CalendarEventDetailOperations,
55
+ ...CalendarFreeBusyOperations,
45
56
  ...TrashOperations,
46
57
  ...SyncOperations,
47
58
  ...ThreadDetailOperations,
@@ -4,7 +4,12 @@ import {
4
4
  AccountRepo,
5
5
  AccountSettingRepo,
6
6
  AddressRepo,
7
+ CalendarCollectionRepo,
8
+ CalendarEventIndexRepo,
9
+ CalendarObjectRepo,
10
+ ConfigImportRepo,
7
11
  createSqliteDatabase,
12
+ DrizzleCalendarUnitOfWork,
8
13
  DrizzleEnvelopeRepository,
9
14
  DrizzleFilterAnchorTransaction,
10
15
  DrizzleMessageFlagRepository,
@@ -25,6 +30,7 @@ import {
25
30
  OutboxAttachmentRepo,
26
31
  OutboxMessageRepo,
27
32
  QuarantineRepo,
33
+ runInTransaction,
28
34
  SenderSignerStandingRepo,
29
35
  } from "@remit/drizzle-service";
30
36
  import { env } from "expect-env";
@@ -65,6 +71,7 @@ export const buildSqliteClient = async (): Promise<RemitClient> => {
65
71
  threadMessage: new DrizzleThreadMessageRepository(genericDb),
66
72
  envelope: new DrizzleEnvelopeRepository(messageDataDb),
67
73
  accountExportRequest: new AccountExportRequestRepo(genericDb),
74
+ configImport: new ConfigImportRepo(genericDb),
68
75
  quarantine: new QuarantineRepo(genericDb),
69
76
  organizeJobRequest: new OrganizeJobRequestRepo(genericDb),
70
77
  placementMove: new MessagePlacementMoveRepo(genericDb),
@@ -75,7 +82,12 @@ export const buildSqliteClient = async (): Promise<RemitClient> => {
75
82
  label: new LabelRepo(genericDb),
76
83
  messageLabel: new MessageLabelRepo(genericDb),
77
84
  senderSignerStanding: new SenderSignerStandingRepo(genericDb),
85
+ calendarCollection: new CalendarCollectionRepo(genericDb),
86
+ calendarObject: new CalendarObjectRepo(genericDb),
87
+ calendarEventIndex: new CalendarEventIndexRepo(genericDb),
88
+ calendarUnitOfWork: new DrizzleCalendarUnitOfWork(genericDb),
78
89
  unitOfWork: new DrizzleUnitOfWork(messageDataDb),
90
+ writeSet: (run) => runInTransaction(genericDb, () => run()),
79
91
  };
80
92
 
81
93
  return createRemitClient({ repositories, ...buildSharedDeps() });
@@ -0,0 +1,39 @@
1
+ import type { EmbedAnchor } from "@remit/config-transfer";
2
+ import { logger } from "@remit/logger-lambda";
3
+ import { buildEmbeddingServiceFromEnv } from "@remit/search-service/from-env";
4
+ import { isSemanticCapabilityAbsence } from "./semantic-capability.js";
5
+
6
+ type Embedder = {
7
+ embed: (texts: string[]) => Promise<number[][]>;
8
+ readonly embeddingId: string;
9
+ };
10
+
11
+ let cached: Embedder | null = null;
12
+
13
+ /**
14
+ * Re-embed a filter's anchor from the source text its file carries. The vector
15
+ * never travels — it is a function of the model that produced it — so this is
16
+ * the one thing an import computes rather than copies.
17
+ *
18
+ * A deployment that ships no vector pipeline answers `undefined` rather than
19
+ * failing the import: the anchor then lands stamped as un-embedded, and the
20
+ * same lazy repair that handles a model migration builds its vector the first
21
+ * time the filter is matched. A configuration file has to be importable on the
22
+ * instance a person is recovering onto, whatever that instance can run.
23
+ */
24
+ export const embedAnchorText: EmbedAnchor = async (sourceText) => {
25
+ try {
26
+ if (!cached) cached = buildEmbeddingServiceFromEnv();
27
+ const [embedding] = await cached.embed([sourceText]);
28
+ return embedding
29
+ ? { embedding, embeddingId: cached.embeddingId }
30
+ : undefined;
31
+ } catch (error) {
32
+ if (!isSemanticCapabilityAbsence(error)) throw error;
33
+ logger.warn(
34
+ { error: error instanceof Error ? error.message : String(error) },
35
+ "No embedding pipeline in this deployment; an imported filter anchor is stored as text and embedded on first use",
36
+ );
37
+ return undefined;
38
+ }
39
+ };