@porulle/plugin-channel-connector 0.10.8 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@porulle/plugin-channel-connector",
3
- "version": "0.10.8",
3
+ "version": "0.11.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -19,7 +19,7 @@
19
19
  "dependencies": {
20
20
  "@hono/zod-openapi": "^1.2.2",
21
21
  "hono": "^4.12.5",
22
- "@porulle/core": "0.10.8"
22
+ "@porulle/core": "0.11.0"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@types/node": "^24.5.2",
@@ -0,0 +1,211 @@
1
+ import type { FieldPath } from "@porulle/core";
2
+
3
+ export const catalogFieldTargets = ["native", "attribute", "meta"] as const;
4
+ export type CatalogFieldTarget = (typeof catalogFieldTargets)[number];
5
+
6
+ export interface CatalogFieldMappingRow {
7
+ fieldPath: FieldPath;
8
+ provider: string;
9
+ target: CatalogFieldTarget;
10
+ remoteKey: string;
11
+ }
12
+
13
+ export type CatalogFieldMapping = CatalogFieldMappingRow[];
14
+
15
+ export type CatalogFieldMappingInput =
16
+ | Array<{ fieldPath: string; provider?: string; target: CatalogFieldTarget; remoteKey: string }>
17
+ | Record<string, { provider?: string; target: CatalogFieldTarget; remoteKey: string }>;
18
+
19
+ const fieldSegment = /^[A-Za-z0-9_-]+$/;
20
+ const forbiddenFieldPaths = ["variants.sku", "variants.barcode", "options", "prices", "entity.status"];
21
+
22
+ export const providerCatalogFieldMappingDefaults: Record<string, CatalogFieldMapping> = {
23
+ shopify: [
24
+ { fieldPath: "attributes.*.title", provider: "shopify", target: "native", remoteKey: "title" },
25
+ { fieldPath: "attributes.*.description", provider: "shopify", target: "native", remoteKey: "body_html" },
26
+ { fieldPath: "attributes.*.seoTitle", provider: "shopify", target: "meta", remoteKey: "seo_title" },
27
+ { fieldPath: "attributes.*.seoDescription", provider: "shopify", target: "meta", remoteKey: "seo_description" },
28
+ { fieldPath: "customFields.*.*", provider: "shopify", target: "meta", remoteKey: "metafields" },
29
+ { fieldPath: "media.*", provider: "shopify", target: "native", remoteKey: "images" },
30
+ { fieldPath: "entity.metadata.*", provider: "shopify", target: "meta", remoteKey: "metafields" },
31
+ ],
32
+ woocommerce: [
33
+ { fieldPath: "attributes.*.title", provider: "woocommerce", target: "native", remoteKey: "name" },
34
+ { fieldPath: "attributes.*.description", provider: "woocommerce", target: "native", remoteKey: "description" },
35
+ { fieldPath: "attributes.*.seoTitle", provider: "woocommerce", target: "meta", remoteKey: "yoast_wpseo_title" },
36
+ { fieldPath: "attributes.*.seoDescription", provider: "woocommerce", target: "meta", remoteKey: "yoast_wpseo_metadesc" },
37
+ { fieldPath: "customFields.*.*", provider: "woocommerce", target: "meta", remoteKey: "porulle_meta_data" },
38
+ { fieldPath: "media.*", provider: "woocommerce", target: "native", remoteKey: "images" },
39
+ { fieldPath: "entity.metadata.*", provider: "woocommerce", target: "meta", remoteKey: "porulle_meta_data" },
40
+ ],
41
+ };
42
+
43
+ export function matchFieldPath(pattern: string, path: string): boolean {
44
+ const patternSegments = pattern.split(".");
45
+ const pathSegments = path.split(".");
46
+ return patternSegments.length === pathSegments.length
47
+ && patternSegments.every((segment, index) => pathSegments[index] !== "" && (segment === "*" || segment === pathSegments[index]));
48
+ }
49
+
50
+ export function isValidCatalogMappingFieldPath(value: string): boolean {
51
+ const segments = value.split(".");
52
+ return segments.length > 0 && segments.every((segment) => segment === "*" || fieldSegment.test(segment));
53
+ }
54
+
55
+ function couldCoverForbiddenSubtree(fieldPath: string, root: string): boolean {
56
+ const fieldSegments = fieldPath.split(".");
57
+ const rootSegments = root.split(".");
58
+ return fieldSegments.length >= rootSegments.length
59
+ && rootSegments.every((segment, index) => fieldSegments[index] === "*" || fieldSegments[index] === segment);
60
+ }
61
+
62
+ function isForbiddenMappingFieldPath(fieldPath: string): boolean {
63
+ return forbiddenFieldPaths.some((root) => couldCoverForbiddenSubtree(fieldPath, root));
64
+ }
65
+
66
+ export function validateCatalogMappingRow(
67
+ input: Partial<CatalogFieldMappingRow> & { fieldPath: string; target: CatalogFieldTarget; remoteKey: string },
68
+ provider: string,
69
+ ): CatalogFieldMappingRow {
70
+ if (!isValidCatalogMappingFieldPath(input.fieldPath)) {
71
+ throw new Error("Catalog mapping field paths must contain dot-separated alphanumeric, underscore, hyphen, or wildcard segments.");
72
+ }
73
+ if (isForbiddenMappingFieldPath(input.fieldPath)) {
74
+ throw new Error(`Catalog mapping cannot write the forbidden field path "${input.fieldPath}".`);
75
+ }
76
+ if (!catalogFieldTargets.includes(input.target)) {
77
+ throw new Error(`Catalog mapping target "${input.target}" is invalid.`);
78
+ }
79
+ const remoteKey = input.remoteKey.trim();
80
+ if (remoteKey.length === 0) {
81
+ throw new Error("Catalog mapping remoteKey must not be empty.");
82
+ }
83
+ const rowProvider = input.provider ?? provider;
84
+ if (rowProvider !== provider) {
85
+ throw new Error(`Catalog mapping provider must be "${provider}" for this store.`);
86
+ }
87
+ if (rowProvider === "woocommerce" && input.target === "meta" && remoteKey.startsWith("_")) {
88
+ throw new Error("WooCommerce meta keys must not start with an underscore.");
89
+ }
90
+ return {
91
+ fieldPath: input.fieldPath,
92
+ provider: rowProvider,
93
+ target: input.target,
94
+ remoteKey,
95
+ };
96
+ }
97
+
98
+ function mappingEntries(input: unknown): unknown[] {
99
+ if (Array.isArray(input)) return input;
100
+ if (!input || typeof input !== "object") throw new Error("Catalog mapping must be an array or an object.");
101
+ return Object.entries(input).map(([fieldPath, value]) => {
102
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Catalog mapping values must be objects.");
103
+ return { ...(value as Record<string, unknown>), fieldPath };
104
+ });
105
+ }
106
+
107
+ function normalizeCatalogMappingRow(row: unknown, provider: string): CatalogFieldMappingRow {
108
+ if (!row || typeof row !== "object" || Array.isArray(row)) throw new Error("Catalog mapping rows must be objects.");
109
+ const value = row as Record<string, unknown>;
110
+ if (typeof value.fieldPath !== "string" || typeof value.target !== "string" || typeof value.remoteKey !== "string") {
111
+ throw new Error("Catalog mapping rows require fieldPath, target, and remoteKey.");
112
+ }
113
+ return validateCatalogMappingRow(
114
+ {
115
+ fieldPath: value.fieldPath,
116
+ ...(typeof value.provider === "string" ? { provider: value.provider } : {}),
117
+ target: value.target as CatalogFieldTarget,
118
+ remoteKey: value.remoteKey,
119
+ },
120
+ provider,
121
+ );
122
+ }
123
+
124
+ export function normalizeCatalogFieldMapping(input: unknown, provider: string): CatalogFieldMapping {
125
+ return mappingEntries(input).map((row) => normalizeCatalogMappingRow(row, provider));
126
+ }
127
+
128
+ function normalizeStoredCatalogFieldMapping(input: unknown, provider: string, warnings: string[]): CatalogFieldMapping {
129
+ let entries: unknown[];
130
+ try {
131
+ entries = mappingEntries(input ?? []);
132
+ } catch (error) {
133
+ warnings.push(error instanceof Error ? error.message : "Stored catalog mapping is invalid.");
134
+ return [];
135
+ }
136
+ return entries.flatMap((row, index) => {
137
+ try {
138
+ return [normalizeCatalogMappingRow(row, provider)];
139
+ } catch (error) {
140
+ const message = error instanceof Error ? error.message : "Stored catalog mapping row is invalid.";
141
+ warnings.push(`Skipped catalog mapping row ${index}: ${message}`);
142
+ return [];
143
+ }
144
+ });
145
+ }
146
+
147
+ function filterableEntries(hint: ReadonlySet<string> | Readonly<Record<string, boolean>>): Array<[string, boolean]> {
148
+ if (hint instanceof Set) return [...hint].map((path) => [path, true]);
149
+ return Object.entries(hint);
150
+ }
151
+
152
+ export function mergeCatalogFieldMapping(
153
+ provider: string,
154
+ overrides: unknown,
155
+ filterableCustomFields?: ReadonlySet<string> | Readonly<Record<string, boolean>>,
156
+ warnings: string[] = [],
157
+ ): CatalogFieldMapping {
158
+ const defaults = (providerCatalogFieldMappingDefaults[provider] ?? []).map((row) => ({ ...row }));
159
+ const rows = normalizeStoredCatalogFieldMapping(overrides, provider, warnings);
160
+ const merged = [...defaults];
161
+ for (const row of rows) {
162
+ const index = merged.findIndex((defaultRow) => defaultRow.fieldPath === row.fieldPath && defaultRow.provider === row.provider);
163
+ if (index === -1) merged.push(row);
164
+ else merged[index] = row;
165
+ }
166
+ if (!filterableCustomFields) return merged;
167
+ const hints = filterableEntries(filterableCustomFields).filter(([path]) => isValidCatalogMappingFieldPath(path));
168
+ if (hints.length === 0) return merged;
169
+ const customFieldPattern = "customFields.*.*";
170
+ const customFieldDefault = merged.find((row) => row.fieldPath === customFieldPattern);
171
+ if (!customFieldDefault) return merged;
172
+ const expanded = hints
173
+ .filter(([path]) => matchFieldPath(customFieldPattern, path))
174
+ .map(([fieldPath, filterable]) => ({
175
+ ...customFieldDefault,
176
+ fieldPath,
177
+ target: filterable ? "attribute" as const : "meta" as const,
178
+ remoteKey: fieldPath.split(".")[1] ?? customFieldDefault.remoteKey,
179
+ }));
180
+ return [...merged.filter((row) => row.fieldPath !== customFieldPattern), ...expanded];
181
+ }
182
+
183
+ function wildcardCount(fieldPath: string): number {
184
+ return fieldPath.split(".").filter((segment) => segment === "*").length;
185
+ }
186
+
187
+ function compareStrings(left: string, right: string): number {
188
+ if (left < right) return -1;
189
+ if (left > right) return 1;
190
+ return 0;
191
+ }
192
+
193
+ export function compareCatalogFieldMappingSpecificity(
194
+ left: CatalogFieldMappingRow,
195
+ right: CatalogFieldMappingRow,
196
+ ): number {
197
+ const wildcardDifference = wildcardCount(left.fieldPath) - wildcardCount(right.fieldPath);
198
+ if (wildcardDifference !== 0) return wildcardDifference;
199
+ const fieldPathDifference = compareStrings(left.fieldPath, right.fieldPath);
200
+ if (fieldPathDifference !== 0) return fieldPathDifference;
201
+ const providerDifference = compareStrings(left.provider, right.provider);
202
+ if (providerDifference !== 0) return providerDifference;
203
+ return compareStrings(left.remoteKey, right.remoteKey);
204
+ }
205
+
206
+ export function selectCatalogFieldMapping(
207
+ mapping: CatalogFieldMapping,
208
+ path: string,
209
+ ): CatalogFieldMappingRow | undefined {
210
+ return mapping.filter((row) => matchFieldPath(row.fieldPath, path)).sort(compareCatalogFieldMappingSpecificity)[0];
211
+ }
package/src/index.ts CHANGED
@@ -41,8 +41,33 @@ export {
41
41
  ChannelConnectorService,
42
42
  canExportTransition,
43
43
  } from "./service.js";
44
+ export {
45
+ isValidCatalogMappingFieldPath,
46
+ matchFieldPath,
47
+ mergeCatalogFieldMapping,
48
+ normalizeCatalogFieldMapping,
49
+ compareCatalogFieldMappingSpecificity,
50
+ providerCatalogFieldMappingDefaults,
51
+ selectCatalogFieldMapping,
52
+ validateCatalogMappingRow,
53
+ } from "./catalog-field-mapping.js";
54
+ export type {
55
+ CatalogFieldMapping,
56
+ CatalogFieldMappingInput,
57
+ CatalogFieldMappingRow,
58
+ CatalogFieldTarget,
59
+ } from "./catalog-field-mapping.js";
44
60
  export { signState, verifyState } from "./oauth-state.js";
45
61
  export type {
62
+ BackfillCatalogOptions,
63
+ BackfillCatalogReport,
64
+ BuildCatalogPushItemsOptions,
65
+ BuildCatalogPushItemsResult,
66
+ CatalogFieldConflict,
67
+ CatalogFieldSkip,
68
+ CatalogPushFieldSkip,
69
+ CatalogPushSkipReason,
70
+ CatalogWriteSettings,
46
71
  ChannelComplianceData,
47
72
  ChannelConnectorPluginOptions,
48
73
  ChannelStockLine,
@@ -138,7 +163,38 @@ export function channelConnectorPlugin(options: ChannelConnectorPluginOptions =
138
163
  const service = new ChannelConnectorService(ctx.db, ctx.services, options);
139
164
  const result = await service.importCatalog(String(input.orgId), String(input.storeId), createSystemActor(String(input.orgId)));
140
165
  if (!result.ok) throw new Error(result.error);
141
- return { output: { imported: result.value.imported, cursor: result.value.cursor } };
166
+ return {
167
+ output: {
168
+ imported: result.value.imported,
169
+ cursor: result.value.cursor,
170
+ ...(result.value.warnings ? { warnings: result.value.warnings } : {}),
171
+ },
172
+ };
173
+ },
174
+ },
175
+ {
176
+ slug: "channel/backfill-catalog",
177
+ concurrency: { key: (input: Record<string, unknown>) => String(input.storeId) },
178
+ handler: async ({ input, ctx }: { input: Record<string, unknown>; ctx: import("@porulle/core").TaskContext }) => {
179
+ const service = new ChannelConnectorService(ctx.db, ctx.services, options);
180
+ const orgId = String(input.orgId);
181
+ const storeId = String(input.storeId);
182
+ const dryRun = input.dryRun === true;
183
+ const result = await service.backfillCatalog(orgId, storeId, createSystemActor(orgId), {
184
+ dryRun,
185
+ ...(input.restart === true ? { resume: false } : {}),
186
+ ...(!dryRun ? { maxPages: 1 } : {}),
187
+ });
188
+ if (!result.ok) throw new Error(result.error);
189
+ if (!result.value.complete && !dryRun) {
190
+ const jobs = ctx.services.jobs as JobsAdapter;
191
+ await jobs.enqueue("channel/backfill-catalog", { orgId, storeId, dryRun }, {
192
+ organizationId: orgId,
193
+ concurrencyKey: storeId,
194
+ supersedes: false,
195
+ });
196
+ }
197
+ return { output: result.value };
142
198
  },
143
199
  },
144
200
  {
@@ -378,11 +434,52 @@ export function channelConnectorPlugin(options: ChannelConnectorPluginOptions =
378
434
  .permission("channels:read")
379
435
  .handler(async ({ params, orgId }: ChannelRouteContext) => unwrap(await service.getStore(orgId, params.id!)));
380
436
 
437
+ channels.get("/stores/{storeId}/catalog-write")
438
+ .summary("Get catalog write settings for a channel store")
439
+ .permission("channels:manage")
440
+ .handler(async ({ params, orgId }: ChannelRouteContext) => unwrap(await service.getCatalogWriteSettings(orgId, params.storeId!)));
441
+
442
+ channels.put("/stores/{storeId}/catalog-write")
443
+ .summary("Update catalog write settings for a channel store")
444
+ .permission("channels:manage")
445
+ .input(z.object({
446
+ enabled: z.boolean().optional(),
447
+ overrides: z.unknown().optional(),
448
+ }).refine((value) => value.enabled !== undefined || value.overrides !== undefined))
449
+ .handler(async ({ params, orgId, input }: ChannelRouteContext) => {
450
+ const values = input as { enabled?: boolean; overrides?: unknown };
451
+ if (values.overrides !== undefined) unwrap(await service.updateCatalogFieldMapping(orgId, params.storeId!, values.overrides));
452
+ if (values.enabled !== undefined) unwrap(await service.updateCatalogWriteEnabled(orgId, params.storeId!, values.enabled));
453
+ return unwrap(await service.getCatalogWriteSettings(orgId, params.storeId!));
454
+ });
455
+
381
456
  channels.get("/stores/{storeId}/reconcile-status")
382
457
  .summary("Get channel reconciliation status")
383
458
  .permission("channels:read")
384
459
  .handler(async ({ params, orgId }: ChannelRouteContext) => unwrap(await service.getReconcileStatus(orgId, params.storeId!)));
385
460
 
461
+ channels.post("/stores/{storeId}/backfill")
462
+ .summary("Backfill a channel catalog into the PIM")
463
+ .permission("channels:manage")
464
+ .input(z.object({ dryRun: z.boolean().optional(), restart: z.boolean().optional() }))
465
+ .handler(async ({ params, orgId, input }: ChannelRouteContext) => {
466
+ const values = input as { dryRun?: boolean; restart?: boolean };
467
+ if (values.dryRun === true) {
468
+ return unwrap(await service.backfillCatalog(orgId, params.storeId!, createSystemActor(orgId), { dryRun: true }));
469
+ }
470
+ const jobs = ctx.services.jobs as JobsAdapter;
471
+ await jobs.enqueue("channel/backfill-catalog", {
472
+ orgId,
473
+ storeId: params.storeId!,
474
+ ...(values.restart === true ? { restart: true } : {}),
475
+ }, {
476
+ organizationId: orgId,
477
+ concurrencyKey: params.storeId!,
478
+ supersedes: false,
479
+ });
480
+ return { enqueued: true, storeId: params.storeId! };
481
+ });
482
+
386
483
  channels.post("/stores/{id}/disconnect")
387
484
  .summary("Disconnect a channel store")
388
485
  .permission("channels:manage")
@@ -6,8 +6,12 @@ import {
6
6
  } from "@porulle/core";
7
7
  import type {
8
8
  ChannelCatalogItem,
9
+ ChannelConnectorError,
9
10
  ChannelInventoryLevel,
10
11
  ChannelOrderSlice,
12
+ ChannelPushCatalogItem,
13
+ ChannelPushCatalogPreviousField,
14
+ ChannelStore,
11
15
  } from "@porulle/core";
12
16
 
13
17
  export interface MockChannelConnectorOptions {
@@ -17,10 +21,64 @@ export interface MockChannelConnectorOptions {
17
21
  throwOnInventory?: boolean;
18
22
  inventoryDelayMs?: number;
19
23
  onFetchInventory?: (ids: string[]) => void;
24
+ pushCatalogFailures?: Record<string, ChannelConnectorError>;
25
+ pushCatalogTransportError?: ChannelConnectorError;
26
+ onPushCatalog?: (items: ChannelPushCatalogItem[]) => void;
20
27
  }
21
28
 
29
+ const defaultCatalog: ChannelCatalogItem[] = [{
30
+ externalId: "mock-product-1",
31
+ slug: "mock-channel-product",
32
+ title: "Mock Channel Product",
33
+ description: "Imported through the mock connector.",
34
+ attributes: [{
35
+ locale: "en",
36
+ title: "Mock Channel Product",
37
+ subtitle: "A complete mock catalog item",
38
+ description: "Imported through the mock connector.",
39
+ richDescription: { blocks: [{ type: "paragraph", text: "Mock product details." }] },
40
+ seoTitle: "Mock Channel Product | Porulle",
41
+ seoDescription: "A mock product with the complete channel catalog shape.",
42
+ }],
43
+ images: [
44
+ {
45
+ externalId: "mock-image-primary",
46
+ url: "https://mock.channel.test/images/mock-product-1-primary.jpg",
47
+ alt: "Mock Channel Product",
48
+ role: "primary",
49
+ sortOrder: 0,
50
+ },
51
+ {
52
+ externalId: "mock-image-variant",
53
+ url: "https://mock.channel.test/images/mock-variant-1.jpg",
54
+ alt: "Mock Channel Product blue variant",
55
+ role: "gallery",
56
+ sortOrder: 1,
57
+ variantExternalIds: ["mock-variant-1"],
58
+ },
59
+ ],
60
+ options: [{
61
+ name: "color",
62
+ displayName: "Color",
63
+ sortOrder: 0,
64
+ values: [{ value: "blue", displayValue: "Blue", sortOrder: 0 }],
65
+ }],
66
+ tags: ["mock", "featured"],
67
+ brand: "Porulle",
68
+ categories: ["mock-products"],
69
+ status: "active",
70
+ variants: [{
71
+ externalId: "mock-variant-1",
72
+ sku: "MOCK-SKU-1",
73
+ barcode: "0123456789012",
74
+ optionValues: { color: "blue" },
75
+ prices: [{ currency: "USD", amount: 2500 }],
76
+ }],
77
+ }];
78
+
22
79
  export function mockChannelConnector(options: MockChannelConnectorOptions = {}) {
23
80
  const orders = new Map<string, ChannelOrderSlice>();
81
+ const catalog = new Map<string, ChannelPushCatalogItem>();
24
82
 
25
83
  return defineChannelConnector({
26
84
  providerId: "mock",
@@ -28,10 +86,11 @@ export function mockChannelConnector(options: MockChannelConnectorOptions = {})
28
86
  importCatalog: true,
29
87
  importInventory: true,
30
88
  pushOrder: true,
89
+ pushCatalog: true,
31
90
  receiveWebhooks: true,
32
91
  },
33
- async importCatalog() {
34
- return Ok({ items: options.catalog ?? [], nextCursor: null });
92
+ async importCatalog(_store?: ChannelStore) {
93
+ return Ok({ items: options.catalog ?? defaultCatalog, nextCursor: null });
35
94
  },
36
95
  async fetchInventory(_store, ids) {
37
96
  const requestedIds = ids ?? [];
@@ -52,6 +111,26 @@ export function mockChannelConnector(options: MockChannelConnectorOptions = {})
52
111
  remoteUrl: `https://mock.channel.test/orders/${remoteOrderId}`,
53
112
  });
54
113
  },
114
+ async pushCatalog(_store, items, opts?: { dryRun?: boolean }) {
115
+ if (options.pushCatalogTransportError) return Err(options.pushCatalogTransportError);
116
+ const outcomes = items.map((item) => {
117
+ const error = options.pushCatalogFailures?.[item.externalId];
118
+ if (error) return { externalId: item.externalId, ok: false, error };
119
+ const previous = catalog.get(item.externalId);
120
+ const previousFields: ChannelPushCatalogPreviousField[] = previous
121
+ ? [...previous.fields, ...(previous.variants ?? []).flatMap((variant) => variant.fields)]
122
+ .map((field) => ({ fieldPath: field.fieldPath, value: structuredClone(field.value) }))
123
+ : [];
124
+ if (opts?.dryRun !== true) catalog.set(item.externalId, structuredClone(item));
125
+ return {
126
+ externalId: item.externalId,
127
+ ok: true,
128
+ ...(previousFields.length > 0 ? { previousFields } : {}),
129
+ };
130
+ });
131
+ if (opts?.dryRun !== true) options.onPushCatalog?.(structuredClone(items));
132
+ return Ok({ outcomes });
133
+ },
55
134
  async fetchOrderStatus(_store, remoteId) {
56
135
  if (!orders.has(remoteId)) {
57
136
  return Err(new CommerceValidationError(`Mock order "${remoteId}" was not found.`));
package/src/schema.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ boolean,
2
3
  index,
3
4
  integer,
4
5
  jsonb,
@@ -8,6 +9,8 @@ import {
8
9
  uniqueIndex,
9
10
  uuid,
10
11
  } from "@porulle/core/drizzle";
12
+ import type { FieldPath } from "@porulle/core";
13
+ import type { CatalogFieldMapping } from "./catalog-field-mapping.js";
11
14
 
12
15
  export const connectedStores = pgTable(
13
16
  "connected_stores",
@@ -20,6 +23,8 @@ export const connectedStores = pgTable(
20
23
  status: text("status", { enum: ["connected", "disconnected", "error"] })
21
24
  .notNull()
22
25
  .default("connected"),
26
+ catalogWriteEnabled: boolean("catalog_write_enabled").notNull().default(false),
27
+ catalogFieldMapping: jsonb("catalog_field_mapping").$type<CatalogFieldMapping>().notNull().default([]),
23
28
  catalogCursor: text("catalog_cursor"),
24
29
  inventoryCursor: text("inventory_cursor"),
25
30
  lastSyncAt: timestamp("last_sync_at", { withTimezone: true }),
@@ -48,6 +53,7 @@ export const channelEntityMap = pgTable(
48
53
  variantId: uuid("variant_id"),
49
54
  lastSyncedAt: timestamp("last_synced_at", { withTimezone: true }).defaultNow().notNull(),
50
55
  syncHash: text("sync_hash").notNull(),
56
+ heldFieldPaths: jsonb("held_field_paths").$type<FieldPath[]>().notNull().default([]),
51
57
  },
52
58
  (table) => ({
53
59
  orgIdx: index("idx_channel_entity_map_org").on(table.organizationId),