@easy-cms/plugin-social 0.0.0-stage → 1.35.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kanawoot K.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @easy-cms/plugin-social
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Social posts for Easy CMS (experimental): write a post once and send it to several channels, each with its own text, now or at a time, with retries and a state per channel. Channels are accounts connected on the Integrations page; the first is a webhook to a Make, n8n or Zapier scenario. Part of [Easy CMS](https://github.com/maritonx/easy-cms), the embedded, code-first headless CMS for Nuxt and Next.js.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @easy-cms/plugin-social
9
+ ```
10
+
11
+ Or `pnpm add`, `yarn add` or `bun add`.
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { socialPlugin } from '@easy-cms/plugin-social'
17
+
18
+ export default defineConfig({
19
+ serverURL: 'https://example.com',
20
+ // …
21
+ plugins: [
22
+ socialPlugin({
23
+ collections: ['posts'],
24
+ url: ({ doc }) => `https://example.com/posts/${doc.slug}`,
25
+ }),
26
+ ],
27
+ })
28
+ ```
29
+
30
+ Then create a migration (`easy-cms migrate:create social`), connect a webhook in **Settings → Integrations → Webhook (social)**, and press **Share on social media** on a post.
31
+
32
+ ## Links
33
+
34
+ [Social posts](https://easycms.dev/docs/social) · [Documentation](https://easycms.dev/docs) ([ภาษาไทย](https://easycms.dev/th/docs)) · [GitHub](https://github.com/maritonx/easy-cms)
35
+
36
+ MIT License
package/dist/admin.js ADDED
@@ -0,0 +1,66 @@
1
+ var x="/social/channels",m="/social/post",w="/social/share";var S=["value","path","doc","collection","id","uiLocale","readOnly","api"],$={en:{pick:"Choose a channel",gone:"{id} (not connected)",none:"No channel is connected yet: add one in Settings \u2192 Integrations.",chars:"{n} characters",charsMax:"{n} / {max} characters",over:"Too long for {channel}",saveFirst:"Save the post first, then post it.",savedOnly:"Posts what is saved: save your changes first.",postNow:"Post now",confirmNow:"Post to {n} channels now? Posts can\u2019t be taken back from here.",schedule:"Schedule",when:"Post at",scheduledFor:"Scheduled for {time}",cancel:"Cancel the schedule",retry:"Retry",waiting:"Not posted",scheduled:"Scheduled",sending:"Sending\u2026",retrying:"Trying again at {time}",posted:"Posted",view:"View post",failed:"Failed",noRight:"You may write this post; someone who may post sends it.",share:"Share on social media",shareSave:"Save first, then share.",sharing:"Creating a post\u2026"},th:{pick:"\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07",gone:"{id} (\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49\u0E40\u0E0A\u0E37\u0E48\u0E2D\u0E21\u0E15\u0E48\u0E2D\u0E41\u0E25\u0E49\u0E27)",none:"\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E21\u0E35\u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07\u0E17\u0E35\u0E48\u0E40\u0E0A\u0E37\u0E48\u0E2D\u0E21\u0E15\u0E48\u0E2D: \u0E40\u0E1E\u0E34\u0E48\u0E21\u0E44\u0E14\u0E49\u0E43\u0E19 Settings \u2192 \u0E01\u0E32\u0E23\u0E40\u0E0A\u0E37\u0E48\u0E2D\u0E21\u0E15\u0E48\u0E2D",chars:"{n} \u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",charsMax:"{n} / {max} \u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",over:"\u0E22\u0E32\u0E27\u0E40\u0E01\u0E34\u0E19\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A {channel}",saveFirst:"\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E01\u0E48\u0E2D\u0E19 \u0E41\u0E25\u0E49\u0E27\u0E04\u0E48\u0E2D\u0E22\u0E42\u0E1E\u0E2A\u0E15\u0E4C",savedOnly:"\u0E08\u0E30\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E15\u0E32\u0E21\u0E17\u0E35\u0E48\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E44\u0E27\u0E49: \u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E01\u0E32\u0E23\u0E41\u0E01\u0E49\u0E44\u0E02\u0E01\u0E48\u0E2D\u0E19",postNow:"\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E40\u0E25\u0E22",confirmNow:"\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E44\u0E1B {n} \u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07\u0E40\u0E25\u0E22\u0E44\u0E2B\u0E21? \u0E22\u0E01\u0E40\u0E25\u0E34\u0E01\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E08\u0E32\u0E01\u0E17\u0E35\u0E48\u0E19\u0E35\u0E48\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49",schedule:"\u0E15\u0E31\u0E49\u0E07\u0E40\u0E27\u0E25\u0E32",when:"\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E40\u0E27\u0E25\u0E32",scheduledFor:"\u0E15\u0E31\u0E49\u0E07\u0E40\u0E27\u0E25\u0E32\u0E44\u0E27\u0E49 {time}",cancel:"\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01\u0E01\u0E32\u0E23\u0E15\u0E31\u0E49\u0E07\u0E40\u0E27\u0E25\u0E32",retry:"\u0E25\u0E2D\u0E07\u0E2D\u0E35\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07",waiting:"\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E42\u0E1E\u0E2A\u0E15\u0E4C",scheduled:"\u0E15\u0E31\u0E49\u0E07\u0E40\u0E27\u0E25\u0E32\u0E44\u0E27\u0E49",sending:"\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2A\u0E48\u0E07\u2026",retrying:"\u0E08\u0E30\u0E25\u0E2D\u0E07\u0E43\u0E2B\u0E21\u0E48\u0E40\u0E27\u0E25\u0E32 {time}",posted:"\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E41\u0E25\u0E49\u0E27",view:"\u0E14\u0E39\u0E42\u0E1E\u0E2A\u0E15\u0E4C",failed:"\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08",noRight:"\u0E04\u0E38\u0E13\u0E40\u0E02\u0E35\u0E22\u0E19\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E19\u0E35\u0E49\u0E44\u0E14\u0E49 \u0E2A\u0E48\u0E27\u0E19\u0E01\u0E32\u0E23\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E2B\u0E49\u0E1C\u0E39\u0E49\u0E17\u0E35\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E40\u0E1B\u0E47\u0E19\u0E04\u0E19\u0E01\u0E14",share:"\u0E41\u0E0A\u0E23\u0E4C\u0E44\u0E1B\u0E42\u0E0B\u0E40\u0E0A\u0E35\u0E22\u0E25",shareSave:"\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E01\u0E48\u0E2D\u0E19 \u0E41\u0E25\u0E49\u0E27\u0E04\u0E48\u0E2D\u0E22\u0E41\u0E0A\u0E23\u0E4C",sharing:"\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u2026"}},n=o=>o.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]);function E(o){if(typeof Intl.Segmenter!="function")return[...o].length;let t=0;for(let e of new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(o))t++;return t}var k=new WeakMap;function T(o){let t=k.get(o);if(t)return t;let e=o("GET",x).then(s=>s).catch(()=>({channels:[],canPost:!1}));return k.set(o,e),e}var C=`
2
+ :host { display: block; font: inherit; color: var(--text); }
3
+ .row { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; }
4
+ .hint { margin: 0; font-size: 0.8rem; color: var(--text-muted); }
5
+ .error { margin: 0; font-size: 0.8rem; color: var(--danger); }
6
+ button {
7
+ display: inline-flex; align-items: center; gap: 0.35rem; min-height: 2rem; padding: 0 0.75rem;
8
+ border: 1px solid var(--border-strong); border-radius: var(--radius-sm, 8px);
9
+ background: var(--surface); color: var(--text); font: inherit; font-size: 0.85rem; font-weight: 500;
10
+ cursor: pointer;
11
+ }
12
+ button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text, #fff); }
13
+ button:hover:not(:disabled) { filter: brightness(0.97); }
14
+ button:focus-visible, select:focus-visible, input:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
15
+ button:disabled { opacity: 0.6; cursor: default; }
16
+ select, input {
17
+ min-height: 2.4rem; padding: 0 0.7rem; border: 1px solid var(--border-strong);
18
+ border-radius: var(--radius-sm, 8px); background: var(--surface); color: var(--text); font: inherit;
19
+ }
20
+ a { color: var(--accent-ink); }
21
+ `,p=class o extends HTMLElement{ctx={value:void 0,path:void 0,doc:{},collection:void 0,id:null,uiLocale:"en",readOnly:!1,api:void 0};channels=[];canPost=!1;asked=!1;queued=!1;html="";constructor(){super();let t=this.attachShadow({mode:"open"});t.addEventListener("click",e=>{let s=e.target.closest("[data-action]"),a=s?.getAttribute("data-action");a&&s?.tagName!=="SELECT"&&this.onAction(a,s)}),t.addEventListener("change",e=>this.onChange(e.target))}static{for(let t of S)Object.defineProperty(o.prototype,t,{get(){return this.ctx[t]},set(e){this.ctx[t]=e,this.update()}})}connectedCallback(){this.update()}t(t,e={}){return(this.ctx.uiLocale==="th"?$.th:$.en)[t].replace(/\{(\w+)\}/g,(a,r)=>String(e[r]??""))}time(t){return new Date(t).toLocaleString(this.ctx.uiLocale==="th"?"th-TH":"en-GB",{dateStyle:"medium",timeStyle:"short"})}labelOf(t){return this.channels.find(e=>e.id===t)?.label??t}update(){!this.asked&&this.ctx.api&&(this.asked=!0,T(this.ctx.api).then(({channels:t,canPost:e})=>{this.channels=t,this.canPost=e,this.update()})),!this.queued&&(this.queued=!0,queueMicrotask(()=>{this.queued=!1;let t=this.shadowRoot;if(!t)return;let e=`<style>${C}${this.css()}</style>${this.render()}`;if(e===this.html)return;let s=t.activeElement?.getAttribute("data-action");this.html=e,t.innerHTML=e,s&&t.querySelector(`[data-action="${s}"]`)?.focus()}))}onAction(t,e){}onChange(t){}css(){return""}},f=class extends p{render(){let t=typeof this.ctx.value=="string"?this.ctx.value:"",e=this.ctx.doc.delivery??null,s=!!t&&e?.channels?.[t]?.state==="posted";if(this.channels.length===0&&!t)return`<p class="hint">${n(this.t("none"))}</p>`;let a=this.channels.some(r=>r.id===t);return`
22
+ <select data-action="pick" aria-label="${n(this.t("pick"))}" ${this.ctx.readOnly||s?"disabled":""}>
23
+ ${t?"":`<option value="">${n(this.t("pick"))}</option>`}
24
+ ${!a&&t?`<option value="${n(t)}" selected>${n(this.t("gone",{id:t}))}</option>`:""}
25
+ ${this.channels.map(r=>`<option value="${n(r.id)}" ${r.id===t?"selected":""}>${n(r.label)}</option>`).join("")}
26
+ </select>
27
+ `}css(){return"select { width: 100%; }"}onChange(t){t.getAttribute("data-action")==="pick"&&this.dispatchEvent(new CustomEvent("change",{detail:t.value}))}},v=class extends p{render(){let t=typeof this.ctx.value=="string"?this.ctx.value:"",e=E(t.trim()),s=Array.isArray(this.ctx.doc.channels)?this.ctx.doc.channels:[],a=/^channels\.(\d+)\.text$/.exec(this.ctx.path??""),h=(a?s.filter((i,d)=>d===Number(a[1])):s.filter(i=>!(typeof i.text=="string"&&i.text.trim()))).map(i=>this.channels.find(d=>d.id===i.connection)).filter(i=>!!i?.maxLength).sort((i,d)=>(i.maxLength??0)-(d.maxLength??0))[0];if(!h)return`<p class="hint">${n(this.t("chars",{n:e}))}</p>`;let u=e>(h.maxLength??Number.POSITIVE_INFINITY);return`<p class="${u?"error":"hint"}">${n(this.t("charsMax",{n:e,max:h.maxLength??0}))}${u?` \xB7 ${n(this.t("over",{channel:h.label}))}`:""}</p>`}},y=class extends p{live=null;busy=!1;notice=null;problems=[];checkedFor=null;timer;disconnectedCallback(){clearTimeout(this.timer)}delivery(){return this.live??this.ctx.value??{channels:{}}}css(){return`
28
+ .panel { display: flex; flex-direction: column; gap: 0.75rem; }
29
+ ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.5rem; }
30
+ li { display: flex; flex-direction: column; gap: 0.2rem; padding: 0.55rem 0.65rem; border: 1px solid var(--border); border-radius: var(--radius-sm, 8px); background: var(--surface); }
31
+ .name { font-weight: 600; font-size: 0.875rem; }
32
+ .state { display: inline-flex; align-self: flex-start; gap: 0.3rem; padding: 0.05rem 0.5rem; border-radius: 999px; font-size: 0.75rem; font-weight: 600; background: var(--surface-2); color: var(--text-muted); }
33
+ .posted .state { background: var(--success-soft); color: var(--ok); }
34
+ .failed .state { background: var(--danger-soft); color: var(--danger); }
35
+ .sending .state, .scheduled .state { background: var(--accent-soft); color: var(--accent-ink); }
36
+ .schedule { display: flex; gap: 0.4rem; flex-wrap: wrap; }
37
+ .schedule input { flex: 1 1 10rem; }
38
+ .warning { margin: 0; padding: 0.5rem 0.65rem; border-radius: var(--radius-sm, 8px); background: var(--warning-soft); color: var(--warning-text); font-size: 0.8rem; }
39
+ `}check(){let{api:t,id:e}=this.ctx,{image:s=null,source:a=null}=this.ctx.doc,r=JSON.stringify([e,s,a]);!t||e===null||r===this.checkedFor||(this.checkedFor=r,t("POST",m,{post:e,action:"check",image:s,source:a}).then(c=>{this.problems=c.problems??[],this.update()}).catch(()=>{}))}render(){if(this.ctx.id===null)return`<p class="hint">${n(this.t("saveFirst"))}</p>`;this.check();let e=this.delivery(),s=(Array.isArray(this.ctx.doc.channels)?this.ctx.doc.channels:[]).filter(i=>typeof i.connection=="string"&&i.connection),a=i=>e.channels?.[i]??{state:"waiting",attempts:0},r=s.filter(i=>["waiting","scheduled"].includes(a(i.connection).state)),c=s.some(i=>a(i.connection).state==="scheduled"),h=s.map(i=>{let d=i.connection,l=a(d),A=l.state==="sending"&&l.attempts>0&&l.nextAttemptAt?this.t("retrying",{time:this.time(l.nextAttemptAt)}):this.t(l.state);return`
40
+ <li class="${l.state}" data-channel="${n(d)}">
41
+ <span class="name">${n(this.labelOf(d))}</span>
42
+ <span class="state">${n(A)}</span>
43
+ ${l.state==="posted"&&l.url?`<a href="${n(l.url)}" target="_blank" rel="noopener">${n(this.t("view"))}</a>`:""}
44
+ ${l.error&&l.state!=="posted"?`<p class="error">${n(l.error)}</p>`:""}
45
+ ${l.state==="failed"&&this.canPost?`<div class="row"><button type="button" data-action="retry" data-channel="${n(d)}" ${this.busy?"disabled":""}>${n(this.t("retry"))}</button></div>`:""}
46
+ </li>`}).join(""),u=this.canPost?r.length===0?"":`
47
+ <div class="row"><button type="button" class="primary" data-action="now" ${this.busy?"disabled":""}>${n(this.t("postNow"))}</button></div>
48
+ ${c&&e.postAt?`<p class="hint">${n(this.t("scheduledFor",{time:this.time(e.postAt)}))}</p>
49
+ <div class="row"><button type="button" data-action="cancel" ${this.busy?"disabled":""}>${n(this.t("cancel"))}</button></div>`:`<div class="schedule">
50
+ <input type="datetime-local" data-field="when" aria-label="${n(this.t("when"))}" />
51
+ <button type="button" data-action="schedule" ${this.busy?"disabled":""}>${n(this.t("schedule"))}</button>
52
+ </div>`}
53
+ <p class="hint">${n(this.t("savedOnly"))}</p>`:`<p class="hint">${n(this.t("noRight"))}</p>`;return`
54
+ <div class="panel">
55
+ ${s.length?`<ul>${h}</ul>`:`<p class="hint">${n(this.t("none"))}</p>`}
56
+ ${this.problems.map(i=>`<p class="warning">${n(i)}</p>`).join("")}
57
+ ${s.length?u:""}
58
+ ${this.notice?`<p class="error" role="alert">${n(this.notice)}</p>`:""}
59
+ </div>
60
+ `}async onAction(t,e){let{api:s,id:a}=this.ctx;if(!s||a===null||this.busy)return;let r={post:a,action:t};if(t==="retry"&&(r.channel=e.getAttribute("data-channel")),t==="schedule"){let c=this.shadowRoot?.querySelector('[data-field="when"]');if(!c?.value){c?.focus();return}r.postAt=new Date(c.value).toISOString()}if(t==="now"){let h=(this.ctx.doc.channels??[]).filter(u=>this.delivery().channels?.[String(u.connection)]?.state!=="posted").length;if(!window.confirm(this.t("confirmNow",{n:h})))return}this.busy=!0,this.notice=null,this.update();try{let c=await s("POST",m,r);this.live=c.delivery,this.watch()}catch(c){this.notice=c.message}finally{this.busy=!1,this.update()}}watch(){clearTimeout(this.timer),!(!Object.values(this.delivery().channels??{}).some(e=>e.state==="sending")||!this.ctx.api||!this.ctx.collection||this.ctx.id===null)&&(this.timer=setTimeout(async()=>{try{let e=await this.ctx.api?.("GET",`/${this.ctx.collection}/${encodeURIComponent(String(this.ctx.id))}?depth=0`);this.live=e.delivery??null,this.update()}catch{}this.watch()},5e3))}},b=class extends p{busy=!1;notice=null;render(){let t=this.ctx.id!==null;return`
61
+ <div class="row">
62
+ <button type="button" data-action="share" ${!t||this.busy?"disabled":""}>${n(this.t(this.busy?"sharing":"share"))}</button>
63
+ </div>
64
+ ${t?"":`<p class="hint">${n(this.t("shareSave"))}</p>`}
65
+ ${this.notice?`<p class="error" role="alert">${n(this.notice)}</p>`:""}
66
+ `}async onAction(t){let{api:e,id:s,collection:a}=this.ctx;if(!(t!=="share"||!e||s===null||this.busy)){this.busy=!0,this.notice=null,this.update();try{let r=await e("POST",w,{collection:a,id:s});this.dispatchEvent(new CustomEvent("navigate",{detail:r.path}))}catch(r){this.notice=r.message}finally{this.busy=!1,this.update()}}}},g=(o,t)=>{customElements.get(o)||customElements.define(o,t)};g("ecms-social-channel",f);g("ecms-social-count",v);g("ecms-social-panel",y);g("ecms-social-share",b);
@@ -0,0 +1,101 @@
1
+ import * as _easy_cms_core from '@easy-cms/core';
2
+ import { IntegrationConfig, EasyCMS } from '@easy-cms/core';
3
+
4
+ /** What a channel posts: the text for it, a link, a public image URL, and the source document. */
5
+ interface SocialMessage {
6
+ /** The social post's id. */
7
+ readonly post: string | number;
8
+ /** `<integration>:<connection name>`. */
9
+ readonly channel: string;
10
+ readonly text: string;
11
+ readonly link: string | null;
12
+ readonly image: {
13
+ readonly url: string;
14
+ readonly alt: string | null;
15
+ } | null;
16
+ readonly source: {
17
+ readonly collection: string;
18
+ readonly id: string | number;
19
+ } | null;
20
+ }
21
+ /**
22
+ * A place social posts go (#312): an integration admins connect accounts to, and how it posts.
23
+ * The webhook comes first; Facebook Pages and LINE follow (#313).
24
+ */
25
+ interface SocialChannel {
26
+ readonly integration: IntegrationConfig;
27
+ /** Characters a post may have there, for the admin's counter. */
28
+ readonly maxLength?: number;
29
+ /** Posts; returns the post's URL when the channel says. Throws `ChannelError` with the reason. */
30
+ readonly send: (values: Readonly<Record<string, string>>, message: SocialMessage) => Promise<{
31
+ url?: string | null;
32
+ }>;
33
+ }
34
+ /** A channel's refusal; `permanent` when trying again won't help (e.g. a revoked token). */
35
+ declare class ChannelError extends Error {
36
+ readonly permanent: boolean;
37
+ constructor(message: string, permanent?: boolean);
38
+ }
39
+
40
+ type Doc = Record<string, unknown>;
41
+ /** What a social post starts with when shared from a document. */
42
+ interface ShareValues {
43
+ readonly title?: string | null;
44
+ readonly text?: string | null;
45
+ readonly link?: string | null;
46
+ /** A media document's id. */
47
+ readonly image?: string | number | null;
48
+ }
49
+ interface SocialPluginOptions {
50
+ /** Collections whose edit page has **Share**, e.g. `['posts']`; the post's source points to them. */
51
+ readonly collections?: readonly string[];
52
+ /**
53
+ * What a shared document fills in. Default: its title (`useAsTitle`), its first textarea (an
54
+ * excerpt), `url`, and its first image.
55
+ */
56
+ readonly share?: (args: {
57
+ doc: Doc;
58
+ collection: string;
59
+ cms: EasyCMS;
60
+ }) => ShareValues | Promise<ShareValues>;
61
+ /** A document's public address, for the post's link, e.g. `({ doc }) => \`https://…/${doc.slug}\``. */
62
+ readonly url?: (args: {
63
+ doc: Doc;
64
+ collection: string;
65
+ }) => string | null | undefined;
66
+ /** Where posts go. Default: the webhook (Make, n8n, Zapier). */
67
+ readonly channels?: readonly SocialChannel[];
68
+ /** Slug of the social posts collection. Default `social-posts`. */
69
+ readonly slug?: string;
70
+ }
71
+ /**
72
+ * Social posts (#312, experimental): write once, send to several channels, each with its own text,
73
+ * now or at a time, with retries and a state per channel. Channels are integrations admins connect
74
+ * on the Integrations page; the webhook comes first.
75
+ */
76
+ declare function socialPlugin(options?: SocialPluginOptions): _easy_cms_core.TypedPlugin<Record<never, never>>;
77
+
78
+ /**
79
+ * A channel's state: `waiting` (not sent), `scheduled`, `sending` (due or being tried again),
80
+ * `posted`, `failed` (given up on).
81
+ */
82
+ type ChannelState = 'waiting' | 'scheduled' | 'sending' | 'posted' | 'failed';
83
+ interface ChannelDelivery {
84
+ state: ChannelState;
85
+ /** The post on the channel, when it says. */
86
+ url?: string | null;
87
+ error?: string | null;
88
+ attempts: number;
89
+ nextAttemptAt?: string | null;
90
+ postedAt?: string | null;
91
+ }
92
+ /** The `delivery` field of a social post: when to post, and each channel's state by connection. */
93
+ interface Delivery {
94
+ postAt?: string | null;
95
+ channels: Record<string, ChannelDelivery>;
96
+ }
97
+
98
+ declare const webhook: SocialChannel;
99
+
100
+ export { ChannelError, socialPlugin, webhook };
101
+ export type { ChannelDelivery, ChannelState, Delivery, ShareValues, SocialChannel, SocialMessage, SocialPluginOptions };
package/dist/index.js ADDED
@@ -0,0 +1,608 @@
1
+ // src/channel.ts
2
+ var ChannelError = class extends Error {
3
+ permanent;
4
+ constructor(message, permanent = false) {
5
+ super(message);
6
+ this.name = "ChannelError";
7
+ this.permanent = permanent;
8
+ }
9
+ };
10
+
11
+ // src/plugin.ts
12
+ import {
13
+ definePlugin
14
+ } from "@easy-cms/core";
15
+
16
+ // src/info.ts
17
+ var INFO = {
18
+ name: "@easy-cms/plugin-social",
19
+ // The plugin API it is written for (`PLUGIN_API_VERSION` of @easy-cms/core).
20
+ apiVersion: 1,
21
+ ...true ? { version: "1.35.1" } : {}
22
+ };
23
+
24
+ // src/shared.ts
25
+ var CHANNELS_PATH = "/social/channels";
26
+ var ACTION_PATH = "/social/post";
27
+ var SHARE_PATH = "/social/share";
28
+
29
+ // src/webhook.ts
30
+ import { createHmac, randomUUID } from "crypto";
31
+ async function post(values, body) {
32
+ const url = values.url ?? "";
33
+ if (!/^https?:\/\//.test(url)) throw new ChannelError("The webhook URL is not http(s)", true);
34
+ const json2 = JSON.stringify(body);
35
+ const delivery = randomUUID();
36
+ const timestamp = Math.floor(Date.now() / 1e3);
37
+ const headers = {
38
+ "content-type": "application/json",
39
+ "x-easy-cms-event": "social.post",
40
+ "x-easy-cms-delivery": delivery,
41
+ "x-easy-cms-timestamp": String(timestamp)
42
+ };
43
+ if (values.secret)
44
+ headers["x-easy-cms-signature-v2"] = `v1=${createHmac("sha256", values.secret).update(`${delivery}.${timestamp}.${json2}`).digest("hex")}`;
45
+ let response;
46
+ try {
47
+ response = await fetch(url, {
48
+ method: "POST",
49
+ headers,
50
+ body: json2,
51
+ signal: AbortSignal.timeout(15e3)
52
+ });
53
+ } catch (error) {
54
+ throw new ChannelError(`The webhook could not be reached: ${error.message}`);
55
+ }
56
+ const text = await response.text().catch(() => "");
57
+ if (!response.ok)
58
+ throw new ChannelError(
59
+ `The webhook answered ${response.status}${text ? `: ${text.slice(0, 200)}` : ""}`,
60
+ response.status >= 400 && response.status < 500 && response.status !== 429
61
+ );
62
+ try {
63
+ const answer = JSON.parse(text);
64
+ return { url: typeof answer.url === "string" ? answer.url : null };
65
+ } catch {
66
+ return { url: null };
67
+ }
68
+ }
69
+ var webhook = {
70
+ integration: {
71
+ id: "social-webhook",
72
+ label: { en: "Webhook (social)", th: "Webhook (\u0E42\u0E0B\u0E40\u0E0A\u0E35\u0E22\u0E25)" },
73
+ category: "social",
74
+ description: {
75
+ en: "Posts go to a URL as signed JSON: a Make, n8n or Zapier scenario that posts to X or anywhere else",
76
+ th: "\u0E2A\u0E48\u0E07\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E40\u0E1B\u0E47\u0E19 JSON \u0E17\u0E35\u0E48\u0E25\u0E07\u0E25\u0E32\u0E22\u0E40\u0E0B\u0E47\u0E19\u0E44\u0E1B\u0E22\u0E31\u0E07 URL \u0E40\u0E0A\u0E48\u0E19 scenario \u0E02\u0E2D\u0E07 Make, n8n \u0E2B\u0E23\u0E37\u0E2D Zapier \u0E17\u0E35\u0E48\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E15\u0E48\u0E2D\u0E44\u0E1B\u0E22\u0E31\u0E07 X \u0E2B\u0E23\u0E37\u0E2D\u0E17\u0E35\u0E48\u0E2D\u0E37\u0E48\u0E19"
77
+ },
78
+ icon: "link",
79
+ docs: "https://easycms.dev/docs/social",
80
+ plugin: "@easy-cms/plugin-social",
81
+ kind: "fields",
82
+ fields: [
83
+ { name: "url", label: "URL", type: "url", required: true },
84
+ {
85
+ name: "secret",
86
+ label: { en: "Signing secret", th: "Secret \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E25\u0E07\u0E25\u0E32\u0E22\u0E40\u0E0B\u0E47\u0E19" },
87
+ description: {
88
+ en: "Signs each post (x-easy-cms-signature-v2), as Easy CMS webhooks are.",
89
+ th: "\u0E43\u0E0A\u0E49\u0E25\u0E07\u0E25\u0E32\u0E22\u0E40\u0E0B\u0E47\u0E19\u0E17\u0E38\u0E01\u0E42\u0E1E\u0E2A\u0E15\u0E4C (x-easy-cms-signature-v2) \u0E41\u0E1A\u0E1A\u0E40\u0E14\u0E35\u0E22\u0E27\u0E01\u0E31\u0E1A webhook \u0E02\u0E2D\u0E07 Easy CMS"
90
+ },
91
+ secret: true
92
+ }
93
+ ],
94
+ // Test sends `{ test: true }`: the scenario can ignore it.
95
+ async test(values) {
96
+ try {
97
+ await post(values, { test: true });
98
+ return { ok: true, account: new URL(values.url ?? "").host };
99
+ } catch (error) {
100
+ return { ok: false, message: error.message };
101
+ }
102
+ }
103
+ },
104
+ send: (values, message) => post(values, { ...message })
105
+ };
106
+
107
+ // src/plugin.ts
108
+ var RETRIES = [6e4, 5 * 6e4, 30 * 6e4];
109
+ var LEASE = 2 * 6e4;
110
+ var SOURCE_WAIT = 60 * 6e4;
111
+ var nobody = () => false;
112
+ var later = (from, ms) => new Date(from.getTime() + ms).toISOString();
113
+ var json = (status, message) => Response.json({ errors: [{ message }] }, { status });
114
+ function socialPlugin(options = {}) {
115
+ const channels = options.channels ?? [webhook];
116
+ const slug = options.slug ?? "social-posts";
117
+ const sources = options.collections ?? [];
118
+ return definePlugin((config) => {
119
+ if (config.collections?.some((c) => c.slug === slug))
120
+ throw new Error(`socialPlugin: there is already a collection "${slug}"; set \`slug\``);
121
+ const missing = sources.filter((s) => !config.collections?.some((c) => c.slug === s));
122
+ if (missing.length > 0)
123
+ throw new Error(`socialPlugin: unknown collection ${missing.map((s) => `"${s}"`).join(", ")}`);
124
+ const channelOf = (connection) => channels.find((c) => connection.startsWith(`${c.integration.id}:`));
125
+ const nameOf = (connection) => connection.slice(connection.indexOf(":") + 1);
126
+ const fields = [
127
+ { name: "title", type: "text", required: true, label: { en: "Title", th: "\u0E0A\u0E37\u0E48\u0E2D" } },
128
+ {
129
+ name: "text",
130
+ type: "textarea",
131
+ required: true,
132
+ label: { en: "Text", th: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21" },
133
+ admin: { after: [{ tag: "ecms-social-count" }] }
134
+ },
135
+ { name: "link", type: "text", label: { en: "Link", th: "\u0E25\u0E34\u0E07\u0E01\u0E4C" } },
136
+ {
137
+ name: "image",
138
+ type: "upload",
139
+ mimeTypes: ["image/*"],
140
+ label: { en: "Image", th: "\u0E23\u0E39\u0E1B" },
141
+ admin: {
142
+ description: {
143
+ en: "Channels fetch it from its public URL.",
144
+ th: "\u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07\u0E08\u0E30\u0E14\u0E36\u0E07\u0E23\u0E39\u0E1B\u0E08\u0E32\u0E01 URL \u0E2A\u0E32\u0E18\u0E32\u0E23\u0E13\u0E30"
145
+ }
146
+ }
147
+ },
148
+ ...sources.length > 0 ? [
149
+ {
150
+ name: "source",
151
+ type: "relationship",
152
+ to: sources.length === 1 ? sources[0] : [...sources],
153
+ label: { en: "Shared from", th: "\u0E41\u0E0A\u0E23\u0E4C\u0E08\u0E32\u0E01" }
154
+ }
155
+ ] : [],
156
+ {
157
+ name: "channels",
158
+ type: "array",
159
+ label: { en: "Channels", th: "\u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07" },
160
+ fields: [
161
+ {
162
+ name: "connection",
163
+ type: "text",
164
+ required: true,
165
+ label: { en: "Channel", th: "\u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07" },
166
+ admin: { component: { tag: "ecms-social-channel" } }
167
+ },
168
+ {
169
+ name: "text",
170
+ type: "textarea",
171
+ label: { en: "Text for this channel", th: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E40\u0E09\u0E1E\u0E32\u0E30\u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07\u0E19\u0E35\u0E49" },
172
+ admin: {
173
+ description: { en: "Empty: the post's text.", th: "\u0E16\u0E49\u0E32\u0E27\u0E48\u0E32\u0E07: \u0E43\u0E0A\u0E49\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E02\u0E2D\u0E07\u0E42\u0E1E\u0E2A\u0E15\u0E4C" },
174
+ after: [{ tag: "ecms-social-count" }]
175
+ }
176
+ }
177
+ ]
178
+ },
179
+ {
180
+ // Each channel's state, written by the plugin; the side panel shows it with the actions.
181
+ name: "delivery",
182
+ type: "json",
183
+ label: { en: "Posting", th: "\u0E01\u0E32\u0E23\u0E42\u0E1E\u0E2A\u0E15\u0E4C" },
184
+ access: { create: nobody, update: nobody },
185
+ admin: { position: "sidebar", component: { tag: "ecms-social-panel" } }
186
+ },
187
+ // When the job should look again: the earliest due channel. Not shown, not sent.
188
+ {
189
+ name: "nextAt",
190
+ type: "text",
191
+ index: true,
192
+ access: { read: nobody, create: nobody, update: nobody }
193
+ }
194
+ ];
195
+ const posts = {
196
+ slug,
197
+ labels: {
198
+ singular: { en: "Social post", th: "\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E42\u0E0B\u0E40\u0E0A\u0E35\u0E22\u0E25" },
199
+ plural: { en: "Social posts", th: "\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E42\u0E0B\u0E40\u0E0A\u0E35\u0E22\u0E25" }
200
+ },
201
+ useAsTitle: "title",
202
+ // Posting is its own permission (`publish`, "Post" in Settings → Roles): drafting isn't.
203
+ admin: { icon: "megaphone", permissions: ["publish"] },
204
+ fields,
205
+ hooks: {
206
+ beforeChange: [
207
+ ({ data, previousDoc: originalDoc }) => {
208
+ const rows = Array.isArray(data.channels) ? data.channels : [];
209
+ const seen = /* @__PURE__ */ new Set();
210
+ const delivery = (originalDoc?.delivery ?? null)?.channels ?? {};
211
+ const before = Array.isArray(originalDoc?.channels) ? originalDoc.channels : [];
212
+ const kept = [];
213
+ for (const row of rows) {
214
+ const connection = String(row.connection ?? "");
215
+ if (seen.has(connection)) continue;
216
+ seen.add(connection);
217
+ if (delivery[connection]?.state === "posted") {
218
+ const old = before.find((r) => r.connection === connection);
219
+ kept.push(old ? { ...row, text: old.text ?? null } : row);
220
+ } else kept.push(row);
221
+ }
222
+ for (const [connection, state] of Object.entries(delivery))
223
+ if (state.state === "posted" && !seen.has(connection)) {
224
+ const old = before.find((r) => r.connection === connection);
225
+ if (old) kept.push(old);
226
+ }
227
+ return { ...data, channels: kept };
228
+ }
229
+ ]
230
+ }
231
+ };
232
+ const mayPost = async (cms, user, id) => {
233
+ if (await cms.roles.allows(user, { collection: slug }, "publish") === false) return false;
234
+ if (id === void 0) return true;
235
+ return (await cms.documentPermissions(slug, String(id), user)).update;
236
+ };
237
+ const imageOf = async (cms, id) => {
238
+ if (id === null || id === void 0 || id === "") return { image: null };
239
+ const media = await cms.findById(
240
+ "media",
241
+ typeof id === "object" ? id.id : id,
242
+ {
243
+ depth: 0
244
+ }
245
+ );
246
+ if (!media) return { error: "The image was deleted" };
247
+ if (media.private === true) return { error: "The image is private: channels can\u2019t fetch it" };
248
+ const raw = String(media.url ?? "");
249
+ const server = cms.config.serverURL?.replace(/\/+$/, "");
250
+ const url = /^https?:\/\//.test(raw) ? raw : server ? `${server}${raw}` : "";
251
+ if (!url) return { error: "Set `serverURL` so channels can fetch the image" };
252
+ const host = new URL(url).hostname;
253
+ if (host === "localhost" || host.endsWith(".localhost") || /^(127\.|\[?::1)/.test(host))
254
+ return { error: `The image is at ${host}, which channels can\u2019t reach` };
255
+ return { image: { url, alt: typeof media.alt === "string" && media.alt ? media.alt : null } };
256
+ };
257
+ const deliveryOf = (doc) => {
258
+ const d = doc.delivery ?? {};
259
+ return { postAt: d.postAt ?? null, channels: { ...d.channels ?? {} } };
260
+ };
261
+ const rowsOf = (doc) => (Array.isArray(doc.channels) ? doc.channels : []).filter(
262
+ (r) => typeof r.connection === "string" && r.connection
263
+ );
264
+ const nextAtOf = (delivery) => {
265
+ const times = Object.values(delivery.channels).filter((c) => c.state === "sending" || c.state === "scheduled").map(
266
+ (c) => c.state === "scheduled" ? delivery.postAt ?? null : c.nextAttemptAt ?? null
267
+ ).filter((t) => !!t).sort();
268
+ return times[0] ?? null;
269
+ };
270
+ const save = (cms, id, delivery, where) => {
271
+ const data = { delivery, nextAt: nextAtOf(delivery) };
272
+ return where ? cms.update(slug, id, data, { live: true, where }) : cms.update(slug, id, data, { live: true });
273
+ };
274
+ const sourceOf = (doc) => {
275
+ const source = doc.source;
276
+ if (source && typeof source === "object" && "relationTo" in source) {
277
+ const value = source.value;
278
+ return {
279
+ collection: String(source.relationTo),
280
+ id: typeof value === "object" ? value.id : value
281
+ };
282
+ }
283
+ if (source != null && sources.length === 1)
284
+ return {
285
+ collection: sources[0],
286
+ id: typeof source === "object" ? source.id : source
287
+ };
288
+ return null;
289
+ };
290
+ const isLive = async (cms, ref) => {
291
+ const config2 = cms.config.collections.find((c) => c.slug === ref.collection);
292
+ if (!config2?.drafts) return true;
293
+ const live = await cms.findById(ref.collection, ref.id, { depth: 0 });
294
+ return !!live && live.status === "published";
295
+ };
296
+ async function sendDue(cms, doc, now = /* @__PURE__ */ new Date()) {
297
+ const id = doc.id;
298
+ const delivery = deliveryOf(doc);
299
+ const due = rowsOf(doc).filter((row) => {
300
+ const state = delivery.channels[row.connection];
301
+ if (!state) return false;
302
+ if (state.state === "scheduled")
303
+ return !!delivery.postAt && delivery.postAt <= now.toISOString();
304
+ return state.state === "sending" && (state.nextAttemptAt ?? "") <= now.toISOString();
305
+ });
306
+ if (due.length === 0) return deliveryOf(doc);
307
+ const lease = later(now, LEASE);
308
+ const claimed = await cms.update(
309
+ slug,
310
+ id,
311
+ { nextAt: lease },
312
+ {
313
+ live: true,
314
+ where: doc.nextAt == null ? { nextAt: { exists: false } } : { nextAt: { equals: doc.nextAt } }
315
+ }
316
+ );
317
+ if (!claimed) return deliveryOf(doc);
318
+ const sourceRef = sourceOf(doc);
319
+ const sourceIssue = sourceRef && !await isLive(cms, sourceRef) ? "The source isn\u2019t published" : null;
320
+ const { image, error: imageError } = {
321
+ image: null,
322
+ error: null,
323
+ ...await imageOf(cms, doc.image)
324
+ };
325
+ for (const row of due) {
326
+ const connection = row.connection;
327
+ const state = { ...delivery.channels[connection] };
328
+ const attempts = state.attempts + 1;
329
+ const fail = async (message, permanent) => {
330
+ const wait = permanent ? void 0 : RETRIES[attempts - 1];
331
+ delivery.channels[connection] = {
332
+ ...state,
333
+ state: wait === void 0 ? "failed" : "sending",
334
+ attempts,
335
+ error: message.slice(0, 500),
336
+ nextAttemptAt: wait === void 0 ? null : later(now, wait)
337
+ };
338
+ if (wait === void 0) {
339
+ cms.emit(
340
+ "social.failed",
341
+ { post: { id, title: doc.title }, channel: connection, error: message },
342
+ { collection: slug, id }
343
+ );
344
+ const channel2 = channelOf(connection);
345
+ if (channel2)
346
+ await cms.integrations.markError(channel2.integration.id, message, nameOf(connection));
347
+ }
348
+ };
349
+ if (sourceIssue) {
350
+ const since = new Date(delivery.postAt ?? now.toISOString()).getTime();
351
+ if (now.getTime() - since < SOURCE_WAIT) {
352
+ delivery.channels[connection] = {
353
+ ...state,
354
+ state: "sending",
355
+ nextAttemptAt: later(now, 6e4)
356
+ };
357
+ continue;
358
+ }
359
+ await fail(`${sourceIssue} after an hour`, true);
360
+ continue;
361
+ }
362
+ if (imageError) {
363
+ await fail(imageError, true);
364
+ continue;
365
+ }
366
+ const channel = channelOf(connection);
367
+ const conn = channel ? await cms.integrations.get(channel.integration.id, { name: nameOf(connection) }) : null;
368
+ if (!channel || !conn) {
369
+ await fail("The channel is no longer connected", true);
370
+ continue;
371
+ }
372
+ try {
373
+ const result = await channel.send(conn.values, {
374
+ post: id,
375
+ channel: connection,
376
+ text: String(row.text || doc.text || ""),
377
+ link: typeof doc.link === "string" && doc.link ? doc.link : null,
378
+ image,
379
+ source: sourceRef ? { collection: sourceRef.collection, id: sourceRef.id } : null
380
+ });
381
+ delivery.channels[connection] = {
382
+ state: "posted",
383
+ attempts,
384
+ url: result.url ?? null,
385
+ error: null,
386
+ nextAttemptAt: null,
387
+ postedAt: now.toISOString()
388
+ };
389
+ await cms.integrations.markUsed(channel.integration.id, conn.name);
390
+ cms.emit(
391
+ "social.posted",
392
+ { post: { id, title: doc.title }, channel: connection, url: result.url ?? null },
393
+ { collection: slug, id }
394
+ );
395
+ } catch (error) {
396
+ await fail(error.message, error instanceof ChannelError && error.permanent);
397
+ }
398
+ }
399
+ await save(cms, id, delivery, { nextAt: { equals: lease } });
400
+ return delivery;
401
+ }
402
+ const channelsEndpoint = {
403
+ path: CHANNELS_PATH,
404
+ method: "get",
405
+ handler: async ({ user, cms }) => {
406
+ if (!user) return json(401, "Log in to see the channels");
407
+ const out = [];
408
+ for (const channel of channels) {
409
+ const { id, label, icon } = channel.integration;
410
+ for (const conn of await cms.integrations.all(id)) {
411
+ const name = typeof label === "string" ? label : label.en ?? id;
412
+ out.push({
413
+ id: `${id}:${conn.name}`,
414
+ label: `${name} \xB7 ${conn.name}`,
415
+ ...icon ? { icon } : {},
416
+ ...channel.maxLength ? { maxLength: channel.maxLength } : {}
417
+ });
418
+ }
419
+ }
420
+ return { channels: out, canPost: await mayPost(cms, user) };
421
+ }
422
+ };
423
+ const actionEndpoint = {
424
+ path: ACTION_PATH,
425
+ method: "post",
426
+ handler: async ({ json: body, user, cms }) => {
427
+ if (!user) return json(401, "Log in to post");
428
+ const input = await body();
429
+ const id = typeof input.post === "string" || typeof input.post === "number" ? input.post : null;
430
+ if (id === null) return json(400, "post is required");
431
+ if (input.action === "check") {
432
+ const saved = await cms.findById(slug, id, {
433
+ depth: 0,
434
+ user,
435
+ overrideAccess: false
436
+ });
437
+ if (!saved) return json(404, "No such post");
438
+ const doc2 = {
439
+ ...saved,
440
+ ..."image" in input ? { image: input.image } : {},
441
+ ..."source" in input ? { source: input.source } : {}
442
+ };
443
+ const problems = [];
444
+ const image = await imageOf(cms, doc2.image);
445
+ if ("error" in image) problems.push(image.error);
446
+ const ref = sourceOf(doc2);
447
+ if (ref && !await isLive(cms, ref))
448
+ problems.push("The source isn\u2019t published yet: its link may not open");
449
+ return { problems };
450
+ }
451
+ if (!await mayPost(cms, user, id)) return json(403, "You may not post this");
452
+ const doc = await cms.findById(slug, id, { depth: 0 });
453
+ if (!doc) return json(404, "No such post");
454
+ const rows = rowsOf(doc);
455
+ const delivery = deliveryOf(doc);
456
+ const now = /* @__PURE__ */ new Date();
457
+ const action = input.action;
458
+ const open = rows.map((r) => r.connection).filter((c) => delivery.channels[c]?.state !== "posted");
459
+ if (action === "now" || action === "schedule" || action === "retry") {
460
+ if (rows.length === 0) return json(400, "Add a channel first");
461
+ const image = await imageOf(cms, doc.image);
462
+ if ("error" in image) return json(400, image.error);
463
+ for (const c of open)
464
+ if (!channelOf(c)) return json(400, `"${c}" is not a channel this site has`);
465
+ }
466
+ if (action === "now" || action === "retry") {
467
+ const targets = action === "retry" ? open.filter((c) => c === input.channel && delivery.channels[c]?.state === "failed") : open.filter((c) => delivery.channels[c]?.state !== "sending");
468
+ if (targets.length === 0)
469
+ return json(400, action === "retry" ? "Nothing to retry" : "Nothing left to post");
470
+ for (const c of targets)
471
+ delivery.channels[c] = {
472
+ state: "sending",
473
+ attempts: 0,
474
+ error: null,
475
+ url: null,
476
+ nextAttemptAt: now.toISOString(),
477
+ postedAt: null
478
+ };
479
+ if (action === "now") delivery.postAt = null;
480
+ const saved = await save(cms, id, delivery);
481
+ return { delivery: await sendDue(cms, saved, now) };
482
+ }
483
+ if (action === "schedule") {
484
+ const postAt = typeof input.postAt === "string" ? new Date(input.postAt) : null;
485
+ if (!postAt || Number.isNaN(postAt.getTime()) || postAt <= now)
486
+ return json(400, "postAt must be a time in the future");
487
+ delivery.postAt = postAt.toISOString();
488
+ for (const c of open)
489
+ delivery.channels[c] = {
490
+ state: "scheduled",
491
+ attempts: 0,
492
+ error: null,
493
+ nextAttemptAt: null
494
+ };
495
+ await save(cms, id, delivery);
496
+ return { delivery };
497
+ }
498
+ if (action === "cancel") {
499
+ delivery.postAt = null;
500
+ for (const [c, state] of Object.entries(delivery.channels))
501
+ if (state.state === "scheduled")
502
+ delivery.channels[c] = { state: "waiting", attempts: 0 };
503
+ await save(cms, id, delivery);
504
+ return { delivery };
505
+ }
506
+ return json(400, "action must be now, schedule, cancel or retry");
507
+ }
508
+ };
509
+ const shareEndpoint = {
510
+ path: SHARE_PATH,
511
+ method: "post",
512
+ handler: async ({ json: body, user, cms }) => {
513
+ if (!user) return json(401, "Log in to share");
514
+ const input = await body();
515
+ const collection = typeof input.collection === "string" ? input.collection : "";
516
+ const id = typeof input.id === "string" || typeof input.id === "number" ? input.id : null;
517
+ if (!sources.includes(collection) || id === null)
518
+ return json(404, "This document can\u2019t be shared");
519
+ if (await cms.roles.allows(user, { collection: slug }, "create") === false)
520
+ return json(403, "You may not create social posts");
521
+ const doc = await cms.findById(collection, id, {
522
+ depth: 0,
523
+ draft: true,
524
+ user,
525
+ overrideAccess: false
526
+ });
527
+ if (!doc) return json(404, "No such document");
528
+ const values = options.share ? await options.share({ doc, collection, cms }) : defaults(
529
+ cms.config.collections.find((c) => c.slug === collection),
530
+ doc
531
+ );
532
+ const link = values.link ?? options.url?.({ doc, collection }) ?? null;
533
+ const connections = [];
534
+ for (const channel of channels)
535
+ for (const conn of await cms.integrations.all(channel.integration.id))
536
+ connections.push(`${channel.integration.id}:${conn.name}`);
537
+ const title = String(values.title ?? "").trim() || `${collection} ${id}`;
538
+ const created = await cms.create(
539
+ slug,
540
+ {
541
+ title,
542
+ text: String(values.text ?? "").trim() || title,
543
+ link,
544
+ image: values.image ?? null,
545
+ source: sources.length === 1 ? id : { relationTo: collection, value: id },
546
+ channels: connections.map((connection) => ({ connection })),
547
+ delivery: { postAt: null, channels: {} }
548
+ },
549
+ { user, overrideAccess: false }
550
+ );
551
+ return { id: created.id, path: `/collections/${slug}/${String(created.id)}` };
552
+ }
553
+ };
554
+ const job = {
555
+ name: "social:send",
556
+ run: async ({ cms, now }) => {
557
+ const due = await cms.find(slug, {
558
+ where: { nextAt: { lte: now.toISOString() } },
559
+ limit: 20,
560
+ depth: 0,
561
+ sort: "nextAt"
562
+ });
563
+ for (const doc of due.docs) await sendDue(cms, doc, now);
564
+ }
565
+ };
566
+ const withShare = (c) => sources.includes(c.slug) ? {
567
+ ...c,
568
+ admin: {
569
+ ...c.admin,
570
+ sidebar: [...c.admin?.sidebar ?? [], { tag: "ecms-social-share" }]
571
+ }
572
+ } : c;
573
+ const integrations = channels.map((c) => c.integration);
574
+ return {
575
+ ...config,
576
+ collections: [...(config.collections ?? []).map(withShare), posts],
577
+ integrations: [...config.integrations ?? [], ...integrations],
578
+ endpoints: [...config.endpoints ?? [], channelsEndpoint, actionEndpoint, shareEndpoint],
579
+ jobs: [...config.jobs ?? [], job],
580
+ events: [.../* @__PURE__ */ new Set([...config.events ?? [], "social.posted", "social.failed"])],
581
+ admin: {
582
+ ...config.admin,
583
+ modules: [.../* @__PURE__ */ new Set([...config.admin?.modules ?? [], "@easy-cms/plugin-social/admin"])]
584
+ }
585
+ };
586
+ }, INFO);
587
+ }
588
+ function defaults(collection, doc) {
589
+ const fields = collection?.fields ?? [];
590
+ const titleField = collection?.useAsTitle;
591
+ const first = (type) => {
592
+ const field = fields.find(
593
+ (f) => "name" in f && f.type === type && doc[f.name] != null && doc[f.name] !== ""
594
+ );
595
+ return field && "name" in field ? doc[field.name] : null;
596
+ };
597
+ const image = first("upload");
598
+ return {
599
+ title: titleField && typeof doc[titleField] === "string" ? doc[titleField] : null,
600
+ text: first("textarea") ?? null,
601
+ image: image && typeof image === "object" ? image.id : image
602
+ };
603
+ }
604
+ export {
605
+ ChannelError,
606
+ socialPlugin,
607
+ webhook
608
+ };
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@easy-cms/plugin-social",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.35.1",
4
+ "description": "Social posts for Easy CMS: write a post once and send it to several channels (webhooks to Make, n8n or Zapier first), with schedules, retries and a status per channel",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./admin": "./dist/admin.js",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "peerDependencies": {
20
+ "@easy-cms/core": "^1.35.1"
21
+ },
22
+ "devDependencies": {
23
+ "happy-dom": "^21.0.4",
24
+ "@easy-cms/core": "^1.35.1",
25
+ "@easy-cms/db-sqlite": "^1.35.1"
26
+ },
27
+ "engines": {
28
+ "node": ">=22.12"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/maritonx/easy-cms.git",
36
+ "directory": "packages/plugin-social"
37
+ },
38
+ "keywords": [
39
+ "easy-cms",
40
+ "easy-cms-plugin",
41
+ "social",
42
+ "webhook",
43
+ "make",
44
+ "n8n"
45
+ ],
46
+ "scripts": {
47
+ "build": "tsup",
48
+ "typecheck": "tsc --noEmit",
49
+ "test": "vitest run"
50
+ }
6
51
  }