@hpcc-js/observablehq-compiler
Version:
hpcc-js - ObservableHQ Compiler (unoffical)
33 lines (27 loc) • 13.8 kB
JavaScript
import{JSDOM as Fe}from"jsdom";import{transpile as M}from"@observablehq/notebook-kit";import{parseJavaScript as H,serialize as Z,deserialize as Q,toNotebook as P,toCell as w}from"@observablehq/notebook-kit";var f={regular:Object.getPrototypeOf(function(){}).constructor,async:Object.getPrototypeOf(async function(){}).constructor,generator:Object.getPrototypeOf(function*(){}).constructor,asyncGenerator:Object.getPrototypeOf(async function*(){}).constructor};function X(e=!1,t=!1){return!e&&!t?f.regular:e&&!t?f.async:!e&&t?f.generator:f.asyncGenerator}function v(e,t=!1,r=!1,n=!1,o){if(o!==void 0)return e.patches.sort((i,s)=>s.start-i.start),e.patches.forEach(i=>{o=o.substring(0,i.start)+i.newText+o.substring(i.end)}),new(X(t,r))(...e.args,n?o.substring(1,o.length-1).trim():`return (
${o}
);`)}function Y(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}var V=e=>e[0]===".",y=(e,t)=>V(e)?Y(t,e):e,ee=new f.async("url","return import(url)");async function q(e){return ee(e)}function O(e,t,r){if(e.type!=="FunctionExpression"&&e.type!=="FunctionDeclaration"&&e.type!=="ArrowFunctionExpression")throw new Error(`Unsupported function type: ${e.type}`);let n=e.async&&e.generator?f.asyncGenerator:e.async?f.async:e.generator?f.generator:f.regular,o=e.params?.map(u=>t.slice(u.start,u.end)).join(", ")??"",i=e.body.type==="BlockStatement",{start:s,end:c}=e.body,a=i?t.slice(s+1,c-1):`return ${t.slice(s,c)}`;if(r){let p=(K=>{let x=K.replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(x)||(x="_"+x),x})(r),m=e.async?"async ":"",g=e.generator?"*":"",z=`return ${m}function${g} ${p}(${o}) {
${a}
}`,R=new Function(z)();try{R.displayName=r}catch{}return R}return n(o,a)}function I(e,t){let{body:r}=H(e);if(r.type==="Program"){if(r.body.length!==1)throw new Error(`Expected a single function, but found ${r.body.length} statements`);return O(r.body[0],e,t)}return O(r,e,t)}var ke=e=>Q(e),Ee=e=>Z(e);function te(e,{inline:t=!0,resolveLocalImports:r=!1,includePinned:n=!0}={}){let o=[];try{let s=M(e,{resolveLocalImports:r});if(o.push({id:e.id,...s,body:t?I(s.body,`cell_${e.id}`):s.body}),n&&e.pinned){let c=M({...e,mode:"md",value:`\`\`\`${e.mode}
${e.value}
\`\`\``});o.push({id:1e6+e.id,...c,body:t?I(c.body,`cell_${1e6+e.id}`):c.body})}}catch(s){console.error(`Error compiling cell ${e.id}:`,s)}return o}function S(e,{inline:t=!0,resolveLocalImports:r=!1,includePinned:n=!0}={}){let o=[];for(let i of e.cells){let s=te(i,{inline:t,resolveLocalImports:r,includePinned:n});o.push(...s)}return o}function $e(e,t=0,r=1){for(let n of e.cells)n.id=t,t+=r;return e}import{FileAttachments as G}from"@observablehq/stdlib";import{getLineInfo as He,tokTypes as ne}from"acorn";import{ancestor as A}from"acorn-walk";import{CellParser as oe,parseCell as ie,walk as se}from"@observablehq/parser";import{ancestor as De}from"acorn-walk";import{make as re}from"acorn-walk";var j=re({Import(){},ViewExpression(e,t,r){r(e.id,t,"Identifier")},MutableExpression(e,t,r){r(e.id,t,"Identifier")}});import{simple as Ge}from"acorn-walk";var $=class extends oe{parseTopLevel(t){for(t.cells||(t.cells=[]);this.type!==ne.eof;){let r=this.parseCell(this.startNode());r.input=this.input,t.cells.push(r)}return this.next(),this.finishNode(t,"Program")}};function b(e){return $.parse(e,{ecmaVersion:"latest"}).cells.map(t=>({type:"Cell",text:e.substring(t.start,t.end),start:t.start,end:t.end}))}function F(e){return ie(e)}var D=se;function ae(e,t){if(e.references===void 0)return{inputs:[],args:[],patches:[]};let r={};e.references.forEach(i=>r[t.substring(i.start,i.end)]=!0);let n={inputs:Object.keys(r),args:Object.keys(r).map(i=>i.split(" ").join("_")),patches:[]},o=(i,s)=>n.patches.push({start:i.start-(e.body?.start??0),end:i.end-(e.body?.start??0),newText:s});return e.body&&A(e.body,{Identifier(i){let s=t.substring(i.start,i.end);r[s]},MutableExpression(i){let c=t.substring(i.start,i.end).split(" ").join("_")+".value";o(i,c)},ViewExpression(i){let c=t.substring(i.start,i.end).split(" ").join("_");o(i,c)},ThisExpression(i,s){t.substring(i.start,i.end)==="this"&&!s.find(a=>a.type==="FunctionExpression")&&o(i,"((this === globalThis || this === globalThis.window)? undefined : this?.valueOf())")}},D),n}function ce(e){return{type:"import",src:e.body.source.value,specifiers:e.body.specifiers?.map(t=>({view:t.view,name:t.imported.name,alias:t.local?.name&&t.imported.name!==t.local.name?t.local.name:t.imported.name}))??[],injections:e.body.injections?.map(t=>({name:t.imported.name,alias:t.local?.name??t.imported.name}))??[]}}function le(e,t,r,n){let o=t.id&&e.substring(t.id.start,t.id.end);return{type:"viewof",variable:{type:"variable",id:o,inputs:r.inputs,func:v(r,t.async,t.generator,t.body.type==="BlockStatement",n)},variableValue:{type:"variable",id:t?.id?.id?.name,inputs:["Generators",o],func:(i,s)=>i.input(s)}}}function ue(e,t,r,n){let o=t.id&&e.substring(t.id.start,t.id.end),i=t?.id?.id?.name,s=`initial ${i}`;return{type:"mutable",initial:{type:"variable",id:s,inputs:r.inputs,func:v(r,t.async,t.generator,t.body.type==="BlockStatement",n)},variable:{type:"variable",id:o,inputs:["Mutable",s],func:(c,a)=>new c(a)},variableValue:{type:"variable",id:i,inputs:[o],func:c=>c.generator}}}function pe(e,t,r,n){return{type:"variable",id:t.id&&e.substring(t.id?.start,t.id?.end),inputs:r.inputs,func:v(r,t.async,t.generator,t.body.type==="BlockStatement",n)}}function _(e,t){let r=F(e),n=r.body&&e.substring(r.body.start,r.body.end);switch(r.body?.type){case"ImportDeclaration":return ce(r);case"ImportExpression":r.body.source.type==="Literal"?n=`import("${y(""+r.body.source.value,t)}")`:console.error("Unexpected import value")}let o=ae(r,e);switch(r.id?.type){case"ViewExpression":return le(e,r,o,n);case"MutableExpression":return ue(e,r,o,n);default:return pe(e,r,o,n)}}var C=class{_files=[];_imports=[];_functions=[];_defines=[];_defineUid=0;_functionUid=0;constructor(){}toString(){return`${this._imports.join(`
`)}
${this._functions.join(`
`).split(`
) {`).join("){")}
export default function define(runtime, observer) {
const main = runtime.module();
function toString() { return this.url; }
const fileAttachments = new Map([
${this._files.map(t=>`["${t.name}", { url: new URL("${t.url}"), mimeType: ${JSON.stringify(t.mime_type)}, toString }]`).join(`,
`)}
]);
main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));
${this._defines.join(`
`)}
return main;
}
`}files(t){this._files=[...this._files,...t]}import(t){this._imports.push(`import define${++this._defineUid} from "${t}"; `)}importDefine(t){let r=t.injections??[],n=r.map(s=>s.name===s.alias?`"${s.name}"`:`{name: "${s.name}", alias: "${s.alias}"}`),o=r.length?`.derive([${n.join(", ")}], main)`:"";this._defines.push(`const child${this._defineUid} = runtime.module(define${this._defineUid})${o};`),(t.specifiers??[]).forEach(s=>{this._defines.push(`main.import("${s.name}"${s.alias&&s.alias!==s.name?`, "${s.alias}"`:""}, child${this._defineUid}); `)})}function(t){let r=t.id??`${++this._functionUid}`,n=r.split(" ");return r=`_${n[n.length-1]}`,this._functions.push(`${t.func?.toString()?.replace("anonymous",`${r}`)}`),r}define(t,r=!0,n=!1,o){o=o??t.id;let i=r?`.variable(observer(${t.id?JSON.stringify(t.id):""}))`:"",s=t.id?`${JSON.stringify(t.id)}, `:"",c=t.inputs??[],a=c.length?`[${c.map(u=>JSON.stringify(u)).join(", ")}], `:"",l=n?t.func?.toString():o;this._defines.push(`main${i}.define(${s}${a}${l});`)}error(t){}};function T(e){return e.split("`").join("\\`")}function k(e,t,r){let n,o;try{n=F(e)}catch(i){o=i}return{ojs:e,offset:t,inlineMD:r,cell:n,error:o}}function U(e){let t=[],r=/(```(?:\s|\S)[\s\S]*?```)/g,n=0,o=r.exec(e);for(;o!==null;){o.index>n&&t.push(k(e.substring(n,o.index),n,!0));let i=o[0];if(i.indexOf("``` ")===0||i.indexOf("```\n")===0||i.indexOf("```\r\n")===0){let c=i.substring(3,i.length-3);t.push(k(c,o.index+3,!1))}else t.push(k(i,o.index,!0));n=o.index+o[0].length,o=r.exec(e)}return e.length>n&&t.push(k(e.substring(n,e.length),n,!0)),t}function E(e){let t=b(e);return{files:[],nodes:t.map((r,n)=>({id:n,mode:"js",value:r.text,start:r.start,end:r.end}))}}function fe(e){let t=b(e).map((r,n)=>w({id:n,mode:"ojs",value:r.text}));return P({cells:t})}function N(e){let t=U(e);return{files:[],nodes:t.map((r,n)=>({id:n,mode:r.inlineMD?"md":"js",value:r.ojs,start:r.offset,end:r.offset+r.ojs.length}))}}function de(e){let t=[];return U(e).forEach(r=>{r.inlineMD?t.push(w({id:t.length+1,mode:"md",value:r.ojs})):b(r.ojs).forEach(n=>{t.push(w({id:t.length+1,mode:"ojs",value:n.text}))})}),P({cells:t})}function h(e,t="https://api.codetabs.com/v1/proxy/?quest=",r=""){let n=e.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/img);if(!n||n.length===0)throw new Error(`Invalid URL: ${e}`);return fetch(e,{headers:{origin:n[0],referer:e}}).then(o=>{if(o.ok)return o;throw new Error("CORS?")}).catch(o=>(e=`${t}${e}${r}`,fetch(e,{headers:{origin:n[0],referer:e}})))}function me(e,t,r){let n=e.indexOf("https://observablehq.com/d")===0;return h(e.replace(`https://observablehq.com/${n?"d/":""}`,"https://api.observablehq.com/document/"),t,r).then(o=>o.json())}async function ye(e,t){let r=y(e,t),n=await h(r).then(s=>s.text()),o;e.endsWith(".ojsnb")?o=JSON.parse(n):e.endsWith(".ojs")?o=E(n):e.endsWith(".omd")?o=N(n):(console.warn(`Unknown file type: ${e}, assuming .ojsnb`),o=JSON.parse(n));let i=W(o,{baseUrl:t});return i.delete=()=>{},i.write=s=>{s.import(r)},i}async function be(e){let t=`https://api.observablehq.com/${e[0]==="@"?e:`d/${e}`}.js?v=3`,r={default:function(o,i){}};try{r=await q(t)}catch{}let n=r.default;return n.delete=()=>{},n.write=o=>{o.import(t)},n}async function ge(e){let t=`https://api.observablehq.com/document/${e}`,r=h(t).then(o=>o.json()).catch(o=>{console.error(t),console.error(o)}),n=W(await r);return n.delete=()=>{},n.write=o=>{o.import(t)},n}async function he(e,t,r,{baseUrl:n,importMode:o}){let i=V(t.src)?await ye(t.src,n??""):o==="recursive"?await ge(t.src):await be(t.src),s=[],c=[];t.specifiers.forEach(l=>{let u=l.view?"viewof ":"";s.push(L(u+l.name,u+l.alias)),l.view&&s.push(L(l.name,l.alias))});let a=(l,u,p)=>{let m=l.module(i);return t.injections.length&&(m=m.derive(t.injections,u)),c.forEach(g=>g(u,p)),s.forEach(g=>g(u,m)),m};return a.importVariables=s,a.variables=c,a.delete=()=>{s.forEach(l=>l.delete()),c.forEach(l=>l.delete()),i.delete()},a.write=l=>{i.write(l),l.importDefine(t)},a}function d(e,t,r,n,o,i=!1){let s,c,a=(l,u)=>{if(t&&u&&(s=u(r,e.id)),c=l.variable(s),arguments.length>1)try{c.define(r,n,o)}catch(p){console.error(p?.message)}if(e.pinned){c=u?l.variable(u(r,e.id)):l.variable();try{c.define(void 0,["md"],p=>p`\`\`\`js
${e.value}
\`\`\``)}catch(p){console.error(p?.message)}}return c};return a.delete=()=>{try{s?._node?.remove()}catch{}s=void 0;try{c?.delete()}catch{}c=void 0},a.write=l=>{if(i)l.define({id:r,inputs:n,func:o},t,!0);else{let u=l.function({id:r,func:o});l.define({id:r,inputs:n,func:o},t,!1,u)}},a}function L(e,t){let r,n=(o,i)=>{r=o.variable(),t===void 0?r.import(e,i):r.import(e,t,i)};return n.delete=()=>{r?.delete()},n}async function J(e,t){let r=[],n=[];try{let i=e.mode&&e.mode!=="js"?`${e.mode}\`${T(e.value)}\``:e.value,s=b(i);for(let c of s){let a=_(c.text,t.baseUrl??"");switch(a.type){case"import":r.push(await he(e,a,c.text,t));break;case"viewof":n.push(d(e,!0,a.variable.id,a.variable.inputs,a.variable.func)),n.push(d(e,!1,a.variableValue.id,a.variableValue.inputs,a.variableValue.func,!0));break;case"mutable":n.push(d(e,!1,a.initial.id,a.initial.inputs,a.initial.func)),n.push(d(e,!1,a.variable.id,a.variable.inputs,a.variable.func)),n.push(d(e,!0,a.variableValue.id,a.variableValue.inputs,a.variableValue.func,!0));break;case"variable":n.push(d(e,!0,a.id,a.inputs,a.func));break}}}catch(i){n.push(d(e,!0,void 0,[],i.message??"Unkown error"))}let o=(i,s,c)=>{r.forEach(a=>a(i,s,c)),n.forEach(a=>a(s,c))};return o.id=e.id,o.modules=r,o.variables=n,o.delete=()=>{n.forEach(i=>i.delete()),r.forEach(i=>i.delete())},o.write=i=>{r.forEach(s=>s.write(i)),n.forEach(s=>s.write(i))},o}function xe(e,t){function r(){return globalThis.url??""}return[e.name,{url:new URL(y(e.url,t.baseUrl??"")),mimeType:e.mime_type,toString:r}]}function we(e=[],t=[],{baseUrl:r=".",importMode:n="precompiled"}={}){let o=e.map(a=>xe(a,{baseUrl:r,importMode:n})),i=new Map(o),s=new Map(t.map(a=>[a.id,a])),c=(a,l)=>{a.fileAttachments||(a.fileAttachments=G);let u=a.module();return u.builtin("FileAttachment",G(p=>i.get(p)??{url:new URL(y(p,r)),mimeType:null})),u.builtin("fetchEx",h),s.forEach(p=>{p(a,u,l)}),u};return c.fileAttachments=i,c.cells=s,c.set=async a=>{let l=await J(a,{baseUrl:r,importMode:n});return c.delete(l.id),s.set(l.id,l),l},c.get=a=>s.get(a),c.delete=a=>{let l=s.get(a);return l?(l.delete(),s.delete(a)):!1},c.clear=()=>{s.forEach(a=>a.delete()),s.clear()},c.write=a=>{a.files(e),s.forEach(l=>l.write(a))},c.toString=(a=new C)=>(c.write(a),a.toString().trim()),c}function ve(e){return!!e&&Array.isArray(e.cells)}function $t(e){return!!e&&Array.isArray(e.nodes)}async function W(e,{baseUrl:t=".",importMode:r="precompiled"}={}){if(ve(e))return S(e);typeof e=="string"&&(e=E(e));let n=await Promise.all(e.nodes.map(o=>J(o,{baseUrl:t,importMode:r})));return we(e.files,n,{baseUrl:t,importMode:r})}var{window:B}=new Fe;globalThis.document=B.document;globalThis.DOMParser=B.DOMParser;export{f as FunctionConstructors,C as Writer,W as compile,te as compileCell,S as compileNotebook,I as constructFunction,v as createFunction,me as download,y as fixRelativeUrl,ke as html2notebook,ve as isNotebookKit,$t as isOhqNotebook,V as isRelativePath,we as notebook,Ee as notebook2html,q as obfuscatedImport,E as ojs2notebook,fe as ojs2notebookKit,N as omd2notebook,de as omd2notebookKit,$e as resetCellIDs,w as toCell,P as toNotebook};
//# sourceMappingURL=index.js.map