UNPKG

2.9 kBJavaScriptView Raw
1const PartytownSnippet = "/* Partytown 0.8.0 - MIT builder.io */\n!function(t,e,n,i,r,o,a,d,s,c,l,p){function u(){p||(p=1,\"/\"==(a=(o.lib||\"/~partytown/\")+(o.debug?\"debug/\":\"\"))[0]&&(s=e.querySelectorAll('script[type=\"text/partytown\"]'),i!=t?i.dispatchEvent(new CustomEvent(\"pt1\",{detail:t})):(d=setTimeout(f,1e4),e.addEventListener(\"pt0\",w),r?h(1):n.serviceWorker?n.serviceWorker.register(a+(o.swPath||\"partytown-sw.js\"),{scope:a}).then((function(t){t.active?h():t.installing&&t.installing.addEventListener(\"statechange\",(function(t){\"activated\"==t.target.state&&h()}))}),console.error):f())))}function h(t){c=e.createElement(t?\"script\":\"iframe\"),t||(c.setAttribute(\"style\",\"display:block;width:0;height:0;border:0;visibility:hidden\"),c.setAttribute(\"aria-hidden\",!0)),c.src=a+\"partytown-\"+(t?\"atomics.js?v=0.8.0\":\"sandbox-sw.html?\"+Date.now()),e.querySelector(o.sandboxParent||\"body\").appendChild(c)}function f(n,r){for(w(),i==t&&(o.forward||[]).map((function(e){delete t[e.split(\".\")[0]]})),n=0;n<s.length;n++)(r=e.createElement(\"script\")).innerHTML=s[n].innerHTML,e.head.appendChild(r);c&&c.parentNode.removeChild(c)}function w(){clearTimeout(d)}o=t.partytown||{},i==t&&(o.forward||[]).map((function(e){l=t,e.split(\".\").map((function(e,n,i){l=l[i[n]]=n+1<i.length?\"push\"==i[n+1]?[]:l[i[n]]||{}:function(){(t._ptf=t._ptf||[]).push(i,arguments)}}))})),\"complete\"==e.readyState?u():(t.addEventListener(\"DOMContentLoaded\",u),t.addEventListener(\"load\",u))}(window,document,navigator,top,window.crossOriginIsolated);";
2
3const createSnippet = (config, snippetCode) => {
4 const { forward = [], ...filteredConfig } = config || {};
5 const configStr = JSON.stringify(filteredConfig, (k, v) => {
6 if (typeof v === 'function') {
7 v = String(v);
8 if (v.startsWith(k + '(')) {
9 v = 'function ' + v;
10 }
11 }
12 return v;
13 });
14 return [
15 `!(function(w,p,f,c){`,
16 Object.keys(filteredConfig).length > 0
17 ? `c=w[p]=Object.assign(w[p]||{},${configStr});`
18 : `c=w[p]=w[p]||{};`,
19 `c[f]=(c[f]||[])`,
20 forward.length > 0 ? `.concat(${JSON.stringify(forward)})` : ``,
21 `})(window,'partytown','forward');`,
22 snippetCode,
23 ].join('');
24};
25
26/**
27 * The `type` attribute for Partytown scripts, which does two things:
28 *
29 * 1. Prevents the `<script>` from executing on the main thread.
30 * 2. Is used as a selector so the Partytown library can find all scripts to execute in a web worker.
31 *
32 * @public
33 */
34const SCRIPT_TYPE = `text/partytown`;
35
36/**
37 * Function that returns the Partytown snippet as a string, which can be
38 * used as the innerHTML of the inlined Partytown script in the head.
39 *
40 * @public
41 */
42const partytownSnippet = (config) => createSnippet(config, PartytownSnippet);
43
44export { SCRIPT_TYPE, partytownSnippet };