@commmerce/app-bridge 1.15.0 → 1.17.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 +10 -1
- package/dist/app-bridge.js +1 -1
- package/dist/client.d.ts +14 -1
- package/dist/client.js +5 -0
- package/dist/host.d.ts +9 -0
- package/dist/host.js +13 -1
- package/dist/protocol.d.ts +31 -0
- package/dist/reference-host.d.ts +8 -1
- package/dist/reference-host.js +13 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @commmerce/app-bridge
|
|
2
2
|
|
|
3
3
|
Connects an app embedded in the Commmerce admin (in an iframe) to the admin around it: admin-level toasts and
|
|
4
|
-
modals, the save bar, a loading bar, the resource picker, the admin's address, and session tokens for your backend.
|
|
4
|
+
modals, the save bar, a loading bar, the resource picker, the admin's address, brand and recent colours, and session tokens for your backend.
|
|
5
5
|
|
|
6
6
|
Docs: https://commmerce.com/commmerceui/#apps--app-bridge
|
|
7
7
|
|
|
@@ -28,6 +28,9 @@ app.on('saveBar.save', save); app.on('saveBar.discard', discard);
|
|
|
28
28
|
const products = await app.resourcePicker({ type: 'product', multiple: true }); // [{ id, title }] or null
|
|
29
29
|
await app.loading.start(); /* … */ await app.loading.stop();
|
|
30
30
|
app.autoResize(); // the admin sizes your frame to your page
|
|
31
|
+
const brand = await app.colors.brandColors(); // [{ value: '#2e6faf', name: 'Primary' }] from the brand settings
|
|
32
|
+
await app.colors.addRecentColor('#2e6faf'); // recents per staff member, newest first, max 16
|
|
33
|
+
// app.colors has the shape of ColorSource in @commmerce/ui: pass it as cm-color-picker's `source`.
|
|
31
34
|
|
|
32
35
|
const token = await app.getSessionToken();
|
|
33
36
|
await fetch('/api/reviews', { headers: { Authorization: `Bearer ${token}` } });
|
|
@@ -69,6 +72,12 @@ Only HS256 is accepted (`none` and every other algorithm are refused). Uses Web
|
|
|
69
72
|
a handler runs; a missing handler answers `not-supported`. `createReferenceHost(...)` is a reference
|
|
70
73
|
implementation built from Commmerce UI components (`cm-modal`, `cm-save-bar`, …).
|
|
71
74
|
|
|
75
|
+
Colours (added in 1.17.0, still protocol v1): `colors.brand` → `[{ value, name? }]`, `colors.recent` → `string[]`
|
|
76
|
+
(newest first) and `colors.addRecent` `{ color }` → the new list. Host handlers `brandColors`, `recentColors` and
|
|
77
|
+
`addRecentColor(color)`; `color` is checked to be 1–200 characters, not to be a valid CSS colour, so treat it as
|
|
78
|
+
text. The reference host takes `brandColors` (default `[]`) and keeps recents in memory for that host only.
|
|
79
|
+
Admins older than 1.17.0 answer `unknown-type`.
|
|
80
|
+
|
|
72
81
|
## Protocol
|
|
73
82
|
|
|
74
83
|
Plain objects over `postMessage`, each with `protocol: 'commmerce-app-bridge'` and `version: 1`:
|
package/dist/app-bridge.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var H="commmerce-app-bridge",O=1,b=class extends Error{constructor(t,r){super(r),this.name="AppBridgeError",this.code=t}};function B(e){if(!e||typeof e!="object")return!1;let t=e;return t.protocol===H&&typeof t.version=="number"&&(t.kind==="request"||t.kind==="response"||t.kind==="event")}function C(e,t){if(!e||e==="*"||e==="null")throw new TypeError(`App Bridge: ${t} must be an exact origin such as https://app.example.com, not "${e}"`);if(String(e).includes("*"))throw new TypeError(`App Bridge: ${t} must be an exact origin such as https://app.example.com, not the pattern "${e}"`);let r=new URL(e).origin;if(r==="null")throw new TypeError(`App Bridge: ${t} "${e}" has no origin`);return r}var W=/^(?!-)[a-z0-9-]{1,63}(?<!-)$/,Z={"https:":"443","http:":"80"};function x(e){return typeof e=="string"&&e.includes("*")}function R(e,t="origin pattern"){let r=u=>new TypeError(`App Bridge: ${t} "${e}" is not a valid origin pattern: ${u}. Use an exact origin such as https://admin.example.com, or a pattern such as https://*.commmerce.com`),n=/^(https?):\/\/\*\.([^:/?#]*)(?::(\d{1,5}))?$/i.exec(String(e));if(!n)throw r("it must be https://*.domain or http://*.domain, with an optional :port and nothing else");let a=`${n[1].toLowerCase()}:`,i=n[2].toLowerCase(),d=i.split(".");if(i.length>253||!d.every(u=>W.test(u)))throw r('the part after "*." must be a domain name (letters, digits, hyphens and dots)');if(d.length<2&&i!=="localhost")throw r('the domain after "*." needs at least one dot, e.g. *.commmerce.com');if(/^(\d+|0x[0-9a-f]*)$/.test(d[d.length-1]))throw r("IP addresses cannot have a wildcard");let m="";if(n[3]!==void 0){let u=Number(n[3]);if(u<1||u>65535)throw r("the port must be 1 to 65535");m=String(u)===Z[a]?"":String(u)}return{scheme:a,domain:i,port:m,source:String(e)}}function N(e,t){let r=typeof e=="string"?R(e):e;if(typeof t!="string"||!t)return!1;let n;try{n=new URL(t)}catch{return!1}if(n.origin==="null"||n.origin!==t.toLowerCase()||n.protocol!==r.scheme||n.port!==r.port)return!1;let a=`.${r.domain}`;if(!n.hostname.endsWith(a))return!1;let i=n.hostname.slice(0,-a.length);return i.length>0&&i.split(".").every(d=>W.test(d))}function F(e,t){return x(e)?N(R(e,"allowed origin"),t):typeof t=="string"&&t===e}var L=new TextEncoder,_=new TextDecoder;function j(e){let t="";return e.forEach(r=>{t+=String.fromCharCode(r)}),btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function I(e){if(!/^[A-Za-z0-9_-]*$/.test(e))throw new y("malformed","Token is not base64url");let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,r=>r.charCodeAt(0))}var D=(e,t)=>crypto.subtle.importKey("raw",L.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t]),y=class extends Error{constructor(t,r){super(r),this.name="SessionTokenError",this.code=t}};async function G(e,t){if(!t)throw new TypeError("signSessionToken: secret is required");let r=Math.floor(Date.now()/1e3),n={iat:r,nbf:r,exp:r+60,jti:crypto.randomUUID(),...e},a=j(L.encode(JSON.stringify({alg:"HS256",typ:"JWT"}))),i=j(L.encode(JSON.stringify(n))),d=await crypto.subtle.sign("HMAC",await D(t,"sign"),L.encode(`${a}.${i}`));return`${a}.${i}.${j(new Uint8Array(d))}`}function $(e){let t=String(e).split(".");if(t.length!==3)throw new y("malformed","Token must have three parts");try{return JSON.parse(_.decode(I(t[1])))}catch(r){throw r instanceof y?r:new y("malformed","Token claims are not JSON")}}async function Q(e,t,r){if(!t)throw new TypeError("verifySessionToken: secret is required");if(!r?.audience)throw new TypeError("verifySessionToken: options.audience (your API key) is required");r.issuer&&x(r.issuer)&&R(r.issuer,"verifySessionToken: options.issuer");let n=String(e).split(".");if(n.length!==3)throw new y("malformed","Token must have three parts");let a;try{a=JSON.parse(_.decode(I(n[0])))}catch{throw new y("malformed","Token header is not JSON")}if(a.alg!=="HS256")throw new y("algorithm",`Algorithm ${a.alg} is not allowed`);if(!await crypto.subtle.verify("HMAC",await D(t,"verify"),I(n[2]),L.encode(`${n[0]}.${n[1]}`)))throw new y("signature","Signature does not match");let d=$(e),m=r.now??Math.floor(Date.now()/1e3),u=r.clockTolerance??5;if(typeof d.exp!="number"||m-u>=d.exp)throw new y("expired","Token has expired");if(typeof d.nbf=="number"&&m+u<d.nbf)throw new y("not-yet-valid","Token is not valid yet");if(d.aud!==r.audience)throw new y("audience","Token is for another app");if(r.issuer&&!F(r.issuer,d.iss))throw new y("issuer","Token was issued by someone else");return d}function X(){let e=document.body;if(!e)return 0;let t=getComputedStyle(e),r=e.getBoundingClientRect().top+parseFloat(t.paddingTop)+parseFloat(t.borderTopWidth);for(let n of e.children){let a=getComputedStyle(n);a.position==="fixed"||a.display==="none"||n.localName==="script"||(r=Math.max(r,n.getBoundingClientRect().bottom+parseFloat(a.marginBottom)))}return Math.ceil(r+scrollY+parseFloat(t.paddingBottom)+parseFloat(t.borderBottomWidth)+parseFloat(t.marginBottom))}var J="commmerce-app-bridge:host-origin";function ee(e=te()){let{ancestorOrigins:t,referrer:r,self:n,remembered:a,sameOriginParent:i}=e;if(t)return t.length&&t[0]!=="null"?t[0]:void 0;if(i)return n;let d;try{d=r?new URL(r).origin:void 0}catch{d=void 0}if(!(!d||d==="null"))return d===n?a||void 0:d}function te(){let e=null;try{e=sessionStorage.getItem(J)}catch{}let t=!1;try{t=window.parent!==window&&window.parent.location.origin===location.origin}catch{}return{ancestorOrigins:location.ancestorOrigins,referrer:document.referrer,self:location.origin,remembered:e,sameOriginParent:t}}function re(e,t){if(!x(e.hostOrigin))return C(e.hostOrigin,"hostOrigin");let r=R(e.hostOrigin,"hostOrigin"),n=e.exactHostOrigin;if(!n){if(t!==window.parent)throw new Error("App Bridge: with a pattern hostOrigin and a custom target, pass exactHostOrigin");n=ee()}if(!n)throw new Error(`App Bridge: hostOrigin is the pattern ${r.source}, but the admin's origin can't be found (no location.ancestorOrigins and no document.referrer, or the admin hides them). Is the page inside the admin?`);if(!N(r,n))throw new Error(`App Bridge: the admin's origin ${n} does not match hostOrigin ${r.source}. Messages to it are refused.`);let a=new URL(n).origin;if(!e.exactHostOrigin)try{sessionStorage.setItem(J,a)}catch{}return a}var ne=["modal.open","resourcePicker.open"],oe=0;function se(e){x(e.hostOrigin)?R(e.hostOrigin,"hostOrigin"):C(e.hostOrigin,"hostOrigin");let t=e.target??window.parent;if(!t||t===window)throw new Error("App Bridge: the app is not inside the admin (no parent window)");let r=re(e,t),n=e.timeout??1e4,a=new Map,i=new Map,d=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,m=!1,u=null,T=new Set,v,f=s=>{if(!B(s.data))return e.onReject?.("not an App Bridge message",s);if(s.source!==t)return e.onReject?.("not from the admin window",s);if(s.origin!==r)return e.onReject?.(`origin ${s.origin} is not ${r}`,s);let l=s.data;if(l.kind==="response"){let g=a.get(l.id);if(!g)return;a.delete(l.id),clearTimeout(g.timer);let w=l;w.ok?g.resolve(w.result):g.reject(new b(w.error?.code??"failed",w.error?.message??"The admin refused the request"))}else l.kind==="event"&&i.get(l.type)?.forEach(g=>g(l.payload))};window.addEventListener("message",f);function o(s,l){if(m)return Promise.reject(new b("failed","App Bridge was destroyed"));let g=`${d}-${++oe}`;return new Promise((w,h)=>{let E={resolve:w,reject:h};ne.includes(s)||(E.timer=setTimeout(()=>{a.delete(g),h(new b("timeout",`The admin did not answer "${s}" within ${n} ms`))},n)),a.set(g,E),t.postMessage({protocol:H,version:1,kind:"request",id:g,type:s,payload:l},r)})}let c=o("ready",e.apiKey?{apiKey:e.apiKey}:{});c.catch(()=>{});let p=(s,l)=>c.then(()=>o(s,l));return{hostOrigin:r,ready:c,toast:{show:(s,l={})=>p("toast.show",{message:s,...l})},modal:{open:s=>p("modal.open",s)},navigate:(s,l={})=>p("navigate",{path:s,...l}),saveBar:{show:(s={})=>p("saveBar.show",s),hide:()=>p("saveBar.hide",{})},resourcePicker:s=>p("resourcePicker.open",s),loading:{start:()=>p("loading.start",{}),stop:()=>p("loading.stop",{})},async getSessionToken(){if(u&&u.exp*1e3-Date.now()>1e4)return u.value;let s=await p("sessionToken.get",{}),l=Number($(s).exp);return u=Number.isFinite(l)?{value:s,exp:l}:null,s},autoResize(){if(v)return v;let s=-1,l=0,g=()=>{l=0;let S=X();S===s||m||(s=S,p("frame.resize",{height:S}).catch(()=>{}))},w=()=>{l||(l=requestAnimationFrame(g))},h=new ResizeObserver(w),E=()=>{h.disconnect(),h.observe(document.body);for(let S of document.body.children)h.observe(S);w()},K=new MutationObserver(E);K.observe(document.body,{childList:!0}),E();let M=()=>{h.disconnect(),K.disconnect(),cancelAnimationFrame(l),T.delete(M),v===M&&(v=void 0)};return T.add(M),v=M,M},on(s,l){let g=i.get(s)??new Set;return i.set(s,g),g.add(l),()=>g.delete(l)},destroy(){m=!0,[...T].forEach(s=>s()),window.removeEventListener("message",f);for(let[,s]of a)clearTimeout(s.timer),s.reject(new b("failed","App Bridge was destroyed"));a.clear(),i.clear()}}}var P=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t,q=(e,t)=>e===void 0||P(e,t),z=e=>e===void 0||typeof e=="boolean";function A(e){if(typeof e!="string"||e.length===0||e.length>2e3||!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||/[\u0000-\u001f\u007f]/.test(e))return!1;try{return new URL(e,"https://app-bridge.invalid").origin==="https://app-bridge.invalid"}catch{return!1}}function V(e,t){switch(e){case"ready":return q(t.apiKey,200)?null:"apiKey must be a string";case"toast.show":return P(t.message,200)?t.tone!==void 0&&!["default","success","critical"].includes(t.tone)?"tone must be default, success or critical":t.duration!==void 0&&!(typeof t.duration=="number"&&t.duration>=2e3&&t.duration<=1e4)?"duration must be 2000\u201310000 ms":null:"message must be 1\u2013200 characters";case"modal.open":{if(!P(t.title,100)||!P(t.message,1e3))return"title (1\u2013100) and message (1\u20131000 characters) are required";let r=t.primaryAction,n=t.secondaryAction;return r!==void 0&&!(r&&P(r.label,40)&&z(r.destructive))?"primaryAction needs a label (1\u201340 characters)":n!==void 0&&!(n&&P(n.label,40))?"secondaryAction needs a label (1\u201340 characters)":null}case"navigate":return A(t.path)?z(t.replace)?null:"replace must be a boolean":"path must be a path inside the app, starting with a single / (no \\, no control characters)";case"frame.resize":return typeof t.height=="number"&&Number.isFinite(t.height)&&t.height>=0&&t.height<=1e5?null:"height must be a number of pixels, 0\u2013100000";case"saveBar.show":return q(t.message,100)&&q(t.saveLabel,40)&&q(t.discardLabel,40)&&z(t.loading)?null:"message (\u2264100), saveLabel and discardLabel (\u226440) must be strings; loading a boolean";case"resourcePicker.open":return["product","customer","collection"].includes(t.type)?z(t.multiple)?null:"multiple must be a boolean":"type must be product, customer or collection";default:return null}}function U(e){let t=C(e.appOrigin,"appOrigin"),{iframe:r,handlers:n}=e,a=!1,i=!1,d=f=>{i||r.contentWindow?.postMessage({protocol:H,version:1,...f},t)},m=(f,o,c)=>d({kind:"response",id:f,ok:!1,error:{code:o,message:c}}),u=(f,o)=>{let c=p=>{if(!p)throw new b("not-supported",`This admin does not support "${f}"`)};switch(f){case"ready":if(e.apiKey&&o.apiKey!==e.apiKey)throw new b("failed","API key does not match this app");a=!0;{let p={version:1,theme:e.info?.theme??"light",locale:e.info?.locale??"en-IN"},s=e.currentPath?e.currentPath():e.info?.path;return s!==void 0&&(p.path=A(s)?s:"/"),p}case"toast.show":return c(n.toast),n.toast(o);case"modal.open":return c(n.modal),n.modal(o);case"navigate":return c(n.navigate),n.navigate(o);case"saveBar.show":return c(n.saveBar),n.saveBar(o);case"saveBar.hide":return c(n.saveBar),n.saveBar(null);case"resourcePicker.open":return c(n.resourcePicker),n.resourcePicker(o);case"loading.start":return c(n.loading),n.loading(!0);case"loading.stop":return c(n.loading),n.loading(!1);case"sessionToken.get":return c(n.sessionToken),n.sessionToken();case"frame.resize":if(n.resize)return n.resize(o);r.style.blockSize=`${Math.ceil(o.height)}px`;return}},T=["ready","toast.show","modal.open","navigate","saveBar.show","saveBar.hide","resourcePicker.open","loading.start","loading.stop","sessionToken.get","frame.resize"],v=async f=>{if(!B(f.data))return e.onReject?.("not an App Bridge message",f);if(!r.contentWindow||f.source!==r.contentWindow)return e.onReject?.("not from the app frame",f);if(f.origin!==t)return e.onReject?.(`origin ${f.origin} is not ${t}`,f);let o=f.data;if(o.kind!=="request"||typeof o.id!="string")return e.onReject?.("not a request",f);let{id:c,type:p}=o;if(o.version!==1)return m(c,"unsupported-version",`This admin speaks App Bridge version ${1}`);if(!T.includes(p))return m(c,"unknown-type",`Unknown request "${String(p)}"`);if(p!=="ready"&&!a)return m(c,"not-ready",'Send "ready" first');let s=o.payload&&typeof o.payload=="object"?o.payload:{},l=V(p,s);if(l)return m(c,"invalid-payload",l);try{let g=await u(p,s);d({kind:"response",id:c,ok:!0,...g===void 0?{}:{result:g}})}catch(g){g instanceof b?m(c,g.code,g.message):m(c,"failed",g instanceof Error?g.message:"The admin could not complete the request")}};return window.addEventListener("message",v),{send(f,o){a&&d({kind:"event",type:f,payload:o})},get connected(){return a},destroy(){i=!0,a=!1,window.removeEventListener("message",v)}}}var ie={product:"products",customer:"customers",collection:"collections"};function k(e,t={},r){let n=document.createElement(e);for(let[a,i]of Object.entries(t))i!==!1&&n.setAttribute(a,i===!0?"":i);return r!==void 0&&(n.textContent=r),n}function Y(e,t,r,n){return new Promise(a=>{let i=k("cm-modal",{heading:t});i.append(r);let d="close";for(let m of n){let u=k("cm-button",{slot:"footer",variant:m.primary?"primary":"secondary"},m.label);u.addEventListener("click",()=>{d=m.value,i.close()}),i.append(u)}i.addEventListener("cm-closed",()=>{i.remove(),a(d)}),e.append(i),i.show()})}function ae(e){let t=e.root??document.body,r,n=k("cm-toast-region",{"data-app-bridge":"toasts",max:"1"}),a=k("cm-progress-bar",{label:"Loading","label-hidden":!0,size:"small",hidden:!0,"data-app-bridge":"loading"});a.style.cssText="position:fixed;inset-block-start:0;inset-inline:0;z-index:1000";let i=k("cm-save-bar",{"data-app-bridge":"save-bar"});i.addEventListener("cm-save",o=>{o.preventDefault(),r.send("saveBar.save",{})}),i.addEventListener("cm-discard",o=>{o.preventDefault(),r.send("saveBar.discard",{})}),t.append(n,a,i);let d={toast({message:o,tone:c="default",duration:p=5e3}){let s=k("cm-toast",{"data-tone":c});s.message=o,s.tone=c==="critical"?"critical":"default",s.duration=p,n.add(s)},async modal({title:o,message:c,primaryAction:p,secondaryAction:s}){let l=[];return s&&l.push({label:s.label,value:"secondary"}),p&&l.push({label:p.label,value:"primary",primary:!0}),await Y(t,o,k("p",{},c),l)},navigate({path:o,replace:c}){if(e.navigate)return e.navigate(o,!!c);let p=`${location.pathname}${location.search}#${o}`;c?history.replaceState(history.state,"",p):history.pushState(history.state,"",p)},saveBar(o){if(!o){i.open=!1;return}i.message=o.message??"Unsaved changes",o.saveLabel&&(i.saveLabel=o.saveLabel),o.discardLabel&&(i.discardLabel=o.discardLabel),i.loading=!!o.loading,i.open=!0},loading(o){a.hidden=!o}};if(e.resources){let o=e.resources;d.resourcePicker=async({type:c,multiple:p})=>{let s=await o(c),l=k(p?"div":"cm-radio-group",p?{}:{label:`Choose ${c}`});l.style.cssText="display:grid;gap:var(--cm-space-10,10px)";for(let h of s)l.append(k(p?"cm-checkbox":"cm-radio",{label:h.title,value:h.id}));if(await Y(t,`Select ${ie[c]}`,l,[{label:"Cancel",value:"secondary"},{label:"Select",value:"primary",primary:!0}])!=="primary")return null;let w=[...l.querySelectorAll("cm-checkbox, cm-radio")].filter(h=>h.checked).map(h=>h.value);return s.filter(h=>w.includes(h.id))}}e.sessionToken&&(d.sessionToken=e.sessionToken);let m=()=>{let o=location.hash.slice(1);try{o=decodeURI(o)}catch{}return o.startsWith("/")?o:"/"},u="",T=()=>{let o=m();o!==u&&(u=o,r.connected&&r.send("path.change",{path:A(o)?o:"/"}))},v=!e.navigate;if(v){let o=d.navigate;d.navigate=c=>(u=c.path,o(c)),u=m(),addEventListener("popstate",T),addEventListener("hashchange",T)}r=U({...e,...v&&!e.currentPath?{currentPath:m}:{},handlers:d});let f=r.destroy;return Object.assign(Object.create(null),{send:r.send,get connected(){return r.connected},destroy(){f(),removeEventListener("popstate",T),removeEventListener("hashchange",T),n.remove(),a.remove(),i.remove()}})}export{b as AppBridgeError,H as PROTOCOL,O as PROTOCOL_VERSION,y as SessionTokenError,se as createApp,U as createHost,ae as createReferenceHost,$ as decodeClaims,A as isAppPath,B as isMessage,x as isOriginPattern,F as matchesOrigin,N as matchesOriginPattern,C as normalizeOrigin,R as parseOriginPattern,G as signSessionToken,V as validatePayload,Q as verifySessionToken};
|
|
1
|
+
var H="commmerce-app-bridge",x=1,b=class extends Error{constructor(t,n){super(n),this.name="AppBridgeError",this.code=t}};function $(e){if(!e||typeof e!="object")return!1;let t=e;return t.protocol===H&&typeof t.version=="number"&&(t.kind==="request"||t.kind==="response"||t.kind==="event")}function L(e,t){if(!e||e==="*"||e==="null")throw new TypeError(`App Bridge: ${t} must be an exact origin such as https://app.example.com, not "${e}"`);if(String(e).includes("*"))throw new TypeError(`App Bridge: ${t} must be an exact origin such as https://app.example.com, not the pattern "${e}"`);let n=new URL(e).origin;if(n==="null")throw new TypeError(`App Bridge: ${t} "${e}" has no origin`);return n}var W=/^(?!-)[a-z0-9-]{1,63}(?<!-)$/,X={"https:":"443","http:":"80"};function C(e){return typeof e=="string"&&e.includes("*")}function P(e,t="origin pattern"){let n=g=>new TypeError(`App Bridge: ${t} "${e}" is not a valid origin pattern: ${g}. Use an exact origin such as https://admin.example.com, or a pattern such as https://*.commmerce.com`),r=/^(https?):\/\/\*\.([^:/?#]*)(?::(\d{1,5}))?$/i.exec(String(e));if(!r)throw n("it must be https://*.domain or http://*.domain, with an optional :port and nothing else");let a=`${r[1].toLowerCase()}:`,i=r[2].toLowerCase(),c=i.split(".");if(i.length>253||!c.every(g=>W.test(g)))throw n('the part after "*." must be a domain name (letters, digits, hyphens and dots)');if(c.length<2&&i!=="localhost")throw n('the domain after "*." needs at least one dot, e.g. *.commmerce.com');if(/^(\d+|0x[0-9a-f]*)$/.test(c[c.length-1]))throw n("IP addresses cannot have a wildcard");let f="";if(r[3]!==void 0){let g=Number(r[3]);if(g<1||g>65535)throw n("the port must be 1 to 65535");f=String(g)===X[a]?"":String(g)}return{scheme:a,domain:i,port:f,source:String(e)}}function j(e,t){let n=typeof e=="string"?P(e):e;if(typeof t!="string"||!t)return!1;let r;try{r=new URL(t)}catch{return!1}if(r.origin==="null"||r.origin!==t.toLowerCase()||r.protocol!==n.scheme||r.port!==n.port)return!1;let a=`.${n.domain}`;if(!r.hostname.endsWith(a))return!1;let i=r.hostname.slice(0,-a.length);return i.length>0&&i.split(".").every(c=>W.test(c))}function F(e,t){return C(e)?j(P(e,"allowed origin"),t):typeof t=="string"&&t===e}var B=new TextEncoder,_=new TextDecoder;function I(e){let t="";return e.forEach(n=>{t+=String.fromCharCode(n)}),btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function U(e){if(!/^[A-Za-z0-9_-]*$/.test(e))throw new y("malformed","Token is not base64url");let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,n=>n.charCodeAt(0))}var D=(e,t)=>crypto.subtle.importKey("raw",B.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t]),y=class extends Error{constructor(t,n){super(n),this.name="SessionTokenError",this.code=t}};async function Z(e,t){if(!t)throw new TypeError("signSessionToken: secret is required");let n=Math.floor(Date.now()/1e3),r={iat:n,nbf:n,exp:n+60,jti:crypto.randomUUID(),...e},a=I(B.encode(JSON.stringify({alg:"HS256",typ:"JWT"}))),i=I(B.encode(JSON.stringify(r))),c=await crypto.subtle.sign("HMAC",await D(t,"sign"),B.encode(`${a}.${i}`));return`${a}.${i}.${I(new Uint8Array(c))}`}function q(e){let t=String(e).split(".");if(t.length!==3)throw new y("malformed","Token must have three parts");try{return JSON.parse(_.decode(U(t[1])))}catch(n){throw n instanceof y?n:new y("malformed","Token claims are not JSON")}}async function G(e,t,n){if(!t)throw new TypeError("verifySessionToken: secret is required");if(!n?.audience)throw new TypeError("verifySessionToken: options.audience (your API key) is required");n.issuer&&C(n.issuer)&&P(n.issuer,"verifySessionToken: options.issuer");let r=String(e).split(".");if(r.length!==3)throw new y("malformed","Token must have three parts");let a;try{a=JSON.parse(_.decode(U(r[0])))}catch{throw new y("malformed","Token header is not JSON")}if(a.alg!=="HS256")throw new y("algorithm",`Algorithm ${a.alg} is not allowed`);if(!await crypto.subtle.verify("HMAC",await D(t,"verify"),U(r[2]),B.encode(`${r[0]}.${r[1]}`)))throw new y("signature","Signature does not match");let c=q(e),f=n.now??Math.floor(Date.now()/1e3),g=n.clockTolerance??5;if(typeof c.exp!="number"||f-g>=c.exp)throw new y("expired","Token has expired");if(typeof c.nbf=="number"&&f+g<c.nbf)throw new y("not-yet-valid","Token is not valid yet");if(c.aud!==n.audience)throw new y("audience","Token is for another app");if(n.issuer&&!F(n.issuer,c.iss))throw new y("issuer","Token was issued by someone else");return c}function Q(){let e=document.body;if(!e)return 0;let t=getComputedStyle(e),n=e.getBoundingClientRect().top+parseFloat(t.paddingTop)+parseFloat(t.borderTopWidth);for(let r of e.children){let a=getComputedStyle(r);a.position==="fixed"||a.display==="none"||r.localName==="script"||(n=Math.max(n,r.getBoundingClientRect().bottom+parseFloat(a.marginBottom)))}return Math.ceil(n+scrollY+parseFloat(t.paddingBottom)+parseFloat(t.borderBottomWidth)+parseFloat(t.marginBottom))}var J="commmerce-app-bridge:host-origin";function ee(e=te()){let{ancestorOrigins:t,referrer:n,self:r,remembered:a,sameOriginParent:i}=e;if(t)return t.length&&t[0]!=="null"?t[0]:void 0;if(i)return r;let c;try{c=n?new URL(n).origin:void 0}catch{c=void 0}if(!(!c||c==="null"))return c===r?a||void 0:c}function te(){let e=null;try{e=sessionStorage.getItem(J)}catch{}let t=!1;try{t=window.parent!==window&&window.parent.location.origin===location.origin}catch{}return{ancestorOrigins:location.ancestorOrigins,referrer:document.referrer,self:location.origin,remembered:e,sameOriginParent:t}}function re(e,t){if(!C(e.hostOrigin))return L(e.hostOrigin,"hostOrigin");let n=P(e.hostOrigin,"hostOrigin"),r=e.exactHostOrigin;if(!r){if(t!==window.parent)throw new Error("App Bridge: with a pattern hostOrigin and a custom target, pass exactHostOrigin");r=ee()}if(!r)throw new Error(`App Bridge: hostOrigin is the pattern ${n.source}, but the admin's origin can't be found (no location.ancestorOrigins and no document.referrer, or the admin hides them). Is the page inside the admin?`);if(!j(n,r))throw new Error(`App Bridge: the admin's origin ${r} does not match hostOrigin ${n.source}. Messages to it are refused.`);let a=new URL(r).origin;if(!e.exactHostOrigin)try{sessionStorage.setItem(J,a)}catch{}return a}var ne=["modal.open","resourcePicker.open"],oe=0;function se(e){C(e.hostOrigin)?P(e.hostOrigin,"hostOrigin"):L(e.hostOrigin,"hostOrigin");let t=e.target??window.parent;if(!t||t===window)throw new Error("App Bridge: the app is not inside the admin (no parent window)");let n=re(e,t),r=e.timeout??1e4,a=new Map,i=new Map,c=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,f=!1,g=null,T=new Set,v,m=s=>{if(!$(s.data))return e.onReject?.("not an App Bridge message",s);if(s.source!==t)return e.onReject?.("not from the admin window",s);if(s.origin!==n)return e.onReject?.(`origin ${s.origin} is not ${n}`,s);let d=s.data;if(d.kind==="response"){let l=a.get(d.id);if(!l)return;a.delete(d.id),clearTimeout(l.timer);let h=d;h.ok?l.resolve(h.result):l.reject(new b(h.error?.code??"failed",h.error?.message??"The admin refused the request"))}else d.kind==="event"&&i.get(d.type)?.forEach(l=>l(d.payload))};window.addEventListener("message",m);function u(s,d){if(f)return Promise.reject(new b("failed","App Bridge was destroyed"));let l=`${c}-${++oe}`;return new Promise((h,k)=>{let O={resolve:h,reject:k};ne.includes(s)||(O.timer=setTimeout(()=>{a.delete(l),k(new b("timeout",`The admin did not answer "${s}" within ${r} ms`))},r)),a.set(l,O),t.postMessage({protocol:H,version:1,kind:"request",id:l,type:s,payload:d},n)})}let p=u("ready",e.apiKey?{apiKey:e.apiKey}:{});p.catch(()=>{});let o=(s,d)=>p.then(()=>u(s,d));return{hostOrigin:n,ready:p,toast:{show:(s,d={})=>o("toast.show",{message:s,...d})},modal:{open:s=>o("modal.open",s)},navigate:(s,d={})=>o("navigate",{path:s,...d}),saveBar:{show:(s={})=>o("saveBar.show",s),hide:()=>o("saveBar.hide",{})},resourcePicker:s=>o("resourcePicker.open",s),loading:{start:()=>o("loading.start",{}),stop:()=>o("loading.stop",{})},colors:{brandColors:()=>o("colors.brand",{}),recentColors:()=>o("colors.recent",{}),addRecentColor:s=>o("colors.addRecent",{color:s})},async getSessionToken(){if(g&&g.exp*1e3-Date.now()>1e4)return g.value;let s=await o("sessionToken.get",{}),d=Number(q(s).exp);return g=Number.isFinite(d)?{value:s,exp:d}:null,s},autoResize(){if(v)return v;let s=-1,d=0,l=()=>{d=0;let S=Q();S===s||f||(s=S,o("frame.resize",{height:S}).catch(()=>{}))},h=()=>{d||(d=requestAnimationFrame(l))},k=new ResizeObserver(h),O=()=>{k.disconnect(),k.observe(document.body);for(let S of document.body.children)k.observe(S);h()},w=new MutationObserver(O);w.observe(document.body,{childList:!0}),O();let M=()=>{k.disconnect(),w.disconnect(),cancelAnimationFrame(d),T.delete(M),v===M&&(v=void 0)};return T.add(M),v=M,M},on(s,d){let l=i.get(s)??new Set;return i.set(s,l),l.add(d),()=>l.delete(d)},destroy(){f=!0,[...T].forEach(s=>s()),window.removeEventListener("message",m);for(let[,s]of a)clearTimeout(s.timer),s.reject(new b("failed","App Bridge was destroyed"));a.clear(),i.clear()}}}var E=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t,z=(e,t)=>e===void 0||E(e,t),N=e=>e===void 0||typeof e=="boolean";function A(e){if(typeof e!="string"||e.length===0||e.length>2e3||!e.startsWith("/")||e.startsWith("//")||e.includes("\\")||/[\u0000-\u001f\u007f]/.test(e))return!1;try{return new URL(e,"https://app-bridge.invalid").origin==="https://app-bridge.invalid"}catch{return!1}}function V(e,t){switch(e){case"ready":return z(t.apiKey,200)?null:"apiKey must be a string";case"toast.show":return E(t.message,200)?t.tone!==void 0&&!["default","success","critical"].includes(t.tone)?"tone must be default, success or critical":t.duration!==void 0&&!(typeof t.duration=="number"&&t.duration>=2e3&&t.duration<=1e4)?"duration must be 2000\u201310000 ms":null:"message must be 1\u2013200 characters";case"modal.open":{if(!E(t.title,100)||!E(t.message,1e3))return"title (1\u2013100) and message (1\u20131000 characters) are required";let n=t.primaryAction,r=t.secondaryAction;return n!==void 0&&!(n&&E(n.label,40)&&N(n.destructive))?"primaryAction needs a label (1\u201340 characters)":r!==void 0&&!(r&&E(r.label,40))?"secondaryAction needs a label (1\u201340 characters)":null}case"navigate":return A(t.path)?N(t.replace)?null:"replace must be a boolean":"path must be a path inside the app, starting with a single / (no \\, no control characters)";case"frame.resize":return typeof t.height=="number"&&Number.isFinite(t.height)&&t.height>=0&&t.height<=1e5?null:"height must be a number of pixels, 0\u2013100000";case"colors.addRecent":return E(t.color,200)?null:"color must be 1\u2013200 characters";case"saveBar.show":return z(t.message,100)&&z(t.saveLabel,40)&&z(t.discardLabel,40)&&N(t.loading)?null:"message (\u2264100), saveLabel and discardLabel (\u226440) must be strings; loading a boolean";case"resourcePicker.open":return["product","customer","collection"].includes(t.type)?N(t.multiple)?null:"multiple must be a boolean":"type must be product, customer or collection";default:return null}}function K(e){let t=L(e.appOrigin,"appOrigin"),{iframe:n,handlers:r}=e,a=!1,i=!1,c=m=>{i||n.contentWindow?.postMessage({protocol:H,version:1,...m},t)},f=(m,u,p)=>c({kind:"response",id:m,ok:!1,error:{code:u,message:p}}),g=(m,u)=>{let p=o=>{if(!o)throw new b("not-supported",`This admin does not support "${m}"`)};switch(m){case"ready":if(e.apiKey&&u.apiKey!==e.apiKey)throw new b("failed","API key does not match this app");a=!0;{let o={version:1,theme:e.info?.theme??"light",locale:e.info?.locale??"en-IN"},s=e.currentPath?e.currentPath():e.info?.path;return s!==void 0&&(o.path=A(s)?s:"/"),o}case"toast.show":return p(r.toast),r.toast(u);case"modal.open":return p(r.modal),r.modal(u);case"navigate":return p(r.navigate),r.navigate(u);case"saveBar.show":return p(r.saveBar),r.saveBar(u);case"saveBar.hide":return p(r.saveBar),r.saveBar(null);case"resourcePicker.open":return p(r.resourcePicker),r.resourcePicker(u);case"loading.start":return p(r.loading),r.loading(!0);case"loading.stop":return p(r.loading),r.loading(!1);case"sessionToken.get":return p(r.sessionToken),r.sessionToken();case"frame.resize":if(r.resize)return r.resize(u);n.style.blockSize=`${Math.ceil(u.height)}px`;return;case"colors.brand":return p(r.brandColors),r.brandColors();case"colors.recent":return p(r.recentColors),r.recentColors();case"colors.addRecent":return p(r.addRecentColor),r.addRecentColor(u.color)}},T=["ready","toast.show","modal.open","navigate","saveBar.show","saveBar.hide","resourcePicker.open","loading.start","loading.stop","sessionToken.get","frame.resize","colors.brand","colors.recent","colors.addRecent"],v=async m=>{if(!$(m.data))return e.onReject?.("not an App Bridge message",m);if(!n.contentWindow||m.source!==n.contentWindow)return e.onReject?.("not from the app frame",m);if(m.origin!==t)return e.onReject?.(`origin ${m.origin} is not ${t}`,m);let u=m.data;if(u.kind!=="request"||typeof u.id!="string")return e.onReject?.("not a request",m);let{id:p,type:o}=u;if(u.version!==1)return f(p,"unsupported-version",`This admin speaks App Bridge version ${1}`);if(!T.includes(o))return f(p,"unknown-type",`Unknown request "${String(o)}"`);if(o!=="ready"&&!a)return f(p,"not-ready",'Send "ready" first');let s=u.payload&&typeof u.payload=="object"?u.payload:{},d=V(o,s);if(d)return f(p,"invalid-payload",d);try{let l=await g(o,s);c({kind:"response",id:p,ok:!0,...l===void 0?{}:{result:l}})}catch(l){l instanceof b?f(p,l.code,l.message):f(p,"failed",l instanceof Error?l.message:"The admin could not complete the request")}};return window.addEventListener("message",v),{send(m,u){a&&c({kind:"event",type:m,payload:u})},get connected(){return a},destroy(){i=!0,a=!1,window.removeEventListener("message",v)}}}var ie=16,ae={product:"products",customer:"customers",collection:"collections"};function R(e,t={},n){let r=document.createElement(e);for(let[a,i]of Object.entries(t))i!==!1&&r.setAttribute(a,i===!0?"":i);return n!==void 0&&(r.textContent=n),r}function Y(e,t,n,r){return new Promise(a=>{let i=R("cm-modal",{heading:t});i.append(n);let c="close";for(let f of r){let g=R("cm-button",{slot:"footer",variant:f.primary?"primary":"secondary"},f.label);g.addEventListener("click",()=>{c=f.value,i.close()}),i.append(g)}i.addEventListener("cm-closed",()=>{i.remove(),a(c)}),e.append(i),i.show()})}function de(e){let t=e.root??document.body,n,r=R("cm-toast-region",{"data-app-bridge":"toasts",max:"1"}),a=R("cm-progress-bar",{label:"Loading","label-hidden":!0,size:"small",hidden:!0,"data-app-bridge":"loading"});a.style.cssText="position:fixed;inset-block-start:0;inset-inline:0;z-index:1000";let i=R("cm-save-bar",{"data-app-bridge":"save-bar"});i.addEventListener("cm-save",o=>{o.preventDefault(),n.send("saveBar.save",{})}),i.addEventListener("cm-discard",o=>{o.preventDefault(),n.send("saveBar.discard",{})}),t.append(r,a,i);let c={toast({message:o,tone:s="default",duration:d=5e3}){let l=R("cm-toast",{"data-tone":s});l.message=o,l.tone=s==="critical"?"critical":"default",l.duration=d,r.add(l)},async modal({title:o,message:s,primaryAction:d,secondaryAction:l}){let h=[];return l&&h.push({label:l.label,value:"secondary"}),d&&h.push({label:d.label,value:"primary",primary:!0}),await Y(t,o,R("p",{},s),h)},navigate({path:o,replace:s}){if(e.navigate)return e.navigate(o,!!s);let d=`${location.pathname}${location.search}#${o}`;s?history.replaceState(history.state,"",d):history.pushState(history.state,"",d)},saveBar(o){if(!o){i.open=!1;return}i.message=o.message??"Unsaved changes",o.saveLabel&&(i.saveLabel=o.saveLabel),o.discardLabel&&(i.discardLabel=o.discardLabel),i.loading=!!o.loading,i.open=!0},loading(o){a.hidden=!o}};if(e.resources){let o=e.resources;c.resourcePicker=async({type:s,multiple:d})=>{let l=await o(s),h=R(d?"div":"cm-radio-group",d?{}:{label:`Choose ${s}`});h.style.cssText="display:grid;gap:var(--cm-space-10,10px)";for(let w of l)h.append(R(d?"cm-checkbox":"cm-radio",{label:w.title,value:w.id}));if(await Y(t,`Select ${ae[s]}`,h,[{label:"Cancel",value:"secondary"},{label:"Select",value:"primary",primary:!0}])!=="primary")return null;let O=[...h.querySelectorAll("cm-checkbox, cm-radio")].filter(w=>w.checked).map(w=>w.value);return l.filter(w=>O.includes(w.id))}}e.sessionToken&&(c.sessionToken=e.sessionToken);let f=(e.brandColors??[]).map(o=>typeof o=="string"?{value:o}:{...o}),g=[];c.brandColors=()=>f.map(o=>({...o})),c.recentColors=()=>[...g],c.addRecentColor=o=>{let s=o.trim(),d=s.toLowerCase();return g=[s,...g.filter(l=>l.toLowerCase()!==d)].slice(0,ie),[...g]};let T=()=>{let o=location.hash.slice(1);try{o=decodeURI(o)}catch{}return o.startsWith("/")?o:"/"},v="",m=()=>{let o=T();o!==v&&(v=o,n.connected&&n.send("path.change",{path:A(o)?o:"/"}))},u=!e.navigate;if(u){let o=c.navigate;c.navigate=s=>(v=s.path,o(s)),v=T(),addEventListener("popstate",m),addEventListener("hashchange",m)}n=K({...e,...u&&!e.currentPath?{currentPath:T}:{},handlers:c});let p=n.destroy;return Object.assign(Object.create(null),{send:n.send,get connected(){return n.connected},destroy(){p(),removeEventListener("popstate",m),removeEventListener("hashchange",m),r.remove(),a.remove(),i.remove()}})}export{b as AppBridgeError,H as PROTOCOL,x as PROTOCOL_VERSION,y as SessionTokenError,se as createApp,K as createHost,de as createReferenceHost,q as decodeClaims,A as isAppPath,$ as isMessage,C as isOriginPattern,F as matchesOrigin,j as matchesOriginPattern,L as normalizeOrigin,P as parseOriginPattern,Z as signSessionToken,V as validatePayload,G as verifySessionToken};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type EventMap, type EventType, type HostInfo, type ToastOptions, type ModalOptions, type ModalResult, type SaveBarOptions, type ResourcePickerOptions, type PickedResource, type NavigateOptions } from './protocol.js';
|
|
1
|
+
import { type EventMap, type EventType, type HostInfo, type ToastOptions, type ModalOptions, type ModalResult, type SaveBarOptions, type ResourcePickerOptions, type PickedResource, type NavigateOptions, type BrandColor } from './protocol.js';
|
|
2
2
|
export interface AppConfig {
|
|
3
3
|
/**
|
|
4
4
|
* The admin's origin, as given in your app settings. Required. Either:
|
|
@@ -52,6 +52,19 @@ export interface App {
|
|
|
52
52
|
start(): Promise<void>;
|
|
53
53
|
stop(): Promise<void>;
|
|
54
54
|
};
|
|
55
|
+
/**
|
|
56
|
+
* The store's brand colours and the staff member's recent colours, kept by the admin. Pass `app.colors` as a
|
|
57
|
+
* colour picker's `source` (it has the shape of `ColorSource` in `@commmerce/ui`). Admins older than 1.17.0
|
|
58
|
+
* reject with `unknown-type`, and the picker then shows no list. Added in 1.17.0.
|
|
59
|
+
*/
|
|
60
|
+
colors: {
|
|
61
|
+
/** The store's brand colours, in the order the merchant set them. */
|
|
62
|
+
brandColors(): Promise<BrandColor[]>;
|
|
63
|
+
/** Recent custom colours, newest first. */
|
|
64
|
+
recentColors(): Promise<string[]>;
|
|
65
|
+
/** Remember a colour the merchant committed. Resolves with the new list, newest first. */
|
|
66
|
+
addRecentColor(color: string): Promise<string[]>;
|
|
67
|
+
};
|
|
55
68
|
/** A short-lived signed token (JWT) for your backend. Cached until 10 seconds before it expires. */
|
|
56
69
|
getSessionToken(): Promise<string>;
|
|
57
70
|
/**
|
package/dist/client.js
CHANGED
|
@@ -164,6 +164,11 @@ export function createApp(config) {
|
|
|
164
164
|
saveBar: { show: (options = {}) => request('saveBar.show', options), hide: () => request('saveBar.hide', {}) },
|
|
165
165
|
resourcePicker: (options) => request('resourcePicker.open', options),
|
|
166
166
|
loading: { start: () => request('loading.start', {}), stop: () => request('loading.stop', {}) },
|
|
167
|
+
colors: {
|
|
168
|
+
brandColors: () => request('colors.brand', {}),
|
|
169
|
+
recentColors: () => request('colors.recent', {}),
|
|
170
|
+
addRecentColor: (color) => request('colors.addRecent', { color }),
|
|
171
|
+
},
|
|
167
172
|
async getSessionToken() {
|
|
168
173
|
if (token && token.exp * 1000 - Date.now() > 10000)
|
|
169
174
|
return token.value;
|
package/dist/host.d.ts
CHANGED
|
@@ -19,6 +19,15 @@ export interface HostHandlers {
|
|
|
19
19
|
sessionToken(): Result<'sessionToken.get'>;
|
|
20
20
|
/** The app's content height changed (`app.autoResize()`). Default: sets the iframe's height. */
|
|
21
21
|
resize?(p: Payload<'frame.resize'>): Result<'frame.resize'>;
|
|
22
|
+
/** The store's brand colours (`app.colors.brandColors()`), from the admin's brand settings. Added in 1.17.0. */
|
|
23
|
+
brandColors?(): Result<'colors.brand'>;
|
|
24
|
+
/** The staff member's recent colours, newest first (`app.colors.recentColors()`). Added in 1.17.0. */
|
|
25
|
+
recentColors?(): Result<'colors.recent'>;
|
|
26
|
+
/**
|
|
27
|
+
* Remember `color` for the staff member: put it first, drop an earlier copy ignoring case, keep at most 16; return
|
|
28
|
+
* the new list. `color` is 1–200 characters and is NOT checked to be a valid CSS colour: treat it as text. Added in 1.17.0.
|
|
29
|
+
*/
|
|
30
|
+
addRecentColor?(color: string): Result<'colors.addRecent'>;
|
|
22
31
|
}
|
|
23
32
|
export interface HostConfig {
|
|
24
33
|
/** The iframe the app runs in. Only messages from its window are accepted. */
|
package/dist/host.js
CHANGED
|
@@ -49,6 +49,8 @@ export function validatePayload(type, p) {
|
|
|
49
49
|
case 'frame.resize':
|
|
50
50
|
return typeof p.height === 'number' && Number.isFinite(p.height) && p.height >= 0 && p.height <= 100000
|
|
51
51
|
? null : 'height must be a number of pixels, 0–100000';
|
|
52
|
+
case 'colors.addRecent':
|
|
53
|
+
return str(p.color, 200) ? null : 'color must be 1–200 characters';
|
|
52
54
|
case 'saveBar.show':
|
|
53
55
|
return optStr(p.message, 100) && optStr(p.saveLabel, 40) && optStr(p.discardLabel, 40) && optBool(p.loading)
|
|
54
56
|
? null : 'message (≤100), saveLabel and discardLabel (≤40) must be strings; loading a boolean';
|
|
@@ -117,10 +119,20 @@ export function createHost(config) {
|
|
|
117
119
|
return handlers.resize(p);
|
|
118
120
|
iframe.style.blockSize = `${Math.ceil(p.height)}px`;
|
|
119
121
|
return;
|
|
122
|
+
case 'colors.brand':
|
|
123
|
+
need(handlers.brandColors);
|
|
124
|
+
return handlers.brandColors();
|
|
125
|
+
case 'colors.recent':
|
|
126
|
+
need(handlers.recentColors);
|
|
127
|
+
return handlers.recentColors();
|
|
128
|
+
case 'colors.addRecent':
|
|
129
|
+
need(handlers.addRecentColor);
|
|
130
|
+
return handlers.addRecentColor(p.color);
|
|
120
131
|
}
|
|
121
132
|
};
|
|
122
133
|
const KNOWN = ['ready', 'toast.show', 'modal.open', 'navigate', 'saveBar.show', 'saveBar.hide',
|
|
123
|
-
'resourcePicker.open', 'loading.start', 'loading.stop', 'sessionToken.get', 'frame.resize'
|
|
134
|
+
'resourcePicker.open', 'loading.start', 'loading.stop', 'sessionToken.get', 'frame.resize',
|
|
135
|
+
'colors.brand', 'colors.recent', 'colors.addRecent'];
|
|
124
136
|
const onMessage = async (event) => {
|
|
125
137
|
if (!isMessage(event.data))
|
|
126
138
|
return config.onReject?.('not an App Bridge message', event);
|
package/dist/protocol.d.ts
CHANGED
|
@@ -54,6 +54,14 @@ export interface NavigateOptions {
|
|
|
54
54
|
/** Replace the current admin history entry instead of adding one. */
|
|
55
55
|
replace?: boolean;
|
|
56
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* A colour with an optional name, e.g. `{ value: '#2e6faf', name: 'Primary' }`: any CSS colour or gradient.
|
|
59
|
+
* The same shape as `ColorSwatch` in `@commmerce/ui`, so `app.colors` can be a colour picker's `source`. Added in 1.17.0.
|
|
60
|
+
*/
|
|
61
|
+
export interface BrandColor {
|
|
62
|
+
value: string;
|
|
63
|
+
name?: string;
|
|
64
|
+
}
|
|
57
65
|
/** What the host tells the app when it connects. */
|
|
58
66
|
export interface HostInfo {
|
|
59
67
|
/** The protocol version the host speaks. */
|
|
@@ -124,6 +132,29 @@ export interface RequestMap {
|
|
|
124
132
|
};
|
|
125
133
|
result: void;
|
|
126
134
|
};
|
|
135
|
+
/**
|
|
136
|
+
* The store's brand colours, as the merchant set them in the admin's brand settings, in their order. Added in 1.17.0
|
|
137
|
+
* (still protocol v1): older admins answer `unknown-type`.
|
|
138
|
+
*/
|
|
139
|
+
'colors.brand': {
|
|
140
|
+
payload: Record<string, never>;
|
|
141
|
+
result: BrandColor[];
|
|
142
|
+
};
|
|
143
|
+
/** The staff member's recent custom colours, newest first. Added in 1.17.0 (still protocol v1). */
|
|
144
|
+
'colors.recent': {
|
|
145
|
+
payload: Record<string, never>;
|
|
146
|
+
result: string[];
|
|
147
|
+
};
|
|
148
|
+
/**
|
|
149
|
+
* Remember a colour the merchant committed in a colour picker: the admin puts it first, drops an earlier copy
|
|
150
|
+
* (ignoring case) and keeps at most 16. Answers the new list, newest first. Added in 1.17.0 (still protocol v1).
|
|
151
|
+
*/
|
|
152
|
+
'colors.addRecent': {
|
|
153
|
+
payload: {
|
|
154
|
+
color: string;
|
|
155
|
+
};
|
|
156
|
+
result: string[];
|
|
157
|
+
};
|
|
127
158
|
}
|
|
128
159
|
export type RequestType = keyof RequestMap;
|
|
129
160
|
/** Events the host sends to the app. */
|
package/dist/reference-host.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type Host, type HostConfig } from './host.js';
|
|
2
|
-
import type { PickedResource, ResourcePickerOptions } from './protocol.js';
|
|
2
|
+
import type { PickedResource, ResourcePickerOptions, BrandColor } from './protocol.js';
|
|
3
3
|
/**
|
|
4
4
|
* A reference admin-side implementation, built from Commmerce UI components (`cm-toast`, `cm-progress-bar`,
|
|
5
5
|
* `cm-modal`, `cm-save-bar`, `cm-button`, `cm-checkbox`, `cm-radio-group`): load `@commmerce/ui` and `@commmerce/tokens` on the page first.
|
|
@@ -19,6 +19,13 @@ export interface ReferenceHostConfig extends Omit<HostConfig, 'handlers'> {
|
|
|
19
19
|
resources?: (type: ResourcePickerOptions['type']) => Promise<PickedResource[]> | PickedResource[];
|
|
20
20
|
/** Fetch a session token from the admin's backend. Without it, `getSessionToken` answers `not-supported`. */
|
|
21
21
|
sessionToken?: () => Promise<string>;
|
|
22
|
+
/**
|
|
23
|
+
* The store's brand colours, answered to `app.colors.brandColors()`: CSS colours or gradients, plain or with a name
|
|
24
|
+
* (`{ value: '#2e6faf', name: 'Primary' }`). Default `[]`. Recent colours are kept in memory for this host only
|
|
25
|
+
* (newest first, no repeats ignoring case, at most 16) and are lost on reload; the real admin keeps them per staff
|
|
26
|
+
* member on its server. Added in 1.17.0.
|
|
27
|
+
*/
|
|
28
|
+
brandColors?: Array<string | BrandColor>;
|
|
22
29
|
}
|
|
23
30
|
/** Connects the app in `iframe` to admin-level UI made from Commmerce UI components. */
|
|
24
31
|
export declare function createReferenceHost(config: ReferenceHostConfig): Host;
|
package/dist/reference-host.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { createHost, isAppPath } from './host.js';
|
|
2
|
+
/** How many recent colours the reference host keeps. */
|
|
3
|
+
const MAX_RECENT = 16;
|
|
2
4
|
const TYPE_NAMES = { product: 'products', customer: 'customers', collection: 'collections' };
|
|
3
5
|
function el(tag, attrs = {}, text) {
|
|
4
6
|
const e = document.createElement(tag);
|
|
@@ -98,6 +100,17 @@ export function createReferenceHost(config) {
|
|
|
98
100
|
}
|
|
99
101
|
if (config.sessionToken)
|
|
100
102
|
handlers.sessionToken = config.sessionToken;
|
|
103
|
+
// Colours: the configured brand colours, and recents in memory for this host instance.
|
|
104
|
+
const brand = (config.brandColors ?? []).map((c) => (typeof c === 'string' ? { value: c } : { ...c }));
|
|
105
|
+
let recents = [];
|
|
106
|
+
handlers.brandColors = () => brand.map((c) => ({ ...c }));
|
|
107
|
+
handlers.recentColors = () => [...recents];
|
|
108
|
+
handlers.addRecentColor = (color) => {
|
|
109
|
+
const value = color.trim();
|
|
110
|
+
const key = value.toLowerCase();
|
|
111
|
+
recents = [value, ...recents.filter((c) => c.toLowerCase() !== key)].slice(0, MAX_RECENT);
|
|
112
|
+
return [...recents];
|
|
113
|
+
};
|
|
101
114
|
// Without a custom navigate, the app's path lives in the admin's #hash: hand it back on connect, and tell the
|
|
102
115
|
// app when Back or Forward moves it (pushState from navigate() fires neither event, so the app's own moves
|
|
103
116
|
// are never echoed back).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@commmerce/app-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.17.0",
|
|
4
4
|
"description": "Connects an app embedded in the Commmerce admin to the admin: toasts, modals, navigation, save bar, resource picker, loading bar and session tokens.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"commmerce",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"test": "vitest run"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
|
-
"@commmerce/ui": "1.
|
|
46
|
+
"@commmerce/ui": "1.17.0",
|
|
47
47
|
"@vitest/browser": "^2.1.8",
|
|
48
48
|
"playwright": "^1.49.0"
|
|
49
49
|
}
|