opscms-meta-plugin 0.6.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,13 +1,36 @@
1
1
  # Changelog
2
2
 
3
- ## 0.6.0
3
+ ## 0.7.0
4
4
 
5
5
  ### Added
6
6
 
7
- - **The host can give the plugin the platform's Meta app.** `metaPlugin({ app: () => ({ appId, appSecret, webhookVerifyToken }) })`: the plugin asks
8
- for it when it needs it, so a host that keeps the app in its own settings needs nothing set on the server, and a change is used at once. What the host
9
- gives wins; `META_APP_ID`, `META_APP_SECRET` and `META_WEBHOOK_VERIFY_TOKEN` stay as the fallback, so a host that passes nothing works as before.
10
- (`META_ENCRYPTION_KEY` is not part of this: it is the key that protects what is stored, so it stays on the server.)
7
+ - **A catalogue item's page address can use the slug of its category: `{category.slug}`.** A shop whose pages are one per category, with the items sizes of it (AvrilBeetails: `/adun/<flavour>`), has no
8
+ slug on its items, so `{slug}` gave every link the item's number and a page that does not exist. The template may now be `https://avrilbeetails.com/adun/{category.slug}`. Both `{slug}` and
9
+ `{category.slug}` may be used together. An item whose category has no slug is left out of the sync and the feed (with a link that leads nowhere Meta would only warn).
10
+
11
+ ### Changed
12
+
13
+ - **A failed call to Meta says what to do.** Meta's own message for a person is shown when it gives one, and a Pixel that cannot be created because the business has not accepted Meta's Pixel
14
+ terms (error 10, subcode 1784018: "Application does not have permission for this action") says so and where to accept them. A failed Pixel creation is also written to the log.
15
+
16
+ ## 0.6.1
17
+
18
+ ### Fixed
19
+
20
+ - **An organization admin (and an editor) could not create a Meta connection, so no site could be connected.** The create rule refused unless the request already named a
21
+ site, but the admin screen asks "may this person create one?" before there is a document, so the answer was always no and "Create New" never appeared (only a
22
+ super-admin saw it). An admin or editor may now start one. Nothing else is looser: the site is still a required field, an editor is still pinned to their own site,
23
+ and a site that is submitted is still checked against the admin's organization.
24
+
25
+ ## 0.6.0
26
+
27
+ ### Changed (breaking)
28
+
29
+ - **The platform's Meta app comes from the host, and only from the host.** `metaPlugin({ app: () => ({ appId, appSecret, webhookVerifyToken }) })`: the
30
+ plugin asks for it when it needs it, so a host that keeps the app in its own settings needs nothing on the server, and a change is used at once.
31
+ `META_APP_ID`, `META_APP_SECRET` and `META_WEBHOOK_VERIFY_TOKEN` are **no longer read**: one place to set the app, no second value that can disagree.
32
+ A host that passes no `app` has Meta Connect, Facebook login and the webhook switched off. (`META_ENCRYPTION_KEY` and `META_OAUTH_STATE_SECRET` are
33
+ not part of this: they protect what is stored and signed, so they stay on the server.)
11
34
 
12
35
  ## 0.4.2
13
36
 
package/README.md CHANGED
@@ -87,18 +87,18 @@ export default buildConfig({
87
87
  ```bash
88
88
  # .env
89
89
  META_ENCRYPTION_KEY=$(openssl rand -hex 32)
90
- META_APP_ID=your-meta-app-id
91
- META_APP_SECRET=your-meta-app-secret
92
90
  ```
93
91
 
92
+ The Meta App itself is **not** set in the environment: the host CMS passes it in (`metaPlugin({ app: () => ({ appId, appSecret, webhookVerifyToken }) })`), from wherever it keeps its own settings (OpsCMS: Platform Settings → Meta app). A host that passes no `app` has Meta Connect, Facebook login and the webhook switched off.
93
+
94
94
  Without `META_ENCRYPTION_KEY`, credentials are stored in plain text (allowed in development; the plugin **fails fast at startup in production** unless you explicitly set `ALLOW_PLAINTEXT_META_CREDS=true`, which you should not do).
95
95
 
96
- `META_APP_ID`/`META_APP_SECRET` are the **one Meta App for the whole deployment** — same pattern as Buffer/Hootsuite/Zapier: every tenant site connects through this single App, they never create their own. There's no API to create a Meta App programmatically (unlike, say, ERPNext's OAuth Client doctype), so this is a one-time manual step:
96
+ The App ID and secret the host passes are the **one Meta App for the whole deployment** — same pattern as Buffer/Hootsuite/Zapier: every tenant site connects through this single App, they never create their own. There's no API to create a Meta App programmatically (unlike, say, ERPNext's OAuth Client doctype), so this is a one-time manual step:
97
97
 
98
98
  1. Create an App at [developers.facebook.com](https://developers.facebook.com), add the **Facebook Login for Business** product (and **Threads API** if you'll connect Threads).
99
99
  2. Add `{PAYLOAD_PUBLIC_SERVER_URL}/api/meta-oauth/callback` and `{PAYLOAD_PUBLIC_SERVER_URL}/api/threads-oauth/callback` as **Valid OAuth Redirect URIs**.
100
100
  3. Switch the App to **Live** mode and request **Advanced Access** (via App Review) for whichever scopes you need — `pages_show_list`, `pages_read_engagement`, `instagram_basic`, `business_management`, `ads_management`, etc. In Development mode, OAuth only works for users added as Testers/Admins/Developers on the App itself — real tenant site owners won't be able to connect until this is done. Meta may also require **Business Verification** for the ads/marketing-adjacent scopes.
101
- 4. Set `META_APP_ID`/`META_APP_SECRET` from that App's Settings → Basic page and restart.
101
+ 4. Give the host the App ID and App secret from that App's Settings → Basic page (OpsCMS: Platform Settings → Meta app). It is used at once; no restart.
102
102
 
103
103
  Site owners never see or enter these — the admin UI shows only a masked, read-only App ID (`GET /api/meta-oauth/app-info`) so they can confirm a platform App is configured before clicking Connect.
104
104
 
@@ -136,7 +136,7 @@ Paste a long-lived Page or System User access token directly into `accessToken`
136
136
 
137
137
  ### Option B — Connect to Meta Business (OAuth)
138
138
 
139
- Uses the one platform-level Meta App set up via `META_APP_ID`/`META_APP_SECRET` (see [Set the encryption key and the platform Meta App](#2-set-the-encryption-key-and-the-platform-meta-app) — that's a one-time deployment setup step, not something each site does). Once that's configured:
139
+ Uses the one platform-level Meta App the host passes in (see [Set the encryption key and the platform Meta App](#2-set-the-encryption-key-and-the-platform-meta-app) — that's a one-time deployment setup step, not something each site does). Once that's configured:
140
140
 
141
141
  1. On the `meta-config` document's 🔑 Connection tab, the panel shows a masked, read-only **Platform Meta App** ID confirming it's configured.
142
142
  2. Click **Connect to Meta Business** — you'll be redirected to Meta's OAuth consent screen requesting `business_management`, `pages_show_list`, `pages_read_engagement`, `pages_manage_metadata`, `instagram_basic`, `ads_management`, `catalog_management`, and `whatsapp_business_management` (trim the scope list in `metaOAuth.ts` if your App's review doesn't cover all of them — Meta simply omits ungranted permissions from the resulting token rather than failing the whole flow).
@@ -145,7 +145,7 @@ Uses the one platform-level Meta App set up via `META_APP_ID`/`META_APP_SECRET`
145
145
 
146
146
  ### Connecting Threads
147
147
 
148
- Threads is a **separate product/API** from Facebook and Instagram — its own OAuth host (`threads.net`, not `facebook.com`), its own token host (`graph.threads.net`, not `graph.facebook.com`), and its own token/profile shape — even though it's added as a product on the *same* Meta App and reuses the same platform-level `META_APP_ID`/`META_APP_SECRET`.
148
+ Threads is a **separate product/API** from Facebook and Instagram — its own OAuth host (`threads.net`, not `facebook.com`), its own token host (`graph.threads.net`, not `graph.facebook.com`), and its own token/profile shape — even though it's added as a product on the *same* Meta App and reuses the same platform-level the app ID/the app secret.
149
149
 
150
150
  1. Add the **Threads API** product to the same Meta App (see setup step above), and register `{PAYLOAD_PUBLIC_SERVER_URL}/api/threads-oauth/callback` as its redirect URI.
151
151
  2. On the **🧵 Threads** tab, click **Connect Threads** — separate consent screen (`threads_basic`, `threads_content_publish`), separate callback, separate stored token (`threadsAccessToken`). Connecting Threads does not affect or require the Facebook/Instagram connection above, or vice versa.
@@ -167,7 +167,7 @@ export interface MetaPluginOptions {
167
167
 
168
168
  | Variable | Required | Description |
169
169
  |---|---|---|
170
- | `META_APP_ID` / `META_APP_SECRET` | For OAuth Connect | The one Meta App for the whole deployment (developers.facebook.com) — every tenant site's Connect button uses this. Not required if every site only ever uses manual Access Token entry. Never entered by a site owner; see [Set the encryption key and the platform Meta App](#2-set-the-encryption-key-and-the-platform-meta-app). |
170
+ | *(the host's `app` option)* | For OAuth Connect | The one Meta App for the whole deployment (developers.facebook.com) — every tenant site's Connect button uses this. Not required if every site only ever uses manual Access Token entry. Not an environment variable, and never entered by a site owner; see [Set the encryption key and the platform Meta App](#2-set-the-encryption-key-and-the-platform-meta-app). |
171
171
  | `META_ENCRYPTION_KEY` | Production: yes | 32-byte hex key (`openssl rand -hex 32`) for AES-256-GCM credential encryption. Separate from `opscms-erpnext-plugin`'s `ERPNEXT_ENCRYPTION_KEY` — rotating one doesn't affect the other. |
172
172
  | `ALLOW_PLAINTEXT_META_CREDS` | No | Set to `true` to explicitly allow plain-text credential storage in production. Do not set this unless you understand the risk (a DB dump/backup leaks every tenant's Meta access token). |
173
173
  | `PAYLOAD_PUBLIC_SERVER_URL` | For Catalog feed + OAuth | Used to build absolute image URLs in the Commerce Catalog feed, and the OAuth callback redirect URIs (`/api/meta-oauth/callback`, `/api/threads-oauth/callback`). Already set for the host CMS's other public-facing needs. |
@@ -177,7 +177,7 @@ export interface MetaPluginOptions {
177
177
 
178
178
  ## The `meta-config` Collection
179
179
 
180
- One document per site. `appId`/`appSecret` are **not** fields here — they're the one platform-level Meta App (`META_APP_ID`/`META_APP_SECRET`), never per-site. Every other credential field is directly editable (manual entry) — the Connect buttons are a convenience layer on top, not a replacement:
180
+ One document per site. `appId`/`appSecret` are **not** fields here — they're the one platform-level Meta App the host passes in, never per-site. Every other credential field is directly editable (manual entry) — the Connect buttons are a convenience layer on top, not a replacement:
181
181
 
182
182
  | Tab | Fields | Notes |
183
183
  |---|---|---|
@@ -187,7 +187,7 @@ One document per site. `appId`/`appSecret` are **not** fields here — they're t
187
187
  | 💬 WhatsApp Business | `whatsappEnabled`, `whatsappPhoneNumberId`, `whatsappBusinessAccountId` | Populates the host CMS's existing `lib/whatsapp.ts` `metaCloud` provider — no plugin code needed for outbound sending. |
188
188
  | 🧵 Threads | `threadsEnabled`, **Connect Threads** button, `threadsUserId`/`threadsUsername` (read-only, set by Connect), `threadsAccessToken` (hidden, encrypted) | Independent OAuth flow — see [Connecting Facebook, Instagram, and Threads](#connecting-facebook-instagram-and-threads). |
189
189
 
190
- Credentials (`accessToken`, `oauthUserAccessToken`, `threadsAccessToken`) are AES-256-GCM encrypted at rest and masked in the admin UI (`••••1234`) for any authenticated non-internal request — the same pattern `ErpnextConfig` uses for `apiKey`/`apiSecret`. `META_APP_SECRET` never touches the database at all — it's read from the environment on each OAuth request.
190
+ Credentials (`accessToken`, `oauthUserAccessToken`, `threadsAccessToken`) are AES-256-GCM encrypted at rest and masked in the admin UI (`••••1234`) for any authenticated non-internal request — the same pattern `ErpnextConfig` uses for `apiKey`/`apiSecret`. the app secret never touches the database at all — it's read from the environment on each OAuth request.
191
191
 
192
192
  ---
193
193
 
@@ -233,7 +233,7 @@ Generic by design: reads whichever collection `catalogSourceCollection` designat
233
233
  | `description` | `description`, `excerpt`, `body` (HTML stripped) |
234
234
  | `price` | `price`, `price_from`, `priceFrom` |
235
235
  | `image_link` | `image`, `featuredImage`, `photo` (resolved to an absolute URL) |
236
- | `link` | `catalogItemUrlTemplate` with `{slug}` substituted |
236
+ | `link` | `catalogItemUrlTemplate` with `{slug}` (the item's slug, else its number) and/or `{category.slug}` (the slug of the item's category) substituted; an item whose `{category.slug}` cannot be filled is left out |
237
237
 
238
238
  Items missing a `title` or `price` are skipped rather than emitted as invalid rows — Meta rejects the whole feed on malformed entries, so a few incomplete source documents shouldn't take down catalog sync for everything else.
239
239
 
@@ -270,7 +270,7 @@ The one real gap: Meta's WhatsApp Cloud API webhook subscription requires a `GET
270
270
 
271
271
  ## Security
272
272
 
273
- - Credentials (`accessToken`) are AES-256-GCM encrypted at rest (`META_ENCRYPTION_KEY`), masked in the admin UI, and only decrypted server-side when actually needed (e.g. `getMetaCredentials()`, the connection-health check). `META_APP_SECRET` is never stored in the database at all — it's read from the environment only, on each OAuth request.
273
+ - Credentials (`accessToken`) are AES-256-GCM encrypted at rest (`META_ENCRYPTION_KEY`), masked in the admin UI, and only decrypted server-side when actually needed (e.g. `getMetaCredentials()`, the connection-health check). the app secret is never stored in the database at all — it's read from the environment only, on each OAuth request.
274
274
  - `accessToken` is only writable by `admin`/`super-admin` roles (`adminOrAboveField` field-level access) — editors can see the masked config but can't rotate credentials or repoint a connection.
275
275
  - `getMetaCredentials()` never falls back across sites — a lookup for one site's slug will never return another tenant's credentials, even on a partial/missing config.
276
276
  - The Commerce Catalog feed is intentionally public (Meta's crawler needs unauthenticated access) but strictly site-scoped — it can never return another site's data, and only returns docs that already belong to the requested site.
@@ -298,8 +298,8 @@ MIT
298
298
 
299
299
  Meta reports what happens on its side to one callback address per app. Register
300
300
  `https://<your CMS>/api/meta-webhook` as the callback of the platform's Meta app, for the
301
- **WhatsApp Business Account** topic, with the verify token from `META_WEBHOOK_VERIFY_TOKEN`.
302
- The app secret (`META_APP_SECRET`) must also be set: every delivery is signed with it, and a
301
+ **WhatsApp Business Account** topic, with the verify token the host passes in (`webhookVerifyToken`).
302
+ The app secret must also be set: every delivery is signed with it, and a
303
303
  delivery with a missing or wrong signature is refused with 401.
304
304
 
305
305
  Each site's business account is subscribed to the app when the site chooses its WhatsApp
@@ -329,7 +329,7 @@ The plugin adds "Continue with Facebook" to the platform's login page, using the
329
329
 
330
330
  - **Who gets in:** someone who already has a platform account. Their Facebook email must be the same as their platform email to join the
331
331
  two; after that they sign in by Facebook id. Signing in never creates an account, and an account is never matched on a different email.
332
- - **Setup:** `META_APP_ID` and `META_APP_SECRET` on the server, the Facebook Login product on the Meta app, and
332
+ - **Setup:** the Meta app given to the plugin by the host, the Facebook Login product on the Meta app, and
333
333
  `<PAYLOAD_PUBLIC_SERVER_URL>/api/meta-login/callback` listed as a valid OAuth redirect URI. Only `email` and `public_profile` are
334
334
  requested, which need no App Review.
335
335
  - **Database:** the plugin adds a unique `facebookId` field to the users collection; the platform needs a migration for the column.
@@ -70,7 +70,7 @@ function useMetaAppInfo() {
70
70
  var MetaAppInfoBadge = ({ appInfo }) => {
71
71
  if (appInfo.loading) return null;
72
72
  if (!appInfo.configured) {
73
- return /* @__PURE__ */ jsx(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
73
+ return /* @__PURE__ */ jsx(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings." });
74
74
  }
75
75
  return /* @__PURE__ */ jsxs("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
76
76
  /* @__PURE__ */ jsx("span", { children: "Platform Meta App" }),
@@ -6,7 +6,7 @@ import {
6
6
  FieldWrapper,
7
7
  StyledSelect,
8
8
  SuccessState
9
- } from "../../chunk-TSCTFPN2.mjs";
9
+ } from "../../chunk-VPSQ2E3Q.mjs";
10
10
 
11
11
  // src/components/MetaCatalogSync/index.tsx
12
12
  import { useCallback, useState } from "react";
@@ -110,7 +110,7 @@ function useMetaAppInfo() {
110
110
  var MetaAppInfoBadge = ({ appInfo }) => {
111
111
  if (appInfo.loading) return null;
112
112
  if (!appInfo.configured) {
113
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
113
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings." });
114
114
  }
115
115
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
116
116
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Platform Meta App" }),
@@ -15,7 +15,7 @@ import {
15
15
  openMetaOAuthPopup,
16
16
  useMetaAppInfo,
17
17
  useOAuthRedirectMessage
18
- } from "../../chunk-TSCTFPN2.mjs";
18
+ } from "../../chunk-VPSQ2E3Q.mjs";
19
19
 
20
20
  // src/components/MetaConnectPanel/index.tsx
21
21
  import { useCallback as useCallback2, useEffect as useEffect2, useRef as useRef2, useState } from "react";
@@ -6,7 +6,7 @@ import {
6
6
  FieldWrapper,
7
7
  LoadingState,
8
8
  StyledSelect
9
- } from "../../chunk-TSCTFPN2.mjs";
9
+ } from "../../chunk-VPSQ2E3Q.mjs";
10
10
 
11
11
  // src/components/MetaPixelSelect/index.tsx
12
12
  import { useState } from "react";
@@ -89,7 +89,7 @@ function useMetaAppInfo() {
89
89
  var MetaAppInfoBadge = ({ appInfo }) => {
90
90
  if (appInfo.loading) return null;
91
91
  if (!appInfo.configured) {
92
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
92
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ErrorState, { message: "Meta App not configured on this deployment \u2014 the platform owner needs to enter its App ID and secret in Platform Settings." });
93
93
  }
94
94
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { style: { ...messageBoxStyle("info"), display: "flex", justifyContent: "space-between", alignItems: "center" }, children: [
95
95
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "Platform Meta App" }),
@@ -9,7 +9,7 @@ import {
9
9
  SuccessState,
10
10
  useMetaAppInfo,
11
11
  useOAuthRedirectMessage
12
- } from "../../chunk-TSCTFPN2.mjs";
12
+ } from "../../chunk-VPSQ2E3Q.mjs";
13
13
 
14
14
  // src/components/ThreadsConnectPanel/index.tsx
15
15
  import { useCallback, useEffect, useState } from "react";
package/dist/index.d.mts CHANGED
@@ -69,7 +69,7 @@ declare function explainTemplateSendError(body: string): {
69
69
  error: string;
70
70
  } | null;
71
71
 
72
- /** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (META_APP_ID/META_APP_SECRET, see utils/metaCrypto.ts), not part of a site's credentials. */
72
+ /** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (given by the host, see utils/metaCrypto.ts), not part of a site's credentials. */
73
73
  interface MetaCredentials {
74
74
  accessToken: string;
75
75
  businessManagerId?: string;
@@ -229,7 +229,7 @@ declare const metaWhatsAppChannel: NotificationChannelProvider<MetaCloudGateway>
229
229
  * The plugin's webhook: the address Meta calls to report what happens on its side.
230
230
  *
231
231
  * Register `https://<your CMS>/api/meta-webhook` as the callback of the platform's Meta app, for the WhatsApp business account
232
- * topic, with the verify token set in the host's Meta app settings (or `META_WEBHOOK_VERIFY_TOKEN`). Each site's business account is subscribed to the app when
232
+ * topic, with the verify token set in the host's Meta app settings. Each site's business account is subscribed to the app when
233
233
  * the site connects (see utils/wabaSubscription.ts), so its events arrive here.
234
234
  *
235
235
  * - GET answers Meta's handshake.
@@ -350,8 +350,9 @@ interface MetaPluginOptions {
350
350
  host?: MetaHost;
351
351
  /**
352
352
  * The platform's Meta app (App ID, secret, webhook verify token), as the host keeps it in its own settings. Called whenever the plugin needs it, so
353
- * keep it quick (answer from memory). What it returns wins over the `META_APP_ID`, `META_APP_SECRET` and `META_WEBHOOK_VERIFY_TOKEN`
354
- * environment variables, which remain the fallback; a host that gives nothing here keeps working from the environment as before.
353
+ * keep it quick (answer from memory). It is the ONLY source: the plugin does not read the app from the server's environment, so a host that does
354
+ * not pass this leaves Meta Connect, Facebook login and the webhook switched off. (`META_ENCRYPTION_KEY`, the key that protects what is stored,
355
+ * is still read from the environment.)
355
356
  */
356
357
  app?: () => MetaAppSettings | null | undefined;
357
358
  }
package/dist/index.d.ts CHANGED
@@ -69,7 +69,7 @@ declare function explainTemplateSendError(body: string): {
69
69
  error: string;
70
70
  } | null;
71
71
 
72
- /** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (META_APP_ID/META_APP_SECRET, see utils/metaCrypto.ts), not part of a site's credentials. */
72
+ /** Resolved Meta API credentials for a single site, decrypted and ready to use. appId/appSecret are deployment-wide (given by the host, see utils/metaCrypto.ts), not part of a site's credentials. */
73
73
  interface MetaCredentials {
74
74
  accessToken: string;
75
75
  businessManagerId?: string;
@@ -229,7 +229,7 @@ declare const metaWhatsAppChannel: NotificationChannelProvider<MetaCloudGateway>
229
229
  * The plugin's webhook: the address Meta calls to report what happens on its side.
230
230
  *
231
231
  * Register `https://<your CMS>/api/meta-webhook` as the callback of the platform's Meta app, for the WhatsApp business account
232
- * topic, with the verify token set in the host's Meta app settings (or `META_WEBHOOK_VERIFY_TOKEN`). Each site's business account is subscribed to the app when
232
+ * topic, with the verify token set in the host's Meta app settings. Each site's business account is subscribed to the app when
233
233
  * the site connects (see utils/wabaSubscription.ts), so its events arrive here.
234
234
  *
235
235
  * - GET answers Meta's handshake.
@@ -350,8 +350,9 @@ interface MetaPluginOptions {
350
350
  host?: MetaHost;
351
351
  /**
352
352
  * The platform's Meta app (App ID, secret, webhook verify token), as the host keeps it in its own settings. Called whenever the plugin needs it, so
353
- * keep it quick (answer from memory). What it returns wins over the `META_APP_ID`, `META_APP_SECRET` and `META_WEBHOOK_VERIFY_TOKEN`
354
- * environment variables, which remain the fallback; a host that gives nothing here keeps working from the environment as before.
353
+ * keep it quick (answer from memory). It is the ONLY source: the plugin does not read the app from the server's environment, so a host that does
354
+ * not pass this leaves Meta Connect, Facebook login and the webhook switched off. (`META_ENCRYPTION_KEY`, the key that protects what is stored,
355
+ * is still read from the environment.)
355
356
  */
356
357
  app?: () => MetaAppSettings | null | undefined;
357
358
  }
package/dist/index.js CHANGED
@@ -155,7 +155,7 @@ var siteScopedCreate = (siteField = "site") => {
155
155
  if (u.role === "super-admin") return true;
156
156
  if (!["admin", "editor"].includes(u.role)) return false;
157
157
  const rawDocSite = submittedSiteId(data, siteField);
158
- if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return false;
158
+ if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return true;
159
159
  const siteId = getUserSiteId(u);
160
160
  if (siteId) return String(rawDocSite) === String(siteId);
161
161
  if (u.role !== "admin") return false;
@@ -308,11 +308,7 @@ function metaAppSettings() {
308
308
  } catch {
309
309
  given = null;
310
310
  }
311
- return {
312
- appId: text(given?.appId) ?? text(process.env.META_APP_ID),
313
- appSecret: text(given?.appSecret) ?? text(process.env.META_APP_SECRET),
314
- webhookVerifyToken: text(given?.webhookVerifyToken) ?? text(process.env.META_WEBHOOK_VERIFY_TOKEN)
315
- };
311
+ return { appId: text(given?.appId), appSecret: text(given?.appSecret), webhookVerifyToken: text(given?.webhookVerifyToken) };
316
312
  }
317
313
  function getMetaAppCredentials() {
318
314
  const { appId, appSecret } = metaAppSettings();
@@ -565,7 +561,7 @@ var MetaConfig = {
565
561
  // ── Tab 1: Connection ────────────────────────────────
566
562
  {
567
563
  label: "\u{1F511} Connection",
568
- description: "META_APP_ID and META_APP_SECRET are set for the whole deployment. Log in with Facebook below. The fields fill in from that login and stay read-only. Disconnect clears them.",
564
+ description: "The Meta app is set once for the whole platform (by the platform owner, in its settings). Log in with Facebook below. The fields fill in from that login and stay read-only. Disconnect clears them.",
569
565
  fields: [
570
566
  {
571
567
  name: "accessToken",
@@ -773,7 +769,7 @@ var MetaConfig = {
773
769
  name: "catalogItemUrlTemplate",
774
770
  type: "text",
775
771
  admin: {
776
- description: 'Item page URL template on the live site \u2014 "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}. Required before products can sync (Meta rejects an item with no link).',
772
+ description: `Item page URL template on the live site. "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}; "{category.slug}" by the slug of the item's category, for a shop with one page per category whose items are sizes of it, e.g. https://avrilbeetails.com/adun/{category.slug}. Required before products can sync (Meta rejects an item with no link).`,
777
773
  condition: (_data, siblingData) => Boolean(siblingData?.catalogEnabled)
778
774
  }
779
775
  },
@@ -914,6 +910,104 @@ var MetaConfig = {
914
910
  timestamps: true
915
911
  };
916
912
 
913
+ // src/sync/catalogProduct.ts
914
+ var COMMERCE_COLLECTION = "catalogue-items";
915
+ function firstDefined(...values) {
916
+ for (const value of values) {
917
+ if (value !== void 0 && value !== null && value !== "") return value;
918
+ }
919
+ return void 0;
920
+ }
921
+ function plainText(value) {
922
+ if (typeof value === "string") return value;
923
+ if (typeof value === "number") return String(value);
924
+ if (value && typeof value === "object") {
925
+ const record = value;
926
+ for (const entry of Object.values(record)) {
927
+ if (typeof entry === "string" && entry.trim()) return entry;
928
+ }
929
+ }
930
+ return "";
931
+ }
932
+ function stripHtml(input) {
933
+ return input.replace(/<[^>]+>/g, "").trim();
934
+ }
935
+ function resolveImageUrl(media, serverUrl4) {
936
+ if (!media) return "";
937
+ if (typeof media === "string") {
938
+ if (media.startsWith("http://") || media.startsWith("https://")) return media;
939
+ return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
940
+ }
941
+ if (typeof media === "object") {
942
+ const record = media;
943
+ const url = typeof record.url === "string" ? record.url : "";
944
+ if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
945
+ const filename = typeof record.filename === "string" ? record.filename : "";
946
+ if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
947
+ }
948
+ return "";
949
+ }
950
+ function relationId2(value) {
951
+ if (typeof value === "string" || typeof value === "number") return value;
952
+ if (value && typeof value === "object" && "id" in value) {
953
+ const id = value.id;
954
+ if (typeof id === "string" || typeof id === "number") return id;
955
+ }
956
+ return void 0;
957
+ }
958
+ function catalogSourceSlug(configured) {
959
+ const slug = typeof configured === "string" ? configured.trim() : "";
960
+ return slug || COMMERCE_COLLECTION;
961
+ }
962
+ var URL_TEMPLATE_PLACEHOLDERS = ["{slug}", "{category.slug}"];
963
+ function hasUrlPlaceholder(template) {
964
+ return URL_TEMPLATE_PLACEHOLDERS.some((placeholder) => template.includes(placeholder));
965
+ }
966
+ function itemLink(doc, template) {
967
+ let link = template.trim();
968
+ if (!hasUrlPlaceholder(link)) return null;
969
+ if (link.includes("{category.slug}")) {
970
+ const category = doc.category;
971
+ const categorySlug = category && typeof category === "object" ? plainText(category.slug).trim() : "";
972
+ if (!categorySlug) return null;
973
+ link = link.split("{category.slug}").join(encodeURIComponent(categorySlug));
974
+ }
975
+ if (link.includes("{slug}")) link = link.split("{slug}").join(encodeURIComponent(plainText(firstDefined(doc.slug, doc.id))));
976
+ return link;
977
+ }
978
+ function toCatalogItem(doc, options) {
979
+ const title = plainText(firstDefined(doc.title, doc.name, doc.heading)).trim();
980
+ const price = firstDefined(doc.price, doc.price_from, doc.priceFrom);
981
+ if (!title || price === void 0 || price === null || price === "") return null;
982
+ const amount = Number(price);
983
+ if (!Number.isFinite(amount)) return null;
984
+ const link = itemLink(doc, options.urlTemplate);
985
+ if (!link) return null;
986
+ const rawDescription = firstDefined(doc.description, doc.excerpt, doc.body);
987
+ const description = rawDescription ? stripHtml(plainText(rawDescription)).slice(0, 5e3) : title;
988
+ const available = doc.available === void 0 ? true : Boolean(doc.available);
989
+ const currency = (options.currency || "NGN").toUpperCase();
990
+ const image = resolveImageUrl(firstDefined(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
991
+ const item = {
992
+ id: String(doc.id),
993
+ title,
994
+ description,
995
+ availability: available ? "in stock" : "out of stock",
996
+ condition: "new",
997
+ price: `${amount.toFixed(2)} ${currency}`,
998
+ link
999
+ };
1000
+ if (image) item.image_link = image;
1001
+ if (options.brand) item.brand = options.brand;
1002
+ return item;
1003
+ }
1004
+ function updateRequest(item) {
1005
+ return { method: "UPDATE", data: item };
1006
+ }
1007
+ function deleteRequest(retailerId) {
1008
+ return { method: "DELETE", data: { id: retailerId } };
1009
+ }
1010
+
917
1011
  // src/endpoints/metaCatalogFeed.ts
918
1012
  function csvEscape(value) {
919
1013
  const str = value === null || value === void 0 ? "" : String(value);
@@ -922,16 +1016,16 @@ function csvEscape(value) {
922
1016
  }
923
1017
  return str;
924
1018
  }
925
- function firstDefined(...values) {
1019
+ function firstDefined2(...values) {
926
1020
  for (const v of values) {
927
1021
  if (v !== void 0 && v !== null && v !== "") return v;
928
1022
  }
929
1023
  return void 0;
930
1024
  }
931
- function stripHtml(input) {
1025
+ function stripHtml2(input) {
932
1026
  return input.replace(/<[^>]+>/g, "").trim();
933
1027
  }
934
- function resolveImageUrl(media, serverUrl4) {
1028
+ function resolveImageUrl2(media, serverUrl4) {
935
1029
  if (!media) return "";
936
1030
  if (typeof media === "string") {
937
1031
  if (media.startsWith("http://") || media.startsWith("https://")) return media;
@@ -1003,16 +1097,15 @@ var metaCatalogFeedEndpoint = {
1003
1097
  const rows = [header.join(",")];
1004
1098
  for (const item of items) {
1005
1099
  const id = String(item.id);
1006
- const title = String(firstDefined(item.title, item.name, item.heading) ?? "");
1007
- const rawDescription = firstDefined(item.description, item.excerpt, item.body);
1008
- const description = rawDescription ? stripHtml(String(rawDescription)).slice(0, 5e3) : "";
1009
- const price = firstDefined(item.price, item.price_from, item.priceFrom);
1100
+ const title = String(firstDefined2(item.title, item.name, item.heading) ?? "");
1101
+ const rawDescription = firstDefined2(item.description, item.excerpt, item.body);
1102
+ const description = rawDescription ? stripHtml2(String(rawDescription)).slice(0, 5e3) : "";
1103
+ const price = firstDefined2(item.price, item.price_from, item.priceFrom);
1010
1104
  const available = item.available === void 0 ? true : Boolean(item.available);
1011
- const slug = String(firstDefined(item.slug, item.id));
1012
- const link = urlTemplate.replace("{slug}", encodeURIComponent(slug));
1013
- const image = firstDefined(item.image, item.featuredImage, item.photo);
1014
- const imageLink = resolveImageUrl(image, serverUrl4);
1015
- if (!title || price === void 0) continue;
1105
+ const link = itemLink(item, urlTemplate);
1106
+ const image = firstDefined2(item.image, item.featuredImage, item.photo);
1107
+ const imageLink = resolveImageUrl2(image, serverUrl4);
1108
+ if (!title || price === void 0 || !link) continue;
1016
1109
  rows.push([
1017
1110
  csvEscape(id),
1018
1111
  csvEscape(title),
@@ -1208,10 +1301,21 @@ var BASE_DELAY_MS = 800;
1208
1301
  function sleep(ms) {
1209
1302
  return new Promise((resolve) => setTimeout(resolve, ms));
1210
1303
  }
1304
+ var KNOWN_SUBCODES = {
1305
+ 1784018: "This business has not accepted Meta's Pixel terms. Open Events Manager for the business, start connecting a Web data source, accept the terms, then try again (or create the Pixel there and choose it here)."
1306
+ };
1307
+ function explainGraphError(body) {
1308
+ const error = body?.error;
1309
+ if (!error) return null;
1310
+ if (error.error_subcode && KNOWN_SUBCODES[error.error_subcode]) return KNOWN_SUBCODES[error.error_subcode];
1311
+ if (error.error_user_msg) return error.error_user_title ? `${error.error_user_title}: ${error.error_user_msg}` : error.error_user_msg;
1312
+ return error.message ?? null;
1313
+ }
1211
1314
  async function parseGraphError(res) {
1212
1315
  try {
1213
1316
  const body = await res.json();
1214
- if (body?.error?.message) return body.error.message;
1317
+ const said = explainGraphError(body);
1318
+ if (said) return said;
1215
1319
  } catch {
1216
1320
  }
1217
1321
  return `Graph API error: ${res.status}`;
@@ -1338,89 +1442,6 @@ function oauthPopupResponse(args) {
1338
1442
  });
1339
1443
  }
1340
1444
 
1341
- // src/sync/catalogProduct.ts
1342
- var COMMERCE_COLLECTION = "catalogue-items";
1343
- function firstDefined2(...values) {
1344
- for (const value of values) {
1345
- if (value !== void 0 && value !== null && value !== "") return value;
1346
- }
1347
- return void 0;
1348
- }
1349
- function plainText(value) {
1350
- if (typeof value === "string") return value;
1351
- if (typeof value === "number") return String(value);
1352
- if (value && typeof value === "object") {
1353
- const record = value;
1354
- for (const entry of Object.values(record)) {
1355
- if (typeof entry === "string" && entry.trim()) return entry;
1356
- }
1357
- }
1358
- return "";
1359
- }
1360
- function stripHtml2(input) {
1361
- return input.replace(/<[^>]+>/g, "").trim();
1362
- }
1363
- function resolveImageUrl2(media, serverUrl4) {
1364
- if (!media) return "";
1365
- if (typeof media === "string") {
1366
- if (media.startsWith("http://") || media.startsWith("https://")) return media;
1367
- return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
1368
- }
1369
- if (typeof media === "object") {
1370
- const record = media;
1371
- const url = typeof record.url === "string" ? record.url : "";
1372
- if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
1373
- const filename = typeof record.filename === "string" ? record.filename : "";
1374
- if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
1375
- }
1376
- return "";
1377
- }
1378
- function relationId2(value) {
1379
- if (typeof value === "string" || typeof value === "number") return value;
1380
- if (value && typeof value === "object" && "id" in value) {
1381
- const id = value.id;
1382
- if (typeof id === "string" || typeof id === "number") return id;
1383
- }
1384
- return void 0;
1385
- }
1386
- function catalogSourceSlug(configured) {
1387
- const slug = typeof configured === "string" ? configured.trim() : "";
1388
- return slug || COMMERCE_COLLECTION;
1389
- }
1390
- function toCatalogItem(doc, options) {
1391
- const title = plainText(firstDefined2(doc.title, doc.name, doc.heading)).trim();
1392
- const price = firstDefined2(doc.price, doc.price_from, doc.priceFrom);
1393
- if (!title || price === void 0 || price === null || price === "") return null;
1394
- const amount = Number(price);
1395
- if (!Number.isFinite(amount)) return null;
1396
- const slug = plainText(firstDefined2(doc.slug, doc.id));
1397
- const template = options.urlTemplate.trim();
1398
- if (!template.includes("{slug}")) return null;
1399
- const rawDescription = firstDefined2(doc.description, doc.excerpt, doc.body);
1400
- const description = rawDescription ? stripHtml2(plainText(rawDescription)).slice(0, 5e3) : title;
1401
- const available = doc.available === void 0 ? true : Boolean(doc.available);
1402
- const currency = (options.currency || "NGN").toUpperCase();
1403
- const image = resolveImageUrl2(firstDefined2(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
1404
- const item = {
1405
- id: String(doc.id),
1406
- title,
1407
- description,
1408
- availability: available ? "in stock" : "out of stock",
1409
- condition: "new",
1410
- price: `${amount.toFixed(2)} ${currency}`,
1411
- link: template.replace("{slug}", encodeURIComponent(slug))
1412
- };
1413
- if (image) item.image_link = image;
1414
- if (options.brand) item.brand = options.brand;
1415
- return item;
1416
- }
1417
- function updateRequest(item) {
1418
- return { method: "UPDATE", data: item };
1419
- }
1420
- function deleteRequest(retailerId) {
1421
- return { method: "DELETE", data: { id: retailerId } };
1422
- }
1423
-
1424
1445
  // src/sync/catalogSync.ts
1425
1446
  function decryptToken(value) {
1426
1447
  if (typeof value !== "string" || !value || value.includes("\u2022")) return "";
@@ -1473,14 +1494,26 @@ async function pushBatch(catalogId, token, requests) {
1473
1494
  const messages = (result.data?.validation_status ?? []).flatMap((row) => row.errors ?? []).map((error) => error.message).filter((message) => Boolean(message));
1474
1495
  return messages.length ? messages.join("; ") : null;
1475
1496
  }
1497
+ async function withCategoryRead(payload, doc, template) {
1498
+ if (!template.includes("{category.slug}")) return doc;
1499
+ const category = doc.category;
1500
+ if (category == null || typeof category === "object") return doc;
1501
+ try {
1502
+ const read = await payload.findByID({ collection: asCollectionSlug("catalogue-categories"), id: category, depth: 0, overrideAccess: true });
1503
+ return { ...doc, category: read };
1504
+ } catch {
1505
+ return doc;
1506
+ }
1507
+ }
1476
1508
  async function syncCatalogDoc(payload, doc, method, collectionSlug) {
1477
1509
  const siteId = relationId2(doc.site);
1478
1510
  if (siteId == null || doc.id == null) return;
1479
1511
  const config = await findCatalogConfig(payload, siteId);
1480
1512
  if (!config || config.sourceCollection !== collectionSlug) return;
1481
1513
  const serverUrl4 = (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
1514
+ const readDoc = method === "DELETE" ? doc : await withCategoryRead(payload, doc, config.urlTemplate);
1482
1515
  const request = method === "DELETE" ? deleteRequest(String(doc.id)) : (() => {
1483
- const item = toCatalogItem(doc, {
1516
+ const item = toCatalogItem(readDoc, {
1484
1517
  urlTemplate: config.urlTemplate,
1485
1518
  serverUrl: serverUrl4,
1486
1519
  brand: config.brand
@@ -1631,7 +1664,7 @@ var metaOAuthStartEndpoint = {
1631
1664
  }
1632
1665
  const appCreds = getMetaAppCredentials();
1633
1666
  if (!appCreds) {
1634
- return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." }, { status: 400 });
1667
+ return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." }, { status: 400 });
1635
1668
  }
1636
1669
  const state = signOAuthState(configId);
1637
1670
  const params = new URLSearchParams({
@@ -1669,7 +1702,7 @@ var metaOAuthCallbackEndpoint = {
1669
1702
  }
1670
1703
  const appCreds = getMetaAppCredentials();
1671
1704
  if (!appCreds) {
1672
- return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
1705
+ return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." });
1673
1706
  }
1674
1707
  const shortLived = await graphGet("/oauth/access_token", {
1675
1708
  client_id: appCreds.appId,
@@ -1900,6 +1933,7 @@ var metaOAuthCreatePixelEndpoint = {
1900
1933
  access_token: token
1901
1934
  });
1902
1935
  if (!result.ok || !result.data?.id) {
1936
+ req.payload.logger.warn(`[meta:pixel] creating a Pixel on business ${business.id} failed (${result.status}): ${result.error || "no reason given"}`);
1903
1937
  return Response.json({ error: result.error || "Pixel creation failed" }, { status: 502 });
1904
1938
  }
1905
1939
  await req.payload.update({
@@ -1952,7 +1986,7 @@ var threadsOAuthStartEndpoint = {
1952
1986
  }
1953
1987
  const appCreds = getMetaAppCredentials();
1954
1988
  if (!appCreds) {
1955
- return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." }, { status: 400 });
1989
+ return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." }, { status: 400 });
1956
1990
  }
1957
1991
  const state = signOAuthState(configId);
1958
1992
  const params = new URLSearchParams({
@@ -1990,7 +2024,7 @@ var threadsOAuthCallbackEndpoint = {
1990
2024
  }
1991
2025
  const appCreds = getMetaAppCredentials();
1992
2026
  if (!appCreds) {
1993
- return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET).")}`, 302);
2027
+ return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings.")}`, 302);
1994
2028
  }
1995
2029
  const shortLived = await threadsPost("/oauth/access_token", {
1996
2030
  client_id: appCreds.appId,
@@ -2182,7 +2216,7 @@ var metaCatalogSyncEndpoint = {
2182
2216
  return Response.json({ error: "Turn on Commerce Catalog and choose a catalog first." }, { status: 400 });
2183
2217
  }
2184
2218
  if (!config.catalogItemUrlTemplate) {
2185
- return Response.json({ error: "Set the item page URL template (it must contain {slug}) before syncing." }, { status: 400 });
2219
+ return Response.json({ error: "Set the item page URL template (it must contain {slug} or {category.slug}) before syncing." }, { status: 400 });
2186
2220
  }
2187
2221
  const siteId = relationId2(config.site);
2188
2222
  if (siteId == null) return Response.json({ error: "This Meta connection has no site." }, { status: 400 });
package/dist/index.mjs CHANGED
@@ -119,7 +119,7 @@ var siteScopedCreate = (siteField = "site") => {
119
119
  if (u.role === "super-admin") return true;
120
120
  if (!["admin", "editor"].includes(u.role)) return false;
121
121
  const rawDocSite = submittedSiteId(data, siteField);
122
- if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return false;
122
+ if (rawDocSite === void 0 || rawDocSite === null || rawDocSite === "") return true;
123
123
  const siteId = getUserSiteId(u);
124
124
  if (siteId) return String(rawDocSite) === String(siteId);
125
125
  if (u.role !== "admin") return false;
@@ -272,11 +272,7 @@ function metaAppSettings() {
272
272
  } catch {
273
273
  given = null;
274
274
  }
275
- return {
276
- appId: text(given?.appId) ?? text(process.env.META_APP_ID),
277
- appSecret: text(given?.appSecret) ?? text(process.env.META_APP_SECRET),
278
- webhookVerifyToken: text(given?.webhookVerifyToken) ?? text(process.env.META_WEBHOOK_VERIFY_TOKEN)
279
- };
275
+ return { appId: text(given?.appId), appSecret: text(given?.appSecret), webhookVerifyToken: text(given?.webhookVerifyToken) };
280
276
  }
281
277
  function getMetaAppCredentials() {
282
278
  const { appId, appSecret } = metaAppSettings();
@@ -529,7 +525,7 @@ var MetaConfig = {
529
525
  // ── Tab 1: Connection ────────────────────────────────
530
526
  {
531
527
  label: "\u{1F511} Connection",
532
- description: "META_APP_ID and META_APP_SECRET are set for the whole deployment. Log in with Facebook below. The fields fill in from that login and stay read-only. Disconnect clears them.",
528
+ description: "The Meta app is set once for the whole platform (by the platform owner, in its settings). Log in with Facebook below. The fields fill in from that login and stay read-only. Disconnect clears them.",
533
529
  fields: [
534
530
  {
535
531
  name: "accessToken",
@@ -737,7 +733,7 @@ var MetaConfig = {
737
733
  name: "catalogItemUrlTemplate",
738
734
  type: "text",
739
735
  admin: {
740
- description: 'Item page URL template on the live site \u2014 "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}. Required before products can sync (Meta rejects an item with no link).',
736
+ description: `Item page URL template on the live site. "{slug}" is replaced per item, e.g. https://thatofadagirl.com/menu/{slug}; "{category.slug}" by the slug of the item's category, for a shop with one page per category whose items are sizes of it, e.g. https://avrilbeetails.com/adun/{category.slug}. Required before products can sync (Meta rejects an item with no link).`,
741
737
  condition: (_data, siblingData) => Boolean(siblingData?.catalogEnabled)
742
738
  }
743
739
  },
@@ -878,6 +874,104 @@ var MetaConfig = {
878
874
  timestamps: true
879
875
  };
880
876
 
877
+ // src/sync/catalogProduct.ts
878
+ var COMMERCE_COLLECTION = "catalogue-items";
879
+ function firstDefined(...values) {
880
+ for (const value of values) {
881
+ if (value !== void 0 && value !== null && value !== "") return value;
882
+ }
883
+ return void 0;
884
+ }
885
+ function plainText(value) {
886
+ if (typeof value === "string") return value;
887
+ if (typeof value === "number") return String(value);
888
+ if (value && typeof value === "object") {
889
+ const record = value;
890
+ for (const entry of Object.values(record)) {
891
+ if (typeof entry === "string" && entry.trim()) return entry;
892
+ }
893
+ }
894
+ return "";
895
+ }
896
+ function stripHtml(input) {
897
+ return input.replace(/<[^>]+>/g, "").trim();
898
+ }
899
+ function resolveImageUrl(media, serverUrl4) {
900
+ if (!media) return "";
901
+ if (typeof media === "string") {
902
+ if (media.startsWith("http://") || media.startsWith("https://")) return media;
903
+ return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
904
+ }
905
+ if (typeof media === "object") {
906
+ const record = media;
907
+ const url = typeof record.url === "string" ? record.url : "";
908
+ if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
909
+ const filename = typeof record.filename === "string" ? record.filename : "";
910
+ if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
911
+ }
912
+ return "";
913
+ }
914
+ function relationId2(value) {
915
+ if (typeof value === "string" || typeof value === "number") return value;
916
+ if (value && typeof value === "object" && "id" in value) {
917
+ const id = value.id;
918
+ if (typeof id === "string" || typeof id === "number") return id;
919
+ }
920
+ return void 0;
921
+ }
922
+ function catalogSourceSlug(configured) {
923
+ const slug = typeof configured === "string" ? configured.trim() : "";
924
+ return slug || COMMERCE_COLLECTION;
925
+ }
926
+ var URL_TEMPLATE_PLACEHOLDERS = ["{slug}", "{category.slug}"];
927
+ function hasUrlPlaceholder(template) {
928
+ return URL_TEMPLATE_PLACEHOLDERS.some((placeholder) => template.includes(placeholder));
929
+ }
930
+ function itemLink(doc, template) {
931
+ let link = template.trim();
932
+ if (!hasUrlPlaceholder(link)) return null;
933
+ if (link.includes("{category.slug}")) {
934
+ const category = doc.category;
935
+ const categorySlug = category && typeof category === "object" ? plainText(category.slug).trim() : "";
936
+ if (!categorySlug) return null;
937
+ link = link.split("{category.slug}").join(encodeURIComponent(categorySlug));
938
+ }
939
+ if (link.includes("{slug}")) link = link.split("{slug}").join(encodeURIComponent(plainText(firstDefined(doc.slug, doc.id))));
940
+ return link;
941
+ }
942
+ function toCatalogItem(doc, options) {
943
+ const title = plainText(firstDefined(doc.title, doc.name, doc.heading)).trim();
944
+ const price = firstDefined(doc.price, doc.price_from, doc.priceFrom);
945
+ if (!title || price === void 0 || price === null || price === "") return null;
946
+ const amount = Number(price);
947
+ if (!Number.isFinite(amount)) return null;
948
+ const link = itemLink(doc, options.urlTemplate);
949
+ if (!link) return null;
950
+ const rawDescription = firstDefined(doc.description, doc.excerpt, doc.body);
951
+ const description = rawDescription ? stripHtml(plainText(rawDescription)).slice(0, 5e3) : title;
952
+ const available = doc.available === void 0 ? true : Boolean(doc.available);
953
+ const currency = (options.currency || "NGN").toUpperCase();
954
+ const image = resolveImageUrl(firstDefined(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
955
+ const item = {
956
+ id: String(doc.id),
957
+ title,
958
+ description,
959
+ availability: available ? "in stock" : "out of stock",
960
+ condition: "new",
961
+ price: `${amount.toFixed(2)} ${currency}`,
962
+ link
963
+ };
964
+ if (image) item.image_link = image;
965
+ if (options.brand) item.brand = options.brand;
966
+ return item;
967
+ }
968
+ function updateRequest(item) {
969
+ return { method: "UPDATE", data: item };
970
+ }
971
+ function deleteRequest(retailerId) {
972
+ return { method: "DELETE", data: { id: retailerId } };
973
+ }
974
+
881
975
  // src/endpoints/metaCatalogFeed.ts
882
976
  function csvEscape(value) {
883
977
  const str = value === null || value === void 0 ? "" : String(value);
@@ -886,16 +980,16 @@ function csvEscape(value) {
886
980
  }
887
981
  return str;
888
982
  }
889
- function firstDefined(...values) {
983
+ function firstDefined2(...values) {
890
984
  for (const v of values) {
891
985
  if (v !== void 0 && v !== null && v !== "") return v;
892
986
  }
893
987
  return void 0;
894
988
  }
895
- function stripHtml(input) {
989
+ function stripHtml2(input) {
896
990
  return input.replace(/<[^>]+>/g, "").trim();
897
991
  }
898
- function resolveImageUrl(media, serverUrl4) {
992
+ function resolveImageUrl2(media, serverUrl4) {
899
993
  if (!media) return "";
900
994
  if (typeof media === "string") {
901
995
  if (media.startsWith("http://") || media.startsWith("https://")) return media;
@@ -967,16 +1061,15 @@ var metaCatalogFeedEndpoint = {
967
1061
  const rows = [header.join(",")];
968
1062
  for (const item of items) {
969
1063
  const id = String(item.id);
970
- const title = String(firstDefined(item.title, item.name, item.heading) ?? "");
971
- const rawDescription = firstDefined(item.description, item.excerpt, item.body);
972
- const description = rawDescription ? stripHtml(String(rawDescription)).slice(0, 5e3) : "";
973
- const price = firstDefined(item.price, item.price_from, item.priceFrom);
1064
+ const title = String(firstDefined2(item.title, item.name, item.heading) ?? "");
1065
+ const rawDescription = firstDefined2(item.description, item.excerpt, item.body);
1066
+ const description = rawDescription ? stripHtml2(String(rawDescription)).slice(0, 5e3) : "";
1067
+ const price = firstDefined2(item.price, item.price_from, item.priceFrom);
974
1068
  const available = item.available === void 0 ? true : Boolean(item.available);
975
- const slug = String(firstDefined(item.slug, item.id));
976
- const link = urlTemplate.replace("{slug}", encodeURIComponent(slug));
977
- const image = firstDefined(item.image, item.featuredImage, item.photo);
978
- const imageLink = resolveImageUrl(image, serverUrl4);
979
- if (!title || price === void 0) continue;
1069
+ const link = itemLink(item, urlTemplate);
1070
+ const image = firstDefined2(item.image, item.featuredImage, item.photo);
1071
+ const imageLink = resolveImageUrl2(image, serverUrl4);
1072
+ if (!title || price === void 0 || !link) continue;
980
1073
  rows.push([
981
1074
  csvEscape(id),
982
1075
  csvEscape(title),
@@ -1172,10 +1265,21 @@ var BASE_DELAY_MS = 800;
1172
1265
  function sleep(ms) {
1173
1266
  return new Promise((resolve) => setTimeout(resolve, ms));
1174
1267
  }
1268
+ var KNOWN_SUBCODES = {
1269
+ 1784018: "This business has not accepted Meta's Pixel terms. Open Events Manager for the business, start connecting a Web data source, accept the terms, then try again (or create the Pixel there and choose it here)."
1270
+ };
1271
+ function explainGraphError(body) {
1272
+ const error = body?.error;
1273
+ if (!error) return null;
1274
+ if (error.error_subcode && KNOWN_SUBCODES[error.error_subcode]) return KNOWN_SUBCODES[error.error_subcode];
1275
+ if (error.error_user_msg) return error.error_user_title ? `${error.error_user_title}: ${error.error_user_msg}` : error.error_user_msg;
1276
+ return error.message ?? null;
1277
+ }
1175
1278
  async function parseGraphError(res) {
1176
1279
  try {
1177
1280
  const body = await res.json();
1178
- if (body?.error?.message) return body.error.message;
1281
+ const said = explainGraphError(body);
1282
+ if (said) return said;
1179
1283
  } catch {
1180
1284
  }
1181
1285
  return `Graph API error: ${res.status}`;
@@ -1279,89 +1383,6 @@ function oauthPopupResponse(args) {
1279
1383
  });
1280
1384
  }
1281
1385
 
1282
- // src/sync/catalogProduct.ts
1283
- var COMMERCE_COLLECTION = "catalogue-items";
1284
- function firstDefined2(...values) {
1285
- for (const value of values) {
1286
- if (value !== void 0 && value !== null && value !== "") return value;
1287
- }
1288
- return void 0;
1289
- }
1290
- function plainText(value) {
1291
- if (typeof value === "string") return value;
1292
- if (typeof value === "number") return String(value);
1293
- if (value && typeof value === "object") {
1294
- const record = value;
1295
- for (const entry of Object.values(record)) {
1296
- if (typeof entry === "string" && entry.trim()) return entry;
1297
- }
1298
- }
1299
- return "";
1300
- }
1301
- function stripHtml2(input) {
1302
- return input.replace(/<[^>]+>/g, "").trim();
1303
- }
1304
- function resolveImageUrl2(media, serverUrl4) {
1305
- if (!media) return "";
1306
- if (typeof media === "string") {
1307
- if (media.startsWith("http://") || media.startsWith("https://")) return media;
1308
- return `${serverUrl4}/api/media/serve/${encodeURIComponent(media)}`;
1309
- }
1310
- if (typeof media === "object") {
1311
- const record = media;
1312
- const url = typeof record.url === "string" ? record.url : "";
1313
- if (url) return url.startsWith("http") ? url : `${serverUrl4}${url}`;
1314
- const filename = typeof record.filename === "string" ? record.filename : "";
1315
- if (filename) return `${serverUrl4}/api/media/serve/${encodeURIComponent(filename)}`;
1316
- }
1317
- return "";
1318
- }
1319
- function relationId2(value) {
1320
- if (typeof value === "string" || typeof value === "number") return value;
1321
- if (value && typeof value === "object" && "id" in value) {
1322
- const id = value.id;
1323
- if (typeof id === "string" || typeof id === "number") return id;
1324
- }
1325
- return void 0;
1326
- }
1327
- function catalogSourceSlug(configured) {
1328
- const slug = typeof configured === "string" ? configured.trim() : "";
1329
- return slug || COMMERCE_COLLECTION;
1330
- }
1331
- function toCatalogItem(doc, options) {
1332
- const title = plainText(firstDefined2(doc.title, doc.name, doc.heading)).trim();
1333
- const price = firstDefined2(doc.price, doc.price_from, doc.priceFrom);
1334
- if (!title || price === void 0 || price === null || price === "") return null;
1335
- const amount = Number(price);
1336
- if (!Number.isFinite(amount)) return null;
1337
- const slug = plainText(firstDefined2(doc.slug, doc.id));
1338
- const template = options.urlTemplate.trim();
1339
- if (!template.includes("{slug}")) return null;
1340
- const rawDescription = firstDefined2(doc.description, doc.excerpt, doc.body);
1341
- const description = rawDescription ? stripHtml2(plainText(rawDescription)).slice(0, 5e3) : title;
1342
- const available = doc.available === void 0 ? true : Boolean(doc.available);
1343
- const currency = (options.currency || "NGN").toUpperCase();
1344
- const image = resolveImageUrl2(firstDefined2(doc.image, doc.featuredImage, doc.photo), options.serverUrl);
1345
- const item = {
1346
- id: String(doc.id),
1347
- title,
1348
- description,
1349
- availability: available ? "in stock" : "out of stock",
1350
- condition: "new",
1351
- price: `${amount.toFixed(2)} ${currency}`,
1352
- link: template.replace("{slug}", encodeURIComponent(slug))
1353
- };
1354
- if (image) item.image_link = image;
1355
- if (options.brand) item.brand = options.brand;
1356
- return item;
1357
- }
1358
- function updateRequest(item) {
1359
- return { method: "UPDATE", data: item };
1360
- }
1361
- function deleteRequest(retailerId) {
1362
- return { method: "DELETE", data: { id: retailerId } };
1363
- }
1364
-
1365
1386
  // src/sync/catalogSync.ts
1366
1387
  function decryptToken(value) {
1367
1388
  if (typeof value !== "string" || !value || value.includes("\u2022")) return "";
@@ -1414,14 +1435,26 @@ async function pushBatch(catalogId, token, requests) {
1414
1435
  const messages = (result.data?.validation_status ?? []).flatMap((row) => row.errors ?? []).map((error) => error.message).filter((message) => Boolean(message));
1415
1436
  return messages.length ? messages.join("; ") : null;
1416
1437
  }
1438
+ async function withCategoryRead(payload, doc, template) {
1439
+ if (!template.includes("{category.slug}")) return doc;
1440
+ const category = doc.category;
1441
+ if (category == null || typeof category === "object") return doc;
1442
+ try {
1443
+ const read = await payload.findByID({ collection: asCollectionSlug("catalogue-categories"), id: category, depth: 0, overrideAccess: true });
1444
+ return { ...doc, category: read };
1445
+ } catch {
1446
+ return doc;
1447
+ }
1448
+ }
1417
1449
  async function syncCatalogDoc(payload, doc, method, collectionSlug) {
1418
1450
  const siteId = relationId2(doc.site);
1419
1451
  if (siteId == null || doc.id == null) return;
1420
1452
  const config = await findCatalogConfig(payload, siteId);
1421
1453
  if (!config || config.sourceCollection !== collectionSlug) return;
1422
1454
  const serverUrl4 = (process.env.PAYLOAD_PUBLIC_SERVER_URL || "").replace(/\/+$/, "");
1455
+ const readDoc = method === "DELETE" ? doc : await withCategoryRead(payload, doc, config.urlTemplate);
1423
1456
  const request = method === "DELETE" ? deleteRequest(String(doc.id)) : (() => {
1424
- const item = toCatalogItem(doc, {
1457
+ const item = toCatalogItem(readDoc, {
1425
1458
  urlTemplate: config.urlTemplate,
1426
1459
  serverUrl: serverUrl4,
1427
1460
  brand: config.brand
@@ -1572,7 +1605,7 @@ var metaOAuthStartEndpoint = {
1572
1605
  }
1573
1606
  const appCreds = getMetaAppCredentials();
1574
1607
  if (!appCreds) {
1575
- return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." }, { status: 400 });
1608
+ return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." }, { status: 400 });
1576
1609
  }
1577
1610
  const state = signOAuthState(configId);
1578
1611
  const params = new URLSearchParams({
@@ -1610,7 +1643,7 @@ var metaOAuthCallbackEndpoint = {
1610
1643
  }
1611
1644
  const appCreds = getMetaAppCredentials();
1612
1645
  if (!appCreds) {
1613
- return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." });
1646
+ return oauthFinished({ ok: false, configId, error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." });
1614
1647
  }
1615
1648
  const shortLived = await graphGet("/oauth/access_token", {
1616
1649
  client_id: appCreds.appId,
@@ -1841,6 +1874,7 @@ var metaOAuthCreatePixelEndpoint = {
1841
1874
  access_token: token
1842
1875
  });
1843
1876
  if (!result.ok || !result.data?.id) {
1877
+ req.payload.logger.warn(`[meta:pixel] creating a Pixel on business ${business.id} failed (${result.status}): ${result.error || "no reason given"}`);
1844
1878
  return Response.json({ error: result.error || "Pixel creation failed" }, { status: 502 });
1845
1879
  }
1846
1880
  await req.payload.update({
@@ -1893,7 +1927,7 @@ var threadsOAuthStartEndpoint = {
1893
1927
  }
1894
1928
  const appCreds = getMetaAppCredentials();
1895
1929
  if (!appCreds) {
1896
- return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET)." }, { status: 400 });
1930
+ return Response.json({ error: "Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings." }, { status: 400 });
1897
1931
  }
1898
1932
  const state = signOAuthState(configId);
1899
1933
  const params = new URLSearchParams({
@@ -1931,7 +1965,7 @@ var threadsOAuthCallbackEndpoint = {
1931
1965
  }
1932
1966
  const appCreds = getMetaAppCredentials();
1933
1967
  if (!appCreds) {
1934
- return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings (or set META_APP_ID and META_APP_SECRET).")}`, 302);
1968
+ return Response.redirect(`${adminBase}/${configId}?threads_oauth_error=${encodeURIComponent("Meta App not configured on this deployment \u2014 enter its App ID and secret in Platform Settings.")}`, 302);
1935
1969
  }
1936
1970
  const shortLived = await threadsPost("/oauth/access_token", {
1937
1971
  client_id: appCreds.appId,
@@ -2123,7 +2157,7 @@ var metaCatalogSyncEndpoint = {
2123
2157
  return Response.json({ error: "Turn on Commerce Catalog and choose a catalog first." }, { status: 400 });
2124
2158
  }
2125
2159
  if (!config.catalogItemUrlTemplate) {
2126
- return Response.json({ error: "Set the item page URL template (it must contain {slug}) before syncing." }, { status: 400 });
2160
+ return Response.json({ error: "Set the item page URL template (it must contain {slug} or {category.slug}) before syncing." }, { status: 400 });
2127
2161
  }
2128
2162
  const siteId = relationId2(config.site);
2129
2163
  if (siteId == null) return Response.json({ error: "This Meta connection has no site." }, { status: 400 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opscms-meta-plugin",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Payload CMS plugin for connecting multi-tenant sites to Meta's network (Facebook Pixel + Conversions API, Facebook/Instagram Commerce Catalog, WhatsApp Business Cloud API). Modular per-channel, per-site — nothing hardcoded to one product line.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",