@foundrykit/guides-plugin 0.1.1 → 0.2.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/README.md CHANGED
@@ -48,10 +48,18 @@ Then regenerate the import map (`payload generate:importmap`) and create a migra
48
48
  | `hubURL` | `process.env.GUIDES_HUB_URL` | The guides hub. |
49
49
  | `siteKey` | `process.env.GUIDES_HUB_KEY` | This site's guides key. Also verifies the hub's webhook signature. |
50
50
  | `features` | `[]` | Feature keys reported to the hub. |
51
+ | `plugins` | `[]` | Extra FoundryKit plugins to report as active (see below). |
51
52
  | `canAuthor` | `() => false` | Who sees and writes Site guides. |
52
53
  | `schedule` | `'0 0 * * * *'` (hourly) | Cron for the backstop pull (Payload's 6-field form), or `false`. |
53
54
  | `disabled` | `false` | |
54
55
 
56
+ ### Plugin guides
57
+
58
+ The hub sends a site the guides for each FoundryKit plugin it runs. Every FoundryKit Payload plugin records its
59
+ npm name in `config.custom.foundrykit.activePlugins` when it is enabled (installed-but-`disabled` doesn't count),
60
+ and this plugin reports that list on every pull. Plugin order in `plugins: [...]` doesn't matter: the list is read
61
+ from the running config. Add a plugin to the `plugins` option only if its version predates self-reporting.
62
+
55
63
  ### The scheduled pull
56
64
 
57
65
  The plugin registers a `guidesSync` task scheduled on the `default` queue. Payload only runs schedules
@@ -73,7 +81,7 @@ A guide shows there when its **help contexts** (set in the hub, or on a site gui
73
81
 
74
82
  | | |
75
83
  | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
76
- | Pull | `GET <hub>/api/sites/feed?pluginVersion=…&features=…` with `Authorization: sites API-Key <key>` |
84
+ | Pull | `GET <hub>/api/sites/feed?pluginVersion=…&features=…&plugins=…` with `Authorization: sites API-Key <key>` |
77
85
  | Ping | The hub POSTs to `/api/guides/sync` with `x-guides-signature: sha256=<HMAC of the body, keyed with the site key>`. Anything else gets 401. |
78
86
  | Site guides | Publish → `POST`/`PATCH <hub>/api/guides[/:id]`; delete → `DELETE`. |
79
87
 
@@ -0,0 +1,10 @@
1
+ import type { Config } from 'payload';
2
+ /**
3
+ * Records this plugin as active in `config.custom.foundrykit.activePlugins`, the list
4
+ * `@foundrykit/guides-plugin` sends to the guides hub so the site gets this plugin's guides.
5
+ * Only call it on the enabled path: installed-but-disabled doesn't count.
6
+ *
7
+ * Every FoundryKit Payload plugin carries its own copy of this file (it's too small for a package);
8
+ * keep them identical.
9
+ */
10
+ export declare const recordActivePlugin: (config: Config, name: string) => Config;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Records this plugin as active in `config.custom.foundrykit.activePlugins`, the list
3
+ * `@foundrykit/guides-plugin` sends to the guides hub so the site gets this plugin's guides.
4
+ * Only call it on the enabled path: installed-but-disabled doesn't count.
5
+ *
6
+ * Every FoundryKit Payload plugin carries its own copy of this file (it's too small for a package);
7
+ * keep them identical.
8
+ */ export const recordActivePlugin = (config, name)=>{
9
+ const foundrykit = config.custom?.foundrykit ?? {};
10
+ return {
11
+ ...config,
12
+ custom: {
13
+ ...config.custom,
14
+ foundrykit: {
15
+ ...foundrykit,
16
+ activePlugins: [
17
+ ...new Set([
18
+ ...foundrykit.activePlugins ?? [],
19
+ name
20
+ ])
21
+ ]
22
+ }
23
+ }
24
+ };
25
+ };
26
+
27
+ //# sourceMappingURL=activePlugins.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/activePlugins.ts"],"sourcesContent":["import type { Config } from 'payload';\n\n/**\n * Records this plugin as active in `config.custom.foundrykit.activePlugins`, the list\n * `@foundrykit/guides-plugin` sends to the guides hub so the site gets this plugin's guides.\n * Only call it on the enabled path: installed-but-disabled doesn't count.\n *\n * Every FoundryKit Payload plugin carries its own copy of this file (it's too small for a package);\n * keep them identical.\n */\nexport const recordActivePlugin = (config: Config, name: string): Config => {\n const foundrykit = (config.custom?.foundrykit ?? {}) as {\n activePlugins?: string[];\n };\n return {\n ...config,\n custom: {\n ...config.custom,\n foundrykit: {\n ...foundrykit,\n activePlugins: [\n ...new Set([...(foundrykit.activePlugins ?? []), name]),\n ],\n },\n },\n };\n};\n"],"names":["recordActivePlugin","config","name","foundrykit","custom","activePlugins","Set"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,MAAMA,qBAAqB,CAACC,QAAgBC;IACjD,MAAMC,aAAcF,OAAOG,MAAM,EAAED,cAAc,CAAC;IAGlD,OAAO;QACL,GAAGF,MAAM;QACTG,QAAQ;YACN,GAAGH,OAAOG,MAAM;YAChBD,YAAY;gBACV,GAAGA,UAAU;gBACbE,eAAe;uBACV,IAAIC,IAAI;2BAAKH,WAAWE,aAAa,IAAI,EAAE;wBAAGH;qBAAK;iBACvD;YACH;QACF;IACF;AACF,EAAE"}
@@ -76,8 +76,12 @@ import { syncGuides } from '../sync.js';
76
76
  type: 'select',
77
77
  options: [
78
78
  {
79
- label: 'General',
80
- value: 'general'
79
+ label: 'Default',
80
+ value: 'default'
81
+ },
82
+ {
83
+ label: 'Plugin',
84
+ value: 'plugin'
81
85
  },
82
86
  {
83
87
  label: 'This site',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/collections/guides.ts"],"sourcesContent":["import type { CollectionConfig, Endpoint } from 'payload';\n\nimport {\n GUIDES_SLUG,\n type ResolvedConfig,\n SIGNATURE_HEADER,\n verifySignature,\n} from '../hub.js';\nimport { syncGuides } from '../sync.js';\n\n/** POST /api/guides/sync: the hub's signed \"guides changed\" ping. Pulls this site's feed. */\nconst syncEndpoint = (config: ResolvedConfig): Endpoint => ({\n path: '/sync',\n method: 'post',\n handler: async req => {\n const body = (await req.text?.()) ?? '';\n if (\n !config.siteKey ||\n !verifySignature(config.siteKey, body, req.headers.get(SIGNATURE_HEADER))\n ) {\n return Response.json(\n { error: 'Signature does not match this site’s guides key.' },\n { status: 401 }\n );\n }\n try {\n return Response.json(await syncGuides(req.payload, config));\n } catch (err) {\n req.payload.logger.error({ err }, 'Guides sync failed');\n return Response.json(\n { error: 'Could not sync from the guides hub.' },\n { status: 502 }\n );\n }\n },\n});\n\n/**\n * The read-only local copy of the guides this site is entitled to. Only sync writes it, so help\n * works when the hub is down and nothing waits on a network call. People read it through the\n * Guides page and Help buttons, not the collection list.\n */\nexport const guidesCollection = (config: ResolvedConfig): CollectionConfig => ({\n slug: GUIDES_SLUG,\n labels: { singular: 'Guide', plural: 'Guides' },\n admin: { hidden: true, useAsTitle: 'title' },\n access: {\n read: ({ req: { user } }) => Boolean(user),\n create: () => false,\n update: () => false,\n delete: () => false,\n },\n endpoints: [syncEndpoint(config)],\n fields: [\n { name: 'hubId', type: 'text', required: true, unique: true, index: true },\n { name: 'title', type: 'text', required: true },\n { name: 'slug', type: 'text', index: true },\n { name: 'summary', type: 'textarea' },\n {\n name: 'scope',\n type: 'select',\n options: [\n { label: 'General', value: 'general' },\n { label: 'This site', value: 'site' },\n ],\n },\n {\n name: 'topic',\n type: 'group',\n fields: [\n { name: 'title', type: 'text' },\n { name: 'order', type: 'number' },\n ],\n },\n { name: 'helpContexts', type: 'text', hasMany: true, index: true },\n { name: 'order', type: 'number' },\n // Lexical JSON from the hub, rendered as-is. Not a richText field: its images and nodes\n // belong to the hub, so this site's editor shouldn't validate or populate them.\n { name: 'body', type: 'json' },\n { name: 'bodyText', type: 'text' },\n { name: 'hubUpdatedAt', type: 'text' },\n ],\n});\n"],"names":["GUIDES_SLUG","SIGNATURE_HEADER","verifySignature","syncGuides","syncEndpoint","config","path","method","handler","req","body","text","siteKey","headers","get","Response","json","error","status","payload","err","logger","guidesCollection","slug","labels","singular","plural","admin","hidden","useAsTitle","access","read","user","Boolean","create","update","delete","endpoints","fields","name","type","required","unique","index","options","label","value","hasMany"],"mappings":"AAEA,SACEA,WAAW,EAEXC,gBAAgB,EAChBC,eAAe,QACV,YAAY;AACnB,SAASC,UAAU,QAAQ,aAAa;AAExC,2FAA2F,GAC3F,MAAMC,eAAe,CAACC,SAAsC,CAAA;QAC1DC,MAAM;QACNC,QAAQ;QACRC,SAAS,OAAMC;YACb,MAAMC,OAAO,AAA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AAED,OAAO;wBAAaC,OAAO;oBAAO;iBACrC;YACH;YACA;gBACEP,MAAM;gBACNC,MAAM;gBACNF,QAAQ;oBACN;wBAAEC,MAAM;wBAASC,MAAM;oBAAO;oBAC9B;wBAAED,MAAM;wBAASC,MAAM;oBAAS;iBACjC;YACH;YACA;gBAAED,MAAM;gBAAgBC,MAAM;gBAAQO,SAAS;gBAAMJ,OAAO;YAAK;YACjE;gBAAEJ,MAAM;gBAASC,MAAM;YAAS;YAChC,wFAAwF;YACxF,gFAAgF;YAChF;gBAAED,MAAM;gBAAQC,MAAM;YAAO;YAC7B;gBAAED,MAAM;gBAAYC,MAAM;YAAO;YACjC;gBAAED,MAAM;gBAAgBC,MAAM;YAAO;SACtC;IACH,CAAA,EAAG"}
1
+ {"version":3,"sources":["../../src/collections/guides.ts"],"sourcesContent":["import type { CollectionConfig, Endpoint } from 'payload';\n\nimport {\n GUIDES_SLUG,\n type ResolvedConfig,\n SIGNATURE_HEADER,\n verifySignature,\n} from '../hub.js';\nimport { syncGuides } from '../sync.js';\n\n/** POST /api/guides/sync: the hub's signed \"guides changed\" ping. Pulls this site's feed. */\nconst syncEndpoint = (config: ResolvedConfig): Endpoint => ({\n path: '/sync',\n method: 'post',\n handler: async req => {\n const body = (await req.text?.()) ?? '';\n if (\n !config.siteKey ||\n !verifySignature(config.siteKey, body, req.headers.get(SIGNATURE_HEADER))\n ) {\n return Response.json(\n { error: 'Signature does not match this site’s guides key.' },\n { status: 401 }\n );\n }\n try {\n return Response.json(await syncGuides(req.payload, config));\n } catch (err) {\n req.payload.logger.error({ err }, 'Guides sync failed');\n return Response.json(\n { error: 'Could not sync from the guides hub.' },\n { status: 502 }\n );\n }\n },\n});\n\n/**\n * The read-only local copy of the guides this site is entitled to. Only sync writes it, so help\n * works when the hub is down and nothing waits on a network call. People read it through the\n * Guides page and Help buttons, not the collection list.\n */\nexport const guidesCollection = (config: ResolvedConfig): CollectionConfig => ({\n slug: GUIDES_SLUG,\n labels: { singular: 'Guide', plural: 'Guides' },\n admin: { hidden: true, useAsTitle: 'title' },\n access: {\n read: ({ req: { user } }) => Boolean(user),\n create: () => false,\n update: () => false,\n delete: () => false,\n },\n endpoints: [syncEndpoint(config)],\n fields: [\n { name: 'hubId', type: 'text', required: true, unique: true, index: true },\n { name: 'title', type: 'text', required: true },\n { name: 'slug', type: 'text', index: true },\n { name: 'summary', type: 'textarea' },\n {\n name: 'scope',\n type: 'select',\n options: [\n { label: 'Default', value: 'default' },\n { label: 'Plugin', value: 'plugin' },\n { label: 'This site', value: 'site' },\n ],\n },\n {\n name: 'topic',\n type: 'group',\n fields: [\n { name: 'title', type: 'text' },\n { name: 'order', type: 'number' },\n ],\n },\n { name: 'helpContexts', type: 'text', hasMany: true, index: true },\n { name: 'order', type: 'number' },\n // Lexical JSON from the hub, rendered as-is. Not a richText field: its images and nodes\n // belong to the hub, so this site's editor shouldn't validate or populate them.\n { name: 'body', type: 'json' },\n { name: 'bodyText', type: 'text' },\n { name: 'hubUpdatedAt', type: 'text' },\n ],\n});\n"],"names":["GUIDES_SLUG","SIGNATURE_HEADER","verifySignature","syncGuides","syncEndpoint","config","path","method","handler","req","body","text","siteKey","headers","get","Response","json","error","status","payload","err","logger","guidesCollection","slug","labels","singular","plural","admin","hidden","useAsTitle","access","read","user","Boolean","create","update","delete","endpoints","fields","name","type","required","unique","index","options","label","value","hasMany"],"mappings":"AAEA,SACEA,WAAW,EAEXC,gBAAgB,EAChBC,eAAe,QACV,YAAY;AACnB,SAASC,UAAU,QAAQ,aAAa;AAExC,2FAA2F,GAC3F,MAAMC,eAAe,CAACC,SAAsC,CAAA;QAC1DC,MAAM;QACNC,QAAQ;QACRC,SAAS,OAAMC;YACb,MAAMC,OAAO,AAAC,MAAMD,IAAIE,IAAI,QAAS;YACrC,IACE,CAACN,OAAOO,OAAO,IACf,CAACV,gBAAgBG,OAAOO,OAAO,EAAEF,MAAMD,IAAII,OAAO,CAACC,GAAG,CAACb,oBACvD;gBACA,OAAOc,SAAS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AAM;oBAAO;oBAC9B;wBAAED,MAAM;wBAASC,MAAM;oBAAS;iBACjC;YACH;YACA;gBAAED,MAAM;gBAAgBC,MAAM;gBAAQO,SAAS;gBAAMJ,OAAO;YAAK;YACjE;gBAAEJ,MAAM;gBAASC,MAAM;YAAS;YAChC,wFAAwF;YACxF,gFAAgF;YAChF;gBAAED,MAAM;gBAAQC,MAAM;YAAO;YAC7B;gBAAED,MAAM;gBAAYC,MAAM;YAAO;YACjC;gBAAED,MAAM;gBAAgBC,MAAM;YAAO;SACtC;IACH,CAAA,EAAG"}
@@ -4,7 +4,7 @@ export type LocalGuide = {
4
4
  title: string;
5
5
  slug?: string | null;
6
6
  summary?: string | null;
7
- scope?: 'general' | 'site' | null;
7
+ scope?: 'default' | 'plugin' | 'site' | null;
8
8
  topic?: {
9
9
  title?: string | null;
10
10
  order?: number | null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/GuideArticle.tsx"],"sourcesContent":["import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical';\nimport { RichText } from '@payloadcms/richtext-lexical/react';\n\nimport { SITE_GUIDES_SLUG } from '../hub.js';\n\nexport type LocalGuide = {\n id: number | string;\n hubId: string;\n title: string;\n slug?: string | null;\n summary?: string | null;\n scope?: 'general' | 'site' | null;\n topic?: { title?: string | null; order?: number | null } | null;\n order?: number | null;\n body?: unknown;\n bodyText?: string | null;\n hubUpdatedAt?: string | null;\n};\n\nconst formatDate = (iso: string) =>\n new Date(iso).toLocaleDateString('en-GB', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n timeZone: 'Europe/London',\n });\n\n// The admin has no type styles, so prose spacing is set here.\nconst prose = `\n.guide-article__body { font-size: 1rem; line-height: 1.6; }\n.guide-article__body h2 { margin: 1.5rem 0 0.5rem; }\n.guide-article__body p { margin: 0.5rem 0; }\n.guide-article__body ol { list-style: decimal; padding-left: 1.5rem; }\n.guide-article__body ul { list-style: disc; padding-left: 1.5rem; }\n.guide-article__body li { margin-bottom: 0.25rem; }\n.guide-article__body img { max-width: 100%; height: auto; margin: 1rem 0; border-radius: 6px; border: 1px solid var(--theme-border-color); }\n`;\n\n/**\n * One guide as a readable article. Bodies come from the hub, so images load from the hub's\n * storage and the default Lexical converters are enough (hub guides only allow external links).\n */\nexport function GuideArticle({\n guide,\n canAuthor,\n}: {\n guide: LocalGuide;\n canAuthor: boolean;\n}) {\n return (\n <article\n style={{\n display: 'flex',\n flexDirection: 'column',\n gap: '1rem',\n maxWidth: '48rem',\n }}\n >\n <style>{prose}</style>\n <header\n style={{ display: 'flex', flexDirection: 'column', gap: '0.25rem' }}\n >\n <h2 style={{ margin: 0 }}>{guide.title}</h2>\n <p\n style={{\n margin: 0,\n color: 'var(--theme-elevation-600)',\n fontSize: '0.875rem',\n }}\n >\n {guide.hubUpdatedAt\n ? `Updated ${formatDate(guide.hubUpdatedAt)}`\n : null}\n {canAuthor && guide.scope === 'site' && (\n <>\n {' · '}\n <a\n href={`/admin/collections/${SITE_GUIDES_SLUG}?where[hubId][equals]=${guide.hubId}`}\n >\n Edit this guide\n </a>\n </>\n )}\n </p>\n </header>\n <div className='guide-article__body'>\n {guide.body ? (\n <RichText data={guide.body as SerializedEditorState} />\n ) : null}\n </div>\n </article>\n );\n}\n"],"names":["RichText","SITE_GUIDES_SLUG","formatDate","iso","Date","toLocaleDateString","day","month","year","timeZone","prose","GuideArticle","guide","canAuthor","article","style","display","flexDirection","gap","maxWidth","header","h2","margin","title","p","color","fontSize","hubUpdatedAt","scope","a","href","hubId","div","className","body","data"],"mappings":";AACA,SAASA,QAAQ,QAAQ,qCAAqC;AAE9D,SAASC,gBAAgB,QAAQ,YAAY;AAgB7C,MAAMC,aAAa,CAACC,MAClB,IAAIC,KAAKD,KAAKE,kBAAkB,CAAC,SAAS;QACxCC,KAAK;QACLC,OAAO;QACPC,MAAM;QACNC,UAAU;IACZ;AAEF,8DAA8D;AAC9D,MAAMC,QAAQ,CAAC;;;;;;;;AAQf,CAAC;AAED;;;CAGC,GACD,OAAO,SAASC,aAAa,EAC3BC,KAAK,EACLC,SAAS,EAIV;IACC,qBACE,MAACC;QACCC,OAAO;YACLC,SAAS;YACTC,eAAe;YACfC,KAAK;YACLC,UAAU;QACZ;;0BAEA,KAACJ;0BAAOL;;0BACR,MAACU;gBACCL,OAAO;oBAAEC,SAAS;oBAAQC,eAAe;oBAAUC,KAAK;gBAAU;;kCAElE,KAACG;wBAAGN,OAAO;4BAAEO,QAAQ;wBAAE;kCAAIV,MAAMW,KAAK;;kCACtC,MAACC;wBACCT,OAAO;4BACLO,QAAQ;4BACRG,OAAO;4BACPC,UAAU;wBACZ;;4BAECd,MAAMe,YAAY,GACf,CAAC,QAAQ,EAAEzB,WAAWU,MAAMe,YAAY,GAAG,GAC3C;4BACHd,aAAaD,MAAMgB,KAAK,KAAK,wBAC5B;;oCACG;kDACD,KAACC;wCACCC,MAAM,CAAC,mBAAmB,EAAE7B,iBAAiB,sBAAsB,EAAEW,MAAMmB,KAAK,EAAE;kDACnF;;;;;;;;0BAOT,KAACC;gBAAIC,WAAU;0BACZrB,MAAMsB,IAAI,iBACT,KAAClC;oBAASmC,MAAMvB,MAAMsB,IAAI;qBACxB;;;;AAIZ"}
1
+ {"version":3,"sources":["../../src/components/GuideArticle.tsx"],"sourcesContent":["import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical';\nimport { RichText } from '@payloadcms/richtext-lexical/react';\n\nimport { SITE_GUIDES_SLUG } from '../hub.js';\n\nexport type LocalGuide = {\n id: number | string;\n hubId: string;\n title: string;\n slug?: string | null;\n summary?: string | null;\n scope?: 'default' | 'plugin' | 'site' | null;\n topic?: { title?: string | null; order?: number | null } | null;\n order?: number | null;\n body?: unknown;\n bodyText?: string | null;\n hubUpdatedAt?: string | null;\n};\n\nconst formatDate = (iso: string) =>\n new Date(iso).toLocaleDateString('en-GB', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n timeZone: 'Europe/London',\n });\n\n// The admin has no type styles, so prose spacing is set here.\nconst prose = `\n.guide-article__body { font-size: 1rem; line-height: 1.6; }\n.guide-article__body h2 { margin: 1.5rem 0 0.5rem; }\n.guide-article__body p { margin: 0.5rem 0; }\n.guide-article__body ol { list-style: decimal; padding-left: 1.5rem; }\n.guide-article__body ul { list-style: disc; padding-left: 1.5rem; }\n.guide-article__body li { margin-bottom: 0.25rem; }\n.guide-article__body img { max-width: 100%; height: auto; margin: 1rem 0; border-radius: 6px; border: 1px solid var(--theme-border-color); }\n`;\n\n/**\n * One guide as a readable article. Bodies come from the hub, so images load from the hub's\n * storage and the default Lexical converters are enough (hub guides only allow external links).\n */\nexport function GuideArticle({\n guide,\n canAuthor,\n}: {\n guide: LocalGuide;\n canAuthor: boolean;\n}) {\n return (\n <article\n style={{\n display: 'flex',\n flexDirection: 'column',\n gap: '1rem',\n maxWidth: '48rem',\n }}\n >\n <style>{prose}</style>\n <header\n style={{ display: 'flex', flexDirection: 'column', gap: '0.25rem' }}\n >\n <h2 style={{ margin: 0 }}>{guide.title}</h2>\n <p\n style={{\n margin: 0,\n color: 'var(--theme-elevation-600)',\n fontSize: '0.875rem',\n }}\n >\n {guide.hubUpdatedAt\n ? `Updated ${formatDate(guide.hubUpdatedAt)}`\n : null}\n {canAuthor && guide.scope === 'site' && (\n <>\n {' · '}\n <a\n href={`/admin/collections/${SITE_GUIDES_SLUG}?where[hubId][equals]=${guide.hubId}`}\n >\n Edit this guide\n </a>\n </>\n )}\n </p>\n </header>\n <div className='guide-article__body'>\n {guide.body ? (\n <RichText data={guide.body as SerializedEditorState} />\n ) : null}\n </div>\n </article>\n );\n}\n"],"names":["RichText","SITE_GUIDES_SLUG","formatDate","iso","Date","toLocaleDateString","day","month","year","timeZone","prose","GuideArticle","guide","canAuthor","article","style","display","flexDirection","gap","maxWidth","header","h2","margin","title","p","color","fontSize","hubUpdatedAt","scope","a","href","hubId","div","className","body","data"],"mappings":";AACA,SAASA,QAAQ,QAAQ,qCAAqC;AAE9D,SAASC,gBAAgB,QAAQ,YAAY;AAgB7C,MAAMC,aAAa,CAACC,MAClB,IAAIC,KAAKD,KAAKE,kBAAkB,CAAC,SAAS;QACxCC,KAAK;QACLC,OAAO;QACPC,MAAM;QACNC,UAAU;IACZ;AAEF,8DAA8D;AAC9D,MAAMC,QAAQ,CAAC;;;;;;;;AAQf,CAAC;AAED;;;CAGC,GACD,OAAO,SAASC,aAAa,EAC3BC,KAAK,EACLC,SAAS,EAIV;IACC,qBACE,MAACC;QACCC,OAAO;YACLC,SAAS;YACTC,eAAe;YACfC,KAAK;YACLC,UAAU;QACZ;;0BAEA,KAACJ;0BAAOL;;0BACR,MAACU;gBACCL,OAAO;oBAAEC,SAAS;oBAAQC,eAAe;oBAAUC,KAAK;gBAAU;;kCAElE,KAACG;wBAAGN,OAAO;4BAAEO,QAAQ;wBAAE;kCAAIV,MAAMW,KAAK;;kCACtC,MAACC;wBACCT,OAAO;4BACLO,QAAQ;4BACRG,OAAO;4BACPC,UAAU;wBACZ;;4BAECd,MAAMe,YAAY,GACf,CAAC,QAAQ,EAAEzB,WAAWU,MAAMe,YAAY,GAAG,GAC3C;4BACHd,aAAaD,MAAMgB,KAAK,KAAK,wBAC5B;;oCACG;kDACD,KAACC;wCACCC,MAAM,CAAC,mBAAmB,EAAE7B,iBAAiB,sBAAsB,EAAEW,MAAMmB,KAAK,EAAE;kDACnF;;;;;;;;0BAOT,KAACC;gBAAIC,WAAU;0BACZrB,MAAMsB,IAAI,iBACT,KAAClC;oBAASmC,MAAMvB,MAAMsB,IAAI;qBACxB;;;;AAIZ"}
package/dist/hub.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Synced from package.json by `pnpm version-packages` (scripts/sync-plugin-version.mjs); a unit test checks it. */
2
- export declare const PLUGIN_VERSION = "0.1.1";
2
+ export declare const PLUGIN_VERSION = "0.2.0";
3
3
  export declare const GUIDES_SLUG = "guides";
4
4
  export declare const SITE_GUIDES_SLUG = "site-guides";
5
5
  export declare const SIGNATURE_HEADER = "x-guides-signature";
@@ -10,6 +10,12 @@ export type GuidesPluginConfig = {
10
10
  siteKey?: string;
11
11
  /** Feature keys this site has, reported to the hub on every sync so Umi can check its Sites record. */
12
12
  features?: string[];
13
+ /**
14
+ * FoundryKit plugins to report as active on top of the ones detected. Each FoundryKit plugin
15
+ * records itself in `config.custom.foundrykit.activePlugins` when enabled; list a plugin here
16
+ * only if it's too old to do that. The hub sends guides for every plugin reported.
17
+ */
18
+ plugins?: string[];
13
19
  /** Who can write site-specific guides here (Umi staff). Default: nobody. */
14
20
  canAuthor?: (user: unknown) => boolean;
15
21
  /**
@@ -23,6 +29,7 @@ export type ResolvedConfig = {
23
29
  hubURL?: string;
24
30
  siteKey?: string;
25
31
  features: string[];
32
+ plugins: string[];
26
33
  canAuthor: (user: unknown) => boolean;
27
34
  schedule: string | false;
28
35
  };
package/dist/hub.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import crypto from 'node:crypto';
2
- /** Synced from package.json by `pnpm version-packages` (scripts/sync-plugin-version.mjs); a unit test checks it. */ export const PLUGIN_VERSION = '0.1.1';
2
+ /** Synced from package.json by `pnpm version-packages` (scripts/sync-plugin-version.mjs); a unit test checks it. */ export const PLUGIN_VERSION = '0.2.0';
3
3
  export const GUIDES_SLUG = 'guides';
4
4
  export const SITE_GUIDES_SLUG = 'site-guides';
5
5
  export const SIGNATURE_HEADER = 'x-guides-signature';
@@ -13,6 +13,7 @@ export const resolveConfig = (options)=>({
13
13
  return options.siteKey ?? process.env.GUIDES_HUB_KEY;
14
14
  },
15
15
  features: options.features ?? [],
16
+ plugins: options.plugins ?? [],
16
17
  canAuthor: options.canAuthor ?? (()=>false),
17
18
  schedule: options.schedule ?? '0 0 * * * *'
18
19
  });
package/dist/hub.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hub.ts"],"sourcesContent":["import crypto from 'node:crypto';\n\n/** Synced from package.json by `pnpm version-packages` (scripts/sync-plugin-version.mjs); a unit test checks it. */\nexport const PLUGIN_VERSION = '0.1.1';\n\nexport const GUIDES_SLUG = 'guides';\nexport const SITE_GUIDES_SLUG = 'site-guides';\nexport const SIGNATURE_HEADER = 'x-guides-signature';\n\nexport type GuidesPluginConfig = {\n /** The guides hub's URL. Default `process.env.GUIDES_HUB_URL`. */\n hubURL?: string;\n /** This site's guides key, from its Sites record in the hub. Default `process.env.GUIDES_HUB_KEY`. */\n siteKey?: string;\n /** Feature keys this site has, reported to the hub on every sync so Umi can check its Sites record. */\n features?: string[];\n /** Who can write site-specific guides here (Umi staff). Default: nobody. */\n canAuthor?: (user: unknown) => boolean;\n /**\n * Cron (Payload's 6-field form, seconds first) for the backstop pull, run by Payload jobs on\n * the `default` queue. Default hourly, `0 0 * * * *`; `false` turns it off.\n */\n schedule?: string | false;\n disabled?: boolean;\n};\n\nexport type ResolvedConfig = {\n hubURL?: string;\n siteKey?: string;\n features: string[];\n canAuthor: (user: unknown) => boolean;\n schedule: string | false;\n};\n\n// Env is read when the hub is called, not when the plugin is registered, so config built before\n// env loads (or a rotated key) still works.\nexport const resolveConfig = (options: GuidesPluginConfig): ResolvedConfig => ({\n get hubURL() {\n return options.hubURL ?? process.env.GUIDES_HUB_URL;\n },\n get siteKey() {\n return options.siteKey ?? process.env.GUIDES_HUB_KEY;\n },\n features: options.features ?? [],\n canAuthor: options.canAuthor ?? (() => false),\n schedule: options.schedule ?? '0 0 * * * *',\n});\n\n/** A request to the hub, authenticated as this site. */\nexport const hubFetch = async (\n config: ResolvedConfig,\n path: string,\n init: RequestInit = {}\n) => {\n if (!config.hubURL || !config.siteKey) {\n throw new Error(\n 'Set GUIDES_HUB_URL and GUIDES_HUB_KEY (or the hubURL and siteKey options) to reach the guides hub.'\n );\n }\n return fetch(new URL(path, config.hubURL), {\n ...init,\n headers: {\n 'content-type': 'application/json',\n authorization: `sites API-Key ${config.siteKey}`,\n ...init.headers,\n },\n signal: AbortSignal.timeout(10_000),\n });\n};\n\n/** True when the header is the hub's HMAC of this exact body, keyed with this site's guides key. */\nexport const verifySignature = (\n key: string,\n body: string,\n header: string | null\n) => {\n if (!header) return false;\n const expected = Buffer.from(\n `sha256=${crypto.createHmac('sha256', key).update(body).digest('hex')}`\n );\n const received = Buffer.from(header);\n return (\n received.length === expected.length &&\n crypto.timingSafeEqual(received, expected)\n );\n};\n"],"names":["crypto","PLUGIN_VERSION","GUIDES_SLUG","SITE_GUIDES_SLUG","SIGNATURE_HEADER","resolveConfig","options","hubURL","process","env","GUIDES_HUB_URL","siteKey","GUIDES_HUB_KEY","features","canAuthor","schedule","hubFetch","config","path","init","Error","fetch","URL","headers","authorization","signal","AbortSignal","timeout","verifySignature","key","body","header","expected","Buffer","from","createHmac","update","digest","received","length","timingSafeEqual"],"mappings":"AAAA,OAAOA,YAAY,cAAc;AAEjC,kHAAkH,GAClH,OAAO,MAAMC,iBAAiB,QAAQ;AAEtC,OAAO,MAAMC,cAAc,SAAS;AACpC,OAAO,MAAMC,mBAAmB,cAAc;AAC9C,OAAO,MAAMC,mBAAmB,qBAAqB;AA2BrD,gGAAgG;AAChG,4CAA4C;AAC5C,OAAO,MAAMC,gBAAgB,CAACC,UAAiD,CAAA;QAC7E,IAAIC,UAAS;YACX,OAAOD,QAAQC,MAAM,IAAIC,QAAQC,GAAG,CAACC,cAAc;QACrD;QACA,IAAIC,WAAU;YACZ,OAAOL,QAAQK,OAAO,IAAIH,QAAQC,GAAG,CAACG,cAAc;QACtD;QACAC,UAAUP,QAAQO,QAAQ,IAAI,EAAE;QAChCC,WAAWR,QAAQQ,SAAS,IAAK,CAAA,IAAM,KAAI;QAC3CC,UAAUT,QAAQS,QAAQ,IAAI;IAChC,CAAA,EAAG;AAEH,sDAAsD,GACtD,OAAO,MAAMC,WAAW,OACtBC,QACAC,MACAC,OAAoB,CAAC,CAAC;IAEtB,IAAI,CAACF,OAAOV,MAAM,IAAI,CAACU,OAAON,OAAO,EAAE;QACrC,MAAM,IAAIS,MACR;IAEJ;IACA,OAAOC,MAAM,IAAIC,IAAIJ,MAAMD,OAAOV,MAAM,GAAG;QACzC,GAAGY,IAAI;QACPI,SAAS;YACP,gBAAgB;YAChBC,eAAe,CAAC,cAAc,EAAEP,OAAON,OAAO,EAAE;YAChD,GAAGQ,KAAKI,OAAO;QACjB;QACAE,QAAQC,YAAYC,OAAO,CAAC;IAC9B;AACF,EAAE;AAEF,kGAAkG,GAClG,OAAO,MAAMC,kBAAkB,CAC7BC,KACAC,MACAC;IAEA,IAAI,CAACA,QAAQ,OAAO;IACpB,MAAMC,WAAWC,OAAOC,IAAI,CAC1B,CAAC,OAAO,EAAElC,OAAOmC,UAAU,CAAC,UAAUN,KAAKO,MAAM,CAACN,MAAMO,MAAM,CAAC,QAAQ;IAEzE,MAAMC,WAAWL,OAAOC,IAAI,CAACH;IAC7B,OACEO,SAASC,MAAM,KAAKP,SAASO,MAAM,IACnCvC,OAAOwC,eAAe,CAACF,UAAUN;AAErC,EAAE"}
1
+ {"version":3,"sources":["../src/hub.ts"],"sourcesContent":["import crypto from 'node:crypto';\n\n/** Synced from package.json by `pnpm version-packages` (scripts/sync-plugin-version.mjs); a unit test checks it. */\nexport const PLUGIN_VERSION = '0.2.0';\n\nexport const GUIDES_SLUG = 'guides';\nexport const SITE_GUIDES_SLUG = 'site-guides';\nexport const SIGNATURE_HEADER = 'x-guides-signature';\n\nexport type GuidesPluginConfig = {\n /** The guides hub's URL. Default `process.env.GUIDES_HUB_URL`. */\n hubURL?: string;\n /** This site's guides key, from its Sites record in the hub. Default `process.env.GUIDES_HUB_KEY`. */\n siteKey?: string;\n /** Feature keys this site has, reported to the hub on every sync so Umi can check its Sites record. */\n features?: string[];\n /**\n * FoundryKit plugins to report as active on top of the ones detected. Each FoundryKit plugin\n * records itself in `config.custom.foundrykit.activePlugins` when enabled; list a plugin here\n * only if it's too old to do that. The hub sends guides for every plugin reported.\n */\n plugins?: string[];\n /** Who can write site-specific guides here (Umi staff). Default: nobody. */\n canAuthor?: (user: unknown) => boolean;\n /**\n * Cron (Payload's 6-field form, seconds first) for the backstop pull, run by Payload jobs on\n * the `default` queue. Default hourly, `0 0 * * * *`; `false` turns it off.\n */\n schedule?: string | false;\n disabled?: boolean;\n};\n\nexport type ResolvedConfig = {\n hubURL?: string;\n siteKey?: string;\n features: string[];\n plugins: string[];\n canAuthor: (user: unknown) => boolean;\n schedule: string | false;\n};\n\n// Env is read when the hub is called, not when the plugin is registered, so config built before\n// env loads (or a rotated key) still works.\nexport const resolveConfig = (options: GuidesPluginConfig): ResolvedConfig => ({\n get hubURL() {\n return options.hubURL ?? process.env.GUIDES_HUB_URL;\n },\n get siteKey() {\n return options.siteKey ?? process.env.GUIDES_HUB_KEY;\n },\n features: options.features ?? [],\n plugins: options.plugins ?? [],\n canAuthor: options.canAuthor ?? (() => false),\n schedule: options.schedule ?? '0 0 * * * *',\n});\n\n/** A request to the hub, authenticated as this site. */\nexport const hubFetch = async (\n config: ResolvedConfig,\n path: string,\n init: RequestInit = {}\n) => {\n if (!config.hubURL || !config.siteKey) {\n throw new Error(\n 'Set GUIDES_HUB_URL and GUIDES_HUB_KEY (or the hubURL and siteKey options) to reach the guides hub.'\n );\n }\n return fetch(new URL(path, config.hubURL), {\n ...init,\n headers: {\n 'content-type': 'application/json',\n authorization: `sites API-Key ${config.siteKey}`,\n ...init.headers,\n },\n signal: AbortSignal.timeout(10_000),\n });\n};\n\n/** True when the header is the hub's HMAC of this exact body, keyed with this site's guides key. */\nexport const verifySignature = (\n key: string,\n body: string,\n header: string | null\n) => {\n if (!header) return false;\n const expected = Buffer.from(\n `sha256=${crypto.createHmac('sha256', key).update(body).digest('hex')}`\n );\n const received = Buffer.from(header);\n return (\n received.length === expected.length &&\n crypto.timingSafeEqual(received, expected)\n );\n};\n"],"names":["crypto","PLUGIN_VERSION","GUIDES_SLUG","SITE_GUIDES_SLUG","SIGNATURE_HEADER","resolveConfig","options","hubURL","process","env","GUIDES_HUB_URL","siteKey","GUIDES_HUB_KEY","features","plugins","canAuthor","schedule","hubFetch","config","path","init","Error","fetch","URL","headers","authorization","signal","AbortSignal","timeout","verifySignature","key","body","header","expected","Buffer","from","createHmac","update","digest","received","length","timingSafeEqual"],"mappings":"AAAA,OAAOA,YAAY,cAAc;AAEjC,kHAAkH,GAClH,OAAO,MAAMC,iBAAiB,QAAQ;AAEtC,OAAO,MAAMC,cAAc,SAAS;AACpC,OAAO,MAAMC,mBAAmB,cAAc;AAC9C,OAAO,MAAMC,mBAAmB,qBAAqB;AAkCrD,gGAAgG;AAChG,4CAA4C;AAC5C,OAAO,MAAMC,gBAAgB,CAACC,UAAiD,CAAA;QAC7E,IAAIC,UAAS;YACX,OAAOD,QAAQC,MAAM,IAAIC,QAAQC,GAAG,CAACC,cAAc;QACrD;QACA,IAAIC,WAAU;YACZ,OAAOL,QAAQK,OAAO,IAAIH,QAAQC,GAAG,CAACG,cAAc;QACtD;QACAC,UAAUP,QAAQO,QAAQ,IAAI,EAAE;QAChCC,SAASR,QAAQQ,OAAO,IAAI,EAAE;QAC9BC,WAAWT,QAAQS,SAAS,IAAK,CAAA,IAAM,KAAI;QAC3CC,UAAUV,QAAQU,QAAQ,IAAI;IAChC,CAAA,EAAG;AAEH,sDAAsD,GACtD,OAAO,MAAMC,WAAW,OACtBC,QACAC,MACAC,OAAoB,CAAC,CAAC;IAEtB,IAAI,CAACF,OAAOX,MAAM,IAAI,CAACW,OAAOP,OAAO,EAAE;QACrC,MAAM,IAAIU,MACR;IAEJ;IACA,OAAOC,MAAM,IAAIC,IAAIJ,MAAMD,OAAOX,MAAM,GAAG;QACzC,GAAGa,IAAI;QACPI,SAAS;YACP,gBAAgB;YAChBC,eAAe,CAAC,cAAc,EAAEP,OAAOP,OAAO,EAAE;YAChD,GAAGS,KAAKI,OAAO;QACjB;QACAE,QAAQC,YAAYC,OAAO,CAAC;IAC9B;AACF,EAAE;AAEF,kGAAkG,GAClG,OAAO,MAAMC,kBAAkB,CAC7BC,KACAC,MACAC;IAEA,IAAI,CAACA,QAAQ,OAAO;IACpB,MAAMC,WAAWC,OAAOC,IAAI,CAC1B,CAAC,OAAO,EAAEnC,OAAOoC,UAAU,CAAC,UAAUN,KAAKO,MAAM,CAACN,MAAMO,MAAM,CAAC,QAAQ;IAEzE,MAAMC,WAAWL,OAAOC,IAAI,CAACH;IAC7B,OACEO,SAASC,MAAM,KAAKP,SAASO,MAAM,IACnCxC,OAAOyC,eAAe,CAACF,UAAUN;AAErC,EAAE"}
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { recordActivePlugin } from './activePlugins.js';
1
2
  import { guidesCollection } from './collections/guides.js';
2
3
  import { siteGuidesCollection } from './collections/siteGuides.js';
3
4
  import { GUIDES_SLUG, resolveConfig, SITE_GUIDES_SLUG } from './hub.js';
@@ -65,7 +66,7 @@ const syncTask = (config)=>({
65
66
  const resolved = resolveConfig(options);
66
67
  const components = config.admin?.components ?? {};
67
68
  const onInit = config.onInit;
68
- return {
69
+ return recordActivePlugin({
69
70
  ...config,
70
71
  collections: [
71
72
  ...(config.collections ?? []).map(withHelp('edit')),
@@ -104,7 +105,7 @@ const syncTask = (config)=>({
104
105
  await onInit?.(payload);
105
106
  void syncIfEmpty(payload, resolved);
106
107
  }
107
- };
108
+ }, '@foundrykit/guides-plugin');
108
109
  };
109
110
  export default guidesPlugin;
110
111
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n CollectionConfig,\n Config,\n GlobalConfig,\n Payload,\n TaskConfig,\n} from 'payload';\n\nimport { guidesCollection } from './collections/guides.js';\nimport { siteGuidesCollection } from './collections/siteGuides.js';\nimport {\n GUIDES_SLUG,\n type GuidesPluginConfig,\n type ResolvedConfig,\n resolveConfig,\n SITE_GUIDES_SLUG,\n} from './hub.js';\nimport { syncGuides } from './sync.js';\n\nexport type {\n GuidesPluginConfig,\n GuidesPluginConfig as PluginConfig,\n} from './hub.js';\nexport { syncGuides } from './sync.js';\n\nconst HELP_BUTTON = '@foundrykit/guides-plugin/client#HelpButton';\n\nconst skipHelp = (slug: string) =>\n slug === GUIDES_SLUG ||\n slug === SITE_GUIDES_SLUG ||\n slug === 'users' ||\n slug.startsWith('payload-');\n\n// Payload reads beforeDocumentControls from `edit` on collections but from `elements` on globals\n// (@payloadcms/next views/Document/renderDocumentSlots), so the slot depends on the kind.\nconst withHelp =\n <T extends CollectionConfig | GlobalConfig>(slot: 'edit' | 'elements') =>\n (entry: T): T => {\n if (skipHelp(entry.slug)) return entry;\n const components = (entry.admin?.components ?? {}) as Record<\n string,\n { beforeDocumentControls?: unknown[] }\n >;\n const current = components[slot] ?? {};\n return {\n ...entry,\n admin: {\n ...entry.admin,\n components: {\n ...components,\n [slot]: {\n ...current,\n beforeDocumentControls: [\n ...(current.beforeDocumentControls ?? []),\n HELP_BUTTON,\n ],\n },\n },\n },\n } as T;\n };\n\nconst syncTask = (config: ResolvedConfig): TaskConfig => ({\n slug: 'guidesSync',\n label: 'Sync guides from the hub',\n handler: async ({ req }) => ({\n output: await syncGuides(req.payload, config),\n }),\n ...(config.schedule\n ? { schedule: [{ cron: config.schedule, queue: 'default' }] }\n : {}),\n});\n\n/** Fills an empty local copy on first boot, without holding startup up or failing it. */\nconst syncIfEmpty = async (payload: Payload, config: ResolvedConfig) => {\n try {\n const { totalDocs } = await payload.count({\n collection: GUIDES_SLUG as never,\n });\n if (totalDocs === 0) await syncGuides(payload, config);\n } catch (err) {\n payload.logger.warn(\n { err },\n 'Guides: first sync from the hub failed; the next webhook or scheduled pull will retry.'\n );\n }\n};\n\n/**\n * CMS guides from the Umi guides hub: a Guides page in the sidebar, a Help button on every edit\n * page, and local search, all read from a local copy the hub keeps in sync. Umi staff\n * (`canAuthor`) write site-specific guides in the Site guides collection; publishing saves\n * them to the hub.\n */\nexport const guidesPlugin =\n (options: GuidesPluginConfig = {}) =>\n (config: Config): Config => {\n if (options.disabled) return config;\n const resolved = resolveConfig(options);\n const components = config.admin?.components ?? {};\n const onInit = config.onInit;\n\n return {\n ...config,\n collections: [\n ...(config.collections ?? []).map(withHelp<CollectionConfig>('edit')),\n guidesCollection(resolved),\n siteGuidesCollection(resolved),\n ],\n globals: (config.globals ?? []).map(withHelp<GlobalConfig>('elements')),\n admin: {\n ...config.admin,\n components: {\n ...components,\n afterNavLinks: [\n ...(components.afterNavLinks ?? []),\n '@foundrykit/guides-plugin/client#GuidesNavLink',\n ],\n views: {\n ...components.views,\n guides: {\n Component: '@foundrykit/guides-plugin/rsc#GuidesView',\n path: '/guides',\n meta: { title: 'Guides' },\n },\n },\n },\n },\n jobs: {\n ...config.jobs,\n tasks: [...(config.jobs?.tasks ?? []), syncTask(resolved)],\n },\n onInit: async payload => {\n await onInit?.(payload);\n void syncIfEmpty(payload, resolved);\n },\n };\n };\n\nexport default guidesPlugin;\n"],"names":["guidesCollection","siteGuidesCollection","GUIDES_SLUG","resolveConfig","SITE_GUIDES_SLUG","syncGuides","HELP_BUTTON","skipHelp","slug","startsWith","withHelp","slot","entry","components","admin","current","beforeDocumentControls","syncTask","config","label","handler","req","output","payload","schedule","cron","queue","syncIfEmpty","totalDocs","count","collection","err","logger","warn","guidesPlugin","options","disabled","resolved","onInit","collections","map","globals","afterNavLinks","views","guides","Component","path","meta","title","jobs","tasks"],"mappings":"AAQA,SAASA,gBAAgB,QAAQ,0BAA0B;AAC3D,SAASC,oBAAoB,QAAQ,8BAA8B;AACnE,SACEC,WAAW,EAGXC,aAAa,EACbC,gBAAgB,QACX,WAAW;AAClB,SAASC,UAAU,QAAQ,YAAY;AAMvC,SAASA,UAAU,QAAQ,YAAY;AAEvC,MAAMC,cAAc;AAEpB,MAAMC,WAAW,CAACC,OAChBA,SAASN,eACTM,SAASJ,oBACTI,SAAS,WACTA,KAAKC,UAAU,CAAC;AAElB,iGAAiG;AACjG,0FAA0F;AAC1F,MAAMC,WACJ,CAA4CC,OAC5C,CAACC;QACC,IAAIL,SAASK,MAAMJ,IAAI,GAAG,OAAOI;QACjC,MAAMC,aAAcD,MAAME,KAAK,EAAED,cAAc,CAAC;QAIhD,MAAME,U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,GAAG,CAAC9B,SAA2B;gBAC7DV,iBAAiBqC;gBACjBpC,qBAAqBoC;aACtB;YACDI,SAAS,AAACvB,CAAAA,OAAOuB,OAAO,IAAI,EAAE,AAAD,EAAGD,GAAG,CAAC9B,SAAuB;YAC3DI,OAAO;gBACL,GAAGI,OAAOJ,KAAK;gBACfD,YAAY;oBACV,GAAGA,UAAU;oBACb6B,eAAe;2BACT7B,WAAW6B,aAAa,IAAI,EAAE;wBAClC;qBACD;oBACDC,OAAO;wBACL,GAAG9B,WAAW8B,KAAK;wBACnBC,QAAQ;4BACNC,WAAW;4BACXC,MAAM;4BACNC,MAAM;gCAAEC,OAAO;4BAAS;wBAC1B;oBACF;gBACF;YACF;YACAC,MAAM;gBACJ,GAAG/B,OAAO+B,IAAI;gBACdC,OAAO;uBAAKhC,OAAO+B,IAAI,EAAEC,SAAS,EAAE;oBAAGjC,SAASoB;iBAAU;YAC5D;YACAC,QAAQ,OAAMf;gBACZ,MAAMe,SAASf;gBACf,KAAKI,YAAYJ,SAASc;YAC5B;QACF;IACF,EAAE;AAEJ,eAAeH,aAAa"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n CollectionConfig,\n Config,\n GlobalConfig,\n Payload,\n TaskConfig,\n} from 'payload';\nimport { recordActivePlugin } from './activePlugins.js';\nimport { guidesCollection } from './collections/guides.js';\nimport { siteGuidesCollection } from './collections/siteGuides.js';\nimport {\n GUIDES_SLUG,\n type GuidesPluginConfig,\n type ResolvedConfig,\n resolveConfig,\n SITE_GUIDES_SLUG,\n} from './hub.js';\nimport { syncGuides } from './sync.js';\n\nexport type {\n GuidesPluginConfig,\n GuidesPluginConfig as PluginConfig,\n} from './hub.js';\nexport { syncGuides } from './sync.js';\n\nconst HELP_BUTTON = '@foundrykit/guides-plugin/client#HelpButton';\n\nconst skipHelp = (slug: string) =>\n slug === GUIDES_SLUG ||\n slug === SITE_GUIDES_SLUG ||\n slug === 'users' ||\n slug.startsWith('payload-');\n\n// Payload reads beforeDocumentControls from `edit` on collections but from `elements` on globals\n// (@payloadcms/next views/Document/renderDocumentSlots), so the slot depends on the kind.\nconst withHelp =\n <T extends CollectionConfig | GlobalConfig>(slot: 'edit' | 'elements') =>\n (entry: T): T => {\n if (skipHelp(entry.slug)) return entry;\n const components = (entry.admin?.components ?? {}) as Record<\n string,\n { beforeDocumentControls?: unknown[] }\n >;\n const current = components[slot] ?? {};\n return {\n ...entry,\n admin: {\n ...entry.admin,\n components: {\n ...components,\n [slot]: {\n ...current,\n beforeDocumentControls: [\n ...(current.beforeDocumentControls ?? []),\n HELP_BUTTON,\n ],\n },\n },\n },\n } as T;\n };\n\nconst syncTask = (config: ResolvedConfig): TaskConfig => ({\n slug: 'guidesSync',\n label: 'Sync guides from the hub',\n handler: async ({ req }) => ({\n output: await syncGuides(req.payload, config),\n }),\n ...(config.schedule\n ? { schedule: [{ cron: config.schedule, queue: 'default' }] }\n : {}),\n});\n\n/** Fills an empty local copy on first boot, without holding startup up or failing it. */\nconst syncIfEmpty = async (payload: Payload, config: ResolvedConfig) => {\n try {\n const { totalDocs } = await payload.count({\n collection: GUIDES_SLUG as never,\n });\n if (totalDocs === 0) await syncGuides(payload, config);\n } catch (err) {\n payload.logger.warn(\n { err },\n 'Guides: first sync from the hub failed; the next webhook or scheduled pull will retry.'\n );\n }\n};\n\n/**\n * CMS guides from the Umi guides hub: a Guides page in the sidebar, a Help button on every edit\n * page, and local search, all read from a local copy the hub keeps in sync. Umi staff\n * (`canAuthor`) write site-specific guides in the Site guides collection; publishing saves\n * them to the hub.\n */\nexport const guidesPlugin =\n (options: GuidesPluginConfig = {}) =>\n (config: Config): Config => {\n if (options.disabled) return config;\n const resolved = resolveConfig(options);\n const components = config.admin?.components ?? {};\n const onInit = config.onInit;\n\n return recordActivePlugin(\n {\n ...config,\n collections: [\n ...(config.collections ?? []).map(withHelp<CollectionConfig>('edit')),\n guidesCollection(resolved),\n siteGuidesCollection(resolved),\n ],\n globals: (config.globals ?? []).map(withHelp<GlobalConfig>('elements')),\n admin: {\n ...config.admin,\n components: {\n ...components,\n afterNavLinks: [\n ...(components.afterNavLinks ?? []),\n '@foundrykit/guides-plugin/client#GuidesNavLink',\n ],\n views: {\n ...components.views,\n guides: {\n Component: '@foundrykit/guides-plugin/rsc#GuidesView',\n path: '/guides',\n meta: { title: 'Guides' },\n },\n },\n },\n },\n jobs: {\n ...config.jobs,\n tasks: [...(config.jobs?.tasks ?? []), syncTask(resolved)],\n },\n onInit: async payload => {\n await onInit?.(payload);\n void syncIfEmpty(payload, resolved);\n },\n },\n '@foundrykit/guides-plugin'\n );\n };\n\nexport default guidesPlugin;\n"],"names":["recordActivePlugin","guidesCollection","siteGuidesCollection","GUIDES_SLUG","resolveConfig","SITE_GUIDES_SLUG","syncGuides","HELP_BUTTON","skipHelp","slug","startsWith","withHelp","slot","entry","components","admin","current","beforeDocumentControls","syncTask","config","label","handler","req","output","payload","schedule","cron","queue","syncIfEmpty","totalDocs","count","collection","err","logger","warn","guidesPlugin","options","disabled","resolved","onInit","collections","map","globals","afterNavLinks","views","guides","Component","path","meta","title","jobs","tasks"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,qBAAqB;AACxD,SAASC,gBAAgB,QAAQ,0BAA0B;AAC3D,SAASC,oBAAoB,QAAQ,8BAA8B;AACnE,SACEC,WAAW,EAGXC,aAAa,EACbC,gBAAgB,QACX,WAAW;AAClB,SAASC,UAAU,QAAQ,YAAY;AAMvC,SAASA,UAAU,QAAQ,YAAY;AAEvC,MAAMC,cAAc;AAEpB,MAAMC,WAAW,CAACC,OAChBA,SAASN,eACTM,SAASJ,oBACTI,SAAS,WACTA,KAAKC,UAAU,CAAC;AAElB,iGAAiG;AACjG,0FAA0F;AAC1F,MAAMC,WACJ,CAA4CC,OAC5C,CAACC;QACC,IAAIL,SAASK,MAAMJ,IAAI,GAAG,OAAOI;QACjC,MAAMC,aAAcD,MAAME,KAAK,EAAED,cAAc,CAAC;QAIhD,MAAME,UAAUF,UAAU,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AG,CAAC9B,SAA2B;gBAC7DV,iBAAiBqC;gBACjBpC,qBAAqBoC;aACtB;YACDI,SAAS,AAACvB,CAAAA,OAAOuB,OAAO,IAAI,EAAE,AAAD,EAAGD,GAAG,CAAC9B,SAAuB;YAC3DI,OAAO;gBACL,GAAGI,OAAOJ,KAAK;gBACfD,YAAY;oBACV,GAAGA,UAAU;oBACb6B,eAAe;2BACT7B,WAAW6B,aAAa,IAAI,EAAE;wBAClC;qBACD;oBACDC,OAAO;wBACL,GAAG9B,WAAW8B,KAAK;wBACnBC,QAAQ;4BACNC,WAAW;4BACXC,MAAM;4BACNC,MAAM;gCAAEC,OAAO;4BAAS;wBAC1B;oBACF;gBACF;YACF;YACAC,MAAM;gBACJ,GAAG/B,OAAO+B,IAAI;gBACdC,OAAO;uBAAKhC,OAAO+B,IAAI,EAAEC,SAAS,EAAE;oBAAGjC,SAASoB;iBAAU;YAC5D;YACAC,QAAQ,OAAMf;gBACZ,MAAMe,SAASf;gBACf,KAAKI,YAAYJ,SAASc;YAC5B;QACF,GACA;IAEJ,EAAE;AAEJ,eAAeH,aAAa"}
package/dist/sync.d.ts CHANGED
@@ -6,7 +6,8 @@ export type FeedGuide = {
6
6
  title: string;
7
7
  slug: string;
8
8
  summary: string;
9
- scope: 'general' | 'site';
9
+ scope: 'default' | 'plugin' | 'site';
10
+ plugin?: string | null;
10
11
  topic: {
11
12
  title?: string;
12
13
  order?: number | null;
@@ -17,10 +18,17 @@ export type FeedGuide = {
17
18
  bodyText: string;
18
19
  updatedAt: string;
19
20
  };
21
+ /**
22
+ * FoundryKit plugins active on this site: the ones that recorded themselves in
23
+ * `config.custom.foundrykit.activePlugins` (read from the running config, so plugin order doesn't
24
+ * matter) plus any listed in the `plugins` option.
25
+ */
26
+ export declare const activePlugins: (payload: Payload, config: ResolvedConfig) => string[];
20
27
  /**
21
28
  * Makes the local guides collection match this site's feed from the hub: adds new guides,
22
29
  * updates changed ones and removes any the site is no longer entitled to. Reports the plugin
23
- * version and features on the way, so the hub's Sites record stays current.
30
+ * version, features and active FoundryKit plugins on the way: the hub keeps them on the Sites
31
+ * record and sends plugin guides for the plugins reported.
24
32
  */
25
33
  export declare const syncGuides: (payload: Payload, config: ResolvedConfig) => Promise<{
26
34
  changed: number;
package/dist/sync.js CHANGED
@@ -15,14 +15,29 @@ const toLocal = (g)=>({
15
15
  bodyText: g.bodyText,
16
16
  hubUpdatedAt: g.updatedAt
17
17
  });
18
+ /**
19
+ * FoundryKit plugins active on this site: the ones that recorded themselves in
20
+ * `config.custom.foundrykit.activePlugins` (read from the running config, so plugin order doesn't
21
+ * matter) plus any listed in the `plugins` option.
22
+ */ export const activePlugins = (payload, config)=>{
23
+ const detected = payload.config.custom?.foundrykit?.activePlugins;
24
+ return [
25
+ ...new Set([
26
+ ...Array.isArray(detected) ? detected.map(String) : [],
27
+ ...config.plugins
28
+ ])
29
+ ];
30
+ };
18
31
  /**
19
32
  * Makes the local guides collection match this site's feed from the hub: adds new guides,
20
33
  * updates changed ones and removes any the site is no longer entitled to. Reports the plugin
21
- * version and features on the way, so the hub's Sites record stays current.
34
+ * version, features and active FoundryKit plugins on the way: the hub keeps them on the Sites
35
+ * record and sends plugin guides for the plugins reported.
22
36
  */ export const syncGuides = async (payload, config)=>{
23
37
  const params = new URLSearchParams({
24
38
  pluginVersion: PLUGIN_VERSION,
25
- features: config.features.join(',')
39
+ features: config.features.join(','),
40
+ plugins: activePlugins(payload, config).join(',')
26
41
  });
27
42
  const res = await hubFetch(config, `/api/sites/feed?${params}`);
28
43
  if (!res.ok) throw new Error(`The guides hub answered ${res.status} to the feed request.`);
package/dist/sync.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sync.ts"],"sourcesContent":["import type { Payload } from 'payload';\n\nimport {\n GUIDES_SLUG,\n hubFetch,\n PLUGIN_VERSION,\n type ResolvedConfig,\n} from './hub.js';\n\n/** One guide as the hub's feed sends it. */\nexport type FeedGuide = {\n id: number | string;\n title: string;\n slug: string;\n summary: string;\n scope: 'general' | 'site';\n topic: { title?: string; order?: number | null } | null;\n helpContexts: string[];\n order: number | null;\n body: unknown;\n bodyText: string;\n updatedAt: string;\n};\n\nconst toLocal = (g: FeedGuide) => ({\n hubId: String(g.id),\n title: g.title,\n slug: g.slug,\n summary: g.summary,\n scope: g.scope,\n topic: { title: g.topic?.title ?? null, order: g.topic?.order ?? null },\n helpContexts: g.helpContexts,\n order: g.order,\n body: g.body,\n bodyText: g.bodyText,\n hubUpdatedAt: g.updatedAt,\n});\n\n/**\n * Makes the local guides collection match this site's feed from the hub: adds new guides,\n * updates changed ones and removes any the site is no longer entitled to. Reports the plugin\n * version and features on the way, so the hub's Sites record stays current.\n */\nexport const syncGuides = async (payload: Payload, config: ResolvedConfig) => {\n const params = new URLSearchParams({\n pluginVersion: PLUGIN_VERSION,\n features: config.features.join(','),\n });\n const res = await hubFetch(config, `/api/sites/feed?${params}`);\n if (!res.ok)\n throw new Error(\n `The guides hub answered ${res.status} to the feed request.`\n );\n const { guides } = (await res.json()) as { guides: FeedGuide[] };\n\n const { docs } = await payload.find({\n collection: GUIDES_SLUG as never,\n pagination: false,\n depth: 0,\n select: { hubId: true, hubUpdatedAt: true } as never,\n });\n const local = new Map(\n (docs as { id: number; hubId: string; hubUpdatedAt?: string }[]).map(d => [\n d.hubId,\n d,\n ])\n );\n\n let changed = 0;\n for (const guide of guides) {\n const existing = local.get(String(guide.id));\n local.delete(String(guide.id));\n if (existing?.hubUpdatedAt === guide.updatedAt) continue;\n const data = toLocal(guide) as never;\n if (existing)\n await payload.update({\n collection: GUIDES_SLUG as never,\n id: existing.id,\n data,\n });\n else await payload.create({ collection: GUIDES_SLUG as never, data });\n changed++;\n }\n for (const stale of local.values())\n await payload.delete({ collection: GUIDES_SLUG as never, id: stale.id });\n\n return { changed, removed: local.size, total: guides.length };\n};\n"],"names":["GUIDES_SLUG","hubFetch","PLUGIN_VERSION","toLocal","g","hubId","String","id","title","slug","summary","scope","topic","order","helpContexts","body","bodyText","hubUpdatedAt","updatedAt","syncGuides","payload","config","params","URLSearchParams","pluginVersion","features","join","res","ok","Error","status","guides","json","docs","find","collection","pagination","depth","select","local","Map","map","d","changed","guide","existing","get","delete","data","update","create","stale","values","removed","size","total","length"],"mappings":"AAEA,SACEA,WAAW,EACXC,QAAQ,EACRC,cAAc,QAET,WAAW;AAiBlB,MAAMC,UAAU,CAACC,IAAkB,CAAA;QACjCC,OAAOC,OAAOF,EAAEG,EAAE;QAClBC,OAAOJ,EAAEI,KAAK;QACdC,MAAML,EAAEK,IAAI;QACZC,SAASN,EAAEM,OAAO;QAClBC,OAAOP,EAAEO,KAAK;QACdC,OAAO;YAAEJ,OAAOJ,EAAEQ,KAAK,EAAEJ,SAAS;YAAMK,OAAOT,EAAEQ,KAAK,EAAEC,SAAS;QAAK;QACtEC,cAAcV,EAAEU,YAAY;QAC5BD,OAAOT,EAAES,KAAK;QACdE,MAAMX,EAAEW,IAAI;QACZC,UAAUZ,EAAEY,QAAQ;QACpBC,cAAcb,EAAEc,SAAS;IAC3B,CAAA;AAEA;;;;CAIC,GACD,OAAO,MAAMC,aAAa,OAAOC,SAAkBC;IACjD,MAAMC,SAAS,IAAIC,gBAAgB;QACjCC,eAAetB;QACfuB,UAAUJ,OAAOI,QAAQ,CAACC,IAAI,CAAC;IACjC;IACA,MAAMC,MAAM,MAAM1B,SAASoB,QAAQ,CAAC,gBAAgB,EAAEC,QAAQ;IAC9D,IAAI,CAACK,IAAIC,EAAE,EACT,MAAM,IAAIC,MACR,CAAC,wBAAwB,EAAEF,IAAIG,MAAM,CAAC,qBAAqB,CAAC;IAEhE,MAAM,EAAEC,MAAM,EAAE,GAAI,MAAMJ,IAAIK,IAAI;IAElC,MAAM,EAAEC,IAAI,EAAE,GAAG,MAAMb,QAAQc,IAAI,CAAC;QAClCC,YAAYnC;QACZoC,YAAY;QACZC,OAAO;QACPC,QAAQ;YAAEjC,OAAO;YAAMY,cAAc;QAAK;IAC5C;IACA,MAAMsB,QAAQ,IAAIC,IAChB,AAACP,KAAgEQ,GAAG,CAACC,CAAAA,IAAK;YACxEA,EAAErC,KAAK;YACPqC;SACD;IAGH,IAAIC,UAAU;IACd,KAAK,MAAMC,SAASb,OAAQ;QAC1B,MAAMc,WAAWN,MAAMO,GAAG,CAACxC,OAAOsC,MAAMrC,EAAE;QAC1CgC,MAAMQ,MAAM,CAACzC,OAAOsC,MAAMrC,EAAE;QAC5B,IAAIsC,UAAU5B,iBAAiB2B,MAAM1B,SAAS,EAAE;QAChD,MAAM8B,OAAO7C,QAAQyC;QACrB,IAAIC,UACF,MAAMzB,QAAQ6B,MAAM,CAAC;YACnBd,YAAYnC;YACZO,IAAIsC,SAAStC,EAAE;YACfyC;QACF;aACG,MAAM5B,QAAQ8B,MAAM,CAAC;YAAEf,YAAYnC;YAAsBgD;QAAK;QACnEL;IACF;IACA,KAAK,MAAMQ,SAASZ,MAAMa,MAAM,GAC9B,MAAMhC,QAAQ2B,MAAM,CAAC;QAAEZ,YAAYnC;QAAsBO,IAAI4C,MAAM5C,EAAE;IAAC;IAExE,OAAO;QAAEoC;QAASU,SAASd,MAAMe,IAAI;QAAEC,OAAOxB,OAAOyB,MAAM;IAAC;AAC9D,EAAE"}
1
+ {"version":3,"sources":["../src/sync.ts"],"sourcesContent":["import type { Payload } from 'payload';\n\nimport {\n GUIDES_SLUG,\n hubFetch,\n PLUGIN_VERSION,\n type ResolvedConfig,\n} from './hub.js';\n\n/** One guide as the hub's feed sends it. */\nexport type FeedGuide = {\n id: number | string;\n title: string;\n slug: string;\n summary: string;\n scope: 'default' | 'plugin' | 'site';\n plugin?: string | null;\n topic: { title?: string; order?: number | null } | null;\n helpContexts: string[];\n order: number | null;\n body: unknown;\n bodyText: string;\n updatedAt: string;\n};\n\nconst toLocal = (g: FeedGuide) => ({\n hubId: String(g.id),\n title: g.title,\n slug: g.slug,\n summary: g.summary,\n scope: g.scope,\n topic: { title: g.topic?.title ?? null, order: g.topic?.order ?? null },\n helpContexts: g.helpContexts,\n order: g.order,\n body: g.body,\n bodyText: g.bodyText,\n hubUpdatedAt: g.updatedAt,\n});\n\n/**\n * FoundryKit plugins active on this site: the ones that recorded themselves in\n * `config.custom.foundrykit.activePlugins` (read from the running config, so plugin order doesn't\n * matter) plus any listed in the `plugins` option.\n */\nexport const activePlugins = (payload: Payload, config: ResolvedConfig) => {\n const detected = (\n payload.config.custom?.foundrykit as { activePlugins?: unknown } | undefined\n )?.activePlugins;\n return [\n ...new Set([\n ...(Array.isArray(detected) ? detected.map(String) : []),\n ...config.plugins,\n ]),\n ];\n};\n\n/**\n * Makes the local guides collection match this site's feed from the hub: adds new guides,\n * updates changed ones and removes any the site is no longer entitled to. Reports the plugin\n * version, features and active FoundryKit plugins on the way: the hub keeps them on the Sites\n * record and sends plugin guides for the plugins reported.\n */\nexport const syncGuides = async (payload: Payload, config: ResolvedConfig) => {\n const params = new URLSearchParams({\n pluginVersion: PLUGIN_VERSION,\n features: config.features.join(','),\n plugins: activePlugins(payload, config).join(','),\n });\n const res = await hubFetch(config, `/api/sites/feed?${params}`);\n if (!res.ok)\n throw new Error(\n `The guides hub answered ${res.status} to the feed request.`\n );\n const { guides } = (await res.json()) as { guides: FeedGuide[] };\n\n const { docs } = await payload.find({\n collection: GUIDES_SLUG as never,\n pagination: false,\n depth: 0,\n select: { hubId: true, hubUpdatedAt: true } as never,\n });\n const local = new Map(\n (docs as { id: number; hubId: string; hubUpdatedAt?: string }[]).map(d => [\n d.hubId,\n d,\n ])\n );\n\n let changed = 0;\n for (const guide of guides) {\n const existing = local.get(String(guide.id));\n local.delete(String(guide.id));\n if (existing?.hubUpdatedAt === guide.updatedAt) continue;\n const data = toLocal(guide) as never;\n if (existing)\n await payload.update({\n collection: GUIDES_SLUG as never,\n id: existing.id,\n data,\n });\n else await payload.create({ collection: GUIDES_SLUG as never, data });\n changed++;\n }\n for (const stale of local.values())\n await payload.delete({ collection: GUIDES_SLUG as never, id: stale.id });\n\n return { changed, removed: local.size, total: guides.length };\n};\n"],"names":["GUIDES_SLUG","hubFetch","PLUGIN_VERSION","toLocal","g","hubId","String","id","title","slug","summary","scope","topic","order","helpContexts","body","bodyText","hubUpdatedAt","updatedAt","activePlugins","payload","config","detected","custom","foundrykit","Set","Array","isArray","map","plugins","syncGuides","params","URLSearchParams","pluginVersion","features","join","res","ok","Error","status","guides","json","docs","find","collection","pagination","depth","select","local","Map","d","changed","guide","existing","get","delete","data","update","create","stale","values","removed","size","total","length"],"mappings":"AAEA,SACEA,WAAW,EACXC,QAAQ,EACRC,cAAc,QAET,WAAW;AAkBlB,MAAMC,UAAU,CAACC,IAAkB,CAAA;QACjCC,OAAOC,OAAOF,EAAEG,EAAE;QAClBC,OAAOJ,EAAEI,KAAK;QACdC,MAAML,EAAEK,IAAI;QACZC,SAASN,EAAEM,OAAO;QAClBC,OAAOP,EAAEO,KAAK;QACdC,OAAO;YAAEJ,OAAOJ,EAAEQ,KAAK,EAAEJ,SAAS;YAAMK,OAAOT,EAAEQ,KAAK,EAAEC,SAAS;QAAK;QACtEC,cAAcV,EAAEU,YAAY;QAC5BD,OAAOT,EAAES,KAAK;QACdE,MAAMX,EAAEW,IAAI;QACZC,UAAUZ,EAAEY,QAAQ;QACpBC,cAAcb,EAAEc,SAAS;IAC3B,CAAA;AAEA;;;;CAIC,GACD,OAAO,MAAMC,gBAAgB,CAACC,SAAkBC;IAC9C,MAAMC,WACJF,QAAQC,MAAM,CAACE,MAAM,EAAEC,YACtBL;IACH,OAAO;WACF,IAAIM,IAAI;eACLC,MAAMC,OAAO,CAACL,YAAYA,SAASM,GAAG,CAACtB,UAAU,EAAE;eACpDe,OAAOQ,OAAO;SAClB;KACF;AACH,EAAE;AAEF;;;;;CAKC,GACD,OAAO,MAAMC,aAAa,OAAOV,SAAkBC;IACjD,MAAMU,SAAS,IAAIC,gBAAgB;QACjCC,eAAe/B;QACfgC,UAAUb,OAAOa,QAAQ,CAACC,IAAI,CAAC;QAC/BN,SAASV,cAAcC,SAASC,QAAQc,IAAI,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  "name": "@foundrykit/guides-plugin",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "CMS guides for Payload 3 client sites: a Guides page, Help buttons on edit pages and local search, synced read-only from the Umi guides hub, with site-specific guides written in place by Umi staff.",
5
5
  "license": "MIT",
6
6
  "type": "module",