@commmerce/app-bridge 0.0.0-stage → 1.0.0-rc.3

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.md ADDED
@@ -0,0 +1,17 @@
1
+ # Commmerce UI Licence — DRAFT, NOT YET IN FORCE
2
+
3
+ > Draft for legal review. Do not publish packages until this is approved.
4
+
5
+ Copyright (c) 2026 Outdo Inc. (Commmerce). All rights reserved.
6
+
7
+ 1. **Grant.** You may install, use and include unmodified copies of the Commmerce UI packages
8
+ (`@commmerce/tokens`, `@commmerce/ui`, `@commmerce/ui-react`, `@commmerce/app-bridge`) in
9
+ software whose purpose is to run on, integrate with or extend a Commmerce platform, including
10
+ apps listed in, or privately installed through, the Commmerce app marketplace.
11
+ 2. **Restrictions.** You may not use the packages, or the Commmerce name, logo or visual identity
12
+ they carry, to build a product that is not for use with a Commmerce platform, or one that
13
+ presents itself as made or endorsed by Commmerce. You may not redistribute the packages on their
14
+ own or as a competing design system.
15
+ 3. **No warranty.** The packages are provided "as is", without warranty of any kind. Commmerce is
16
+ not liable for any claim or damages arising from their use.
17
+ 4. **Termination.** This licence ends automatically if you breach it.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # @commmerce/app-bridge
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
+ 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.
5
+
6
+ **Preview.** Protocol version 1. APIs can change between releases; read the release notes before upgrading.
7
+ Docs: https://commmerce.com/blog/commmerceui/#apps--app-bridge
8
+
9
+ ## In your app (inside the iframe)
10
+
11
+ ```js
12
+ import { createApp } from '@commmerce/app-bridge';
13
+ // or, without a build step, pinned to a version:
14
+ // import { createApp } from 'https://commmerce.com/blog/commmerceui/v/<version>/app-bridge.js';
15
+
16
+ // ADMIN_ORIGIN, from your app settings (render it into the page from your server): 'https://*.commmerce.com'
17
+ // (any Commmerce admin on a subdomain; recommended) or one exact origin.
18
+ const app = createApp({ hostOrigin: ADMIN_ORIGIN, apiKey: 'YOUR_API_KEY' });
19
+ const { theme } = await app.ready; // 'light' | 'dark'
20
+
21
+ await app.toast.show('Product saved', { tone: 'success' });
22
+ const choice = await app.modal.open({
23
+ title: 'Delete review?', message: 'This can\'t be undone.',
24
+ primaryAction: { label: 'Delete review', destructive: true }, secondaryAction: { label: 'Cancel' },
25
+ }); // 'primary' | 'secondary' | 'close'
26
+ await app.navigate('/reviews/42'); // updates the admin's address
27
+ await app.saveBar.show({ message: 'Unsaved changes' });
28
+ app.on('saveBar.save', save); app.on('saveBar.discard', discard);
29
+ const products = await app.resourcePicker({ type: 'product', multiple: true }); // [{ id, title }] or null
30
+ await app.loading.start(); /* … */ await app.loading.stop();
31
+ app.autoResize(); // the admin sizes your frame to your page
32
+
33
+ const token = await app.getSessionToken();
34
+ await fetch('/api/reviews', { headers: { Authorization: `Bearer ${token}` } });
35
+ ```
36
+
37
+ `hostOrigin` is required: an exact origin, or a pattern such as `https://*.commmerce.com`. A pattern matches the
38
+ same scheme and port, and any host name ending in `.commmerce.com` with at least one label before it
39
+ (`admin.commmerce.com`, `a.b.commmerce.com`); never the bare domain, look-alikes (`evilcommmerce.com`,
40
+ `commmerce.com.evil.com`), other schemes or ports, or IP addresses. Only one leading `*.` is allowed, the domain
41
+ needs a dot, and there is no path (`*` and `https://*.com` are refused).
42
+
43
+ With a pattern, the app finds the admin's actual origin (`location.ancestorOrigins[0]`, or the origin of
44
+ `document.referrer` in browsers without it), checks it against the pattern, and throws if it doesn't match or
45
+ can't be found. Either way the app talks to one exact origin for the session (`app.hostOrigin`): requests are only
46
+ posted to it, never to `*`, and messages from any other origin, or from any window except the admin's, are ignored.
47
+ `exactHostOrigin` passes the admin's origin yourself (still checked against the pattern).
48
+
49
+ ## On your backend: verify the session token
50
+
51
+ ```js
52
+ import { verifySessionToken } from '@commmerce/app-bridge/session-token';
53
+
54
+ const claims = await verifySessionToken(token, process.env.COMMMERCE_APP_SECRET, {
55
+ audience: process.env.COMMMERCE_API_KEY,
56
+ issuer: process.env.COMMMERCE_ADMIN_ORIGIN, // exact origin or pattern (https://*.commmerce.com); always pass it
57
+ });
58
+ // claims.dest: the store; claims.sub: the staff member. Throws SessionTokenError (answer 401) otherwise.
59
+ // Serve only stores that installed your app: look claims.dest up, and answer 403 if it is not there.
60
+ // Never take the store from the request itself.
61
+ ```
62
+
63
+ Tokens are HS256 JWTs signed with your app secret and live 60 seconds. Claims: `iss` (admin origin), `dest` (store
64
+ origin), `aud` (your API key), `sub` (staff member id), `sid` (admin session), `iat`, `nbf`, `exp`, `jti`.
65
+ Only HS256 is accepted (`none` and every other algorithm are refused). Uses Web Crypto: Node 18+, Deno, Bun, edge runtimes.
66
+
67
+ ## In the admin (host)
68
+
69
+ `createHost({ iframe, appOrigin, handlers })` answers requests from one app frame. Payloads are validated before
70
+ a handler runs; a missing handler answers `not-supported`. `createReferenceHost(...)` is a reference
71
+ implementation built from Commmerce UI components (`cm-modal`, `cm-save-bar`, …).
72
+
73
+ ## Protocol
74
+
75
+ Plain objects over `postMessage`, each with `protocol: 'commmerce-app-bridge'` and `version: 1`:
76
+ requests `{ kind: 'request', id, type, payload }`, responses `{ kind: 'response', id, ok, result | error }`,
77
+ events `{ kind: 'event', type, payload }`. The app sends `ready` first. Error codes: `unsupported-version`,
78
+ `unknown-type`, `invalid-payload`, `not-supported`, `not-ready`, `failed`, `timeout`.
79
+
80
+ Made and maintained by Commmerce. Support: support@commmerce.com
@@ -0,0 +1 @@
1
+ var H="commmerce-app-bridge",R=1,w=class extends Error{constructor(t,r){super(r),this.name="AppBridgeError",this.code=t}};function A(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 K=/^(?!-)[a-z0-9-]{1,63}(?<!-)$/,Z={"https:":"443","http:":"80"};function x(e){return typeof e=="string"&&e.includes("*")}function O(e,t="origin pattern"){let r=i=>new TypeError(`App Bridge: ${t} "${e}" is not a valid origin pattern: ${i}. 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()}:`,s=n[2].toLowerCase(),l=s.split(".");if(s.length>253||!l.every(i=>K.test(i)))throw r('the part after "*." must be a domain name (letters, digits, hyphens and dots)');if(l.length<2&&s!=="localhost")throw r('the domain after "*." needs at least one dot, e.g. *.commmerce.com');if(/^(\d+|0x[0-9a-f]*)$/.test(l[l.length-1]))throw r("IP addresses cannot have a wildcard");let m="";if(n[3]!==void 0){let i=Number(n[3]);if(i<1||i>65535)throw r("the port must be 1 to 65535");m=String(i)===Z[a]?"":String(i)}return{scheme:a,domain:s,port:m,source:String(e)}}function z(e,t){let r=typeof e=="string"?O(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 s=n.hostname.slice(0,-a.length);return s.length>0&&s.split(".").every(l=>K.test(l))}function F(e,t){return x(e)?z(O(e,"allowed origin"),t):typeof t=="string"&&t===e}var L=new TextEncoder,W=new TextDecoder;function j(e){let t="";return e.forEach(r=>{t+=String.fromCharCode(r)}),btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N(e){if(!/^[A-Za-z0-9_-]*$/.test(e))throw new v("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 _=(e,t)=>crypto.subtle.importKey("raw",L.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t]),v=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"}))),s=j(L.encode(JSON.stringify(n))),l=await crypto.subtle.sign("HMAC",await _(t,"sign"),L.encode(`${a}.${s}`));return`${a}.${s}.${j(new Uint8Array(l))}`}function B(e){let t=String(e).split(".");if(t.length!==3)throw new v("malformed","Token must have three parts");try{return JSON.parse(W.decode(N(t[1])))}catch(r){throw r instanceof v?r:new v("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)&&O(r.issuer,"verifySessionToken: options.issuer");let n=String(e).split(".");if(n.length!==3)throw new v("malformed","Token must have three parts");let a;try{a=JSON.parse(W.decode(N(n[0])))}catch{throw new v("malformed","Token header is not JSON")}if(a.alg!=="HS256")throw new v("algorithm",`Algorithm ${a.alg} is not allowed`);if(!await crypto.subtle.verify("HMAC",await _(t,"verify"),N(n[2]),L.encode(`${n[0]}.${n[1]}`)))throw new v("signature","Signature does not match");let l=B(e),m=r.now??Math.floor(Date.now()/1e3),i=r.clockTolerance??5;if(typeof l.exp!="number"||m-i>=l.exp)throw new v("expired","Token has expired");if(typeof l.nbf=="number"&&m+i<l.nbf)throw new v("not-yet-valid","Token is not valid yet");if(l.aud!==r.audience)throw new v("audience","Token is for another app");if(r.issuer&&!F(r.issuer,l.iss))throw new v("issuer","Token was issued by someone else");return l}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 D="commmerce-app-bridge:host-origin";function ee(e=te()){let{ancestorOrigins:t,referrer:r,self:n,remembered:a}=e;if(t)return t.length&&t[0]!=="null"?t[0]:void 0;let s;try{s=r?new URL(r).origin:void 0}catch{s=void 0}if(!(!s||s==="null"))return s===n?a||void 0:s}function te(){let e=null;try{e=sessionStorage.getItem(D)}catch{}return{ancestorOrigins:location.ancestorOrigins,referrer:document.referrer,self:location.origin,remembered:e}}function re(e,t){if(!x(e.hostOrigin))return C(e.hostOrigin,"hostOrigin");let r=O(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(!z(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(D,a)}catch{}return a}var ne=["modal.open","resourcePicker.open"],oe=0;function se(e){x(e.hostOrigin)?O(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,s=new Map,l=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,m=!1,i=null,y=new Set,f,d=o=>{if(!A(o.data))return e.onReject?.("not an App Bridge message",o);if(o.source!==t)return e.onReject?.("not from the admin window",o);if(o.origin!==r)return e.onReject?.(`origin ${o.origin} is not ${r}`,o);let p=o.data;if(p.kind==="response"){let u=a.get(p.id);if(!u)return;a.delete(p.id),clearTimeout(u.timer);let b=p;b.ok?u.resolve(b.result):u.reject(new w(b.error?.code??"failed",b.error?.message??"The admin refused the request"))}else p.kind==="event"&&s.get(p.type)?.forEach(u=>u(p.payload))};window.addEventListener("message",d);function c(o,p){if(m)return Promise.reject(new w("failed","App Bridge was destroyed"));let u=`${l}-${++oe}`;return new Promise((b,k)=>{let E={resolve:b,reject:k};ne.includes(o)||(E.timer=setTimeout(()=>{a.delete(u),k(new w("timeout",`The admin did not answer "${o}" within ${n} ms`))},n)),a.set(u,E),t.postMessage({protocol:H,version:1,kind:"request",id:u,type:o,payload:p},r)})}let g=c("ready",e.apiKey?{apiKey:e.apiKey}:{});g.catch(()=>{});let h=(o,p)=>g.then(()=>c(o,p));return{hostOrigin:r,ready:g,toast:{show:(o,p={})=>h("toast.show",{message:o,...p})},modal:{open:o=>h("modal.open",o)},navigate:(o,p={})=>h("navigate",{path:o,...p}),saveBar:{show:(o={})=>h("saveBar.show",o),hide:()=>h("saveBar.hide",{})},resourcePicker:o=>h("resourcePicker.open",o),loading:{start:()=>h("loading.start",{}),stop:()=>h("loading.stop",{})},async getSessionToken(){if(i&&i.exp*1e3-Date.now()>1e4)return i.value;let o=await h("sessionToken.get",{}),p=Number(B(o).exp);return i=Number.isFinite(p)?{value:o,exp:p}:null,o},autoResize(){if(f)return f;let o=-1,p=0,u=()=>{p=0;let S=X();S===o||m||(o=S,h("frame.resize",{height:S}).catch(()=>{}))},b=()=>{p||(p=requestAnimationFrame(u))},k=new ResizeObserver(b),E=()=>{k.disconnect(),k.observe(document.body);for(let S of document.body.children)k.observe(S);b()},U=new MutationObserver(E);U.observe(document.body,{childList:!0}),E();let M=()=>{k.disconnect(),U.disconnect(),cancelAnimationFrame(p),y.delete(M),f===M&&(f=void 0)};return y.add(M),f=M,M},on(o,p){let u=s.get(o)??new Set;return s.set(o,u),u.add(p),()=>u.delete(p)},destroy(){m=!0,[...y].forEach(o=>o()),window.removeEventListener("message",d);for(let[,o]of a)clearTimeout(o.timer),o.reject(new w("failed","App Bridge was destroyed"));a.clear(),s.clear()}}}var P=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t,$=(e,t)=>e===void 0||P(e,t),q=e=>e===void 0||typeof e=="boolean";function J(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 $(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)&&q(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 J(t.path)?q(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 $(t.message,100)&&$(t.saveLabel,40)&&$(t.discardLabel,40)&&q(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)?q(t.multiple)?null:"multiple must be a boolean":"type must be product, customer or collection";default:return null}}function I(e){let t=C(e.appOrigin,"appOrigin"),{iframe:r,handlers:n}=e,a=!1,s=!1,l=d=>{s||r.contentWindow?.postMessage({protocol:H,version:1,...d},t)},m=(d,c,g)=>l({kind:"response",id:d,ok:!1,error:{code:c,message:g}}),i=(d,c)=>{let g=h=>{if(!h)throw new w("not-supported",`This admin does not support "${d}"`)};switch(d){case"ready":if(e.apiKey&&c.apiKey!==e.apiKey)throw new w("failed","API key does not match this app");return a=!0,{version:1,theme:e.info?.theme??"light",locale:e.info?.locale??"en-IN"};case"toast.show":return g(n.toast),n.toast(c);case"modal.open":return g(n.modal),n.modal(c);case"navigate":return g(n.navigate),n.navigate(c);case"saveBar.show":return g(n.saveBar),n.saveBar(c);case"saveBar.hide":return g(n.saveBar),n.saveBar(null);case"resourcePicker.open":return g(n.resourcePicker),n.resourcePicker(c);case"loading.start":return g(n.loading),n.loading(!0);case"loading.stop":return g(n.loading),n.loading(!1);case"sessionToken.get":return g(n.sessionToken),n.sessionToken();case"frame.resize":if(n.resize)return n.resize(c);r.style.blockSize=`${Math.ceil(c.height)}px`;return}},y=["ready","toast.show","modal.open","navigate","saveBar.show","saveBar.hide","resourcePicker.open","loading.start","loading.stop","sessionToken.get","frame.resize"],f=async d=>{if(!A(d.data))return e.onReject?.("not an App Bridge message",d);if(!r.contentWindow||d.source!==r.contentWindow)return e.onReject?.("not from the app frame",d);if(d.origin!==t)return e.onReject?.(`origin ${d.origin} is not ${t}`,d);let c=d.data;if(c.kind!=="request"||typeof c.id!="string")return e.onReject?.("not a request",d);let{id:g,type:h}=c;if(c.version!==1)return m(g,"unsupported-version",`This admin speaks App Bridge version ${1}`);if(!y.includes(h))return m(g,"unknown-type",`Unknown request "${String(h)}"`);if(h!=="ready"&&!a)return m(g,"not-ready",'Send "ready" first');let o=c.payload&&typeof c.payload=="object"?c.payload:{},p=V(h,o);if(p)return m(g,"invalid-payload",p);try{let u=await i(h,o);l({kind:"response",id:g,ok:!0,...u===void 0?{}:{result:u}})}catch(u){u instanceof w?m(g,u.code,u.message):m(g,"failed",u instanceof Error?u.message:"The admin could not complete the request")}};return window.addEventListener("message",f),{send(d,c){a&&l({kind:"event",type:d,payload:c})},get connected(){return a},destroy(){s=!0,a=!1,window.removeEventListener("message",f)}}}var ie={product:"products",customer:"customers",collection:"collections"};function T(e,t={},r){let n=document.createElement(e);for(let[a,s]of Object.entries(t))s!==!1&&n.setAttribute(a,s===!0?"":s);return r!==void 0&&(n.textContent=r),n}function Y(e,t,r,n){return new Promise(a=>{let s=T("cm-modal",{heading:t});s.append(r);let l="close";for(let m of n){let i=T("cm-button",{slot:"footer",variant:m.primary?"primary":"secondary"},m.label);i.addEventListener("click",()=>{l=m.value,s.close()}),s.append(i)}s.addEventListener("cm-closed",()=>{s.remove(),a(l)}),e.append(s),s.show()})}function ae(e){let t=e.root??document.body,r,n=T("cm-toast-region",{"data-app-bridge":"toasts",max:"1"}),a=T("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 s=T("cm-save-bar",{"data-app-bridge":"save-bar"});s.addEventListener("cm-save",i=>{i.preventDefault(),r.send("saveBar.save",{})}),s.addEventListener("cm-discard",i=>{i.preventDefault(),r.send("saveBar.discard",{})}),t.append(n,a,s);let l={toast({message:i,tone:y="default",duration:f=5e3}){let d=T("cm-toast",{"data-tone":y});d.message=i,d.tone=y==="critical"?"critical":"default",d.duration=f,n.add(d)},async modal({title:i,message:y,primaryAction:f,secondaryAction:d}){let c=[];return d&&c.push({label:d.label,value:"secondary"}),f&&c.push({label:f.label,value:"primary",primary:!0}),await Y(t,i,T("p",{},y),c)},navigate({path:i,replace:y}){if(e.navigate)return e.navigate(i,!!y);let f=`${location.pathname}${location.search}#${i}`;y?history.replaceState(history.state,"",f):history.pushState(history.state,"",f)},saveBar(i){if(!i){s.open=!1;return}s.message=i.message??"Unsaved changes",i.saveLabel&&(s.saveLabel=i.saveLabel),i.discardLabel&&(s.discardLabel=i.discardLabel),s.loading=!!i.loading,s.open=!0},loading(i){a.hidden=!i}};if(e.resources){let i=e.resources;l.resourcePicker=async({type:y,multiple:f})=>{let d=await i(y),c=T(f?"div":"cm-radio-group",f?{}:{label:`Choose ${y}`});c.style.cssText="display:grid;gap:var(--cm-space-10,10px)";for(let o of d)c.append(T(f?"cm-checkbox":"cm-radio",{label:o.title,value:o.id}));if(await Y(t,`Select ${ie[y]}`,c,[{label:"Cancel",value:"secondary"},{label:"Select",value:"primary",primary:!0}])!=="primary")return null;let h=[...c.querySelectorAll("cm-checkbox, cm-radio")].filter(o=>o.checked).map(o=>o.value);return d.filter(o=>h.includes(o.id))}}e.sessionToken&&(l.sessionToken=e.sessionToken),r=I({...e,handlers:l});let m=r.destroy;return Object.assign(Object.create(null),{send:r.send,get connected(){return r.connected},destroy(){m(),n.remove(),a.remove(),s.remove()}})}export{w as AppBridgeError,H as PROTOCOL,R as PROTOCOL_VERSION,v as SessionTokenError,se as createApp,I as createHost,ae as createReferenceHost,B as decodeClaims,J as isAppPath,A as isMessage,x as isOriginPattern,F as matchesOrigin,z as matchesOriginPattern,C as normalizeOrigin,O as parseOriginPattern,G as signSessionToken,V as validatePayload,Q as verifySessionToken};
@@ -0,0 +1,82 @@
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';
2
+ export interface AppConfig {
3
+ /**
4
+ * The admin's origin, as given in your app settings. Required. Either:
5
+ * - an exact origin, e.g. `https://admin.example.com`; or
6
+ * - a pattern, e.g. `https://*.commmerce.com`, to run inside any Commmerce admin on a subdomain of that domain
7
+ * (see `matchesOriginPattern` for exactly what matches). The app finds the admin's actual origin
8
+ * (`location.ancestorOrigins[0]`, or the origin of `document.referrer` in browsers without it), checks it
9
+ * against the pattern, and throws if it doesn't match or can't be found.
10
+ *
11
+ * Either way the app then talks to ONE concrete origin (`app.hostOrigin`) for the whole session: requests are
12
+ * only ever posted to it (never to `*`), and messages from any other origin are ignored. `*` is refused.
13
+ */
14
+ hostOrigin: string;
15
+ /**
16
+ * With a pattern `hostOrigin` only: the admin's concrete origin, instead of finding it from the page. It must
17
+ * still match the pattern. For tests, or when the admin sends no referrer and the browser has no
18
+ * `location.ancestorOrigins`. If it isn't really the admin's origin, the browser drops every request
19
+ * and `ready` rejects with `timeout`.
20
+ */
21
+ exactHostOrigin?: string;
22
+ /** Your app's API key. Sent to the admin when connecting; it becomes the session token's `aud`. */
23
+ apiKey?: string;
24
+ /** How long to wait for an answer, in ms. Default 10000. Modals and the resource picker wait for the merchant, without a limit. */
25
+ timeout?: number;
26
+ /** The admin window. Default `window.parent`. */
27
+ target?: Window;
28
+ /** Called with the reason whenever a message is ignored (wrong origin, wrong sender, not App Bridge). For logging. */
29
+ onReject?: (reason: string, event: MessageEvent) => void;
30
+ }
31
+ /** What `createApp()` returns. Every method returns a promise that settles when the admin has acted on it. */
32
+ export interface App {
33
+ /** The one admin origin this app talks to: `hostOrigin` itself, or with a pattern, the admin origin it matched. */
34
+ readonly hostOrigin: string;
35
+ /** Settles once the admin has accepted the connection. Every request waits for it. */
36
+ readonly ready: Promise<HostInfo>;
37
+ toast: {
38
+ show(message: string, options?: ToastOptions): Promise<void>;
39
+ };
40
+ modal: {
41
+ open(options: ModalOptions): Promise<ModalResult>;
42
+ };
43
+ /** Updates the admin's address to `path` (within your app), so links, reloads and the back button work. */
44
+ navigate(path: string, options?: NavigateOptions): Promise<void>;
45
+ saveBar: {
46
+ show(options?: SaveBarOptions): Promise<void>;
47
+ hide(): Promise<void>;
48
+ };
49
+ /** Opens the admin's picker. Resolves with what was chosen, or `null` if the merchant cancelled. */
50
+ resourcePicker(options: ResourcePickerOptions): Promise<PickedResource[] | null>;
51
+ loading: {
52
+ start(): Promise<void>;
53
+ stop(): Promise<void>;
54
+ };
55
+ /** A short-lived signed token (JWT) for your backend. Cached until 10 seconds before it expires. */
56
+ getSessionToken(): Promise<string>;
57
+ /**
58
+ * Keeps the admin's frame as tall as your page, so the merchant scrolls the admin, not a box inside it.
59
+ * Sends the height now and whenever it changes. Measures your content, not the window, so don't size content
60
+ * with `vh` units. Calling it again returns the same stop function. Returns a function that stops it.
61
+ */
62
+ autoResize(): () => void;
63
+ /** Listens for an admin event. Returns a function that stops listening. */
64
+ on<T extends EventType>(type: T, listener: (payload: EventMap[T]) => void): () => void;
65
+ /** Stops listening and rejects pending requests. */
66
+ destroy(): void;
67
+ }
68
+ /**
69
+ * Where the admin around this page seems to be, for a pattern `hostOrigin`. Only a candidate: the caller checks it
70
+ * against the pattern, and the browser's own `postMessage` origin check stops anything being sent to another
71
+ * window. Uses `location.ancestorOrigins[0]` when the browser has it (it is the parent's origin, or `"null"` when
72
+ * the admin hides it). Otherwise the origin of `document.referrer`: the page that loaded this one into the frame.
73
+ * After a link inside the app, the referrer is the app's own page, so the origin remembered for this tab is used.
74
+ */
75
+ export declare function detectHostOrigin(source?: {
76
+ ancestorOrigins?: ArrayLike<string> | null;
77
+ referrer?: string;
78
+ self?: string;
79
+ remembered?: string | null;
80
+ }): string | undefined;
81
+ /** Connects an app running in an iframe to the Commmerce admin around it. */
82
+ export declare function createApp(config: AppConfig): App;
package/dist/client.js ADDED
@@ -0,0 +1,223 @@
1
+ import { PROTOCOL, PROTOCOL_VERSION, AppBridgeError, isMessage, normalizeOrigin, isOriginPattern, parseOriginPattern, matchesOriginPattern, } from './protocol.js';
2
+ import { decodeClaims } from './session-token.js';
3
+ /**
4
+ * The height of the page's content: the lowest edge of the body's children (fixed-position ones excluded),
5
+ * plus the body's own bottom padding, border and margin. It does not depend on the frame's height, so a page
6
+ * with `min-height: 100vh` or `height: 100%` can't make the frame grow without end.
7
+ */
8
+ function contentHeight() {
9
+ const body = document.body;
10
+ if (!body)
11
+ return 0;
12
+ const bs = getComputedStyle(body);
13
+ let bottom = body.getBoundingClientRect().top + parseFloat(bs.paddingTop) + parseFloat(bs.borderTopWidth);
14
+ for (const child of body.children) {
15
+ const cs = getComputedStyle(child);
16
+ if (cs.position === 'fixed' || cs.display === 'none' || child.localName === 'script')
17
+ continue;
18
+ bottom = Math.max(bottom, child.getBoundingClientRect().bottom + parseFloat(cs.marginBottom));
19
+ }
20
+ return Math.ceil(bottom + scrollY + parseFloat(bs.paddingBottom) + parseFloat(bs.borderBottomWidth) + parseFloat(bs.marginBottom));
21
+ }
22
+ const REMEMBER = 'commmerce-app-bridge:host-origin';
23
+ /**
24
+ * Where the admin around this page seems to be, for a pattern `hostOrigin`. Only a candidate: the caller checks it
25
+ * against the pattern, and the browser's own `postMessage` origin check stops anything being sent to another
26
+ * window. Uses `location.ancestorOrigins[0]` when the browser has it (it is the parent's origin, or `"null"` when
27
+ * the admin hides it). Otherwise the origin of `document.referrer`: the page that loaded this one into the frame.
28
+ * After a link inside the app, the referrer is the app's own page, so the origin remembered for this tab is used.
29
+ */
30
+ export function detectHostOrigin(source = currentPage()) {
31
+ const { ancestorOrigins, referrer, self, remembered } = source;
32
+ if (ancestorOrigins)
33
+ return ancestorOrigins.length && ancestorOrigins[0] !== 'null' ? ancestorOrigins[0] : undefined;
34
+ let from;
35
+ try {
36
+ from = referrer ? new URL(referrer).origin : undefined;
37
+ }
38
+ catch {
39
+ from = undefined;
40
+ }
41
+ if (!from || from === 'null')
42
+ return undefined;
43
+ if (from === self)
44
+ return remembered || undefined;
45
+ return from;
46
+ }
47
+ function currentPage() {
48
+ let remembered = null;
49
+ try {
50
+ remembered = sessionStorage.getItem(REMEMBER);
51
+ }
52
+ catch { /* storage blocked */ }
53
+ return { ancestorOrigins: location.ancestorOrigins, referrer: document.referrer, self: location.origin, remembered };
54
+ }
55
+ /** The concrete admin origin to talk to, checked against `hostOrigin` (exact or pattern). */
56
+ function resolveHostOrigin(config, target) {
57
+ if (!isOriginPattern(config.hostOrigin))
58
+ return normalizeOrigin(config.hostOrigin, 'hostOrigin');
59
+ const pattern = parseOriginPattern(config.hostOrigin, 'hostOrigin');
60
+ let candidate = config.exactHostOrigin;
61
+ if (!candidate) {
62
+ if (target !== window.parent)
63
+ throw new Error('App Bridge: with a pattern hostOrigin and a custom target, pass exactHostOrigin');
64
+ candidate = detectHostOrigin();
65
+ }
66
+ if (!candidate) {
67
+ throw new Error(`App Bridge: hostOrigin is the pattern ${pattern.source}, but the admin's origin can't be found `
68
+ + '(no location.ancestorOrigins and no document.referrer, or the admin hides them). Is the page inside the admin?');
69
+ }
70
+ if (!matchesOriginPattern(pattern, candidate)) {
71
+ throw new Error(`App Bridge: the admin's origin ${candidate} does not match hostOrigin ${pattern.source}. Messages to it are refused.`);
72
+ }
73
+ const origin = new URL(candidate).origin;
74
+ if (!config.exactHostOrigin) {
75
+ try {
76
+ sessionStorage.setItem(REMEMBER, origin);
77
+ }
78
+ catch { /* storage blocked */ }
79
+ }
80
+ return origin;
81
+ }
82
+ const WAITS_FOR_MERCHANT = ['modal.open', 'resourcePicker.open'];
83
+ let seq = 0;
84
+ /** Connects an app running in an iframe to the Commmerce admin around it. */
85
+ export function createApp(config) {
86
+ // A bad setting is reported first, before anything about the page.
87
+ if (isOriginPattern(config.hostOrigin))
88
+ parseOriginPattern(config.hostOrigin, 'hostOrigin');
89
+ else
90
+ normalizeOrigin(config.hostOrigin, 'hostOrigin');
91
+ const target = config.target ?? window.parent;
92
+ if (!target || target === window)
93
+ throw new Error('App Bridge: the app is not inside the admin (no parent window)');
94
+ const hostOrigin = resolveHostOrigin(config, target);
95
+ const timeout = config.timeout ?? 10000;
96
+ const pending = new Map();
97
+ const listeners = new Map();
98
+ const prefix = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
99
+ let destroyed = false;
100
+ let token = null;
101
+ const stopResize = new Set();
102
+ let resizing;
103
+ const onMessage = (event) => {
104
+ if (!isMessage(event.data))
105
+ return config.onReject?.('not an App Bridge message', event);
106
+ if (event.source !== target)
107
+ return config.onReject?.('not from the admin window', event);
108
+ if (event.origin !== hostOrigin)
109
+ return config.onReject?.(`origin ${event.origin} is not ${hostOrigin}`, event);
110
+ const msg = event.data;
111
+ if (msg.kind === 'response') {
112
+ const p = pending.get(msg.id);
113
+ if (!p)
114
+ return;
115
+ pending.delete(msg.id);
116
+ clearTimeout(p.timer);
117
+ const r = msg;
118
+ if (r.ok)
119
+ p.resolve(r.result);
120
+ else
121
+ p.reject(new AppBridgeError(r.error?.code ?? 'failed', r.error?.message ?? 'The admin refused the request'));
122
+ }
123
+ else if (msg.kind === 'event') {
124
+ listeners.get(msg.type)?.forEach((l) => l(msg.payload));
125
+ }
126
+ };
127
+ window.addEventListener('message', onMessage);
128
+ function send(type, payload) {
129
+ if (destroyed)
130
+ return Promise.reject(new AppBridgeError('failed', 'App Bridge was destroyed'));
131
+ const id = `${prefix}-${++seq}`;
132
+ return new Promise((resolve, reject) => {
133
+ const entry = {
134
+ resolve: resolve, reject,
135
+ };
136
+ if (!WAITS_FOR_MERCHANT.includes(type)) {
137
+ entry.timer = setTimeout(() => {
138
+ pending.delete(id);
139
+ reject(new AppBridgeError('timeout', `The admin did not answer "${type}" within ${timeout} ms`));
140
+ }, timeout);
141
+ }
142
+ pending.set(id, entry);
143
+ target.postMessage({ protocol: PROTOCOL, version: PROTOCOL_VERSION, kind: 'request', id, type, payload }, hostOrigin);
144
+ });
145
+ }
146
+ const ready = send('ready', config.apiKey ? { apiKey: config.apiKey } : {});
147
+ ready.catch(() => { }); // surfaced through every later request
148
+ const request = (type, payload) => ready.then(() => send(type, payload));
149
+ return {
150
+ hostOrigin,
151
+ ready,
152
+ toast: { show: (message, options = {}) => request('toast.show', { message, ...options }) },
153
+ modal: { open: (options) => request('modal.open', options) },
154
+ navigate: (path, options = {}) => request('navigate', { path, ...options }),
155
+ saveBar: { show: (options = {}) => request('saveBar.show', options), hide: () => request('saveBar.hide', {}) },
156
+ resourcePicker: (options) => request('resourcePicker.open', options),
157
+ loading: { start: () => request('loading.start', {}), stop: () => request('loading.stop', {}) },
158
+ async getSessionToken() {
159
+ if (token && token.exp * 1000 - Date.now() > 10000)
160
+ return token.value;
161
+ const value = await request('sessionToken.get', {});
162
+ const exp = Number(decodeClaims(value).exp);
163
+ token = Number.isFinite(exp) ? { value, exp } : null;
164
+ return value;
165
+ },
166
+ autoResize() {
167
+ if (resizing)
168
+ return resizing; // already running: one observer per app
169
+ let last = -1;
170
+ let frame = 0;
171
+ const send = () => {
172
+ frame = 0;
173
+ const height = contentHeight();
174
+ if (height === last || destroyed)
175
+ return;
176
+ last = height;
177
+ request('frame.resize', { height }).catch(() => { });
178
+ };
179
+ const schedule = () => { if (!frame)
180
+ frame = requestAnimationFrame(send); };
181
+ // Watch the body and each of its children: with `body { height: 100% }` the body itself never grows.
182
+ const sizes = new ResizeObserver(schedule);
183
+ const watchChildren = () => {
184
+ sizes.disconnect();
185
+ sizes.observe(document.body);
186
+ for (const child of document.body.children)
187
+ sizes.observe(child);
188
+ schedule();
189
+ };
190
+ const children = new MutationObserver(watchChildren);
191
+ children.observe(document.body, { childList: true });
192
+ watchChildren();
193
+ const stop = () => {
194
+ sizes.disconnect();
195
+ children.disconnect();
196
+ cancelAnimationFrame(frame);
197
+ stopResize.delete(stop);
198
+ if (resizing === stop)
199
+ resizing = undefined;
200
+ };
201
+ stopResize.add(stop);
202
+ resizing = stop;
203
+ return stop;
204
+ },
205
+ on(type, listener) {
206
+ const set = listeners.get(type) ?? new Set();
207
+ listeners.set(type, set);
208
+ set.add(listener);
209
+ return () => set.delete(listener);
210
+ },
211
+ destroy() {
212
+ destroyed = true;
213
+ [...stopResize].forEach((stop) => stop());
214
+ window.removeEventListener('message', onMessage);
215
+ for (const [, p] of pending) {
216
+ clearTimeout(p.timer);
217
+ p.reject(new AppBridgeError('failed', 'App Bridge was destroyed'));
218
+ }
219
+ pending.clear();
220
+ listeners.clear();
221
+ },
222
+ };
223
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { type RequestMap, type RequestType, type EventMap, type EventType, type HostInfo } from './protocol.js';
2
+ type Payload<T extends RequestType> = RequestMap[T]['payload'];
3
+ type Result<T extends RequestType> = RequestMap[T]['result'] | Promise<RequestMap[T]['result']>;
4
+ /**
5
+ * What the admin does for each request. Payloads are validated before a handler runs. Every string in them
6
+ * comes from the app: show it as text, never as HTML. A missing handler answers `not-supported`.
7
+ */
8
+ export interface HostHandlers {
9
+ toast(p: Payload<'toast.show'>): Result<'toast.show'>;
10
+ modal(p: Payload<'modal.open'>): Result<'modal.open'>;
11
+ /** `path` always starts with `/` and is relative to the app's place in the admin. */
12
+ navigate(p: Payload<'navigate'>): Result<'navigate'>;
13
+ /** Called with the options to show the save bar, or `null` to hide it. */
14
+ saveBar(p: Payload<'saveBar.show'> | null): Result<'saveBar.show'>;
15
+ resourcePicker(p: Payload<'resourcePicker.open'>): Result<'resourcePicker.open'>;
16
+ /** `true` to show the admin loading bar, `false` to hide it. */
17
+ loading(on: boolean): Result<'loading.start'>;
18
+ /** Get a fresh token for this app from the admin's backend (which holds the app secret). */
19
+ sessionToken(): Result<'sessionToken.get'>;
20
+ /** The app's content height changed (`app.autoResize()`). Default: sets the iframe's height. */
21
+ resize?(p: Payload<'frame.resize'>): Result<'frame.resize'>;
22
+ }
23
+ export interface HostConfig {
24
+ /** The iframe the app runs in. Only messages from its window are accepted. */
25
+ iframe: HTMLIFrameElement;
26
+ /** The app's exact origin, e.g. `https://app.example.com`. Messages from any other origin are ignored; `*` is refused. */
27
+ appOrigin: string;
28
+ handlers: Partial<HostHandlers>;
29
+ /** Sent to the app when it connects. */
30
+ info?: Partial<Omit<HostInfo, 'version'>>;
31
+ /** If set, the app's `ready` request must carry this API key. */
32
+ apiKey?: string;
33
+ /** Called with the reason whenever a message is ignored. For logging. */
34
+ onReject?: (reason: string, event: MessageEvent) => void;
35
+ }
36
+ export interface Host {
37
+ /** Sends an event to the app (e.g. `saveBar.save`, `theme.change`). Dropped until the app has connected. */
38
+ send<T extends EventType>(type: T, payload: EventMap[T]): void;
39
+ /** True once the app has connected with `ready`. */
40
+ readonly connected: boolean;
41
+ destroy(): void;
42
+ }
43
+ /**
44
+ * True for a path that stays inside the app: starts with one `/`, has no `\\` (browsers read `/\\host` as
45
+ * `//host`) and no control characters, and resolves to the same origin as its base.
46
+ */
47
+ export declare function isAppPath(v: unknown): v is string;
48
+ /** Returns an error message if the payload is wrong for its type, else null. */
49
+ export declare function validatePayload(type: RequestType, p: Record<string, unknown>): string | null;
50
+ /** Admin side: answers App Bridge requests from the app in `iframe`. */
51
+ export declare function createHost(config: HostConfig): Host;
52
+ export {};