@symbo.ls/utils 3.14.782 → 3.14.783
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/dist/cjs/sharedLibraries.js +4 -1
- package/dist/esm/sharedLibraries.js +4 -1
- package/package.json +1 -1
- package/sharedLibraries.js +413 -3
|
@@ -1 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var L=Object.defineProperty;var ne=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var se=Object.prototype.hasOwnProperty;var re=(e,t)=>{for(var o in t)L(e,o,{get:t[o],enumerable:!0})},ie=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of oe(t))!se.call(e,s)&&s!==o&&L(e,s,{get:()=>t[s],enumerable:!(n=ne(t,s))||n.enumerable});return e};var ce=e=>ie(L({},"__esModule",{value:!0}),e);var Je={};re(Je,{LIBRARY_SCOPES_KEY:()=>S,__resetBuiltinMethodWarnings:()=>de,bindLibraryGlobalScopes:()=>Pe,deepDefaults:()=>w,fetchLibraryData:()=>te,isWrappedLibrary:()=>O,mergeSharedLibraries:()=>De,mergeSharedLibraryDesignSystems:()=>Ye,normalizeIgnoreList:()=>I,normalizeLibraryKey:()=>g,resolveSharedLibraries:()=>ze,sharedLibrary:()=>ye});module.exports=ce(Je);var l=require("./types.js"),_=require("./keys.js"),ee=require("./env.js"),d=require("./object.js");const $="system",ae="https://smbls-kv.nika-980.workers.dev",le="https://api.symbols.app";function g(e){const t=String(e||"").trim();if(!t)return{owner:$,key:"",full:""};let o=null,n=t;if(t.includes("/")){const i=t.indexOf("/");o=t.slice(0,i),n=t.slice(i+1)}n=n.replace(/\.symbo\.ls$/iu,""),o||(o=$);const s=n?`${o}/${n}`:"";return{owner:o,key:n,full:s}}const w=(e,t,o,n)=>{for(const s in t){const i=n?`${n}/${s}`:s;o&&o.has(i)||(s in e?(0,l.isObject)(e[s])&&(0,l.isObject)(t[s])&&w(e[s],t[s],o,i):e[s]=t[s])}},P=(e,t,o)=>{if(!(0,l.isObject)(e)||!t.size)return e;const n=`${o}/`;let s=!1;for(const c of t)if(c.startsWith(n)){s=!0;break}if(!s)return e;const i={};for(const c in e){if(!Object.prototype.hasOwnProperty.call(e,c))continue;const r=`${o}/${c}`;t.has(r)||(i[c]=P(e[c],t,r))}return i},fe=new Set,ue=new Set(["components","pages","functions","snippets","methods"]),N=(e,t)=>t===""&&ue.has(e),M=["fontFamily","fontfamily","font_family","FONT_FAMILY"],C=e=>{const t=new Map;if(!(0,l.isObject)(e))return t;for(const o of M){const n=e[o];if((0,l.isObject)(n))for(const s in n)!(0,l.isObject)(n[s])||!n[s].isDefault||(t.has(o)||t.set(o,new Set),t.get(o).add(s))}return t},F=(e,t)=>{for(const o of M){const n=e[o];if(!(0,l.isObject)(n))continue;const s=t.get(o);let i=null;for(const c in n){const r=n[c];if(!(0,l.isObject)(r)||!r.isDefault||s&&s.has(c))continue;const a={...r};delete a.isDefault,i||(i={...n}),i[c]=a}i&&(e[o]=i)}},pe=e=>e.replace(/\.js$/iu,""),I=e=>{const t=new Set;if(!Array.isArray(e))return t;for(const o of e){if(!(0,l.isString)(o))continue;const n=o.split("/").map(s=>pe(s.trim())).filter(Boolean).join("/");n&&t.add(n)}return t},ye=(e,t={})=>({library:e,ignoreList:Array.isArray(t.ignoreList)?t.ignoreList:[]}),O=e=>(0,l.isObject)(e)&&Array.isArray(e.ignoreList)&&("library"in e||"key"in e||"name"in e),V=e=>e.library!==void 0?e.library:e.key??e.name,A=new Set,de=()=>{A.clear()},he=(e,t)=>{const o=t.filter(n=>!A.has(n));if(o.length){for(const n of o)A.add(n);(0,ee.isLoudDevRuntime)()&&console.warn(`[smbls] shared library "${e}" ships ${o.map(n=>`methods.${n}`).join(", ")} \u2014 named like a built-in element method. Refused: the built-in wins; a library cannot replace an element method on the consuming app. If the app wants this version, declare it in the app's OWN methods.`)}},be=(e,t,o)=>{let n=null;for(const s in e)if((0,_.isProtectedElementMethod)(s)&&(t.has(`methods/${s}`)||o.push(s),!n)){n={};for(const i in e)(0,_.isProtectedElementMethod)(i)||(n[i]=e[i])}return n||e},U=(e,t)=>{const o=I(e.sharedLibIgnore);return e.sharePages===!1&&o.add("pages"),o.size?new Set([...t,...o]):t},R=["functions","methods","snippets"],D=["components","pages"],Y=Symbol.for("smbls.libraryScope"),S="__libraryScopes",W=new Map,me=()=>Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4),b=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),ge=/const __scope = |const __peers_* = |const _s = el\?\.scope|\?\.context\?\.globalScope\?\./,z=e=>{try{return(0,d.getFunctionSource)(e)}catch{return null}},J=e=>{if(typeof e!="function")return null;const t=z(e);return(0,l.isString)(t)&&ge.test(t)&&(0,d.hasFunction)(t)?t:null},G=e=>(0,l.isString)(e)&&(0,d.hasFunction)(e)||J(e)!==null,Se=e=>{const t=e.globalScope;return(0,l.isObject)(t)&&Object.keys(t).some(o=>G(t[o]))?!0:R.some(o=>{const n=e[o];return!!n&&typeof n=="object"&&Object.keys(n).some(s=>G(n[s]))})},ke=(e,t,o)=>{const n=e.globalScope,s=t.globalScope;if(o.has("globalScope")||!(0,l.isObject)(n)||!(0,l.isObject)(s)||!Se(t))return 0;let i=0;for(const c of Object.keys(s))o.has(`globalScope/${c}`)||b(n,c)&&i++;return i},_e=[[/const __scope = (\(\(\) => \{ const r = [\s\S]*?\}\)\(\));/g,"const __scope = $RESOLVE($1);"],[/const __scope = this \?\? \{\};/g,"const __scope = $RESOLVE(this ?? {});"],[/const (__peers_*) = (this && this !== globalThis && this\.context && this\.context\.globalScope \? this\.scope \?\? this\.context\.globalScope : this);/g,"const $1 = $RESOLVE($2);"],[/const _s = (el\?\.scope \?\? el\?\.context\?\.globalScope \?\? \{\});/g,"const _s = $RESOLVE($1);"],[/(?<![\w$.])(this|[A-Za-z_$][\w$]*)\?\.context\?\.globalScope\?\./g,"$RESOLVE($1?.context?.globalScope)?."]],we=e=>{const t=e.split(""),o=[];let n=0,s=0;const i=(r,a)=>{for(let u=r;u<a;u++)t[u]!==`
|
|
2
|
+
`&&(t[u]="~")},c=()=>{const r=n;for(;n<e.length;){const a=e[n];if(a==="\\"){n+=2;continue}if(a==="`"){i(r,n),n++;return}if(a==="$"&&e[n+1]==="{"){i(r,n),n+=2,o.push(s),s++;return}n++}i(r,n)};for(;n<e.length;){const r=e[n];if(r==="/"&&e[n+1]==="/"){const a=e.indexOf(`
|
|
3
|
+
`,n),u=a===-1?e.length:a;i(n,u),n=u;continue}if(r==="/"&&e[n+1]==="*"){const a=e.indexOf("*/",n+2),u=a===-1?e.length:a+2;i(n,u),n=u;continue}if(r==='"'||r==="'"){const a=r,u=++n;for(;n<e.length&&e[n]!==a&&e[n]!==`
|
|
4
|
+
`;)e[n]==="\\"&&n++,n++;i(u,n),n++;continue}if(r==="`"){n++,c();continue}if(r==="{"){s++,n++;continue}if(r==="}"){if(s--,o.length&&s===o[o.length-1]){o.pop(),n++,c();continue}n++;continue}n++}return t.join("")},K=(e,t)=>{if(!(0,l.isString)(e)||!e.includes("__scope = ")&&!e.includes("__peers")&&!e.includes("const _s = ")&&!e.includes("?.context?.globalScope?.")||!(0,d.hasFunction)(e))return e;const o=`(globalThis[Symbol.for('smbls.libraryScope')] || ((_, v) => v))(${JSON.stringify(t)}, `;let n=e;for(const[s,i]of _e){const c=we(n);n=n.replace(s,(...r)=>{const a=r[r.length-2];return c[a]==="~"||c[a]!==n[a]?r[0]:i.replace(/\$RESOLVE\(/g,o).replace(/\$(\d)/g,(u,f)=>r[Number(f)])})}return n},k=(e,t)=>{if((0,l.isString)(e))return K(e,t);const o=J(e);return o===null?e:K(o,t)},Oe={lazy:!0,window:globalThis},q=(e,t)=>{const o=k(e,t);if(o===e||!(0,l.isString)(o))return o;try{const n=(0,d.deepDestringifyFunctions)({v:o},{},Oe).v;return typeof n!="function"?o:(Object.defineProperty(n,"toJSON",{value:()=>o,configurable:!0}),n)}catch{return o}},E=e=>{if(!e||typeof e!="object")return!1;if(Array.isArray(e))return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},H=(e,t,o=new WeakMap)=>{if((0,l.isString)(e)||typeof e=="function")return q(e,t);if((0,d.isStringTag)(e)||!E(e))return e;if(o.has(e))return o.get(e);const n=Array.isArray(e)?[]:Object.getPrototypeOf(e)===null?Object.create(null):{};o.set(e,n);for(const s of Object.keys(e))n[s]=H(e[s],t,o);return n},Le=(e,t)=>{const o={...e},n={};for(const s of Object.keys(e.globalScope))n[s]=k(e.globalScope[s],t);o.globalScope=n;for(const s of R){const i=e[s];if(!E(i))continue;const c={};for(const r of Object.keys(i))c[r]=q(i[r],t);o[s]=c}for(const s of D)E(e[s])&&(o[s]=H(e[s],t));return o},Z=new WeakMap,$e=(e,t,o)=>{let n=Z.get(e);n||Z.set(e,n=new Map);let s=n.get(t);if(s)return s;const i=(c,r)=>b(o,c)&&o[c]===r;return s=new Proxy(e,{get(c,r){if(typeof r=="symbol"||b(c,r))return Reflect.get(c,r);const a=Reflect.get(c,r);return b(t,r)&&(a===void 0||i(r,a))||a===void 0?t[r]:a},set(c,r,a){return typeof r!="symbol"&&!b(c,r)&&b(t,r)?(t[r]=a,!0):Reflect.set(c,r,a)},has:(c,r)=>Reflect.has(c,r)||r in t}),n.set(t,s),s},Ae=e=>!!e&&typeof e=="object"&&!!e.__raw&&typeof e.__raw=="object",Re=(e,t)=>{const o=W.get(e);return o?t===o.consumerGs?o.libGs:Ae(t)?$e(t,o.libGs,o.consumerGs):t:t},Ee=()=>{typeof globalThis[Y]!="function"&&Object.defineProperty(globalThis,Y,{value:Re,configurable:!0})},j=e=>{const t=e[S];return Array.isArray(t)?t:null},je=e=>O(e)?e.library:e,Ie=(e,t,o)=>{const n=j(e);return!!n&&n.some(s=>s&&s.index===t&&(!s.key||s.key===o.key)&&(0,l.isString)(s.id)&&Te(e,s.id))},Te=(e,t)=>{const o=JSON.stringify(t),n=new Set,s=i=>{if((0,l.isString)(i))return i.includes(o);if(!i||typeof i!="object"||n.has(i))return!1;n.add(i);for(const c in i)if(s(i[c]))return!0;return!1};for(const i of["globalScope",...R,...D])if(s(e[i]))return!0;return!1},Be=(e,t)=>{const o={};for(const n of Object.keys(e))o[n]=k(e[n],t);return o},Q=new WeakMap,Pe=(e,t=null)=>{const o=e&&j(e);if(!o||!o.length)return 0;const n=e.globalScope;if(!(0,l.isObject)(n))return 0;const s=Array.isArray(e.sharedLibraries)?e.sharedLibraries:[];let i=Q.get(n);i||Q.set(n,i=new Set),Ee();let c=0;for(const r of o){if(!r||!(0,l.isString)(r.id)||i.has(r.id))continue;const a=je(s[r.index]);if(!a||!(0,l.isObject)(a.globalScope)||r.key&&a.key!==r.key)continue;const u=y=>typeof y=="function"?z(y):y,f=(y,m)=>{if(y===m)return!0;const T=u(y),B=u(m);return(0,l.isString)(T)||(0,l.isString)(B)?T===B:JSON.stringify(y)===JSON.stringify(m)},p=(0,l.isObject)(t)?(Array.isArray(r.landed)?r.landed:[]).filter(y=>(0,l.isString)(y)&&b(a.globalScope,y)&&b(t,y)&&f(t[y],k(a.globalScope[y],r.id))):[],h=(0,d.destringifyGlobalScope)(Be(a.globalScope,r.id));Object.setPrototypeOf(h,n),W.set(r.id,{libGs:h,consumerGs:n});for(const y of p)n[y]=h[y];i.add(r.id),c++}return c},Ne=(e,t,o,n="library",s=-1)=>{const i=U(t,o),c=!Ie(e,s,t)&&ke(e,t,i)>0?`${n}#${me()}`:null,r=c?Le(t,c):t,a=c?new Set(Object.keys(e.globalScope)):null,u=[];for(const f in r)if(Object.prototype.hasOwnProperty.call(r,f)&&!(f==="sharePages"||f==="sharedLibIgnore")&&f!==S&&!f.startsWith("__")&&f!=="app"&&!i.has(f)){if((0,l.isObject)(r[f])&&(0,l.isObject)(e[f])){if(f==="designSystem")w(e[f],r[f],i,f);else for(const p in r[f])if(!i.has(`${f}/${p}`)){if(f==="methods"&&(0,_.isProtectedElementMethod)(p)){p in e[f]||u.push(p);continue}p in e[f]?N(f,e[f][p])&&!N(f,r[f][p])&&(e[f][p]=r[f][p]):e[f][p]=r[f][p]}}else if(!(f in e)){const p=r[f],h=f==="methods"&&p&&typeof p=="object"?be(p,i,u):p;e[f]=P(h,i,f)}}c&&(j(e)||(e[S]=[]),e[S].push({id:c,index:s,key:(0,l.isString)(t.key)?t.key:null,landed:Object.keys(r.globalScope).filter(f=>!a.has(f))})),u.length&&he(n,u)},Me=(e,t,o)=>{if(e!==t){const n=V(e);if((0,l.isString)(n)&&n)return n;if(e.key||e.name)return e.key||e.name}return t&&(t.key||t.name)||`sharedLibraries[${o}]`},Ce=`${$}/default`,Fe=e=>(0,l.isString)(e)&&e!==""&&g(e).full===Ce,Ve=(e,t)=>{if((0,l.isString)(t.key)&&t.key)return t.key;if(e!==t){if((0,l.isString)(e.key)&&e.key)return e.key;if((0,l.isString)(e.name)&&e.name)return e.name}return null},Ue=e=>{const t=[],o=[];for(let n=0;n<e.length;n++){const s=e[n];let i=s,c=fe;if(O(i)&&(c=I(i.ignoreList),i=i.library),!(0,l.isObject)(i))continue;const r={entry:s,lib:i,ignore:c,index:n};Fe(Ve(s,i))?o.push(r):t.push(r)}return{linked:t,bases:o}},X=(e,t,o)=>{const n=C(t()),{linked:s,bases:i}=Ue(e);for(const r of s)o(r);const c=!n.size&&i.length?C(t()):null;for(const r of i)o(r);return n.size?n:c&&c.size?c:null},De=(e,t)=>{if(!t||!t.length)return;const o=e.designSystem,n=X(t,()=>e.designSystem,({entry:s,lib:i,ignore:c,index:r})=>Ne(e,i,c,Me(s,i,r),r));n&&(e.designSystem!==o&&(e.designSystem={...e.designSystem}),F(e.designSystem,n))},Ye=(e,t,o=w)=>{if(!(0,l.isObject)(e)||!Array.isArray(t)||!t.length)return e;const n=X(t,()=>e,({lib:s,ignore:i})=>{const c=s.designSystem;if(!c||typeof c!="object")return;const r=U(s,i);r.has("designSystem")||o(e,c,r,"designSystem")});return n&&F(e,n),e};async function te(e,t={}){if((t.provider||"kv")==="api")return x(e,t);const n=await We(e,t);return n||x(e,t)}async function We(e,t={}){const o=t.kvBaseUrl||ae,n=t.env||"production",s=`${o}/kv/${encodeURIComponent(e)}?env=${n}`;try{const i=await fetch(s,{method:"GET"});return i.ok&&(await i.json())?.value||null}catch{return null}}async function x(e,t={}){const o=t.apiBaseUrl||le,{key:n}=g(e);try{const s=`${o}/core/projects/libraries/available?search=${encodeURIComponent(n)}&limit=10`,i=await fetch(s,{method:"GET"});if(!i.ok)return null;const c=await i.json(),a=(c?.items||c?.data||(Array.isArray(c)?c:[])).find(y=>{const{key:m}=g(y?.key);return m.toLowerCase()===n.toLowerCase()});if(!a?.id&&!a?._id)return null;const u=a.id||a._id,f=`${o}/core/projects/${encodeURIComponent(u)}/data?branch=main`,p=await fetch(f,{method:"GET"});if(!p.ok)return null;const h=await p.json();return h?.data||h||null}catch{return null}}async function v(e,t={}){if((0,l.isObject)(e))return e;if((0,l.isString)(e)){const{full:o}=g(e);if(!o)return null;try{const n=await te(o,t);return n||console.warn(`[smbls] Shared library "${o}" not found`),n}catch(n){return console.warn(`[smbls] Failed to fetch shared library "${o}":`,n.message),null}}return null}async function ze(e,t={}){return!e||!e.length?[]:(await Promise.all(e.map(async n=>{if(O(n)){const s=await v(V(n),t);return s?{library:s,ignoreList:n.ignoreList}:null}return v(n,t)}))).filter(Boolean)}
|
|
@@ -1 +1,4 @@
|
|
|
1
|
-
import{isObject as
|
|
1
|
+
import{isObject as p,isString as y}from"./types.js";import{isProtectedElementMethod as _}from"./keys.js";import{isLoudDevRuntime as ee}from"./env.js";import{destringifyGlobalScope as te,hasFunction as w,getFunctionSource as ne,deepDestringifyFunctions as oe,isStringTag as se}from"./object.js";const O="system",re="https://smbls-kv.nika-980.workers.dev",ie="https://api.symbols.app";function g(e){const n=String(e||"").trim();if(!n)return{owner:O,key:"",full:""};let o=null,t=n;if(n.includes("/")){const i=n.indexOf("/");o=n.slice(0,i),t=n.slice(i+1)}t=t.replace(/\.symbo\.ls$/iu,""),o||(o=O);const s=t?`${o}/${t}`:"";return{owner:o,key:t,full:s}}const L=(e,n,o,t)=>{for(const s in n){const i=t?`${t}/${s}`:s;o&&o.has(i)||(s in e?p(e[s])&&p(n[s])&&L(e[s],n[s],o,i):e[s]=n[s])}},B=(e,n,o)=>{if(!p(e)||!n.size)return e;const t=`${o}/`;let s=!1;for(const c of n)if(c.startsWith(t)){s=!0;break}if(!s)return e;const i={};for(const c in e){if(!Object.prototype.hasOwnProperty.call(e,c))continue;const r=`${o}/${c}`;n.has(r)||(i[c]=B(e[c],n,r))}return i},ce=new Set,ae=new Set(["components","pages","functions","snippets","methods"]),P=(e,n)=>n===""&&ae.has(e),N=["fontFamily","fontfamily","font_family","FONT_FAMILY"],M=e=>{const n=new Map;if(!p(e))return n;for(const o of N){const t=e[o];if(p(t))for(const s in t)!p(t[s])||!t[s].isDefault||(n.has(o)||n.set(o,new Set),n.get(o).add(s))}return n},C=(e,n)=>{for(const o of N){const t=e[o];if(!p(t))continue;const s=n.get(o);let i=null;for(const c in t){const r=t[c];if(!p(r)||!r.isDefault||s&&s.has(c))continue;const a={...r};delete a.isDefault,i||(i={...t}),i[c]=a}i&&(e[o]=i)}},le=e=>e.replace(/\.js$/iu,""),F=e=>{const n=new Set;if(!Array.isArray(e))return n;for(const o of e){if(!y(o))continue;const t=o.split("/").map(s=>le(s.trim())).filter(Boolean).join("/");t&&n.add(t)}return n},De=(e,n={})=>({library:e,ignoreList:Array.isArray(n.ignoreList)?n.ignoreList:[]}),$=e=>p(e)&&Array.isArray(e.ignoreList)&&("library"in e||"key"in e||"name"in e),V=e=>e.library!==void 0?e.library:e.key??e.name,A=new Set,Ye=()=>{A.clear()},fe=(e,n)=>{const o=n.filter(t=>!A.has(t));if(o.length){for(const t of o)A.add(t);ee()&&console.warn(`[smbls] shared library "${e}" ships ${o.map(t=>`methods.${t}`).join(", ")} \u2014 named like a built-in element method. Refused: the built-in wins; a library cannot replace an element method on the consuming app. If the app wants this version, declare it in the app's OWN methods.`)}},ue=(e,n,o)=>{let t=null;for(const s in e)if(_(s)&&(n.has(`methods/${s}`)||o.push(s),!t)){t={};for(const i in e)_(i)||(t[i]=e[i])}return t||e},U=(e,n)=>{const o=F(e.sharedLibIgnore);return e.sharePages===!1&&o.add("pages"),o.size?new Set([...n,...o]):n},R=["functions","methods","snippets"],D=["components","pages"],Y=Symbol.for("smbls.libraryScope"),S="__libraryScopes",W=new Map,pe=()=>Math.random().toString(36).slice(2,10)+Date.now().toString(36).slice(-4),b=(e,n)=>Object.prototype.hasOwnProperty.call(e,n),ye=/const __scope = |const __peers_* = |const _s = el\?\.scope|\?\.context\?\.globalScope\?\./,z=e=>{try{return ne(e)}catch{return null}},J=e=>{if(typeof e!="function")return null;const n=z(e);return y(n)&&ye.test(n)&&w(n)?n:null},G=e=>y(e)&&w(e)||J(e)!==null,de=e=>{const n=e.globalScope;return p(n)&&Object.keys(n).some(o=>G(n[o]))?!0:R.some(o=>{const t=e[o];return!!t&&typeof t=="object"&&Object.keys(t).some(s=>G(t[s]))})},he=(e,n,o)=>{const t=e.globalScope,s=n.globalScope;if(o.has("globalScope")||!p(t)||!p(s)||!de(n))return 0;let i=0;for(const c of Object.keys(s))o.has(`globalScope/${c}`)||b(t,c)&&i++;return i},be=[[/const __scope = (\(\(\) => \{ const r = [\s\S]*?\}\)\(\));/g,"const __scope = $RESOLVE($1);"],[/const __scope = this \?\? \{\};/g,"const __scope = $RESOLVE(this ?? {});"],[/const (__peers_*) = (this && this !== globalThis && this\.context && this\.context\.globalScope \? this\.scope \?\? this\.context\.globalScope : this);/g,"const $1 = $RESOLVE($2);"],[/const _s = (el\?\.scope \?\? el\?\.context\?\.globalScope \?\? \{\});/g,"const _s = $RESOLVE($1);"],[/(?<![\w$.])(this|[A-Za-z_$][\w$]*)\?\.context\?\.globalScope\?\./g,"$RESOLVE($1?.context?.globalScope)?."]],me=e=>{const n=e.split(""),o=[];let t=0,s=0;const i=(r,a)=>{for(let f=r;f<a;f++)n[f]!==`
|
|
2
|
+
`&&(n[f]="~")},c=()=>{const r=t;for(;t<e.length;){const a=e[t];if(a==="\\"){t+=2;continue}if(a==="`"){i(r,t),t++;return}if(a==="$"&&e[t+1]==="{"){i(r,t),t+=2,o.push(s),s++;return}t++}i(r,t)};for(;t<e.length;){const r=e[t];if(r==="/"&&e[t+1]==="/"){const a=e.indexOf(`
|
|
3
|
+
`,t),f=a===-1?e.length:a;i(t,f),t=f;continue}if(r==="/"&&e[t+1]==="*"){const a=e.indexOf("*/",t+2),f=a===-1?e.length:a+2;i(t,f),t=f;continue}if(r==='"'||r==="'"){const a=r,f=++t;for(;t<e.length&&e[t]!==a&&e[t]!==`
|
|
4
|
+
`;)e[t]==="\\"&&t++,t++;i(f,t),t++;continue}if(r==="`"){t++,c();continue}if(r==="{"){s++,t++;continue}if(r==="}"){if(s--,o.length&&s===o[o.length-1]){o.pop(),t++,c();continue}t++;continue}t++}return n.join("")},K=(e,n)=>{if(!y(e)||!e.includes("__scope = ")&&!e.includes("__peers")&&!e.includes("const _s = ")&&!e.includes("?.context?.globalScope?.")||!w(e))return e;const o=`(globalThis[Symbol.for('smbls.libraryScope')] || ((_, v) => v))(${JSON.stringify(n)}, `;let t=e;for(const[s,i]of be){const c=me(t);t=t.replace(s,(...r)=>{const a=r[r.length-2];return c[a]==="~"||c[a]!==t[a]?r[0]:i.replace(/\$RESOLVE\(/g,o).replace(/\$(\d)/g,(f,l)=>r[Number(l)])})}return t},k=(e,n)=>{if(y(e))return K(e,n);const o=J(e);return o===null?e:K(o,n)},ge={lazy:!0,window:globalThis},q=(e,n)=>{const o=k(e,n);if(o===e||!y(o))return o;try{const t=oe({v:o},{},ge).v;return typeof t!="function"?o:(Object.defineProperty(t,"toJSON",{value:()=>o,configurable:!0}),t)}catch{return o}},E=e=>{if(!e||typeof e!="object")return!1;if(Array.isArray(e))return!0;const n=Object.getPrototypeOf(e);return n===Object.prototype||n===null},H=(e,n,o=new WeakMap)=>{if(y(e)||typeof e=="function")return q(e,n);if(se(e)||!E(e))return e;if(o.has(e))return o.get(e);const t=Array.isArray(e)?[]:Object.getPrototypeOf(e)===null?Object.create(null):{};o.set(e,t);for(const s of Object.keys(e))t[s]=H(e[s],n,o);return t},Se=(e,n)=>{const o={...e},t={};for(const s of Object.keys(e.globalScope))t[s]=k(e.globalScope[s],n);o.globalScope=t;for(const s of R){const i=e[s];if(!E(i))continue;const c={};for(const r of Object.keys(i))c[r]=q(i[r],n);o[s]=c}for(const s of D)E(e[s])&&(o[s]=H(e[s],n));return o},Z=new WeakMap,ke=(e,n,o)=>{let t=Z.get(e);t||Z.set(e,t=new Map);let s=t.get(n);if(s)return s;const i=(c,r)=>b(o,c)&&o[c]===r;return s=new Proxy(e,{get(c,r){if(typeof r=="symbol"||b(c,r))return Reflect.get(c,r);const a=Reflect.get(c,r);return b(n,r)&&(a===void 0||i(r,a))||a===void 0?n[r]:a},set(c,r,a){return typeof r!="symbol"&&!b(c,r)&&b(n,r)?(n[r]=a,!0):Reflect.set(c,r,a)},has:(c,r)=>Reflect.has(c,r)||r in n}),t.set(n,s),s},_e=e=>!!e&&typeof e=="object"&&!!e.__raw&&typeof e.__raw=="object",we=(e,n)=>{const o=W.get(e);return o?n===o.consumerGs?o.libGs:_e(n)?ke(n,o.libGs,o.consumerGs):n:n},Oe=()=>{typeof globalThis[Y]!="function"&&Object.defineProperty(globalThis,Y,{value:we,configurable:!0})},j=e=>{const n=e[S];return Array.isArray(n)?n:null},Le=e=>$(e)?e.library:e,$e=(e,n,o)=>{const t=j(e);return!!t&&t.some(s=>s&&s.index===n&&(!s.key||s.key===o.key)&&y(s.id)&&Ae(e,s.id))},Ae=(e,n)=>{const o=JSON.stringify(n),t=new Set,s=i=>{if(y(i))return i.includes(o);if(!i||typeof i!="object"||t.has(i))return!1;t.add(i);for(const c in i)if(s(i[c]))return!0;return!1};for(const i of["globalScope",...R,...D])if(s(e[i]))return!0;return!1},Re=(e,n)=>{const o={};for(const t of Object.keys(e))o[t]=k(e[t],n);return o},Q=new WeakMap,We=(e,n=null)=>{const o=e&&j(e);if(!o||!o.length)return 0;const t=e.globalScope;if(!p(t))return 0;const s=Array.isArray(e.sharedLibraries)?e.sharedLibraries:[];let i=Q.get(t);i||Q.set(t,i=new Set),Oe();let c=0;for(const r of o){if(!r||!y(r.id)||i.has(r.id))continue;const a=Le(s[r.index]);if(!a||!p(a.globalScope)||r.key&&a.key!==r.key)continue;const f=d=>typeof d=="function"?z(d):d,l=(d,m)=>{if(d===m)return!0;const I=f(d),T=f(m);return y(I)||y(T)?I===T:JSON.stringify(d)===JSON.stringify(m)},u=p(n)?(Array.isArray(r.landed)?r.landed:[]).filter(d=>y(d)&&b(a.globalScope,d)&&b(n,d)&&l(n[d],k(a.globalScope[d],r.id))):[],h=te(Re(a.globalScope,r.id));Object.setPrototypeOf(h,t),W.set(r.id,{libGs:h,consumerGs:t});for(const d of u)t[d]=h[d];i.add(r.id),c++}return c},Ee=(e,n,o,t="library",s=-1)=>{const i=U(n,o),c=!$e(e,s,n)&&he(e,n,i)>0?`${t}#${pe()}`:null,r=c?Se(n,c):n,a=c?new Set(Object.keys(e.globalScope)):null,f=[];for(const l in r)if(Object.prototype.hasOwnProperty.call(r,l)&&!(l==="sharePages"||l==="sharedLibIgnore")&&l!==S&&!l.startsWith("__")&&l!=="app"&&!i.has(l)){if(p(r[l])&&p(e[l])){if(l==="designSystem")L(e[l],r[l],i,l);else for(const u in r[l])if(!i.has(`${l}/${u}`)){if(l==="methods"&&_(u)){u in e[l]||f.push(u);continue}u in e[l]?P(l,e[l][u])&&!P(l,r[l][u])&&(e[l][u]=r[l][u]):e[l][u]=r[l][u]}}else if(!(l in e)){const u=r[l],h=l==="methods"&&u&&typeof u=="object"?ue(u,i,f):u;e[l]=B(h,i,l)}}c&&(j(e)||(e[S]=[]),e[S].push({id:c,index:s,key:y(n.key)?n.key:null,landed:Object.keys(r.globalScope).filter(l=>!a.has(l))})),f.length&&fe(t,f)},je=(e,n,o)=>{if(e!==n){const t=V(e);if(y(t)&&t)return t;if(e.key||e.name)return e.key||e.name}return n&&(n.key||n.name)||`sharedLibraries[${o}]`},Ie=`${O}/default`,Te=e=>y(e)&&e!==""&&g(e).full===Ie,Be=(e,n)=>{if(y(n.key)&&n.key)return n.key;if(e!==n){if(y(e.key)&&e.key)return e.key;if(y(e.name)&&e.name)return e.name}return null},Pe=e=>{const n=[],o=[];for(let t=0;t<e.length;t++){const s=e[t];let i=s,c=ce;if($(i)&&(c=F(i.ignoreList),i=i.library),!p(i))continue;const r={entry:s,lib:i,ignore:c,index:t};Te(Be(s,i))?o.push(r):n.push(r)}return{linked:n,bases:o}},X=(e,n,o)=>{const t=M(n()),{linked:s,bases:i}=Pe(e);for(const r of s)o(r);const c=!t.size&&i.length?M(n()):null;for(const r of i)o(r);return t.size?t:c&&c.size?c:null},ze=(e,n)=>{if(!n||!n.length)return;const o=e.designSystem,t=X(n,()=>e.designSystem,({entry:s,lib:i,ignore:c,index:r})=>Ee(e,i,c,je(s,i,r),r));t&&(e.designSystem!==o&&(e.designSystem={...e.designSystem}),C(e.designSystem,t))},Je=(e,n,o=L)=>{if(!p(e)||!Array.isArray(n)||!n.length)return e;const t=X(n,()=>e,({lib:s,ignore:i})=>{const c=s.designSystem;if(!c||typeof c!="object")return;const r=U(s,i);r.has("designSystem")||o(e,c,r,"designSystem")});return t&&C(e,t),e};async function Ne(e,n={}){if((n.provider||"kv")==="api")return x(e,n);const t=await Me(e,n);return t||x(e,n)}async function Me(e,n={}){const o=n.kvBaseUrl||re,t=n.env||"production",s=`${o}/kv/${encodeURIComponent(e)}?env=${t}`;try{const i=await fetch(s,{method:"GET"});return i.ok&&(await i.json())?.value||null}catch{return null}}async function x(e,n={}){const o=n.apiBaseUrl||ie,{key:t}=g(e);try{const s=`${o}/core/projects/libraries/available?search=${encodeURIComponent(t)}&limit=10`,i=await fetch(s,{method:"GET"});if(!i.ok)return null;const c=await i.json(),a=(c?.items||c?.data||(Array.isArray(c)?c:[])).find(d=>{const{key:m}=g(d?.key);return m.toLowerCase()===t.toLowerCase()});if(!a?.id&&!a?._id)return null;const f=a.id||a._id,l=`${o}/core/projects/${encodeURIComponent(f)}/data?branch=main`,u=await fetch(l,{method:"GET"});if(!u.ok)return null;const h=await u.json();return h?.data||h||null}catch{return null}}async function v(e,n={}){if(p(e))return e;if(y(e)){const{full:o}=g(e);if(!o)return null;try{const t=await Ne(o,n);return t||console.warn(`[smbls] Shared library "${o}" not found`),t}catch(t){return console.warn(`[smbls] Failed to fetch shared library "${o}":`,t.message),null}}return null}async function Ge(e,n={}){return!e||!e.length?[]:(await Promise.all(e.map(async t=>{if($(t)){const s=await v(V(t),n);return s?{library:s,ignoreList:t.ignoreList}:null}return v(t,n)}))).filter(Boolean)}export{S as LIBRARY_SCOPES_KEY,Ye as __resetBuiltinMethodWarnings,We as bindLibraryGlobalScopes,L as deepDefaults,Ne as fetchLibraryData,$ as isWrappedLibrary,ze as mergeSharedLibraries,Je as mergeSharedLibraryDesignSystems,F as normalizeIgnoreList,g as normalizeLibraryKey,Ge as resolveSharedLibraries,De as sharedLibrary};
|
package/package.json
CHANGED
package/sharedLibraries.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { isObject, isString } from './types.js'
|
|
4
4
|
import { isProtectedElementMethod } from './keys.js'
|
|
5
5
|
import { isLoudDevRuntime } from './env.js'
|
|
6
|
+
import { destringifyGlobalScope, hasFunction, getFunctionSource, deepDestringifyFunctions, isStringTag } from './object.js'
|
|
6
7
|
|
|
7
8
|
const DEFAULT_LIBRARY_OWNER = 'system'
|
|
8
9
|
|
|
@@ -354,13 +355,413 @@ const librarySkip = (sharedLib, ignore) => {
|
|
|
354
355
|
: ignore
|
|
355
356
|
}
|
|
356
357
|
|
|
357
|
-
|
|
358
|
-
|
|
358
|
+
// ── one globalScope per library ───────────────────────────────────────────
|
|
359
|
+
//
|
|
360
|
+
// frank emits each project's free variables into ONE flat globalScope: every
|
|
361
|
+
// library carries its own mutable-let holder `Smut`, and a minified helper
|
|
362
|
+
// (symbolize-core's `s2`) lands under the same short name in each library that
|
|
363
|
+
// inlines it, meaning something different in each. The add-missing merge
|
|
364
|
+
// below is first-wins, so such a name in a library resolved to the consumer's
|
|
365
|
+
// (or an earlier library's) — and the library's own code, which finds its
|
|
366
|
+
// peers through `this.scope ?? this.context.globalScope` (the CONSUMER's
|
|
367
|
+
// element), read the consumer's `Smut` and called the consumer's `s2`.
|
|
368
|
+
//
|
|
369
|
+
// A library whose EMITTED globalScope shares ANY name with what the context
|
|
370
|
+
// already holds — even byte-identical text: two `Smut` IIFEs are two
|
|
371
|
+
// containers — keeps its own globalScope. Its emitted code is not wrapped and
|
|
372
|
+
// its `this` is never replaced: the only change is to the statement frank
|
|
373
|
+
// emits to FIND the peers (the four shapes below — scopeRewriter
|
|
374
|
+
// buildScopeDecl and the toJSON peer rewrite). That statement's value passes
|
|
375
|
+
// through the library's scope resolver, which answers the consumer's
|
|
376
|
+
// globalScope (or a scope store chained to it) with the library's own. The
|
|
377
|
+
// element, `this`, and anything handed to consumer code stay the real ones.
|
|
378
|
+
// Libraries without a shared name, names a library does not define, and
|
|
379
|
+
// libraries bundled from source (real values, no emitted text) are merged
|
|
380
|
+
// exactly as before.
|
|
381
|
+
const LIBRARY_FUNCTION_BAGS = ['functions', 'methods', 'snippets']
|
|
382
|
+
const LIBRARY_DEFINITION_BAGS = ['components', 'pages']
|
|
383
|
+
const LIBRARY_SCOPE = Symbol.for('smbls.libraryScope')
|
|
384
|
+
// The merge's record travels WITH the context data (`__libraryScopes`), so a
|
|
385
|
+
// merge done before the browser (smbls start / the runner, brender, any host
|
|
386
|
+
// that pre-merges with this function and serializes the result) is bound by
|
|
387
|
+
// the browser runtime exactly like a merge done in it: [{ id, index, key,
|
|
388
|
+
// landed }] — `index` into `context.sharedLibraries`, whose library payload
|
|
389
|
+
// the browser re-scopes with the same `id` (the payload is not copied).
|
|
390
|
+
export const LIBRARY_SCOPES_KEY = '__libraryScopes'
|
|
391
|
+
const libraryScopes = new Map() // id -> { libGs, consumerGs }
|
|
392
|
+
const scopeToken = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4)
|
|
393
|
+
|
|
394
|
+
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k)
|
|
395
|
+
|
|
396
|
+
// A library's EMITTED code — frank's output: a string, or a function revived
|
|
397
|
+
// from one (mermaid SSR deep-destringifies the payload; `smbls fetch` writes a
|
|
398
|
+
// library's payload to files that the runner / brender bundle). Emitted code
|
|
399
|
+
// carries one of frank's peer statements; a library bundled from its own
|
|
400
|
+
// SOURCE never does, keeps its real closures and never reads globalScope for
|
|
401
|
+
// its own names.
|
|
402
|
+
const PEER_STATEMENT_HINT = /const __scope = |const __peers_* = |const _s = el\?\.scope|\?\.context\?\.globalScope\?\./
|
|
403
|
+
// The SOURCE text of a function (a lazily revived one answers its stored
|
|
404
|
+
// source — Function.prototype.toString would read the wrapper).
|
|
405
|
+
const functionText = (v) => {
|
|
406
|
+
try {
|
|
407
|
+
return getFunctionSource(v)
|
|
408
|
+
} catch (_) {
|
|
409
|
+
return null
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
// Frank's emission revived to a function: its text holds a peer statement.
|
|
413
|
+
// A function without one (a library bundled from SOURCE, or a helper that
|
|
414
|
+
// needs no peers) keeps its closures and is never converted.
|
|
415
|
+
const emittedFunctionText = (v) => {
|
|
416
|
+
if (typeof v !== 'function') return null
|
|
417
|
+
const text = functionText(v)
|
|
418
|
+
return isString(text) && PEER_STATEMENT_HINT.test(text) && hasFunction(text) ? text : null
|
|
419
|
+
}
|
|
420
|
+
// Emitted CODE: function text as a string, or a function revived from it.
|
|
421
|
+
// A data string (a constant, copy) does not count.
|
|
422
|
+
const isEmittedValue = (v) => (isString(v) && hasFunction(v)) || emittedFunctionText(v) !== null
|
|
423
|
+
|
|
424
|
+
const libraryCarriesEmittedCode = (sharedLib) => {
|
|
425
|
+
const gs = sharedLib.globalScope
|
|
426
|
+
if (isObject(gs) && Object.keys(gs).some((k) => isEmittedValue(gs[k]))) return true
|
|
427
|
+
return LIBRARY_FUNCTION_BAGS.some((bag) => {
|
|
428
|
+
const b = sharedLib[bag]
|
|
429
|
+
return !!b && typeof b === 'object' && Object.keys(b).some((k) => isEmittedValue(b[k]))
|
|
430
|
+
})
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const sharedGlobalScopeNames = (context, sharedLib, skip) => {
|
|
434
|
+
const own = context.globalScope
|
|
435
|
+
const lib = sharedLib.globalScope
|
|
436
|
+
if (skip.has('globalScope') || !isObject(own) || !isObject(lib)) return 0
|
|
437
|
+
if (!libraryCarriesEmittedCode(sharedLib)) return 0
|
|
438
|
+
let n = 0
|
|
439
|
+
for (const k of Object.keys(lib)) {
|
|
440
|
+
if (skip.has(`globalScope/${k}`)) continue
|
|
441
|
+
if (hasOwn(own, k)) n++
|
|
442
|
+
}
|
|
443
|
+
return n
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// The peer-finding statements frank emits, exactly. Only their VALUE is
|
|
447
|
+
// routed through the resolver; nothing else in the text changes.
|
|
448
|
+
const PEER_STATEMENTS = [
|
|
449
|
+
// scopeRewriter buildScopeDecl, receiver form (`r = this` / `r = el`)
|
|
450
|
+
[/const __scope = (\(\(\) => \{ const r = [\s\S]*?\}\)\(\));/g, 'const __scope = $RESOLVE($1);'],
|
|
451
|
+
// scopeRewriter buildScopeDecl, globalScope-helper form
|
|
452
|
+
[/const __scope = this \?\? \{\};/g, 'const __scope = $RESOLVE(this ?? {});'],
|
|
453
|
+
// toJSON peer rewrite, receiver-callable form
|
|
454
|
+
[/const (__peers_*) = (this && this !== globalThis && this\.context && this\.context\.globalScope \? this\.scope \?\? this\.context\.globalScope : this);/g, 'const $1 = $RESOLVE($2);'],
|
|
455
|
+
// toJSON peer rewrite, `el`-parameter form
|
|
456
|
+
[/const _s = (el\?\.scope \?\? el\?\.context\?\.globalScope \?\? \{\});/g, 'const _s = $RESOLVE($1);'],
|
|
457
|
+
// scopeRewriter replaceVarWithScopeAwareOfParamDefaults: a free var read
|
|
458
|
+
// inside a PARAMETER DEFAULT (the body's peer statement cannot reach it)
|
|
459
|
+
[/(?<![\w$.])(this|[A-Za-z_$][\w$]*)\?\.context\?\.globalScope\?\./g, '$RESOLVE($1?.context?.globalScope)?.']
|
|
460
|
+
]
|
|
461
|
+
|
|
462
|
+
// A copy of `code` with string / template-text / comment interiors blanked
|
|
463
|
+
// ('~', same offsets) and `${ … }` substitutions kept as code — so a peer form
|
|
464
|
+
// written INSIDE a literal (docs text, a code sample) is never rewritten.
|
|
465
|
+
// Regex literals are not modelled: a peer form inside one is not a realistic
|
|
466
|
+
// shape, and the statement forms are exact multi-token statements.
|
|
467
|
+
const codeMask = (code) => {
|
|
468
|
+
const out = code.split('')
|
|
469
|
+
const stack = [] // template nesting: brace depth when a `${` opened
|
|
470
|
+
let i = 0
|
|
471
|
+
let depth = 0
|
|
472
|
+
const blank = (from, to) => { for (let k = from; k < to; k++) if (out[k] !== '\n') out[k] = '~' }
|
|
473
|
+
const scanTemplate = () => { // at the char after an opening ` (or after a closing } of ${)
|
|
474
|
+
const start = i
|
|
475
|
+
while (i < code.length) {
|
|
476
|
+
const c = code[i]
|
|
477
|
+
if (c === '\\') { i += 2; continue }
|
|
478
|
+
if (c === '`') { blank(start, i); i++; return }
|
|
479
|
+
if (c === '$' && code[i + 1] === '{') { blank(start, i); i += 2; stack.push(depth); depth++; return }
|
|
480
|
+
i++
|
|
481
|
+
}
|
|
482
|
+
blank(start, i)
|
|
483
|
+
}
|
|
484
|
+
while (i < code.length) {
|
|
485
|
+
const c = code[i]
|
|
486
|
+
if (c === '/' && code[i + 1] === '/') { const e = code.indexOf('\n', i); const end = e === -1 ? code.length : e; blank(i, end); i = end; continue }
|
|
487
|
+
if (c === '/' && code[i + 1] === '*') { const e = code.indexOf('*/', i + 2); const end = e === -1 ? code.length : e + 2; blank(i, end); i = end; continue }
|
|
488
|
+
if (c === '"' || c === "'") {
|
|
489
|
+
const q = c; const start = ++i
|
|
490
|
+
while (i < code.length && code[i] !== q && code[i] !== '\n') { if (code[i] === '\\') i++; i++ }
|
|
491
|
+
blank(start, i); i++; continue
|
|
492
|
+
}
|
|
493
|
+
if (c === '`') { i++; scanTemplate(); continue }
|
|
494
|
+
if (c === '{') { depth++; i++; continue }
|
|
495
|
+
if (c === '}') {
|
|
496
|
+
depth--
|
|
497
|
+
if (stack.length && depth === stack[stack.length - 1]) { stack.pop(); i++; scanTemplate(); continue }
|
|
498
|
+
i++; continue
|
|
499
|
+
}
|
|
500
|
+
i++
|
|
501
|
+
}
|
|
502
|
+
return out.join('')
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// Scope the peer statements of ONE emitted function string. Only strings the
|
|
506
|
+
// runtime itself revives as functions (`hasFunction`, destringify's own test)
|
|
507
|
+
// are touched — a component's text, a page's copy, any data string stays as
|
|
508
|
+
// authored — and a match counts only where it starts in code, never inside a
|
|
509
|
+
// string / template text / comment.
|
|
510
|
+
const scopeLibraryText = (text, id) => {
|
|
511
|
+
if (!isString(text) || (!text.includes('__scope = ') && !text.includes('__peers') && !text.includes('const _s = ') && !text.includes('?.context?.globalScope?.'))) return text
|
|
512
|
+
if (!hasFunction(text)) return text
|
|
513
|
+
const resolve = `(globalThis[Symbol.for('smbls.libraryScope')] || ((_, v) => v))(${JSON.stringify(id)}, `
|
|
514
|
+
let out = text
|
|
515
|
+
for (const [re, tpl] of PEER_STATEMENTS) {
|
|
516
|
+
// every replacement keeps the earlier offsets valid only per pass: rescan
|
|
517
|
+
// the mask of the CURRENT text for each form
|
|
518
|
+
const m = codeMask(out)
|
|
519
|
+
out = out.replace(re, (...args) => {
|
|
520
|
+
const offset = args[args.length - 2]
|
|
521
|
+
if (m[offset] === '~' || m[offset] !== out[offset]) return args[0]
|
|
522
|
+
return tpl.replace(/\$RESOLVE\(/g, resolve).replace(/\$(\d)/g, (_, k) => args[Number(k)])
|
|
523
|
+
})
|
|
524
|
+
}
|
|
525
|
+
return out
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// One library value as merged: emitted text scoped to `id`; a function of
|
|
529
|
+
// emitted text becomes its scoped TEXT (the runtime revives it like any
|
|
530
|
+
// emitted string — frank's emission is closure-free by construction); any
|
|
531
|
+
// other value as is.
|
|
532
|
+
const scopedValue = (v, id) => {
|
|
533
|
+
if (isString(v)) return scopeLibraryText(v, id)
|
|
534
|
+
const text = emittedFunctionText(v)
|
|
535
|
+
return text === null ? v : scopeLibraryText(text, id)
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// A bag / definition value as merged: if the merge scoped it (emitted text,
|
|
539
|
+
// or a revived emitted function turned back into text), the merge revives that
|
|
540
|
+
// text ITSELF — lazily, the runtime's own revival — because nothing later
|
|
541
|
+
// does for every payload kind: createDomql revives the bags only for raw-JSON
|
|
542
|
+
// payloads (a boot-revived or local-source payload is left as it is).
|
|
543
|
+
const LIBRARY_REVIVAL = { lazy: true, window: globalThis }
|
|
544
|
+
// The revived function serializes as its scoped TEXT (`toJSON`): a merge done
|
|
545
|
+
// in Node and written out as JSON (the runner's project.json, brender) keeps
|
|
546
|
+
// the code instead of dropping it, and the browser's boot pass revives it.
|
|
547
|
+
const scopedCodeValue = (v, id) => {
|
|
548
|
+
const out = scopedValue(v, id)
|
|
549
|
+
if (out === v || !isString(out)) return out
|
|
550
|
+
try {
|
|
551
|
+
const fn = deepDestringifyFunctions({ v: out }, {}, LIBRARY_REVIVAL).v
|
|
552
|
+
if (typeof fn !== 'function') return out
|
|
553
|
+
Object.defineProperty(fn, 'toJSON', { value: () => out, configurable: true })
|
|
554
|
+
return fn
|
|
555
|
+
} catch (_) {
|
|
556
|
+
return out
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const isPlainContainer = (v) => {
|
|
561
|
+
if (!v || typeof v !== 'object') return false
|
|
562
|
+
if (Array.isArray(v)) return true
|
|
563
|
+
const proto = Object.getPrototypeOf(v)
|
|
564
|
+
return proto === Object.prototype || proto === null
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// A copy of a definition tree (component / page and its children) with every
|
|
568
|
+
// emitted text scoped; the library's own object is never written.
|
|
569
|
+
const scopeLibraryTree = (v, id, seen = new WeakMap()) => {
|
|
570
|
+
if (isString(v) || typeof v === 'function') return scopedCodeValue(v, id)
|
|
571
|
+
if (isStringTag(v)) return v // a source STRING that looks like code stays a string
|
|
572
|
+
if (!isPlainContainer(v)) return v
|
|
573
|
+
if (seen.has(v)) return seen.get(v)
|
|
574
|
+
const out = Array.isArray(v) ? [] : (Object.getPrototypeOf(v) === null ? Object.create(null) : {})
|
|
575
|
+
seen.set(v, out)
|
|
576
|
+
for (const k of Object.keys(v)) out[k] = scopeLibraryTree(v[k], id, seen)
|
|
577
|
+
return out
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// The library as merged: its emitted globalScope, function bags and
|
|
581
|
+
// definitions with the peer statements scoped to `id`.
|
|
582
|
+
const scopedLibrary = (sharedLib, id) => {
|
|
583
|
+
const out = { ...sharedLib }
|
|
584
|
+
const gs = {}
|
|
585
|
+
for (const k of Object.keys(sharedLib.globalScope)) gs[k] = scopedValue(sharedLib.globalScope[k], id)
|
|
586
|
+
out.globalScope = gs
|
|
587
|
+
for (const bag of LIBRARY_FUNCTION_BAGS) {
|
|
588
|
+
const from = sharedLib[bag]
|
|
589
|
+
if (!isPlainContainer(from)) continue
|
|
590
|
+
const copy = {}
|
|
591
|
+
for (const k of Object.keys(from)) copy[k] = scopedCodeValue(from[k], id)
|
|
592
|
+
out[bag] = copy
|
|
593
|
+
}
|
|
594
|
+
for (const bag of LIBRARY_DEFINITION_BAGS) {
|
|
595
|
+
if (isPlainContainer(sharedLib[bag])) out[bag] = scopeLibraryTree(sharedLib[bag], id)
|
|
596
|
+
}
|
|
597
|
+
return out
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// The scope a library reads through an element's scope store: the element's
|
|
601
|
+
// own locals and its ancestors first, then the LIBRARY's globalScope where
|
|
602
|
+
// the consumer's would answer, then the consumer's. A view of the store —
|
|
603
|
+
// never the element, never `this`.
|
|
604
|
+
const scopeViews = new WeakMap() // store -> Map<libGs, view>
|
|
605
|
+
const libraryStoreView = (store, libGs, consumerGs) => {
|
|
606
|
+
let byLib = scopeViews.get(store)
|
|
607
|
+
if (!byLib) scopeViews.set(store, (byLib = new Map()))
|
|
608
|
+
let view = byLib.get(libGs)
|
|
609
|
+
if (view) return view
|
|
610
|
+
const fromConsumer = (p, v) => hasOwn(consumerGs, p) && consumerGs[p] === v
|
|
611
|
+
view = new Proxy(store, {
|
|
612
|
+
get (t, p) {
|
|
613
|
+
if (typeof p === 'symbol' || hasOwn(t, p)) return Reflect.get(t, p)
|
|
614
|
+
const v = Reflect.get(t, p)
|
|
615
|
+
if (hasOwn(libGs, p) && (v === undefined || fromConsumer(p, v))) return libGs[p]
|
|
616
|
+
return v === undefined ? libGs[p] : v
|
|
617
|
+
},
|
|
618
|
+
set (t, p, v) {
|
|
619
|
+
if (typeof p !== 'symbol' && !hasOwn(t, p) && hasOwn(libGs, p)) {
|
|
620
|
+
libGs[p] = v
|
|
621
|
+
return true
|
|
622
|
+
}
|
|
623
|
+
return Reflect.set(t, p, v)
|
|
624
|
+
},
|
|
625
|
+
has: (t, p) => Reflect.has(t, p) || p in libGs
|
|
626
|
+
})
|
|
627
|
+
byLib.set(libGs, view)
|
|
628
|
+
return view
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
const isScopeStore = (v) => !!v && typeof v === 'object' && !!v.__raw && typeof v.__raw === 'object'
|
|
632
|
+
|
|
633
|
+
// globalThis[Symbol.for('smbls.libraryScope')](id, value): what a scoped
|
|
634
|
+
// peer statement evaluates to. Before the library is bound, or for a value
|
|
635
|
+
// that is not the consumer's globalScope / a store, the value as is.
|
|
636
|
+
const resolveLibraryScope = (id, value) => {
|
|
637
|
+
const rec = libraryScopes.get(id)
|
|
638
|
+
if (!rec) return value
|
|
639
|
+
if (value === rec.consumerGs) return rec.libGs
|
|
640
|
+
if (isScopeStore(value)) return libraryStoreView(value, rec.libGs, rec.consumerGs)
|
|
641
|
+
return value
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
const installLibraryScopeResolver = () => {
|
|
645
|
+
if (typeof globalThis[LIBRARY_SCOPE] !== 'function') {
|
|
646
|
+
Object.defineProperty(globalThis, LIBRARY_SCOPE, { value: resolveLibraryScope, configurable: true })
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const libraryScopeRecordsOf = (context) => {
|
|
651
|
+
const list = context[LIBRARY_SCOPES_KEY]
|
|
652
|
+
return Array.isArray(list) ? list : null
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const unwrapLibrary = (entry) => (isWrappedLibrary(entry) ? entry.library : entry)
|
|
656
|
+
|
|
657
|
+
// A library this context's data already carries a record for (merged before
|
|
658
|
+
// this runtime — the runner, brender): its scoped entries are in place under
|
|
659
|
+
// that record's id, so this merge must not isolate it a second time.
|
|
660
|
+
const priorLibraryScope = (context, index, library) => {
|
|
661
|
+
const list = libraryScopeRecordsOf(context)
|
|
662
|
+
return !!list && list.some((rec) => rec && rec.index === index && (!rec.key || rec.key === library.key) &&
|
|
663
|
+
isString(rec.id) && carriesScopeId(context, rec.id))
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// A record is the trace of a real merge only if that merge's scoped text is
|
|
667
|
+
// in the context: some code string carries its id. A record without one (made
|
|
668
|
+
// up, or stale) must not switch this merge's isolation off.
|
|
669
|
+
const carriesScopeId = (context, id) => {
|
|
670
|
+
const needle = JSON.stringify(id)
|
|
671
|
+
const seen = new Set()
|
|
672
|
+
const walk = (v) => {
|
|
673
|
+
if (isString(v)) return v.includes(needle)
|
|
674
|
+
if (!v || typeof v !== 'object' || seen.has(v)) return false
|
|
675
|
+
seen.add(v)
|
|
676
|
+
for (const k in v) if (walk(v[k])) return true
|
|
677
|
+
return false
|
|
678
|
+
}
|
|
679
|
+
for (const bag of ['globalScope', ...LIBRARY_FUNCTION_BAGS, ...LIBRARY_DEFINITION_BAGS]) {
|
|
680
|
+
if (walk(context[bag])) return true
|
|
681
|
+
}
|
|
682
|
+
return false
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
const scopedGlobalScopeOf = (gs, id) => {
|
|
686
|
+
const out = {}
|
|
687
|
+
for (const k of Object.keys(gs)) out[k] = scopedValue(gs[k], id)
|
|
688
|
+
return out
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
const boundScopes = new WeakMap() // consumer globalScope -> Set<id>
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* After the runtime revived `context.globalScope` and the bags (createDomql),
|
|
695
|
+
* give every library recorded in `context.__libraryScopes` — by this merge or
|
|
696
|
+
* by one done before this runtime — its own revived globalScope (falling back
|
|
697
|
+
* to the consumer's for names it does not define) and register it for the
|
|
698
|
+
* resolver its scoped peer statements call. The library's names the consumer
|
|
699
|
+
* did NOT hold (`landed`) become the library's own values in the consumer's
|
|
700
|
+
* globalScope — one value, shared by both. Returns the number bound.
|
|
701
|
+
*/
|
|
702
|
+
export const bindLibraryGlobalScopes = (context, mergedGlobalScope = null) => {
|
|
703
|
+
const records = context && libraryScopeRecordsOf(context)
|
|
704
|
+
if (!records || !records.length) return 0
|
|
705
|
+
const consumerGs = context.globalScope
|
|
706
|
+
if (!isObject(consumerGs)) return 0
|
|
707
|
+
const libraries = Array.isArray(context.sharedLibraries) ? context.sharedLibraries : []
|
|
708
|
+
let done = boundScopes.get(consumerGs)
|
|
709
|
+
if (!done) boundScopes.set(consumerGs, (done = new Set()))
|
|
710
|
+
installLibraryScopeResolver()
|
|
711
|
+
let n = 0
|
|
712
|
+
for (const rec of records) {
|
|
713
|
+
if (!rec || !isString(rec.id) || done.has(rec.id)) continue
|
|
714
|
+
const lib = unwrapLibrary(libraries[rec.index])
|
|
715
|
+
if (!lib || !isObject(lib.globalScope) || (rec.key && lib.key !== rec.key)) continue
|
|
716
|
+
// A landed name is one the CONSUMER did not have: the library defines it
|
|
717
|
+
// and the merged (pre-revival) consumer globalScope holds exactly the
|
|
718
|
+
// library's own scoped value under it — so neither a library nor a record
|
|
719
|
+
// can re-point a name the consumer owns. (A consumer whose own value is
|
|
720
|
+
// byte-identical to the library's is indistinguishable here: it can only
|
|
721
|
+
// re-point its own name to an identical value, through its own data.)
|
|
722
|
+
const asText = (v) => (typeof v === 'function' ? functionText(v) : v)
|
|
723
|
+
const sameValue = (a, b) => {
|
|
724
|
+
if (a === b) return true
|
|
725
|
+
const ta = asText(a)
|
|
726
|
+
const tb = asText(b)
|
|
727
|
+
if (isString(ta) || isString(tb)) return ta === tb // functions compare by source text
|
|
728
|
+
return JSON.stringify(a) === JSON.stringify(b)
|
|
729
|
+
}
|
|
730
|
+
const landed = !isObject(mergedGlobalScope)
|
|
731
|
+
? []
|
|
732
|
+
: (Array.isArray(rec.landed) ? rec.landed : []).filter((k) =>
|
|
733
|
+
isString(k) && hasOwn(lib.globalScope, k) && hasOwn(mergedGlobalScope, k) &&
|
|
734
|
+
sameValue(mergedGlobalScope[k], scopedValue(lib.globalScope[k], rec.id)))
|
|
735
|
+
const libGs = destringifyGlobalScope(scopedGlobalScopeOf(lib.globalScope, rec.id))
|
|
736
|
+
Object.setPrototypeOf(libGs, consumerGs)
|
|
737
|
+
libraryScopes.set(rec.id, { libGs, consumerGs })
|
|
738
|
+
for (const k of landed) consumerGs[k] = libGs[k]
|
|
739
|
+
done.add(rec.id)
|
|
740
|
+
n++
|
|
741
|
+
}
|
|
742
|
+
return n
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
const mergeOneLibrary = (context, library, ignore, label = 'library', index = -1) => {
|
|
746
|
+
const skip = librarySkip(library, ignore)
|
|
747
|
+
// a library sharing a globalScope name keeps its own (see above)
|
|
748
|
+
const scopeId = !priorLibraryScope(context, index, library) && sharedGlobalScopeNames(context, library, skip) > 0
|
|
749
|
+
? `${label}#${scopeToken()}`
|
|
750
|
+
: null
|
|
751
|
+
const sharedLib = scopeId ? scopedLibrary(library, scopeId) : library
|
|
752
|
+
const landedBefore = scopeId ? new Set(Object.keys(context.globalScope)) : null
|
|
359
753
|
const refusedMethods = []
|
|
360
754
|
for (const key in sharedLib) {
|
|
361
755
|
if (!Object.prototype.hasOwnProperty.call(sharedLib, key)) continue
|
|
362
756
|
// merge directives, not library content
|
|
363
757
|
if (key === 'sharePages' || key === 'sharedLibIgnore') continue
|
|
758
|
+
// the merge's own record (see LIBRARY_SCOPES_KEY): written only by the
|
|
759
|
+
// merge, never taken from a library payload — a library carrying one
|
|
760
|
+
// could re-point another library's (or the consumer's) globalScope names
|
|
761
|
+
if (key === LIBRARY_SCOPES_KEY) continue
|
|
762
|
+
// no `__` key of a library payload is consumer content (the server merge
|
|
763
|
+
// skips them too): merge bookkeeping and markers are the merge's own
|
|
764
|
+
if (key.startsWith('__')) continue
|
|
364
765
|
// A library's `app` is its own standalone deployment root — chrome, boot
|
|
365
766
|
// hooks, watchers — never consumer content, so it is excluded
|
|
366
767
|
// UNCONDITIONALLY, on both merge branches, declaration or not. Six of the
|
|
@@ -408,6 +809,15 @@ const mergeOneLibrary = (context, sharedLib, ignore, label = 'library') => {
|
|
|
408
809
|
context[key] = copyWithNestedIgnores(value, skip, key)
|
|
409
810
|
}
|
|
410
811
|
}
|
|
812
|
+
if (scopeId) {
|
|
813
|
+
if (!libraryScopeRecordsOf(context)) context[LIBRARY_SCOPES_KEY] = []
|
|
814
|
+
context[LIBRARY_SCOPES_KEY].push({
|
|
815
|
+
id: scopeId,
|
|
816
|
+
index,
|
|
817
|
+
key: isString(library.key) ? library.key : null,
|
|
818
|
+
landed: Object.keys(sharedLib.globalScope).filter((k) => !landedBefore.has(k))
|
|
819
|
+
})
|
|
820
|
+
}
|
|
411
821
|
if (refusedMethods.length) warnRefusedBuiltinMethods(label, refusedMethods)
|
|
412
822
|
}
|
|
413
823
|
|
|
@@ -549,7 +959,7 @@ export const mergeSharedLibraries = (context, libraries) => {
|
|
|
549
959
|
libraries,
|
|
550
960
|
() => context.designSystem,
|
|
551
961
|
({ entry, lib, ignore, index }) =>
|
|
552
|
-
mergeOneLibrary(context, lib, ignore, libraryLabel(entry, lib, index))
|
|
962
|
+
mergeOneLibrary(context, lib, ignore, libraryLabel(entry, lib, index), index)
|
|
553
963
|
)
|
|
554
964
|
if (!claims) return
|
|
555
965
|
// A consumer with no design system of its own holds the first library's
|