shopar-plugin 1.1.1 → 1.1.2-alpha.0

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/README.md CHANGED
@@ -33,7 +33,7 @@ There are two distinct ways of integrating the plugin: via Script tag and via NP
33
33
  Add the following script to your HTML.
34
34
 
35
35
  ```html
36
- <script src="https://cdn.jsdelivr.net/npm/shopar-plugin@1.1.1/dist/shopar-plugin.js"></script>
36
+ <script src="https://cdn.jsdelivr.net/npm/shopar-plugin@{{VERSION}}/dist/shopar-plugin.js"></script>
37
37
  ```
38
38
 
39
39
  It is possible to use a different CDN instead of [jsDelivr](https://www.jsdelivr.com/) (e.g. [cdnjs](https://cdnjs.com/), [unpkg](https://www.unpkg.com/)), or even a relative path if the plugin is distributed as a static asset to your app. Just make sure to set the `baseUrl` parameter accordingly (see [setup options](#shoparpluginsetupoptions) for more details).
@@ -205,7 +205,7 @@ Options used for the plugin setup:
205
205
  - `baseUrl` (optional)
206
206
  - Type: `string`
207
207
  - If provided, defines where the additional ShopAR plugin files are fetched from.
208
- - Default value: `https://cdn.jsdelivr.net/npm/shopar-plugin@1.1.1/dist`
208
+ - Default value: `https://cdn.jsdelivr.net/npm/shopar-plugin@{{VERSION}}/dist`
209
209
  - `defaultUI` (optional)
210
210
  - Type: `boolean`
211
211
  - If provided and set to `false`, disables the default UI (buttons and error UI).
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ShopAR__analytics={})}(this,function(t){"use strict";function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,n;var s=e(function(){if(n)return i;function t(t){return Number.isInteger(t)&&t>=0}function e(t){this.name="ArgumentError",this.message=t}return n=1,i=function(i,n){if(n=n||{},"function"!=typeof i)throw new e("fetch must be a function");if("object"!=typeof n)throw new e("defaults must be an object");if(void 0!==n.retries&&!t(n.retries))throw new e("retries must be a positive integer");if(void 0!==n.retryDelay&&!t(n.retryDelay)&&"function"!=typeof n.retryDelay)throw new e("retryDelay must be a positive integer or a function returning a positive integer");if(void 0!==n.retryOn&&!Array.isArray(n.retryOn)&&"function"!=typeof n.retryOn)throw new e("retryOn property expects an array or function");return n=Object.assign({retries:3,retryDelay:1e3,retryOn:[]},n),function(s,r){var o=n.retries,a=n.retryDelay,c=n.retryOn;if(r&&void 0!==r.retries){if(!t(r.retries))throw new e("retries must be a positive integer");o=r.retries}if(r&&void 0!==r.retryDelay){if(!t(r.retryDelay)&&"function"!=typeof r.retryDelay)throw new e("retryDelay must be a positive integer or a function returning a positive integer");a=r.retryDelay}if(r&&r.retryOn){if(!Array.isArray(r.retryOn)&&"function"!=typeof r.retryOn)throw new e("retryOn property expects an array or function");c=r.retryOn}return new Promise(function(t,e){var n=function(n){var a="undefined"!=typeof Request&&s instanceof Request?s.clone():s;i(a,r).then(function(i){if(Array.isArray(c)&&-1===c.indexOf(i.status))t(i);else if("function"==typeof c)try{return Promise.resolve(c(n,null,i)).then(function(e){e?l(n,null,i):t(i)}).catch(e)}catch(t){e(t)}else n<o?l(n,null,i):t(i)}).catch(function(t){if("function"==typeof c)try{Promise.resolve(c(n,t,null)).then(function(i){i?l(n,t,null):e(t)}).catch(function(t){e(t)})}catch(t){e(t)}else n<o?l(n,t,null):e(t)})};function l(t,e,i){var s="function"==typeof a?a(t,e,i):a;setTimeout(function(){n(++t)},s)}n(0)})}}}());var r,o;!function(t){t.unknown="unknown",t.user="user",t.organization="organization",t.anonymous="anonymous"}(r||(r={})),function(t){t.api="api",t.query="query",t.ingest="ingest"}(o||(o={}));class a{scope;type;value;remaining;reset;constructor(t=r.unknown,e=o.api,i=0,n=-1,s=new Date){this.scope=t,this.type=e,this.value=i,this.remaining=n,this.reset=s}}function c(t,e,i,n,s){const o=new a,c=t.headers.get(e.toLowerCase())||r.unknown;o.scope=r[c];const l=t.headers.get(i.toLowerCase())||"",h=parseInt(l,10);isNaN(h)||(o.value=h);const u=t.headers.get(n.toLowerCase())||"",f=parseInt(u,10);isNaN(f)||(o.remaining=f);const p=t.headers.get(s.toLowerCase())||"",m=parseInt(p,10);return isNaN(m)||(o.reset=new Date(1e3*m)),o}class l{config;constructor(t){this.config=t}async doReq(t,e,i={},n={},r=this.config.timeout,a=!1){let l=a?t:`${this.config.baseUrl}${t}`;const u=this._prepareSearchParams(n);u&&(l+=`?${u.toString()}`);const f={...this.config.headers,...i.headers},p=await s(fetch)(l,{retries:1,retryDelay:function(t,e,i){return 1e3*Math.pow(2,t)},retryOn:[503,502,504,500],headers:f,method:e,body:i.body?i.body:void 0,signal:AbortSignal.timeout(r),cache:"no-store"});if(204===p.status)return p;if(429==p.status){const t=function(t){let e;return t.url?.endsWith("/ingest")?(e=c(t,"","X-IngestLimit-Limit","X-IngestLimit-Remaining","X-IngestLimit-Reset"),e.type=o.ingest):t.url?.endsWith("/query")||t.url?.endsWith("/_apl")?(e=c(t,"","X-QueryLimit-Limit","X-QueryLimit-Remaining","X-QueryLimit-Reset"),e.type=o.query):(e=c(t,"X-RateLimit-Scope","X-RateLimit-Limit","X-RateLimit-Remaining","X-RateLimit-Reset"),e.type=o.api),e}(p);return Promise.reject(new h(t))}if(401===p.status)return Promise.reject(new Error("forbidden"));if(p.status>=400){const t=await p.json();return Promise.reject(new Error(t.message))}return await p.json()}post(t,e={},i={},n=this.config.timeout,s=!1){return this.doReq(t,"POST",e,i,n,s)}get(t,e={},i={},n=this.config.timeout){return this.doReq(t,"GET",e,i,n)}put(t,e={},i={},n=this.config.timeout){return this.doReq(t,"PUT",e,i,n)}delete(t,e={},i={},n=this.config.timeout){return this.doReq(t,"DELETE",e,i,n)}_prepareSearchParams=t=>{const e=new URLSearchParams;let i=!1;return Object.keys(t).forEach(n=>{t[n]&&(e.append(n,t[n]),i=!0)}),i?e:null}}class h extends Error{limit;shortcircuit;message="";constructor(t,e=!1){super(),this.limit=t,this.shortcircuit=e,Object.setPrototypeOf(this,h.prototype);const i=h.timeUntilReset(t);this.message=`${t.type} limit exceeded, try again in ${i.minutes}m${i.seconds}s`,t.type==o.api&&(this.message=`${t.scope} `+this.message)}static timeUntilReset(t){const e=t.reset.getTime()-(new Date).getTime(),i=Math.floor(e/1e3%60);return{total:e,minutes:Math.floor(e/1e3/60%60),seconds:i}}}const u="https://api.axiom.co";function f(t,e){return t.edgeUrl?function(t,e){try{const i=new URL(t),n=i.pathname;return""===n||"/"===n?(i.pathname=`/v1/ingest/${e}`,i.toString()):(i.pathname=n.replace(/\/+$/,""),i.toString())}catch{return`${t.replace(/\/+$/,"")}/v1/ingest/${e}`}}(t.edgeUrl,e):t.edge?`https://${t.edge}/v1/ingest/${e}`:t.url?function(t,e){try{const i=new URL(t),n=i.pathname;return""===n||"/"===n?(i.pathname=`/v1/datasets/${e}/ingest`,i.toString()):(i.pathname=n.replace(/\/+$/,""),i.toString())}catch{return`${t.replace(/\/+$/,"")}/v1/datasets/${e}/ingest`}}(t.url,e):`${u}/v1/datasets/${e}/ingest`}class p{client;clientOptions;constructor({orgId:t="",token:e,url:i,edge:n,edgeUrl:s,onError:r}){e||console.warn("Missing Axiom token"),this.clientOptions={orgId:t,token:e,url:i,edge:n,edgeUrl:s,onError:r};const o=i?i.replace(/\/+$/,""):u,a={Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+e};"undefined"==typeof window&&(a["User-Agent"]="axiom-js/1.4.0"),t&&(a["X-Axiom-Org-Id"]=t),this.client=new l({baseUrl:o,headers:a,timeout:2e4})}}var m,d,g,y,v,w,b,O;!function(t){t.TimestampField="_time";t.Service=class extends p{localPath="/v1/datasets";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=(t,e)=>{const i=new URLSearchParams;i.set("referrer",e?.referrer??"");const n=`/v2/datasets?${i.toString()}`;return this.client.post(n,{body:JSON.stringify(t)})};update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t);trim=(t,e)=>{const i={maxDuration:e};return this.client.post(this.localPath+"/"+t+"/trim",{body:JSON.stringify(i)})}}}(m||(m={})),function(t){t.Service=class extends p{current=()=>this.client.get("/v1/user")}}(d||(d={}));class S{ingestFn;id;options;events=[];activeFlush=Promise.resolve();nextFlush=setTimeout(()=>{},0);lastFlush=new Date;constructor(t,e,i){this.ingestFn=t,this.id=e,this.options=i}ingest=t=>{Array.isArray(t)?this.events=this.events.concat(t):this.events.push(t),this.events.length>=1e3||this.lastFlush.getTime()<Date.now()-1e3?(clearTimeout(this.nextFlush),this.activeFlush=this.flush()):(clearTimeout(this.nextFlush),this.nextFlush=setTimeout(()=>{this.activeFlush=this.flush()},1e3))};flush=async()=>{const t=this.events.splice(0,this.events.length);if(clearTimeout(this.nextFlush),await this.activeFlush,0===t.length)return void(this.lastFlush=new Date);let e=null;try{e=await this.ingestFn(this.id,t,this.options)}catch(t){throw t}finally{this.lastFlush=new Date}return e}}class x extends p{datasets;users;localPath="/v1";onError=console.error;constructor(t){t.token&&t.token.startsWith("xapt")&&console.warn("Using a personal token (`xapt-...`) is deprecated for security reasons. Please use an API token (`xaat-...`) instead. Support for personal tokens will be removed in a future release."),super(t),this.datasets=new m.Service(t),this.users=new d.Service(t),t.onError&&(this.onError=t.onError)}ingestRaw=async(t,e,i=g.JSON,n=y.Identity,s)=>{try{const r=f(this.clientOptions,t);return await this.client.post(r,{headers:{"Content-Type":i,"Content-Encoding":n},body:e},{"timestamp-field":s?.timestampField,"timestamp-format":s?.timestampFormat,"csv-delimiter":s?.csvDelimiter},void 0,!0)}catch(t){return this.onError(t),await Promise.resolve({ingested:0,failed:0,processedBytes:0,blocksCreated:0,walLength:0})}};queryLegacy=(t,e,i)=>this.client.post(this.localPath+"/datasets/"+t+"/query",{body:JSON.stringify(e)},{"streaming-duration":i?.streamingDuration,nocache:i?.noCache},12e4);query=(t,e)=>{const i={apl:t};return e?.startTime&&(i.startTime=e?.startTime),e?.endTime&&(i.endTime=e?.endTime),this.client.post(this.localPath+"/datasets/_apl",{body:JSON.stringify(i)},{"streaming-duration":e?.streamingDuration,nocache:e?.noCache,format:e?.format??"legacy",cursor:e?.cursor},12e4).then(t=>{if("tabular"!==e?.format)return t;const i=t;return{...t,tables:i.tables.map(t=>({...t,events:function*(){let t=0;if(this.columns)for(;t<=this.columns[0].length;){const e=Object.fromEntries(this.fields.map((e,i)=>[e.name,this.columns[i][t]]));if(t>=this.columns[0].length)return e;yield e,t++}}}))}})};aplQuery=(t,e)=>this.query(t,e)}class P extends x{batch={};ingest=(t,e,i)=>{const n=function(t,e){return`${t}:${e?.timestampField||"-"}:${e?.timestampFormat||"-"}:${e?.csvDelimiter||"-"}`}(t,i);return this.batch[n]||(this.batch[n]=new S((t,e,i)=>{const n=(Array.isArray(e)?e:[e]).map(t=>JSON.stringify(t)).join("\n");return this.ingestRaw(t,n,g.NDJSON,y.Identity,i)},t,i)),this.batch[n].ingest(e)};flush=async()=>{let t=[];for(const e in this.batch)t.push(this.batch[e].flush().catch(this.onError));await Promise.all(t).catch(this.onError)}}let N;BigInt.prototype.toJSON=function(){return this.toString()},function(t){t.JSON="application/json",t.NDJSON="application/x-ndjson",t.CSV="text/csv"}(g||(g={})),function(t){t.Identity="",t.GZIP="gzip"}(y||(y={})),function(t){t.Count="count",t.Distinct="distinct",t.Sum="sum",t.Avg="avg",t.Min="min",t.Max="max",t.Topk="topk",t.Percentiles="percentiles",t.Histogram="histogram",t.Variance="variance",t.Stdev="stdev",t.ArgMin="argmin",t.ArgMax="argmax",t.MakeSet="makeset",t.MakeSetIf="makesetif",t.CountIf="countif",t.CountDistinctIf="distinctif"}(v||(v={})),function(t){t.And="and",t.Or="or",t.Not="not",t.Equal="==",t.NotEqual="!=",t.Exists="exists",t.NotExists="not-exists",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.LessThan="<",t.LessThanOrEqualTo="<=",t.Gt="gt",t.Gte="gte",t.Lt="lt",t.Lte="lte",t.StartsWith="starts-with",t.NotStartsWith="not-starts-with",t.EndsWith="ends-with",t.NotEndsWith="not-ends-with",t.Contains="contains",t.NotContains="not-contains",t.Regexp="regexp",t.NotRegexp="not-regexp"}(w||(w={})),function(t){t.Service=class extends p{localPath="/v2/annotations";list=t=>this.client.get(this.localPath,{},t);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t)}}(b||(b={})),function(t){t.Service=class extends p{localPath="/v2/monitors";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t)}}(O||(O={})),t.initializeImpl=function(){N=new P({token:"xaat-f69a9dd7-3988-4fc2-849b-4a0978468c25"})},t.trackEventImpl=function(t,e){N.ingest("shopar-plugin",Object.assign({name:t},e))}});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ShopAR__analytics={})}(this,function(t){"use strict";function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,n;var s=e(function(){if(n)return i;function t(t){return Number.isInteger(t)&&t>=0}function e(t){this.name="ArgumentError",this.message=t}return n=1,i=function(i,n){if(n=n||{},"function"!=typeof i)throw new e("fetch must be a function");if("object"!=typeof n)throw new e("defaults must be an object");if(void 0!==n.retries&&!t(n.retries))throw new e("retries must be a positive integer");if(void 0!==n.retryDelay&&!t(n.retryDelay)&&"function"!=typeof n.retryDelay)throw new e("retryDelay must be a positive integer or a function returning a positive integer");if(void 0!==n.retryOn&&!Array.isArray(n.retryOn)&&"function"!=typeof n.retryOn)throw new e("retryOn property expects an array or function");return n=Object.assign({retries:3,retryDelay:1e3,retryOn:[]},n),function(s,r){var o=n.retries,a=n.retryDelay,c=n.retryOn;if(r&&void 0!==r.retries){if(!t(r.retries))throw new e("retries must be a positive integer");o=r.retries}if(r&&void 0!==r.retryDelay){if(!t(r.retryDelay)&&"function"!=typeof r.retryDelay)throw new e("retryDelay must be a positive integer or a function returning a positive integer");a=r.retryDelay}if(r&&r.retryOn){if(!Array.isArray(r.retryOn)&&"function"!=typeof r.retryOn)throw new e("retryOn property expects an array or function");c=r.retryOn}return new Promise(function(t,e){var n=function(n){var a="undefined"!=typeof Request&&s instanceof Request?s.clone():s;i(a,r).then(function(i){if(Array.isArray(c)&&-1===c.indexOf(i.status))t(i);else if("function"==typeof c)try{return Promise.resolve(c(n,null,i)).then(function(e){e?l(n,null,i):t(i)}).catch(e)}catch(t){e(t)}else n<o?l(n,null,i):t(i)}).catch(function(t){if("function"==typeof c)try{Promise.resolve(c(n,t,null)).then(function(i){i?l(n,t,null):e(t)}).catch(function(t){e(t)})}catch(t){e(t)}else n<o?l(n,t,null):e(t)})};function l(t,e,i){var s="function"==typeof a?a(t,e,i):a;setTimeout(function(){n(++t)},s)}n(0)})}}}());var r,o;!function(t){t.unknown="unknown",t.user="user",t.organization="organization",t.anonymous="anonymous"}(r||(r={})),function(t){t.api="api",t.query="query",t.ingest="ingest"}(o||(o={}));class a{scope;type;value;remaining;reset;constructor(t=r.unknown,e=o.api,i=0,n=-1,s=new Date){this.scope=t,this.type=e,this.value=i,this.remaining=n,this.reset=s}}function c(t,e,i,n,s){const o=new a,c=t.headers.get(e.toLowerCase())||r.unknown;o.scope=r[c];const l=t.headers.get(i.toLowerCase())||"",h=parseInt(l,10);isNaN(h)||(o.value=h);const u=t.headers.get(n.toLowerCase())||"",f=parseInt(u,10);isNaN(f)||(o.remaining=f);const p=t.headers.get(s.toLowerCase())||"",m=parseInt(p,10);return isNaN(m)||(o.reset=new Date(1e3*m)),o}class l{config;constructor(t){this.config=t}async doReq(t,e,i={},n={},r=this.config.timeout,a=!1){let l=a?t:`${this.config.baseUrl}${t}`;const u=this._prepareSearchParams(n);u&&(l+=`?${u.toString()}`);const f={...this.config.headers,...i.headers},p=await s(fetch)(l,{retries:1,retryDelay:function(t,e,i){return 1e3*Math.pow(2,t)},retryOn:[503,502,504,500],headers:f,method:e,body:i.body?i.body:void 0,signal:AbortSignal.timeout(r),cache:"no-store"});if(204===p.status)return p;if(429==p.status){const t=function(t){let e;return t.url?.endsWith("/ingest")?(e=c(t,"","X-IngestLimit-Limit","X-IngestLimit-Remaining","X-IngestLimit-Reset"),e.type=o.ingest):t.url?.endsWith("/query")||t.url?.endsWith("/_apl")?(e=c(t,"","X-QueryLimit-Limit","X-QueryLimit-Remaining","X-QueryLimit-Reset"),e.type=o.query):(e=c(t,"X-RateLimit-Scope","X-RateLimit-Limit","X-RateLimit-Remaining","X-RateLimit-Reset"),e.type=o.api),e}(p);return Promise.reject(new h(t))}if(401===p.status)return Promise.reject(new Error("forbidden"));if(p.status>=400){const t=await p.json();return Promise.reject(new Error(t.message))}return await p.json()}post(t,e={},i={},n=this.config.timeout,s=!1){return this.doReq(t,"POST",e,i,n,s)}get(t,e={},i={},n=this.config.timeout){return this.doReq(t,"GET",e,i,n)}put(t,e={},i={},n=this.config.timeout){return this.doReq(t,"PUT",e,i,n)}delete(t,e={},i={},n=this.config.timeout){return this.doReq(t,"DELETE",e,i,n)}_prepareSearchParams=t=>{const e=new URLSearchParams;let i=!1;return Object.keys(t).forEach(n=>{t[n]&&(e.append(n,t[n]),i=!0)}),i?e:null}}class h extends Error{limit;shortcircuit;message="";constructor(t,e=!1){super(),this.limit=t,this.shortcircuit=e,Object.setPrototypeOf(this,h.prototype);const i=h.timeUntilReset(t);this.message=`${t.type} limit exceeded, try again in ${i.minutes}m${i.seconds}s`,t.type==o.api&&(this.message=`${t.scope} `+this.message)}static timeUntilReset(t){const e=t.reset.getTime()-(new Date).getTime(),i=Math.floor(e/1e3%60);return{total:e,minutes:Math.floor(e/1e3/60%60),seconds:i}}}const u="https://api.axiom.co";function f(t,e){return t.edgeUrl?function(t,e){try{const i=new URL(t),n=i.pathname;return""===n||"/"===n?(i.pathname=`/v1/ingest/${e}`,i.toString()):(i.pathname=n.replace(/\/+$/,""),i.toString())}catch{return`${t.replace(/\/+$/,"")}/v1/ingest/${e}`}}(t.edgeUrl,e):t.edge?`https://${t.edge}/v1/ingest/${e}`:t.url?function(t,e){try{const i=new URL(t),n=i.pathname;return""===n||"/"===n?(i.pathname=`/v1/datasets/${e}/ingest`,i.toString()):(i.pathname=n.replace(/\/+$/,""),i.toString())}catch{return`${t.replace(/\/+$/,"")}/v1/datasets/${e}/ingest`}}(t.url,e):`${u}/v1/datasets/${e}/ingest`}class p{client;clientOptions;constructor({orgId:t="",token:e,url:i,edge:n,edgeUrl:s,onError:r}){e||console.warn("Missing Axiom token"),this.clientOptions={orgId:t,token:e,url:i,edge:n,edgeUrl:s,onError:r};const o=i?i.replace(/\/+$/,""):u,a={Accept:"application/json","Content-Type":"application/json",Authorization:"Bearer "+e};"undefined"==typeof window&&(a["User-Agent"]="axiom-js/1.4.0"),t&&(a["X-Axiom-Org-Id"]=t),this.client=new l({baseUrl:o,headers:a,timeout:2e4})}}var m,d,g,y,v,w,b,O;!function(t){t.TimestampField="_time";t.Service=class extends p{localPath="/v1/datasets";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=(t,e)=>{const i=new URLSearchParams;i.set("referrer",e?.referrer??"");const n=`/v2/datasets?${i.toString()}`;return this.client.post(n,{body:JSON.stringify(t)})};update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t);trim=(t,e)=>{const i={maxDuration:e};return this.client.post(this.localPath+"/"+t+"/trim",{body:JSON.stringify(i)})}}}(m||(m={})),function(t){t.Service=class extends p{current=()=>this.client.get("/v1/user")}}(d||(d={}));class S{ingestFn;id;options;events=[];activeFlush=Promise.resolve();nextFlush=setTimeout(()=>{},0);lastFlush=new Date;constructor(t,e,i){this.ingestFn=t,this.id=e,this.options=i}ingest=t=>{Array.isArray(t)?this.events=this.events.concat(t):this.events.push(t),this.events.length>=1e3||this.lastFlush.getTime()<Date.now()-1e3?(clearTimeout(this.nextFlush),this.activeFlush=this.flush()):(clearTimeout(this.nextFlush),this.nextFlush=setTimeout(()=>{this.activeFlush=this.flush()},1e3))};flush=async()=>{const t=this.events.splice(0,this.events.length);if(clearTimeout(this.nextFlush),await this.activeFlush,0===t.length)return void(this.lastFlush=new Date);let e=null;try{e=await this.ingestFn(this.id,t,this.options)}catch(t){throw t}finally{this.lastFlush=new Date}return e}}class x extends p{datasets;users;localPath="/v1";onError=console.error;constructor(t){t.token&&t.token.startsWith("xapt")&&console.warn("Using a personal token (`xapt-...`) is deprecated for security reasons. Please use an API token (`xaat-...`) instead. Support for personal tokens will be removed in a future release."),super(t),this.datasets=new m.Service(t),this.users=new d.Service(t),t.onError&&(this.onError=t.onError)}ingestRaw=async(t,e,i=g.JSON,n=y.Identity,s)=>{try{const r=f(this.clientOptions,t);return await this.client.post(r,{headers:{"Content-Type":i,"Content-Encoding":n},body:e},{"timestamp-field":s?.timestampField,"timestamp-format":s?.timestampFormat,"csv-delimiter":s?.csvDelimiter},void 0,!0)}catch(t){return this.onError(t),await Promise.resolve({ingested:0,failed:0,processedBytes:0,blocksCreated:0,walLength:0})}};queryLegacy=(t,e,i)=>this.client.post(this.localPath+"/datasets/"+t+"/query",{body:JSON.stringify(e)},{"streaming-duration":i?.streamingDuration,nocache:i?.noCache},12e4);query=(t,e)=>{const i={apl:t};return e?.startTime&&(i.startTime=e?.startTime),e?.endTime&&(i.endTime=e?.endTime),this.client.post(this.localPath+"/datasets/_apl",{body:JSON.stringify(i)},{"streaming-duration":e?.streamingDuration,nocache:e?.noCache,format:e?.format??"legacy",cursor:e?.cursor},12e4).then(t=>{if("tabular"!==e?.format)return t;const i=t;return{...t,tables:i.tables.map(t=>({...t,events:function*(){let t=0;if(this.columns)for(;t<=this.columns[0].length;){const e=Object.fromEntries(this.fields.map((e,i)=>[e.name,this.columns[i][t]]));if(t>=this.columns[0].length)return e;yield e,t++}}}))}})};aplQuery=(t,e)=>this.query(t,e)}class P extends x{batch={};ingest=(t,e,i)=>{const n=function(t,e){return`${t}:${e?.timestampField||"-"}:${e?.timestampFormat||"-"}:${e?.csvDelimiter||"-"}`}(t,i);return this.batch[n]||(this.batch[n]=new S((t,e,i)=>{const n=(Array.isArray(e)?e:[e]).map(t=>JSON.stringify(t)).join("\n");return this.ingestRaw(t,n,g.NDJSON,y.Identity,i)},t,i)),this.batch[n].ingest(e)};flush=async()=>{let t=[];for(const e in this.batch)t.push(this.batch[e].flush().catch(this.onError));await Promise.all(t).catch(this.onError)}}let N;BigInt.prototype.toJSON=function(){return this.toString()},function(t){t.JSON="application/json",t.NDJSON="application/x-ndjson",t.CSV="text/csv"}(g||(g={})),function(t){t.Identity="",t.GZIP="gzip"}(y||(y={})),function(t){t.Count="count",t.Distinct="distinct",t.Sum="sum",t.Avg="avg",t.Min="min",t.Max="max",t.Topk="topk",t.Percentiles="percentiles",t.Histogram="histogram",t.Variance="variance",t.Stdev="stdev",t.ArgMin="argmin",t.ArgMax="argmax",t.MakeSet="makeset",t.MakeSetIf="makesetif",t.CountIf="countif",t.CountDistinctIf="distinctif"}(v||(v={})),function(t){t.And="and",t.Or="or",t.Not="not",t.Equal="==",t.NotEqual="!=",t.Exists="exists",t.NotExists="not-exists",t.GreaterThan=">",t.GreaterThanOrEqualTo=">=",t.LessThan="<",t.LessThanOrEqualTo="<=",t.Gt="gt",t.Gte="gte",t.Lt="lt",t.Lte="lte",t.StartsWith="starts-with",t.NotStartsWith="not-starts-with",t.EndsWith="ends-with",t.NotEndsWith="not-ends-with",t.Contains="contains",t.NotContains="not-contains",t.Regexp="regexp",t.NotRegexp="not-regexp"}(w||(w={})),function(t){t.Service=class extends p{localPath="/v2/annotations";list=t=>this.client.get(this.localPath,{},t);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t)}}(b||(b={})),function(t){t.Service=class extends p{localPath="/v2/monitors";list=()=>this.client.get(this.localPath);get=t=>this.client.get(this.localPath+"/"+t);create=t=>this.client.post(this.localPath,{body:JSON.stringify(t)});update=(t,e)=>this.client.put(this.localPath+"/"+t,{body:JSON.stringify(e)});delete=t=>this.client.delete(this.localPath+"/"+t)}}(O||(O={})),t.initializeImpl=function(){N=new P({token:"xaat-16d05fdd-4ab9-4990-acba-7cee24974bfb"})},t.trackEventImpl=function(t,e){N.ingest("shopar-plugin-alpha",Object.assign({name:t},e))}});
@@ -43,6 +43,127 @@ declare const strings_: {
43
43
  };
44
44
  type Strings = typeof strings_;
45
45
 
46
+ /**
47
+ * Truescale output measurements
48
+ */
49
+ type FaceMeasurement = {
50
+ /**
51
+ * Face width in millimeters.
52
+ */
53
+ faceWidth: number;
54
+ /**
55
+ * Interpupillary distance in millimeters.
56
+ */
57
+ IPD: number;
58
+ };
59
+ /**
60
+ * Type that wraps face position and orientation.
61
+ */
62
+ type FacePose = {
63
+ /**
64
+ * Face position in uncalibrated 3D space.
65
+ */
66
+ translation: number[];
67
+ /**
68
+ * Face rotation represented as Tait-Bryan angles (nautical angles).
69
+ *
70
+ * Sequence of fields in this array is yaw, pitch, roll (heading, elevation, bank).
71
+ */
72
+ rotation: number[];
73
+ };
74
+ /**
75
+ * Plugin controller.
76
+ */
77
+ type Plugin = {
78
+ /**
79
+ * Launches the AR view.
80
+ * Set to `undefined` if AR is not supported for given SKU.
81
+ *
82
+ * @returns A promise that resolves when AR is launched.
83
+ */
84
+ launchAR?: () => Promise<void>;
85
+ /**
86
+ * Launches the 3D view.
87
+ * Set to `undefined` if 3D is not supported for given SKU.
88
+ *
89
+ * @returns A promise that resolves when 3D is launched.
90
+ */
91
+ launch3D?: () => Promise<void>;
92
+ /**
93
+ * Closes the AR view.
94
+ * Set to `undefined` if AR is not supported for given SKU.
95
+ *
96
+ * @returns A promise that resolves when AR is closed.
97
+ */
98
+ closeAR?: () => Promise<void>;
99
+ /**
100
+ * Closes the 3D view.
101
+ * Set to `undefined` if 3D is not supported for given SKU.
102
+ *
103
+ * @returns A promise that resolves when 3D is closed.
104
+ */
105
+ close3D?: () => Promise<void>;
106
+ /**
107
+ * Closes the AR or 3D view.
108
+ * Set to `undefined` if neither AR nor 3D are supported for given SKU.
109
+ *
110
+ * @returns A promise that resolves when AR or 3D is closed.
111
+ */
112
+ close?: () => Promise<void>;
113
+ /**
114
+ * Returns the current user interactivity value.
115
+ *
116
+ * @returns `true` is user interactivity is enabled and `false` otherwise.
117
+ */
118
+ isInteractive: () => boolean;
119
+ /**
120
+ * Sets user interactivity to the provided value. Set to `false` to ignore input events.
121
+ *
122
+ * @param value The provided value.
123
+ */
124
+ setInteractive: (interactive: boolean) => void;
125
+ };
126
+ /**
127
+ * Vision plugin controller
128
+ */
129
+ type VisionPlugin = {
130
+ /**
131
+ * Register a face pose callback which will be called if face is detected.
132
+ */
133
+ registerFacePoseListener?: (facePoseListener: (facePose: FacePose) => void) => void;
134
+ /**
135
+ * Register a face measurement callback which will be called if face is detected.
136
+ */
137
+ registerFaceMeasurementListener?: (faceMeasurementListener: (faceMeasurement: FaceMeasurement) => void) => void;
138
+ /**
139
+ * Switch the AR effect for preview
140
+ *
141
+ * This call is a thin wrapper around DeepAR.switchEffect API.
142
+ *
143
+ * @param arUrl A path to the AR effect file
144
+ * @returns Promise that resolves when an effect start rendering
145
+ */
146
+ switchEffect?: (arUrl: string) => Promise<void>;
147
+ /**
148
+ * Clear the AR effect
149
+ *
150
+ * Call this after switchEffect to clear the loaded effect.
151
+ * @returns void
152
+ */
153
+ clearEffect?: () => void;
154
+ /**
155
+ * Closes the vision plugin and releases the camera.
156
+ *
157
+ * @returns A promise that resolves when AR is closed.
158
+ */
159
+ close?: () => void;
160
+ };
161
+
162
+ type ArVideoConfig = {
163
+ video: HTMLVideoElement;
164
+ mirror: boolean;
165
+ };
166
+
46
167
  /** Preview state values. */
47
168
  declare const PREVIEW_STATES: readonly ["AR", "3D"];
48
169
  /** Preview state type. */
@@ -252,6 +373,32 @@ type SetupOptions = {
252
373
  * @see debounce3DEngagementMs
253
374
  */
254
375
  onDebounced3DEngagement?: (durationMs: number) => void;
376
+ /**
377
+ * If provided, it will be used as the video source for AR instead of the default camera used by plugin.
378
+ *
379
+ * Example of loading HTMLVideoElement:
380
+ * ```js
381
+ * function loadVideo(src) {
382
+ * const video = document.createElement('video');
383
+ * video.src = src;
384
+ * video.muted = true;
385
+ * video.setAttribute("playsinline", "playsinline");
386
+ * video.load();
387
+ * video.onloadedmetadata = () => {
388
+ * video.play();
389
+ * };
390
+ *
391
+ * return video;
392
+ * }
393
+ * ```
394
+ */
395
+ customArVideo?: ArVideoConfig;
396
+ /**
397
+ * If provided, it will be used as the true scale face width, in millimeters, for AR glasses.
398
+ *
399
+ * If not provided, the value is determined by ShopAR True Scale technology.
400
+ */
401
+ customTrueScaleFaceWidth?: number;
255
402
  _internalOptions?: any;
256
403
  };
257
404
  /**
@@ -322,122 +469,6 @@ declare class QRError extends LaunchARError {
322
469
  constructor(message?: string);
323
470
  }
324
471
 
325
- /**
326
- * Truescale output measurements
327
- */
328
- type FaceMeasurement = {
329
- /**
330
- * Face width in millimeters.
331
- */
332
- faceWidth: number;
333
- /**
334
- * Interpupillary distance in millimeters.
335
- */
336
- IPD: number;
337
- };
338
- /**
339
- * Type that wraps face position and orientation.
340
- */
341
- type FacePose = {
342
- /**
343
- * Face position in uncalibrated 3D space.
344
- */
345
- translation: number[];
346
- /**
347
- * Face rotation represented as Tait-Bryan angles (nautical angles).
348
- *
349
- * Sequence of fields in this array is yaw, pitch, roll (heading, elevation, bank).
350
- */
351
- rotation: number[];
352
- };
353
- /**
354
- * Plugin controller.
355
- */
356
- type Plugin = {
357
- /**
358
- * Launches the AR view.
359
- * Set to `undefined` if AR is not supported for given SKU.
360
- *
361
- * @returns A promise that resolves when AR is launched.
362
- */
363
- launchAR?: () => Promise<void>;
364
- /**
365
- * Launches the 3D view.
366
- * Set to `undefined` if 3D is not supported for given SKU.
367
- *
368
- * @returns A promise that resolves when 3D is launched.
369
- */
370
- launch3D?: () => Promise<void>;
371
- /**
372
- * Closes the AR view.
373
- * Set to `undefined` if AR is not supported for given SKU.
374
- *
375
- * @returns A promise that resolves when AR is closed.
376
- */
377
- closeAR?: () => Promise<void>;
378
- /**
379
- * Closes the 3D view.
380
- * Set to `undefined` if 3D is not supported for given SKU.
381
- *
382
- * @returns A promise that resolves when 3D is closed.
383
- */
384
- close3D?: () => Promise<void>;
385
- /**
386
- * Closes the AR or 3D view.
387
- * Set to `undefined` if neither AR nor 3D are supported for given SKU.
388
- *
389
- * @returns A promise that resolves when AR or 3D is closed.
390
- */
391
- close?: () => Promise<void>;
392
- /**
393
- * Returns the current user interactivity value.
394
- *
395
- * @returns `true` is user interactivity is enabled and `false` otherwise.
396
- */
397
- isInteractive: () => boolean;
398
- /**
399
- * Sets user interactivity to the provided value. Set to `false` to ignore input events.
400
- *
401
- * @param value The provided value.
402
- */
403
- setInteractive: (interactive: boolean) => void;
404
- };
405
- /**
406
- * Vision plugin controller
407
- */
408
- type VisionPlugin = {
409
- /**
410
- * Register a face pose callback which will be called if face is detected.
411
- */
412
- registerFacePoseListener?: (facePoseListener: (facePose: FacePose) => void) => void;
413
- /**
414
- * Register a face measurement callback which will be called if face is detected.
415
- */
416
- registerFaceMeasurementListener?: (faceMeasurementListener: (faceMeasurement: FaceMeasurement) => void) => void;
417
- /**
418
- * Switch the AR effect for preview
419
- *
420
- * This call is a thin wrapper around DeepAR.switchEffect API.
421
- *
422
- * @param arUrl A path to the AR effect file
423
- * @returns Promise that resolves when an effect start rendering
424
- */
425
- switchEffect?: (arUrl: string) => Promise<void>;
426
- /**
427
- * Clear the AR effect
428
- *
429
- * Call this after switchEffect to clear the loaded effect.
430
- * @returns void
431
- */
432
- clearEffect?: () => void;
433
- /**
434
- * Closes the vision plugin and releases the camera.
435
- *
436
- * @returns A promise that resolves when AR is closed.
437
- */
438
- close?: () => void;
439
- };
440
-
441
472
  /**
442
473
  * ShopAR vision plugin.
443
474
  *
@@ -503,4 +534,4 @@ declare const plugin: {
503
534
  };
504
535
 
505
536
  export { ApiError, CameraPermissionDeniedError, Launch3DError, LaunchARError, PREVIEW_STATES, PluginError, QRError, SanitizationError, ValidationError, plugin, vision };
506
- export type { FaceMeasurement, FacePose, KeyFrameConfig, Plugin, PreviewState, SetupOptions, SkuData, VisionOptions, VisionPlugin };
537
+ export type { ArVideoConfig, FaceMeasurement, FacePose, KeyFrameConfig, Plugin, PreviewState, SetupOptions, SkuData, VisionOptions, VisionPlugin };