Skip to content

Instantly share code, notes, and snippets.

@bundle-js
Created March 22, 2023 06:27
Show Gist options
  • Select an option

  • Save bundle-js/742329b634b1fbc0e436b8252abc2f03 to your computer and use it in GitHub Desktop.

Select an option

Save bundle-js/742329b634b1fbc0e436b8252abc2f03 to your computer and use it in GitHub Desktop.
var W=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var ot=(e,t)=>{for(var r in t)W(e,r,{get:t[r],enumerable:!0})},z=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rt(t))!nt.call(e,o)&&o!==r&&W(e,o,{get:()=>t[o],enumerable:!(n=et(t,o))||n.enumerable});return e},y=(e,t,r)=>(z(e,t,"default"),r&&z(r,t,"default"));var i={};ot(i,{Vue:()=>st,Vue2:()=>at,del:()=>ft,install:()=>ut,isVue2:()=>it,isVue3:()=>L,set:()=>lt});y(i,Ct);import*as st from"vue";import*as Ct from"vue";var it=!1,L=!0,at=void 0;function ut(){}function lt(e,t,r){return Array.isArray(e)?(e.length=Math.max(e.length,t),e.splice(t,1,r),r):(e[t]=r,r)}function ft(e,t){if(Array.isArray(e)){e.splice(t,1);return}delete e[t]}var _=class extends Array{static from(t){return t instanceof this?t:new this(t)}};var S=class extends _{constructor(t){if(super(),Symbol.iterator in Object(t))this.iterator=t[Symbol.iterator]();else throw new TypeError("Argument must implement the iteration protocol.")}[Symbol.iterator](){let t=this,r=0;return{next(){return t.length<=r&&t.push(t.iterator.next()),t[r++]}}}touchNext(t=1){let r=0;for(;r++<t;){let n=this[this.length-1];if(n&&n.done)break;this.push(this.iterator.next())}return this[this.length-1]}};var $=class extends _{constructor(t){if(super(),Symbol.asyncIterator in Object(t))this.iterator=t[Symbol.asyncIterator]();else if(Symbol.iterator in Object(t))this.iterator=t[Symbol.iterator]();else throw new TypeError("Argument must implement the iteration protocol.")}[Symbol.asyncIterator](){let t=this,r=0;return{async next(){return t.length<=r&&t.push(t.iterator.next()),t[r++]}}}async touchNext(t=1){let r=0;for(;r++<t;){let n=this[this.length-1];if(n&&(await n).done)break;this.push(this.iterator.next())}return this[this.length-1]}};function j(e,t){return Array.isArray(t)?t.map(r=>K(e,r)):K(e,t)}function K(e,t){for(let r of e)if(r.hasMessage(t))return r;return null}var v=class{constructor(t){this.value=t}valueOf(){return this.value}},a=class extends v{constructor(t="???"){super(t)}toString(t){return`{${this.value}}`}},m=class extends v{constructor(t,r={}){super(t),this.opts=r}toString(t){try{return t.memoizeIntlObject(Intl.NumberFormat,this.opts).format(this.value)}catch(r){return t.reportError(r),this.value.toString(10)}}},d=class extends v{constructor(t,r={}){super(t),this.opts=r}toString(t){try{return t.memoizeIntlObject(Intl.DateTimeFormat,this.opts).format(this.value)}catch(r){return t.reportError(r),new Date(this.value).toISOString()}}};var Z=100,ct="\u2068",mt="\u2069";function ht(e,t,r){if(r===t||r instanceof m&&t instanceof m&&r.value===t.value)return!0;if(t instanceof m&&typeof r=="string"){let n=e.memoizeIntlObject(Intl.PluralRules,t.opts).select(t.value);if(r===n)return!0}return!1}function G(e,t,r){return t[r]?N(e,t[r].value):(e.reportError(new RangeError("No default")),new a)}function B(e,t){let r=[],n=Object.create(null);for(let o of t)o.type==="narg"?n[o.name]=O(e,o.value):r.push(O(e,o));return{positional:r,named:n}}function O(e,t){switch(t.type){case"str":return t.value;case"num":return new m(t.value,{minimumFractionDigits:t.precision});case"var":return pt(e,t);case"mesg":return dt(e,t);case"term":return gt(e,t);case"func":return wt(e,t);case"select":return yt(e,t);default:return new a}}function pt(e,{name:t}){let r;if(e.params)if(Object.prototype.hasOwnProperty.call(e.params,t))r=e.params[t];else return new a(`$${t}`);else if(e.args&&Object.prototype.hasOwnProperty.call(e.args,t))r=e.args[t];else return e.reportError(new ReferenceError(`Unknown variable: $${t}`)),new a(`$${t}`);if(r instanceof v)return r;switch(typeof r){case"string":return r;case"number":return new m(r);case"object":if(r instanceof Date)return new d(r.getTime());default:return e.reportError(new TypeError(`Variable type not supported: $${t}, ${typeof r}`)),new a(`$${t}`)}}function dt(e,{name:t,attr:r}){let n=e.bundle._messages.get(t);if(!n)return e.reportError(new ReferenceError(`Unknown message: ${t}`)),new a(t);if(r){let o=n.attributes[r];return o?N(e,o):(e.reportError(new ReferenceError(`Unknown attribute: ${r}`)),new a(`${t}.${r}`))}return n.value?N(e,n.value):(e.reportError(new ReferenceError(`No value: ${t}`)),new a(t))}function gt(e,{name:t,attr:r,args:n}){let o=`-${t}`,s=e.bundle._terms.get(o);if(!s)return e.reportError(new ReferenceError(`Unknown term: ${o}`)),new a(o);if(r){let l=s.attributes[r];if(l){e.params=B(e,n).named;let g=N(e,l);return e.params=null,g}return e.reportError(new ReferenceError(`Unknown attribute: ${r}`)),new a(`${o}.${r}`)}e.params=B(e,n).named;let u=N(e,s.value);return e.params=null,u}function wt(e,{name:t,args:r}){let n=e.bundle._functions[t];if(!n)return e.reportError(new ReferenceError(`Unknown function: ${t}()`)),new a(`${t}()`);if(typeof n!="function")return e.reportError(new TypeError(`Function ${t}() is not callable`)),new a(`${t}()`);try{let o=B(e,r);return n(o.positional,o.named)}catch(o){return e.reportError(o),new a(`${t}()`)}}function yt(e,{selector:t,variants:r,star:n}){let o=O(e,t);if(o instanceof a)return G(e,r,n);for(let s of r){let u=O(e,s.key);if(ht(e,o,u))return N(e,s.value)}return G(e,r,n)}function U(e,t){if(e.dirty.has(t))return e.reportError(new RangeError("Cyclic reference")),new a;e.dirty.add(t);let r=[],n=e.bundle._useIsolating&&t.length>1;for(let o of t){if(typeof o=="string"){r.push(e.bundle._transform(o));continue}if(e.placeables++,e.placeables>Z)throw e.dirty.delete(t),new RangeError(`Too many placeables expanded: ${e.placeables}, max allowed is ${Z}`);n&&r.push(ct),r.push(O(e,o).toString(e)),n&&r.push(mt)}return e.dirty.delete(t),r.join("")}function N(e,t){return typeof t=="string"?e.bundle._transform(t):U(e,t)}var C=class{constructor(t,r,n){this.dirty=new WeakSet,this.params=null,this.placeables=0,this.bundle=t,this.errors=r,this.args=n}reportError(t){if(!this.errors||!(t instanceof Error))throw t;this.errors.push(t)}memoizeIntlObject(t,r){let n=this.bundle._intls.get(t);n||(n={},this.bundle._intls.set(t,n));let o=JSON.stringify(r);return n[o]||(n[o]=new t(this.bundle.locales,r)),n[o]}};function P(e,t){let r=Object.create(null);for(let[n,o]of Object.entries(e))t.includes(n)&&(r[n]=o.valueOf());return r}var q=["unitDisplay","currencyDisplay","useGrouping","minimumIntegerDigits","minimumFractionDigits","maximumFractionDigits","minimumSignificantDigits","maximumSignificantDigits"];function J(e,t){let r=e[0];if(r instanceof a)return new a(`NUMBER(${r.valueOf()})`);if(r instanceof m)return new m(r.valueOf(),{...r.opts,...P(t,q)});if(r instanceof d)return new m(r.valueOf(),{...P(t,q)});throw new TypeError("Invalid argument to NUMBER")}var X=["dateStyle","timeStyle","fractionalSecondDigits","dayPeriod","hour12","weekday","era","year","month","day","hour","minute","second","timeZoneName"];function H(e,t){let r=e[0];if(r instanceof a)return new a(`DATETIME(${r.valueOf()})`);if(r instanceof d)return new d(r.valueOf(),{...r.opts,...P(t,X)});if(r instanceof m)return new d(r.valueOf(),{...P(t,X)});throw new TypeError("Invalid argument to DATETIME")}var Q=new Map;function Y(e){let t=Array.isArray(e)?e.join(" "):e,r=Q.get(t);return r===void 0&&(r=new Map,Q.set(t,r)),r}var T=class{constructor(t,{functions:r,useIsolating:n=!0,transform:o=s=>s}={}){this._terms=new Map,this._messages=new Map,this.locales=Array.isArray(t)?t:[t],this._functions={NUMBER:J,DATETIME:H,...r},this._useIsolating=n,this._transform=o,this._intls=Y(t)}hasMessage(t){return this._messages.has(t)}getMessage(t){return this._messages.get(t)}addResource(t,{allowOverrides:r=!1}={}){let n=[];for(let o=0;o<t.body.length;o++){let s=t.body[o];if(s.id.startsWith("-")){if(r===!1&&this._terms.has(s.id)){n.push(new Error(`Attempt to override an existing term: "${s.id}"`));continue}this._terms.set(s.id,s)}else{if(r===!1&&this._messages.has(s.id)){n.push(new Error(`Attempt to override an existing message: "${s.id}"`));continue}this._messages.set(s.id,s)}}return n}formatPattern(t,r=null,n=null){if(typeof t=="string")return this._transform(t);let o=new C(this,n,r);try{return U(o,t).toString(o)}catch(s){if(o.errors&&s instanceof Error)return o.errors.push(s),new a().toString(o);throw s}}};function I(e,t){if(!e)throw new Error(`[fluent-vue] ${t}`)}function F(e,...t){console.warn(`[fluent-vue] ${e}`,...t)}var M=Symbol("root-context"),k=class{constructor(e,t){this.options=t,this.format=(r,n)=>{var o;let s=this.getBundle(r),u=this.getMessage(s,r);return(o=this._format(s,u,n))!=null?o:r},this.formatAttrs=(r,n)=>{var o;let s=this.getBundle(r),u=this.getMessage(s,r);return(o=this._formatAttrs(s,u,n))!=null?o:{}},this.formatWithAttrs=(r,n)=>{var o;let s=this.getBundle(r),u=this.getMessage(s,r),l=this._format(s,u,n);return{value:l??r,attributes:(o=this._formatAttrs(s,u,n))!=null?o:{},hasValue:l!==null}},this.$t=this.format,this.$ta=this.formatAttrs,this.bundles=e}getBundle(e){return j(this.bundles.value,e)}getMessage(e,t){let r=e?.getMessage(t);return r===void 0?(this.options.warnMissing(t),null):r}formatPattern(e,t,r,n){let o=[],s=e.formatPattern(r,n,o);for(let u of o)F(`Error when formatting message with key [${t}]`,u);return s}_format(e,t,r){return e===null||t===null||t.value===null?null:this.formatPattern(e,t.id,t.value,r)}_formatAttrs(e,t,r){if(e===null||t===null)return null;let n={};for(let[o,s]of Object.entries(t.attributes))n[o]=this.formatPattern(e,t.id,s,r);return n}};function Et(e,t){let r=new T(e,{functions:t._functions,useIsolating:t._useIsolating,transform:t._transform});return r._terms=new Map(t._terms),r._messages=new Map(t._messages),r}function*vt(e,t){for(let r of e)yield*t(r)}function p(e,t){if(t==null)return e;let r=t.$options,n=r.fluent;if(n==null)return e;if(r._fluent!=null)return r._fluent;let o=(0,i.computed)(()=>S.from(vt(e.bundles.value,u=>Object.entries(n).map(([l,g])=>{let E=l.split(/[\s+,]/);if(u.locales.filter(c=>E.includes(c)).length===0)return u;let f=Et(E,u);return f.addResource(g,{allowOverrides:!0}),f})))),s=new k(o,e.options);return r._fluent=s,s}function bt(){let e=(0,i.getCurrentInstance)();I(e!=null,"useFluent called outside of setup");let t=(0,i.inject)(M);return I(t!=null,"useFluent called without installing plugin"),p(t,e.proxy)}var V={global:["title","aria-label","aria-valuetext","aria-moz-hint"],a:["download"],area:["download","alt"],input:["alt","placeholder"],menuitem:["label"],menu:["label"],optgroup:["label"],option:["label"],track:["label"],img:["alt"],textarea:["placeholder"],th:["abbr"]};function xt(e,t,r=[]){if(r.includes(e))return!0;let n=e.toLowerCase(),o=t.localName;if(V.global.includes(n))return!0;if(V[o]==null)return!1;if(V[o].includes(n))return!0;if(t.namespaceURI==="http://www.w3.org/1999/xhtml"&&o==="input"&&n==="value"){let s=t.type.toLowerCase();if(s==="submit"||s==="button"||s==="reset")return!0}return!1}function D(e,t,r){let n=r.arg;if(n===void 0){F("v-t directive is missing arg with translation key");return}let o=t.formatWithAttrs(n,r.value);o.hasValue&&(e.textContent=o.value);let s=Object.keys(r.modifiers);for(let[u,l]of Object.entries(o.attributes))xt(u,e,s)&&e.setAttribute(u,l)}function _t(e){return{mounted(t,r){(0,i.watchEffect)(()=>{let n=p(e,r.instance);D(t,n,r)})},updated(t,r){let n=p(e,r.instance);D(t,n,r)}}}function At(e){return{bind(t,r,n){let o=p(e,n.context);D(t,o,r)},update(t,r,n){let o=p(e,n.context);D(t,o,r)}}}var St=/-(\w)/g;function Nt(e){return e.replace(St,(t,r)=>r.toUpperCase())}function tt(e){let t=e?.$parent,r=t?.$options;return r!=null&&r.fluent==null?tt(t):t}var Rt=/<|&#?\w+;/,Ot=(0,i.defineComponent)({name:"i18n",props:{path:{type:String,required:!0},tag:{type:String,default:"span"},args:{type:Object,default:()=>({})},html:{type:Boolean,default:!1}},setup(e,{slots:t,attrs:r}){let n=(0,i.inject)(M);I(n!=null,"i18n component used without installing plugin");let o=(0,i.getCurrentInstance)(),s=tt(o?.proxy),u=p(n,s),l=(0,i.computed)(()=>{let f=Object.assign({},e.args,...Object.keys(t).map(A=>({[A]:`\uFFFF\uFFFE${A}\uFFFF`}))),c=u.formatWithAttrs(e.path,f),w=Object.fromEntries(Object.entries(c.attributes).map(([A,h])=>[Nt(A),h]));return{value:c.value,attributes:w}}),g=f=>f?.split("\uFFFF").map(c=>c.startsWith("\uFFFE")?t[c.replace("\uFFFE","")](l.value.attributes):c),E=f=>{if(f.nodeType===3)return g(f.nodeValue);if(f.nodeType===1){let c=f;return(0,i.h)(c.nodeName.toLowerCase(),{...Object.fromEntries(Array.from(c.attributes).map(w=>[w.name,w.value]))},Array.from(c.childNodes).map(w=>E(w)))}return F(`Unsupported node type: ${f.nodeType}. If you need support for it, please, create an issue in fluent-vue repository.`),[]},R=(0,i.computed)(()=>!e.html||!Rt.test(l.value.value)?g(l.value.value):u.options.parseMarkup(l.value.value).map(E));return()=>(0,i.h)(e.tag,{...r},R.value)}});function Tt(e){I(typeof DOMParser<"u","DOMParser is not available. Please provide a custom parseMarkup function.");let r=new DOMParser().parseFromString(e,"text/html");return Array.from(r.body.childNodes)}function It(e){F(`Could not find translation for key [${e}]`)}function Ft(e){return e.warnMissing===!0||e.warnMissing==null?It:e.warnMissing===!1?()=>{}:e.warnMissing}function Mt(e){var t;return{warnMissing:Ft(e),parseMarkup:(t=e.parseMarkup)!=null?t:Tt}}function Se(e){let t=(0,i.shallowRef)(e.bundles),r=Mt(e),n=new k(t,r);return{get bundles(){return t.value},set bundles(o){t.value=o},format:n.format.bind(n),formatAttrs:n.formatAttrs.bind(n),formatWithAttrs:n.formatWithAttrs.bind(n),install(o){var s,u,l,g,E,R;let f=((u=(s=e.globals)==null?void 0:s.functions)==null?void 0:u.format)||"$t",c=((g=(l=e.globals)==null?void 0:l.functions)==null?void 0:g.formatAttrs)||"$ta",w=((E=e.globals)==null?void 0:E.directive)||"t",A=((R=e.globals)==null?void 0:R.component)||"i18n";if(L){let h=o;h.provide(M,n),h.config.globalProperties[f]=function(b,x){return p(n,this).format(b,x)},h.config.globalProperties[c]=function(b,x){return p(n,this).formatAttrs(b,x)},h.directive(w,_t(n))}else{let h=o;h.mixin({provide(){return{[M]:n}}}),h.prototype[f]=function(b,x){return p(n,this).format(b,x)},h.prototype[c]=function(b,x){return p(n,this).formatAttrs(b,x)},h.directive(w,At(n))}o.component(A,Ot)}}}export{Se as createFluentVue,bt as useFluent};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment