@snowplow/snowtype 0.18.0 → 0.20.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/dist/index.js CHANGED
@@ -1,116 +1,119 @@
1
- "use strict";var di=Object.create;var he=Object.defineProperty;var li=Object.getOwnPropertyDescriptor;var gi=Object.getOwnPropertyNames;var mi=Object.getPrototypeOf,fi=Object.prototype.hasOwnProperty;var hi=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of gi(e))!fi.call(t,o)&&o!==n&&he(t,o,{get:()=>e[o],enumerable:!(i=li(e,o))||i.enumerable});return t};var h=(t,e,n)=>(n=t!=null?di(mi(t)):{},hi(e||!t||!t.__esModule?he(n,"default",{value:t,enumerable:!0}):n,t));var qn=h(require("process")),$=require("@commander-js/extra-typings");var Si={AuthError:"Authentication failed. Check if your API key and organization ID are correct.",ConfigAlreadyExists:"Snowtype config file already exists.",ConfigNotExists:"Snowtype config file does not exist in current directory. Start with running 'init'.",ConfigInvalid:"Snowtype config exists but it is invalid.",InternalError:"An internal error occured.",InvalidOption:"Invalid option provided.",MissingOptions:"Action called with no options.",WriteLockFile:"Failed writing lock file.",ReadLockFile:"Lock file is invalid or corrupted. Please recover it or delete it, and run `snowtype generate` so a new one will be created.",GenerationFailed:"Something went wrong with code generation.",PatchingNotSupported:"Patching is only supported using a Snowtype config file in JSON format.",DevNotAllowed:"Code generation using schemas in DEV environment not allowed. Publish the schemas and retry.",AuthCredentialsMissing:"Required API key credentials not detected. Please refer to https://docs.snowplow.io/docs/collecting-data/code-generation/using-the-cli/#authenticating-with-the-console"},vi="Please report a bug.",y=class extends Error{code;constructor(e,n=""){let i=Si[e].concat(n);super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e}},ut=class extends y{constructor(){super("GenerationFailed")}},tt=class extends y{constructor(){super("ConfigAlreadyExists")}},dt=class extends y{constructor(){super("ConfigNotExists")}},lt=class extends y{constructor(e){super("ConfigInvalid",e)}},gt=class extends y{constructor(e){super("InternalError",e.concat(vi))}},B=class extends y{constructor(e,n){let i=`Value ${n} is an invalid ${e}.`;super("InvalidOption",i)}},mt=class extends y{constructor(){super("MissingOptions")}},O=class extends y{constructor(){super("AuthError")}},H=class extends y{constructor(){super("WriteLockFile")}},ft=class extends y{constructor(e){super("ReadLockFile",` ${e}`)}},ht=class extends y{constructor(){super("PatchingNotSupported")}},St=class extends y{constructor(){super("DevNotAllowed")}},vt=class extends y{constructor(){super("AuthCredentialsMissing")}};var Se=h(require("got"));async function ve({schema:t}){return(await(0,Se.default)(`https://raw.githubusercontent.com/snowplow/iglu-central/master/schemas/${t.replace("iglu:","")}`)).body}var rt=h(require("got"));var xe=require("js-sha256"),Gt=h(require("node:assert"));var u=h(require("joi")),Et=require("@snowplow/snowtype-core");var Ut=h(require("node:assert"));var et="snowtype.config",yt=".js",wt=".ts",It=".json",ye=Object.freeze([yt,wt,It]),J=".snowtype-lock.json",_t="snowplow";var nt={"google-tag-manager":[{value:"javascript-gtm",name:"JavaScript"}],"@snowplow/javascript-tracker":[{value:"javascript",name:"JavaScript"}],"@snowplow/browser-tracker":[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"}],"@snowplow/node-tracker":[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"}],"snowplow-android-tracker":[{value:"kotlin",name:"Kotlin"}],"snowplow-ios-tracker":[{value:"swift",name:"Swift"}],"snowplow-golang-tracker":[{value:"go",name:"Go"}],"@snowplow/react-native-tracker":[{value:"typescript",name:"TypeScript"}],"snowplow-flutter-tracker":[{value:"dart",name:"Dart"}],"snowplow-java-tracker":[{value:"java",name:"Java"}]},we={commands:{generate:{instructions:!1,validations:!1,disallowDevSchemas:!1,deprecateOnlyOnProdAvailableUpdates:!1},update:{maximumBump:"major",showOnlyProdUpdates:!1,regenerateOnUpdate:!1},patch:{regenerateOnPatch:!1}}},Ie=["iglu:com.snowplowanalytics.snowplow/page_ping/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1","iglu:com.snowplowanalytics.snowplow/page_view/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/screen_view/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/button_click/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/application_background/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/application_foreground/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/application_install/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/screen_end/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/custom_event/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/expose_element/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/create_element/jsonschema/1-0-0"],Ee="iglu:com.snowplowanalytics.snowplow.ecommerce";var Pt=require("lodash");function Ce(t){let e=t.split("-");(0,Ut.default)(e.length===3,"invalid SchemaVer"),(0,Ut.default)(e.filter(n=>isNaN(parseInt(n))).length===0,"invalid SchemaVer")}function k(t){t.options=(0,Pt.merge)((0,Pt.cloneDeep)(we),t.options||{})}var Pe=new RegExp("^iglu:[a-zA-Z0-9-_.]+/[a-zA-Z0-9-_]+/[a-zA-Z0-9-_]+/[0-9]+-[0-9]+-[0-9]+$"),yi=new RegExp("^[A-Z][a-zA-Z0-9]*$"),wi=u.default.object().required().keys({tracker:u.default.string().required().valid(...Et.trackerTemplates),language:u.default.string().required().valid(...Et.languageIds),outpath:u.default.string().required(),namespace:u.default.when("language",{is:"swift",then:u.default.string().regex(yi).optional(),otherwise:u.default.forbidden().messages({"any.unknown":"namespace is only supported for 'swift' language"})}),organizationId:u.default.string().when("dataStructures",{is:u.default.array().min(1),then:u.default.required(),otherwise:u.default.optional()}).when("eventSpecificationIds",{is:u.default.array().min(1),then:u.default.required(),otherwise:u.default.optional()}).when("dataProductIds",{is:u.default.array().min(1),then:u.default.required(),otherwise:u.default.optional()}),igluCentralSchemas:u.default.array().optional().items(u.default.string().regex(Pe)),repositories:u.default.array().optional().items(u.default.string()),dataStructures:u.default.array().optional().items(u.default.string().regex(Pe)),eventSpecificationIds:u.default.array().optional().items(u.default.string()),dataProductIds:u.default.array().optional().items(u.default.string()),options:u.default.object().optional().keys({commands:u.default.object().optional().keys({generate:u.default.object().optional().keys({instructions:u.default.boolean().optional(),validations:u.default.boolean().optional(),disallowDevSchemas:u.default.boolean().optional(),deprecateOnlyOnProdAvailableUpdates:u.default.boolean().optional()}),patch:u.default.object().optional().keys({regenerateOnPatch:u.default.boolean().optional()}),update:u.default.object().optional().keys({maximumBump:u.default.string().valid("major","minor","patch").optional(),regenerateOnUpdate:u.default.boolean().optional(),showOnlyProdUpdates:u.default.boolean().optional()})})})}),K=t=>{let e=wi.validate(t,{abortEarly:!1,convert:!1});if(e.error)throw new lt(e.error.annotate());return t};function Ii(t){let e=xe.sha256.create();return e.update(t),e.hex()}function Ae(t,e){let{vendor:n,name:i,format:o}=T(t);return Ii(`${e}-${n}-${i}-${o}`)}function T(t){let e=t.replace("iglu:",""),[n,i,o,r]=e.split("/");return(0,Gt.default)(typeof n=="string"&&typeof i=="string"&&typeof o=="string"&&typeof r=="string",`invalid iglu uri ${t}`),Ce(r),{vendor:n,name:i,format:o,version:r}}function De(t,{vendor:e,name:n,format:i,version:o}){let r=t.replace("iglu:",""),[a,s,c,p]=r.split("/");return`iglu:${e||a}/${n||s}/${i||c}/${o||p}`}function be(t){return t.some(e=>e.eventSchema.isEcomTemplateSchema)}function it(t){let[e,n,i]=t.split("-").map(o=>parseInt(o));return{model:e,revision:n,addition:i}}function Oe(t,e,n=0){if(t===e&&n!==0)return"patch";let{model:i,revision:o,addition:r}=it(t),{model:a,revision:s,addition:c}=it(e);if(i!==a)return"major";if(o!==s)return"minor";if(r!==c)return"patch";(0,Gt.default)(!1,"SchemaVer checking went wrong")}var ot=class extends Error{response;constructor(e){let n=e.response?.statusCode||0,{method:i,url:o}=e.options,r=e.response?.body||e.message,a=[[n,i,o].filter(Boolean).join(" "),r].filter(Boolean).join(`
2
- `);super(a),this.response={statusCode:n,body:r}}};function zt(t){return!!Object.hasOwn(t||{},"response")}var j="0.18.0";var ke=h(require("p-limit")),A=class t{apiKeyId;apiKey;organizationId;accessToken;pLimit;dataProductsCache=new Map;eventSpecsCache=new Map;schemaVersionsDraftsCache=new Map;schemaVersionsDevCache=new Map;schemaVersionsProdCache=new Map;sourceApplicationsCache=new Map;apiUrl=process.env.SNOWPLOW_CONSOLE_API_URL||"https://console.snowplowanalytics.com/api/msc";constructor({apiKeyId:e,apiKey:n,organizationId:i,requestLimit:o=20}){this.apiKeyId=e,this.apiKey=n,this.organizationId=i,this.pLimit=(0,ke.default)(o)}static async create(e){let n=new t(e);return await n.initialize(e),n}static createLazy(e){return new t(e)}async initialize(e){await this.fetchAccessToken(),e.enableSupportForNonDataProductsTier?await Promise.all([this.bulkFetchAllSchemaDraftsVersions(),this.bulkFetchAllSchemaVersions("DEV"),this.bulkFetchAllSchemaVersions("PROD")]):await Promise.all([this.bulkFetchAllDataProducts(),this.bulkFetchAllEventSpecifications(),this.bulkFetchAllSchemaDraftsVersions(),this.bulkFetchAllSchemaVersions("DEV"),this.bulkFetchAllSchemaVersions("PROD")])}async bulkFetchAllDataProducts(){let e=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-products/v2`,n=await this.fetchResource(e);n.data.forEach(i=>this.dataProductsCache.set(i.id,i)),n.includes.sourceApplications?.forEach(i=>{this.sourceApplicationsCache.set(i.id,i)})}async bulkFetchAllEventSpecifications(){let e=`${this.apiUrl}/v1/organizations/${this.organizationId}/event-specs/v1`,n=await this.fetchResource(e);n.data.forEach(i=>{let o={...n.metadata,outdatedDsWarnings:n.metadata?.outdatedDsWarnings.filter(a=>a.id===i.id)||[],hiddenDsWarnings:n.metadata?.hiddenDsWarnings.filter(a=>a.id===i.id)||[],metrics:n.metadata?.metrics.filter(a=>a.id===i.id)||[]},r={data:i,metadata:o};this.eventSpecsCache.set(i.id,r)})}async bulkFetchAllSchemaVersions(e){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/schemas/versions?env=${e}`,i=await this.fetchResource(n),o=e==="DEV"?this.schemaVersionsDevCache:this.schemaVersionsProdCache;i.forEach(r=>{let a=`iglu:${r.self.vendor}/${r.self.name}/${r.self.format}/${r.self.version}`;o.set(a,r)})}async bulkFetchAllSchemaDraftsVersions(){let e=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structure-drafts/v1/schemas`,n=await this.fetchResource(e),i=this.schemaVersionsDraftsCache;n.forEach(o=>{let r=`iglu:${o.self.vendor}/${o.self.name}/${o.self.format}/${o.self.version}`;i.set(r,o)})}async fetchAccessToken(){if(this.accessToken)return this.accessToken;let e=`${this.apiUrl}/v1/organizations/${this.organizationId}/credentials/v3/token`,{accessToken:n}=await(0,rt.default)(e,{headers:{"X-API-Key-Id":this.apiKeyId,"X-API-Key":this.apiKey,"X-Snowtype":j}}).json();return this.accessToken=n,n}fetchResource(e){return this.pLimit(async()=>{try{let n=await this.fetchAccessToken();return await(0,rt.default)(e,{headers:{Authorization:"Bearer "+n,"X-Snowtype":j}}).json()}catch(n){throw zt(n)?new ot(n):n}})}postResource(e,n){return this.pLimit(async()=>{try{let i=await this.fetchAccessToken();return await rt.default.post(e,{headers:{Authorization:"Bearer "+i,"X-Snowtype":j},json:n}).json()}catch(i){throw zt(i)?new ot(i):i}})}getSchemaVersion({schema:e,env:n="DEV"}){return(n==="DEV"?this.schemaVersionsDevCache:this.schemaVersionsProdCache).get(e)??(()=>{throw new Error(`Schema ${e} not found in ${n} environment`)})()}getAllSchemaDraftVersion(){return this.schemaVersionsDraftsCache}async fetchDeployments({schema:e,deploymentEnv:n}){let i=Ae(e,this.organizationId),o=25,r=[],a=!0,s=0,c=p=>`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${i}/deployments?size=${o}&from=${p}${n?`&env=${n}`:""}`;for(;a;){let p=await this.fetchResource(c(s));s+=o,r=r.concat(p),p.length===0&&(a=!1)}return r}getEventSpecificationById(e){let n=this.eventSpecsCache.get(e)??(()=>{throw new Error(`Event specification ${e} not found`)})();return{data:n.data,metadata:n.metadata}}async fetchImageVariant({imageId:e,imageVariant:n}){let i=`${this.apiUrl}/v1/organizations/${this.organizationId}/images/v1/${e}/${n}`,o=await this.fetchAccessToken();return(0,rt.default)(i,{headers:{Authorization:"Bearer "+o,"X-Snowtype":j}})}getDataProductById(e){let n=this.dataProductsCache.get(e)??(()=>{throw new Error(`Data product ${e} not found`)})(),i=(n.sourceApplications||[]).map(o=>this.sourceApplicationsCache.get(o)).filter(Boolean);return{data:[n],includes:{sourceApplications:i}}}async batchFetchEventSpecifications(e){if(e.length===0)return;let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/event-specs/v1/versions`;(await this.postResource(n,{eventSpecifications:e})).data.forEach(o=>{let r=this.eventSpecsCache.get(o.id);this.eventSpecsCache.set(o.id,{data:o,metadata:r?.metadata??{outdatedDsWarnings:[],hiddenDsWarnings:[],metrics:[]}})})}async authenticate(){try{return await this.fetchAccessToken(),!0}catch{return!1}}};var F=require("path"),I=require("fs");var Xt=h(require("util")),Yt=require("tsx/cjs/api");var W=(()=>{let t="json";return{setFormat:i=>t=i,getFormat:()=>t}})();var bt=require("@snowplow/snowtype-core");var xt=require("fs");var Ct=h(require("node:assert"));var Te=require("semver");function Fe(t,e,n){try{let i=(0,xt.readFileSync)(n,{encoding:"utf-8"}),o=JSON.parse(i);return o[t].some(a=>a===e)||o[t].push(e),(0,xt.writeFileSync)(n,Jt(o)),!0}catch(i){return console.error(i),!1}}var Ei=(t,e)=>{let{model:n,revision:i,addition:o}=it(t.version),{model:r,revision:a,addition:s}=it(e.version);return(0,Ct.default)(n!==void 0&&i!==void 0&&o!==void 0&&r!==void 0&&a!==void 0&&s!==void 0,`Invalid version number comparing (${t}, ${e})`),n>r?1:n<r?-1:i>a?1:i<a?-1:o>s?1:o<s?-1:t.patchLevel>e.patchLevel&&t.contentHash!==e.contentHash?1:e.patchLevel>t.patchLevel&&t.contentHash!==e.contentHash||t.env==="DEV"&&e.env==="PROD"?-1:t.env==="PROD"&&e.env==="DEV"?1:0};async function Le(t,e,n,i){return(await Promise.all(e.map(async r=>{let{version:a}=T(r),s=await t.fetchDeployments({schema:r,...i&&{deploymentEnv:"PROD"}}),c=Pi(s,a,n);c.sort(Ei);let p=c.pop();if(!p)return null;let d={previous:r,next:De(r,{version:p.version}),nextEnv:p.env};return p.version!==a?{...d,nextReason:"version"}:p.patchLevel>0&&p.env==="DEV"?{...d,nextReason:"patch"}:null}))).flatMap(r=>r===null?[]:[r])}async function Bt(t,e){return Promise.all(e.map(async n=>{try{t.getSchemaVersion({schema:n,env:"PROD"})}catch(i){if(i.response?.statusCode===404||i.message?.includes("not found in PROD environment"))try{return t.getSchemaVersion({schema:n,env:"DEV"}),n}catch(r){if(!(r.response?.statusCode===404||r.message?.includes("not found in DEV environment")))throw r}}return null})).then(n=>n.flatMap(i=>i!==null?[i]:[]))}async function Re(t,e,n){let{eventSpecifications:i}=n,o={};return await Promise.all(e.map(async r=>{let a=!(r in i),s=i[r]??0,c=t.getEventSpecificationById(r).data;if((0,Ct.default)(!!c,`failed to fetch event spec ${r}`),(0,Ct.default)(c.version!=null,`event spec with no version ${r}`),!c.event?.source)return r;let p=[c.event?.source,...c.entities?.tracked?.map(l=>l.source)||[]].flatMap(l=>typeof l=="string"?[l]:[]),d=await Bt(t,p);return(a||(c.version??0)>s)&&(o[r]={previous:s,next:c.version??0,isNew:a,devOnlySchema:d}),r})),o}function Pi(t,e,n){return t.filter(i=>Ht(e,i.version)!==1).filter(i=>i.version!==e||i.patchLevel).map(i=>({...i,updateType:Oe(i.version,e,i.patchLevel)})).filter(Ci(n))}function Ci(t){return({updateType:e})=>{switch(t){case"major":return!0;case"minor":return e==="patch"||e==="minor";case"patch":return e==="patch"}}}function Ht(t,e){let n=t.replaceAll("-","."),i=e.replaceAll("-",".");return(0,Te.compare)(n,i)}var Ne=require("cli-spinner"),w=h(require("chalk"));function Ve(){let t=new Ne.Spinner;return t.setSpinnerString(18),t}var xi="https://snowplow.io",Ai="https://docs.snowplow.io/docs/collecting-data/code-generation/",at={SUCCESS:"\u2714",LOG:"\u2139",DEBUG:"\u27A4",ERROR:"\u2717",WARN:"\u26A0"},je={LINK:"#9911BB",OPTION:"#9911DD"};function $e(t){return w.default.hex(je.LINK).bold(t)}function M(t){return w.default.hex(je.OPTION).italic(t)}function At(t,e){return t==="h1"?w.default.bold.underline(e):w.default.bold(e)}function We(){return`
3
- ${At("h1","CLI Help")}
1
+ "use strict";var po=Object.create;var Jt=Object.defineProperty;var uo=Object.getOwnPropertyDescriptor;var lo=Object.getOwnPropertyNames;var mo=Object.getPrototypeOf,go=Object.prototype.hasOwnProperty;var fo=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of lo(t))!go.call(e,o)&&o!==n&&Jt(e,o,{get:()=>t[o],enumerable:!(i=uo(t,o))||i.enumerable});return e};var y=(e,t,n)=>(n=e!=null?po(mo(e)):{},fo(t||!e||!e.__esModule?Jt(n,"default",{value:e,enumerable:!0}):n,e));var Ui=y(require("process")),B=require("@commander-js/extra-typings");var ho={AuthError:"Authentication failed. Check if your API key and organization ID are correct.",ConfigAlreadyExists:"Snowtype config file already exists.",ConfigNotExists:"Snowtype config file does not exist in current directory. Start with running 'init'.",ConfigInvalid:"Snowtype config exists but it is invalid.",InternalError:"An internal error occured.",InvalidOption:"Invalid option provided.",MissingOptions:"Action called with no options.",WriteLockFile:"Failed writing lock file.",ReadLockFile:"Lock file is invalid or corrupted. Please recover it or delete it, and run `snowtype generate` so a new one will be created.",GenerationFailed:"Something went wrong with code generation.",DuplicateEventSpecification:"The same event specification is reached more than once, from Console or from more than one local data product: ",LocalResource:"A local definition cannot be read: ",LocalVersionMissing:"An event specification in a local data product does not declare its version: ",LocalSchemaMissing:"A schema referenced by a local event specification is not among the repositories or the Iglu Central schemas the configuration declares: ",CheckFailed:"The generated code is not up to date with the tracking definitions. Run `snowtype generate` and commit the result.",PatchingNotSupported:"Patching is only supported using a Snowtype config file in JSON format.",DevNotAllowed:"Code generation using schemas in DEV environment not allowed. Publish the schemas and retry.",AuthCredentialsMissing:"Required API key credentials not detected. Please refer to https://docs.snowplow.io/docs/collecting-data/code-generation/using-the-cli/#authenticating-with-the-console"},So="Please report a bug.",v=class extends Error{code;constructor(t,n=""){let i=ho[t].concat(n);super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t}},Pe=class extends v{constructor(){super("GenerationFailed")}},Ee=class extends v{constructor(t){super("DuplicateEventSpecification",t.join(", "))}},P=class extends v{constructor(t,n){super("LocalResource",`${t}, ${n}`)}},Ce=class extends v{constructor(t){super("LocalVersionMissing",`${t}. Add a version to it in the data product file, matching the version the platform holds.`)}},xe=class extends v{constructor(t,n){super("LocalSchemaMissing",`${n??"no source declared"}, referenced by "${t}"`)}},Ae=class extends v{constructor(t){super("CheckFailed",`
2
+ ${t.map(n=>` ${n}`).join(`
3
+ `)}`)}},de=class extends v{constructor(){super("ConfigAlreadyExists")}},De=class extends v{constructor(){super("ConfigNotExists")}},ke=class extends v{constructor(t){super("ConfigInvalid",t)}},be=class extends v{constructor(t){super("InternalError",t.concat(So))}},Q=class extends v{constructor(t,n){let i=`Value ${n} is an invalid ${t}.`;super("InvalidOption",i)}},Oe=class extends v{constructor(){super("MissingOptions")}},V=class extends v{constructor(){super("AuthError")}},ee=class extends v{constructor(){super("WriteLockFile")}},Te=class extends v{constructor(t){super("ReadLockFile",` ${t}`)}},Le=class extends v{constructor(){super("PatchingNotSupported")}},Fe=class extends v{constructor(){super("DevNotAllowed")}},$e=class extends v{constructor(){super("AuthCredentialsMissing")}};var Kt=y(require("got"));async function qt({schema:e}){return(await(0,Kt.default)(`https://raw.githubusercontent.com/snowplow/iglu-central/master/schemas/${e.replace("iglu:","")}`)).body}var fe=y(require("got"));var tn=require("js-sha256"),st=y(require("node:assert"));var l=y(require("joi")),Ve=require("@snowplow/snowtype-core");var at=y(require("node:assert"));var ue="snowtype.config",Re=".js",Ne=".ts",Me=".json",Xt=Object.freeze([Re,Ne,Me]),te=".snowtype-lock.json",rt="snowplow";var le={"google-tag-manager":[{value:"javascript-gtm",name:"JavaScript"}],"@snowplow/javascript-tracker":[{value:"javascript",name:"JavaScript"}],"@snowplow/browser-tracker":[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"}],"@snowplow/node-tracker":[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"}],"snowplow-android-tracker":[{value:"kotlin",name:"Kotlin"}],"snowplow-ios-tracker":[{value:"swift",name:"Swift"}],"snowplow-golang-tracker":[{value:"go",name:"Go"}],"@snowplow/react-native-tracker":[{value:"typescript",name:"TypeScript"}],"snowplow-flutter-tracker":[{value:"dart",name:"Dart"}],"snowplow-java-tracker":[{value:"java",name:"Java"}]},Yt={commands:{generate:{instructions:!1,validations:!1,disallowDevSchemas:!1,deprecateOnlyOnProdAvailableUpdates:!1},update:{maximumBump:"major",showOnlyProdUpdates:!1,regenerateOnUpdate:!1},patch:{regenerateOnPatch:!1}}},Zt=["iglu:com.snowplowanalytics.snowplow/page_ping/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/link_click/jsonschema/1-0-1","iglu:com.snowplowanalytics.snowplow/page_view/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/screen_view/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/button_click/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/application_background/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/application_foreground/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/application_install/jsonschema/1-0-0","iglu:com.snowplowanalytics.mobile/screen_end/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/custom_event/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/expose_element/jsonschema/1-0-0","iglu:com.snowplowanalytics.snowplow/create_element/jsonschema/1-0-0"],je="iglu:com.snowplowanalytics.snowplow.ecommerce";var We=require("lodash");function en(e){let t=e.split("-");(0,at.default)(t.length===3,"invalid SchemaVer"),(0,at.default)(t.filter(n=>isNaN(parseInt(n))).length===0,"invalid SchemaVer")}function W(e){e.options=(0,We.merge)((0,We.cloneDeep)(Yt),e.options||{})}var Qt=new RegExp("^iglu:[a-zA-Z0-9-_.]+/[a-zA-Z0-9-_]+/[a-zA-Z0-9-_]+/[0-9]+-[0-9]+-[0-9]+$"),vo=new RegExp("^[A-Z][a-zA-Z0-9]*$"),wo=l.default.object().required().keys({tracker:l.default.string().required().valid(...Ve.trackerTemplates),language:l.default.string().required().valid(...Ve.languageIds),outpath:l.default.string().required(),namespace:l.default.when("language",{is:"swift",then:l.default.string().regex(vo).optional(),otherwise:l.default.forbidden().messages({"any.unknown":"namespace is only supported for 'swift' language"})}),organizationId:l.default.string().when("dataStructures",{is:l.default.array().min(1),then:l.default.required(),otherwise:l.default.optional()}).when("eventSpecificationIds",{is:l.default.array().min(1),then:l.default.required(),otherwise:l.default.optional()}).when("dataProductIds",{is:l.default.array().min(1),then:l.default.required(),otherwise:l.default.optional()}),igluCentralSchemas:l.default.array().optional().items(l.default.string().regex(Qt)),repositories:l.default.array().optional().items(l.default.string()),localDataProducts:l.default.array().optional().items(l.default.string()),dataStructures:l.default.array().optional().items(l.default.string().regex(Qt)),eventSpecificationIds:l.default.array().optional().items(l.default.string()),dataProductIds:l.default.array().optional().items(l.default.string()),options:l.default.object().optional().keys({commands:l.default.object().optional().keys({generate:l.default.object().optional().keys({instructions:l.default.boolean().optional(),validations:l.default.boolean().optional(),disallowDevSchemas:l.default.boolean().optional(),deprecateOnlyOnProdAvailableUpdates:l.default.boolean().optional()}),patch:l.default.object().optional().keys({regenerateOnPatch:l.default.boolean().optional()}),update:l.default.object().optional().keys({maximumBump:l.default.string().valid("major","minor","patch").optional(),regenerateOnUpdate:l.default.boolean().optional(),showOnlyProdUpdates:l.default.boolean().optional()})})})}),ne=e=>{let t=wo.validate(e,{abortEarly:!1,convert:!1});if(t.error)throw new ke(t.error.annotate());return e};function yo(e){let t=tn.sha256.create();return t.update(e),t.hex()}function nn(e,t){let{vendor:n,name:i,format:o}=_(e);return yo(`${t}-${n}-${i}-${o}`)}function _(e){let t=e.replace("iglu:",""),[n,i,o,r]=t.split("/");return(0,st.default)(typeof n=="string"&&typeof i=="string"&&typeof o=="string"&&typeof r=="string",`invalid iglu uri ${e}`),en(r),{vendor:n,name:i,format:o,version:r}}function on(e,{vendor:t,name:n,format:i,version:o}){let r=e.replace("iglu:",""),[a,p,s,c]=r.split("/");return`iglu:${t||a}/${n||p}/${i||s}/${o||c}`}function rn(e){return e.some(t=>t.eventSchema.isEcomTemplateSchema)}function me(e){let[t,n,i]=e.split("-").map(o=>parseInt(o));return{model:t,revision:n,addition:i}}function an(e,t,n=0){if(e===t&&n!==0)return"patch";let{model:i,revision:o,addition:r}=me(e),{model:a,revision:p,addition:s}=me(t);if(i!==a)return"major";if(o!==p)return"minor";if(r!==s)return"patch";(0,st.default)(!1,"SchemaVer checking went wrong")}var ge=class extends Error{response;constructor(t){let n=t.response?.statusCode||0,{method:i,url:o}=t.options,r=t.response?.body||t.message,a=[[n,i,o].filter(Boolean).join(" "),r].filter(Boolean).join(`
4
+ `);super(a),this.response={statusCode:n,body:r}}};function ct(e){return!!Object.hasOwn(e||{},"response")}var J="0.20.0";var sn=y(require("p-limit")),T=class e{apiKeyId;apiKey;organizationId;accessToken;pLimit;dataProductsCache=new Map;eventSpecsCache=new Map;schemaVersionsDraftsCache=new Map;schemaVersionsDevCache=new Map;schemaVersionsProdCache=new Map;sourceApplicationsCache=new Map;apiUrl=process.env.SNOWPLOW_CONSOLE_API_URL||"https://console.snowplowanalytics.com/api/msc";constructor({apiKeyId:t,apiKey:n,organizationId:i,requestLimit:o=20}){this.apiKeyId=t,this.apiKey=n,this.organizationId=i,this.pLimit=(0,sn.default)(o)}static async create(t){let n=new e(t);return await n.initialize(t),n}static createLazy(t){return new e(t)}async initialize(t){await this.fetchAccessToken(),t.enableSupportForNonDataProductsTier?await Promise.all([this.bulkFetchAllSchemaDraftsVersions(),this.bulkFetchAllSchemaVersions("DEV"),this.bulkFetchAllSchemaVersions("PROD")]):await Promise.all([this.bulkFetchAllDataProducts(),this.bulkFetchAllEventSpecifications(),this.bulkFetchAllSchemaDraftsVersions(),this.bulkFetchAllSchemaVersions("DEV"),this.bulkFetchAllSchemaVersions("PROD")])}async bulkFetchAllDataProducts(){let t=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-products/v2`,n=await this.fetchResource(t);n.data.forEach(i=>this.dataProductsCache.set(i.id,i)),n.includes.sourceApplications?.forEach(i=>{this.sourceApplicationsCache.set(i.id,i)})}async bulkFetchAllEventSpecifications(){let t=`${this.apiUrl}/v1/organizations/${this.organizationId}/event-specs/v1`,n=await this.fetchResource(t);n.data.forEach(i=>{let o={...n.metadata,outdatedDsWarnings:n.metadata?.outdatedDsWarnings.filter(a=>a.id===i.id)||[],hiddenDsWarnings:n.metadata?.hiddenDsWarnings.filter(a=>a.id===i.id)||[],metrics:n.metadata?.metrics.filter(a=>a.id===i.id)||[]},r={data:i,metadata:o};this.eventSpecsCache.set(i.id,r)})}async bulkFetchAllSchemaVersions(t){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/schemas/versions?env=${t}`,i=await this.fetchResource(n),o=t==="DEV"?this.schemaVersionsDevCache:this.schemaVersionsProdCache;i.forEach(r=>{let a=`iglu:${r.self.vendor}/${r.self.name}/${r.self.format}/${r.self.version}`;o.set(a,r)})}async bulkFetchAllSchemaDraftsVersions(){let t=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structure-drafts/v1/schemas`,n=await this.fetchResource(t),i=this.schemaVersionsDraftsCache;n.forEach(o=>{let r=`iglu:${o.self.vendor}/${o.self.name}/${o.self.format}/${o.self.version}`;i.set(r,o)})}async fetchAccessToken(){if(this.accessToken)return this.accessToken;let t=`${this.apiUrl}/v1/organizations/${this.organizationId}/credentials/v3/token`,{accessToken:n}=await(0,fe.default)(t,{headers:{"X-API-Key-Id":this.apiKeyId,"X-API-Key":this.apiKey,"X-Snowtype":J}}).json();return this.accessToken=n,n}fetchResource(t){return this.pLimit(async()=>{try{let n=await this.fetchAccessToken();return await(0,fe.default)(t,{headers:{Authorization:"Bearer "+n,"X-Snowtype":J}}).json()}catch(n){throw ct(n)?new ge(n):n}})}postResource(t,n){return this.pLimit(async()=>{try{let i=await this.fetchAccessToken();return await fe.default.post(t,{headers:{Authorization:"Bearer "+i,"X-Snowtype":J},json:n}).json()}catch(i){throw ct(i)?new ge(i):i}})}getSchemaVersion({schema:t,env:n="DEV"}){return(n==="DEV"?this.schemaVersionsDevCache:this.schemaVersionsProdCache).get(t)??(()=>{throw new Error(`Schema ${t} not found in ${n} environment`)})()}getAllSchemaDraftVersion(){return this.schemaVersionsDraftsCache}async fetchDeployments({schema:t,deploymentEnv:n}){let i=nn(t,this.organizationId),o=25,r=[],a=!0,p=0,s=c=>`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${i}/deployments?size=${o}&from=${c}${n?`&env=${n}`:""}`;for(;a;){let c=await this.fetchResource(s(p));p+=o,r=r.concat(c),c.length===0&&(a=!1)}return r}getEventSpecificationById(t){let n=this.eventSpecsCache.get(t)??(()=>{throw new Error(`Event specification ${t} not found`)})();return{data:n.data,metadata:n.metadata}}async fetchImageVariant({imageId:t,imageVariant:n}){let i=`${this.apiUrl}/v1/organizations/${this.organizationId}/images/v1/${t}/${n}`,o=await this.fetchAccessToken();return(0,fe.default)(i,{headers:{Authorization:"Bearer "+o,"X-Snowtype":J}})}getDataProductById(t){let n=this.dataProductsCache.get(t)??(()=>{throw new Error(`Data product ${t} not found`)})(),i=(n.sourceApplications||[]).map(o=>this.sourceApplicationsCache.get(o)).filter(Boolean);return{data:[n],includes:{sourceApplications:i}}}async batchFetchEventSpecifications(t){if(t.length===0)return;let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/event-specs/v1/versions`;(await this.postResource(n,{eventSpecifications:t})).data.forEach(o=>{let r=this.eventSpecsCache.get(o.id);this.eventSpecsCache.set(o.id,{data:o,metadata:r?.metadata??{outdatedDsWarnings:[],hiddenDsWarnings:[],metrics:[]}})})}async authenticate(){try{return await this.fetchAccessToken(),!0}catch{return!1}}};var U=require("path"),x=require("fs");var ft=y(require("util")),ht=require("tsx/cjs/api");var K=(()=>{let e="json";return{setFormat:i=>e=i,getFormat:()=>e}})();var Be=require("@snowplow/snowtype-core");var Ue=require("fs");var _e=y(require("node:assert"));var cn=require("semver");function pn(e,t,n){try{let i=(0,Ue.readFileSync)(n,{encoding:"utf-8"}),o=JSON.parse(i);return o[e].some(a=>a===t)||o[e].push(t),(0,Ue.writeFileSync)(n,ut(o)),!0}catch(i){return console.error(i),!1}}var Io=(e,t)=>{let{model:n,revision:i,addition:o}=me(e.version),{model:r,revision:a,addition:p}=me(t.version);return(0,_e.default)(n!==void 0&&i!==void 0&&o!==void 0&&r!==void 0&&a!==void 0&&p!==void 0,`Invalid version number comparing (${e}, ${t})`),n>r?1:n<r?-1:i>a?1:i<a?-1:o>p?1:o<p?-1:e.patchLevel>t.patchLevel&&e.contentHash!==t.contentHash?1:t.patchLevel>e.patchLevel&&e.contentHash!==t.contentHash||e.env==="DEV"&&t.env==="PROD"?-1:e.env==="PROD"&&t.env==="DEV"?1:0};async function dn(e,t,n,i){return(await Promise.all(t.map(async r=>{let{version:a}=_(r),p=await e.fetchDeployments({schema:r,...i&&{deploymentEnv:"PROD"}}),s=Po(p,a,n);s.sort(Io);let c=s.pop();if(!c)return null;let d={previous:r,next:on(r,{version:c.version}),nextEnv:c.env};return c.version!==a?{...d,nextReason:"version"}:c.patchLevel>0&&c.env==="DEV"?{...d,nextReason:"patch"}:null}))).flatMap(r=>r===null?[]:[r])}async function pt(e,t){return Promise.all(t.map(async n=>{try{e.getSchemaVersion({schema:n,env:"PROD"})}catch(i){if(i.response?.statusCode===404||i.message?.includes("not found in PROD environment"))try{return e.getSchemaVersion({schema:n,env:"DEV"}),n}catch(r){if(!(r.response?.statusCode===404||r.message?.includes("not found in DEV environment")))throw r}}return null})).then(n=>n.flatMap(i=>i!==null?[i]:[]))}async function un(e,t,n){let{eventSpecifications:i}=n,o={};return await Promise.all(t.map(async r=>{let a=!(r in i),p=i[r]??0,s=e.getEventSpecificationById(r).data;if((0,_e.default)(!!s,`failed to fetch event spec ${r}`),(0,_e.default)(s.version!=null,`event spec with no version ${r}`),!s.event?.source)return r;let c=[s.event?.source,...s.entities?.tracked?.map(u=>u.source)||[]].flatMap(u=>typeof u=="string"?[u]:[]),d=await pt(e,c);return(a||(s.version??0)>p)&&(o[r]={previous:p,next:s.version??0,isNew:a,devOnlySchema:d}),r})),o}function Po(e,t,n){return e.filter(i=>dt(t,i.version)!==1).filter(i=>i.version!==t||i.patchLevel).map(i=>({...i,updateType:an(i.version,t,i.patchLevel)})).filter(Eo(n))}function Eo(e){return({updateType:t})=>{switch(e){case"major":return!0;case"minor":return t==="patch"||t==="minor";case"patch":return t==="patch"}}}function dt(e,t){let n=e.replaceAll("-","."),i=t.replaceAll("-",".");return(0,cn.compare)(n,i)}var mn=require("cli-spinner"),C=y(require("chalk"));function gn(){let e=new mn.Spinner;return e.setSpinnerString(18),e}var Co="https://snowplow.io",xo="https://docs.snowplow.io/docs/collecting-data/code-generation/",he={SUCCESS:"\u2714",LOG:"\u2139",DEBUG:"\u27A4",ERROR:"\u2717",WARN:"\u26A0"},fn={LINK:"#9911BB",OPTION:"#9911DD"};function ln(e){return C.default.hex(fn.LINK).bold(e)}function q(e){return C.default.hex(fn.OPTION).italic(e)}function Ge(e,t){return e==="h1"?C.default.bold.underline(t):C.default.bold(t)}function hn(){return`
5
+ ${Ge("h1","CLI Help")}
4
6
 
5
- For more information visit the Snowplow website ${$e(xi)}
7
+ For more information visit the Snowplow website ${ln(Co)}
6
8
 
7
- For details see the CLI documentation ${$e(Ai)}
9
+ For details see the CLI documentation ${ln(xo)}
8
10
 
9
- ${At("h2","How to get started")}
10
- 1. Use ${w.default.cyanBright("snowtype init")} to initialize the setup.
11
- 2. Use ${w.default.cyanBright("snowtype patch")} to add a Data Structure or Event Specification.
12
- 3. Use ${w.default.cyanBright("snowtype generate")} to generate tracking code.
11
+ ${Ge("h2","How to get started")}
12
+ 1. Use ${C.default.cyanBright("snowtype init")} to initialize the setup.
13
+ 2. Use ${C.default.cyanBright("snowtype patch")} to add a Data Structure or Event Specification.
14
+ 3. Use ${C.default.cyanBright("snowtype generate")} to generate tracking code.
13
15
 
14
- ${At("h2","Available commands")}
15
- To learn more about each CLI command, use the ${M("--help")} option, for example, ${M("snowtype init --help")}.
16
+ ${Ge("h2","Available commands")}
17
+ To learn more about each CLI command, use the ${q("--help")} option, for example, ${q("snowtype init --help")}.
16
18
 
17
- ${M("snowtype init")}
19
+ ${q("snowtype init")}
18
20
  Initialize the setup of Snowtype code generation in a project. Creates the \`snowtype.config.json\` file.
19
21
 
20
- ${M("snowtype patch")}
22
+ ${q("snowtype patch")}
21
23
  Adds new Data Structures and Event Specifications in the \`snowtype.config.json\` file.
22
24
 
23
- ${M("snowtype generate")}
25
+ ${q("snowtype generate")}
24
26
  Generates tracking code based on configuration on the \`snowtype.config.json\` file.
25
27
 
26
- ${M("snowtype update")}
28
+ ${q("snowtype update")}
27
29
  Checks for latest version updates in Data Structures and Event Specifications.
28
30
 
29
- ${At("h2","Debug")}
30
- Use the ${M("-v")} to output verbose logs
31
- `}function Me(t){let e=`${at.SUCCESS}: `;return w.default.cyanBright(e)+t}function Dt(t){let e=`${at.WARN} Warning: `;return w.default.hex("#FFA500")(e)+t}function _e(t){let e=`${at.LOG} ${t}`;return w.default.yellowBright(e)}function Ue(t){let e=`${at.DEBUG} Debug: `;return w.default.magenta(e)+t}function Ge(t){let e=`${at.ERROR} Error: `;return w.default.redBright(e)+t}function ze(t,e){let n=`- ${t}`,i=`+ ${e}`;return`
32
- ${w.default.magenta(n)}
33
- ${w.default.cyanBright(i)}
34
- `}var qe=h(require("mime-types"));var Be=t=>{let e={outdatedDsWarnings:[],hiddenDsWarnings:[],metrics:[]};return t.reduce((n,i)=>Di({currentMetadata:n,eventSpecificationId:i.eventSpecification.id,newMetadata:i.metadata||e}),{})};function Di({currentMetadata:t,eventSpecificationId:e,newMetadata:n}){let i=(o,r)=>o.id>r.id?1:-1;return{...t,[e]:{hiddenDsWarnings:n.hiddenDsWarnings.sort(i).map(o=>({sources:o.sources})),outdatedDsWarnings:n.outdatedDsWarnings.sort(i).map(o=>({sources:o.sources}))}}}var He=t=>(e,n)=>{bi(e,n||"").forEach(t.warn)};function bi(t,e){let n=Oi(t.outdatedDsWarnings,e),i=ki(t.hiddenDsWarnings,e);return n.concat(i)}function Oi(t,e){return t.reduce((n,i)=>{let o=i.sources.map(r=>[`Source: ${r.source}`,`Latest Version: ${r.latestVersion}`].join(`
35
- `));return[...n,`${["Outdated Data Structures detected:",`Data Product Id: ${e}`,`Event Specification Id: ${i.id}`,...o].join(`
36
- `)}`]},[])}function ki(t,e){return t.reduce((n,i)=>{let o=i.sources.map(r=>`Source: ${r.source}`).join(`
37
- `);return[...n,`${["Hidden Data Structures detected:",`Data Product Id: ${e}`,`Event Specification Id: ${i.id}`,o].join(`
38
- `)}`]},[])}async function Je(t,e){let n=Fi(t),i=await Promise.all(n.map(async r=>({schema:r,deployments:await e.fetchDeployments({schema:r,deploymentEnv:"PROD"})}))),o=Ti(i);return Li(t,o)}var Ti=t=>t.flatMap(({schema:e,deployments:n})=>{let{version:i}=T(e);return n.filter(r=>Ht(i,r.version)===-1).length===0?[]:[e]}),Fi=t=>_(Object.entries(t).filter(([,e])=>e.outdatedDsWarnings.length!==0).flatMap(([,e])=>e.outdatedDsWarnings.flatMap(n=>n.sources.map(i=>i.source)))),Li=(t,e)=>Object.keys(t).reduce((n,i)=>{let o=t[i];if(o){let r=o.outdatedDsWarnings.flatMap(({sources:a})=>{let s=a.filter(c=>e.includes(c.source));return s.length>0?[{sources:s}]:[]});n[i]={...o,outdatedDsWarnings:r}}return n},{});function U(t,e){return e.map(i=>t.getDataProductById(i)).flatMap(({data:[i]})=>i?i.eventSpecs:[]).map(i=>i.id)}function Ri(t){let{original:e}=t,[n,i]=e.split("/").reverse();return{imageVariant:n,imageId:i}}async function Xe(t,e){let n=[];if(!(e&&e.length))return[];for(let i of e){let{description:o,appIds:r,url:a,variantUrls:s}=i,c={description:o,appIds:r,url:a};if(s){let{imageVariant:p,imageId:d}=Ri(s),l=await t.fetchImageVariant({imageId:d,imageVariant:p});c.imageBuffer=l.rawBody,c.imageExtension=qe.default.extension(l.headers["content-type"])||""}n.push(c)}return n}function Ye(t,e,n){return{eventSpecificationsWithId:e.map(o=>{let r=t.getEventSpecificationById(o),a=r.data;if(typeof a>"u"||typeof a.event>"u")return[];r.metadata&&He(n)(r.metadata,a.dataProductId);let c=Kt(a.event.source);c&&n.warn("Currently code will not be generated for `Standard` events. Skipping...");let p=a.triggers,d=a.name,l=a.version,S=a.sourceApplications||[],m=a.event.schema,g=c?Ni(a.event.source):Ke(t,a,a.event.source),f=a.entities?.tracked||[],x=f.map(({source:G,schema:v,minCardinality:E})=>({original:Ke(t,a,G),propertyRule:v,minCardinality:E}));return{eventSpecification:{name:d||"",id:o,dataProductId:a.dataProductId||"",dataProductName:""},version:l||0,eventSchema:g,entitiesSchemas:x,entities:f,triggers:p,propertyRules:m,sourceApplicationIds:S,metadata:r.metadata}}).flat()}}async function Ze(t){return await Promise.all(t.map(async n=>JSON.parse(await ve({schema:n}))))}async function Qe(t,e){return await Promise.all(e.map(i=>t.getSchemaVersion({schema:i})))}function tn(t,e){return e.flatMap(({eventSpecification:{dataProductId:r}})=>r?[r]:[]).map(r=>t.getDataProductById(r)).map(r=>r.data[0]&&{...r.data[0],sourceApplications:(r.includes.sourceApplications||[]).filter(a=>a!==void 0)}).filter($i)}function en(t,e){let n=t.reduce((o,r)=>(o[r.id]={...r},o),{});return e.map(o=>{let r=n[o.eventSpecification.dataProductId],a=o.sourceApplicationIds.flatMap(s=>r?.sourceApplications.find(c=>c.id===s)||[]);return{...o,eventSpecification:{id:o.eventSpecification.id,name:o.eventSpecification.name,dataProductId:r?.id||"",dataProductName:r?.name||"",...r?.domain?{dataProductDomain:r.domain}:{}},sourceApplications:a}})}function $i(t){return!!t}function Ke(t,e,n){let i=e.event?.schema?.properties?.type?.enum?.[0];return n.match(Ee)?{self:T(n),isEcomTemplateSchema:i}:t.getSchemaVersion({schema:n})}function nn(t){return t.reduce((n,i)=>{let o=i.eventSpecification.id;return i.entities.forEach(({source:r,minCardinality:a,maxCardinality:s})=>{if(typeof a<"u"||typeof s<"u"){let c={minCardinality:a,maxCardinality:s};n[o]=n[o]||{},n[o][r]=c}}),n},{})}function Ni(t){return{self:{...T(t)}}}function on(t,e,n){return t.filter(i=>{let{data:o}=e.getEventSpecificationById(i),r=e.getAllSchemaDraftVersion(),a=o.event?r.has(o.event.source):!1,s=o.entities?.tracked?o.entities.tracked.filter(c=>r.has(c.source)):[];if(a||s.length>0){let c=[];if(a&&o.event&&c.push(`Event DS: ${o.event.source}`),s.length>0){let p=s.map(d=>d.source).join(", ");c.push(`Entity DS: [${p}]`)}return n.warn(`Event specification with ID "${i}" has been excluded because it contains draft data structures - ${c.join(" | ")}`),!1}else return!0})}function rn(t,e,n){return t.filter(i=>{let o=e.getAllSchemaDraftVersion().has(i);return o&&n.warn(`DS ${i} is skipped because it is draft`),!o})}var Vi="SNOWPLOW_CONSOLE_API_KEY_ID",ji="SNOWPLOW_CONSOLE_API_KEY";function cn(t){return t.length!==0}function Jt(t){return JSON.stringify(t,null,2)}function pn(t){let e={organizationId:t.organizationId,tracker:t.tracker,language:t.language,outpath:t.outpath};return Object.assign({igluCentralSchemas:[],dataStructures:[],repositories:[],eventSpecificationIds:[],dataProductIds:[]},e)}function Wi(t){switch(t){case"typescript":return`${et}${wt}`;case"javascript":return`${et}${yt}`;case"json":return`${et}${It}`;default:return""}}var an=t=>(0,I.existsSync)(t)&&!(0,I.lstatSync)(t).isDirectory(),Mi=t=>et+t,_i=t=>({isTS:t.endsWith(wt),isJSON:t.endsWith(It),isJS:t.endsWith(yt)}),qt=t=>({configDir:(0,F.dirname)(t),configPath:t,..._i(t)});function D(t){let e=(0,F.isAbsolute)(t)?t:(0,F.resolve)(process.cwd(),t);if(an(e))return qt(e);if(!(0,I.existsSync)(e))throw new Error(`Can't find a root directory while resolving a config file path.
39
- Provided path to resolve: ${t}
40
- cwd: ${process.cwd()}`);let[n]=ye.map(i=>(0,F.resolve)(e,Mi(i))).filter(an);return qt(typeof n!="string"?e:n)}function Ot(t,e){let n=W.getFormat(),i=Wi(n),o=(0,F.resolve)(e,i),r=`const config = ${Xt.default.inspect(t,!1,null)}
41
- `,a='import { SnowtypeConfig } from "@snowplow/snowtype/types";',s=`const config: SnowtypeConfig = ${Xt.default.inspect(t,!1,null)}
42
- `,c="module.exports = config;",p="export default config;";return n==="json"?(0,I.writeFileSync)(o,Jt(t)):(0,I.writeFileSync)(o,(n==="typescript"?[a,s,p]:[r,c]).join(`
43
- `))}function L(t){let e=(0,I.statSync)(t,{throwIfNoEntry:!1});return e===void 0?!1:e.isFile()}function Zt(t){return(0,I.readFileSync)(t,{encoding:"utf-8"})}var Ui=async t=>(await(0,Yt.require)(t,__filename)).default;async function R(t){let{configPath:e,isJS:n,isJSON:i,isTS:o}=D(t),r;return o?(r=await Ui(e),W.setFormat("typescript")):n?(r=(await import(e)).default,W.setFormat("javascript")):i&&(r=JSON.parse(Zt(e)),W.setFormat("json")),typeof r=="function"&&(r=await r()),r}function q(t){try{return JSON.parse(Zt(t))}catch(e){throw new ft(e instanceof Error?e.message:String(e))}}async function un(t,e){t.debug("Checking for existing configuration.."),await Qt(!0,e),t.success("Valid configuration found")}async function Qt(t,e){let{configPath:n,isJS:i,isJSON:o,isTS:r}=D(e),a=o===!0||r===!0||i===!0,s=r===!1&&i===!1&&o===!1,c;if(r?c=(await(0,Yt.require)(n,__filename)).default:i?c=(await import(n)).default:o&&(c=JSON.parse(Zt(n))),typeof c=="function"&&(c=await c()),t){if(s)throw new dt;K(c)}else if(a)try{throw K(c),new tt}catch(p){if(p instanceof tt)throw p}}function dn(t){return{javascript:".js","javascript-gtm":".js",typescript:".ts",kotlin:".kt",swift:".swift",go:".go",dart:".dart",java:".java"}[t]||""}function ln(t,e){let n={eventSpecifications:{}};t.forEach(i=>{n.eventSpecifications[i.eventSpecification.id]=i.version});try{(0,I.writeFileSync)(e,JSON.stringify(n,null,2))}catch{throw new H}}function gn(t,e){let n=q(e),i={...n,eventSpecifications:{...n.eventSpecifications,...t}};try{(0,I.writeFileSync)(e,JSON.stringify(i,null,2))}catch{throw new H}}function mn(t,e){return t.reduce((n,i)=>(i in e.eventSpecifications?(n.lockedIds.push(i),n.batchSpecs.push({id:i,version:e.eventSpecifications[i]})):n.skippedIds.push(i),n),{lockedIds:[],skippedIds:[],batchSpecs:[]})}function fn(t,e){if(!L(e))return[];let n=q(e),i=new Set(t),o=[];for(let r of Object.keys(n.eventSpecifications))i.has(r)||(o.push(r),delete n.eventSpecifications[r]);if(o.length===0)return[];try{(0,I.writeFileSync)(e,JSON.stringify(n,null,2))}catch{throw new H}return o}function hn(t,e,n){let i=Object.entries(t);i.length>0&&n.success("Available Event Specification Updates"),i.forEach(([o,r])=>{n.diff(r.isNew?`${o}: (new)`:`${o}: version ${r.previous}`,`${o}: version ${r.next}`),r.devOnlySchema.length>0&&(n.warn("This Event Specification uses schema that are not in production."),n.warn(r.devOnlySchema.join(" ")))}),e.length>0&&n.success("Available Data Structures Updates"),e.forEach(o=>{let r=`${o.previous}`,a=`${o.next}`;if(n.diff(r,a),o.nextReason==="patch"&&n.warn("The most recent version of this schema has been patched. Possible update required."),o.nextEnv==="DEV"){let s=o.next.split("/").pop();n.warn(`This data structure version (${s}) is not in production.`)}})}function Sn(t){let e=t.optsWithGlobals();return{...e,apiKeyId:e.apiKeyId||process.env[Vi],apiKey:e.apiKey||process.env[ji]}}function C(t){return!!(Array.isArray(t)&&!t.length)}function _(t){return[...new Set(t)]}function kt(t){let e=_(t);return e.sort(),e}function Gi(t){return t.flatMap(e=>{let n=(0,bt.joinIgluSchemaUrlParts)(e.eventSchema.self),i=e.entities.map(o=>o.source);return[n,...i]})}async function vn(t,e,n,i){let o=t.map(s=>(0,bt.joinIgluSchemaUrlParts)(s.self)),r=Gi(e),a=await Bt(n,_([...o,...r]));if(a.length>0&&(console.log(`
44
- `,Dt(`Generating code using schemas in DEV environment, tracking against those will result in failed events. Schemas in DEV:
31
+ ${Ge("h2","Debug")}
32
+ Use the ${q("-v")} to output verbose logs
33
+ `}function Sn(e){let t=`${he.SUCCESS}: `;return C.default.cyanBright(t)+e}function ze(e){let t=`${he.WARN} Warning: `;return C.default.hex("#FFA500")(t)+e}function vn(e){let t=`${he.LOG} ${e}`;return C.default.yellowBright(t)}function wn(e){let t=`${he.DEBUG} Debug: `;return C.default.magenta(t)+e}function yn(e){let t=`${he.ERROR} Error: `;return C.default.redBright(t)+e}function In(e,t){let n=`- ${e}`,i=`+ ${t}`;return`
34
+ ${C.default.magenta(n)}
35
+ ${C.default.cyanBright(i)}
36
+ `}var An=y(require("mime-types")),Dn=y(require("fs/promises")),kn=require("path");var Pn=e=>{let t={outdatedDsWarnings:[],hiddenDsWarnings:[],metrics:[]};return e.reduce((n,i)=>lt({currentMetadata:n,eventSpecificationId:i.eventSpecification.id,newMetadata:i.metadata||t}),{})};function lt({currentMetadata:e,eventSpecificationId:t,newMetadata:n}){let i=(o,r)=>o.id>r.id?1:-1;return{...e,[t]:{hiddenDsWarnings:n.hiddenDsWarnings.sort(i).map(o=>({sources:o.sources})),outdatedDsWarnings:n.outdatedDsWarnings.sort(i).map(o=>({sources:o.sources}))}}}var En=e=>(t,n)=>{Ao(t,n||"").forEach(e.warn)};function Ao(e,t){let n=Do(e.outdatedDsWarnings,t),i=ko(e.hiddenDsWarnings,t);return n.concat(i)}function Do(e,t){return e.reduce((n,i)=>{let o=i.sources.map(r=>[`Source: ${r.source}`,`Latest Version: ${r.latestVersion}`].join(`
37
+ `));return[...n,`${["Outdated Data Structures detected:",`Data Product Id: ${t}`,`Event Specification Id: ${i.id}`,...o].join(`
38
+ `)}`]},[])}function ko(e,t){return e.reduce((n,i)=>{let o=i.sources.map(r=>`Source: ${r.source}`).join(`
39
+ `);return[...n,`${["Hidden Data Structures detected:",`Data Product Id: ${t}`,`Event Specification Id: ${i.id}`,o].join(`
40
+ `)}`]},[])}async function Cn(e,t){let n=Oo(e),i=await Promise.all(n.map(async r=>({schema:r,deployments:await t.fetchDeployments({schema:r,deploymentEnv:"PROD"})}))),o=bo(i);return To(e,o)}var bo=e=>e.flatMap(({schema:t,deployments:n})=>{let{version:i}=_(t);return n.filter(r=>dt(i,r.version)===-1).length===0?[]:[t]}),Oo=e=>X(Object.entries(e).filter(([,t])=>t.outdatedDsWarnings.length!==0).flatMap(([,t])=>t.outdatedDsWarnings.flatMap(n=>n.sources.map(i=>i.source)))),To=(e,t)=>Object.keys(e).reduce((n,i)=>{let o=e[i];if(o){let r=o.outdatedDsWarnings.flatMap(({sources:a})=>{let p=a.filter(s=>t.includes(s.source));return p.length>0?[{sources:p}]:[]});n[i]={...o,outdatedDsWarnings:r}}return n},{});function Y(e,t){return t.map(i=>e.getDataProductById(i)).flatMap(({data:[i]})=>i?i.eventSpecs:[]).map(i=>i.id)}function Lo(e){let{original:t}=e,[n,i]=t.split("/").reverse();return{imageVariant:n,imageId:i}}async function bn(e,t){let n=[];if(!(t&&t.length))return[];for(let i of t){let{description:o,appIds:r,url:a,variantUrls:p,imagePath:s}=i,c={description:o,appIds:r,url:a};if(s!==void 0)c.imageBuffer=await Dn.default.readFile(s),c.imageExtension=(0,kn.extname)(s).replace(".","");else if(p){let{imageVariant:d,imageId:u}=Lo(p),g=await e.fetchImageVariant({imageId:u,imageVariant:d});c.imageBuffer=g.rawBody,c.imageExtension=An.default.extension(g.headers["content-type"])||""}n.push(c)}return n}function On(e,t,n){return{eventSpecificationsWithId:t.map(o=>{let r=e.getEventSpecificationById(o),a=r.data;if(typeof a>"u"||typeof a.event>"u")return[];r.metadata&&En(n)(r.metadata,a.dataProductId);let s=M(a.event.source);s&&n.warn("Currently code will not be generated for `Standard` events. Skipping...");let c=a.triggers,d=a.name,u=a.version,g=a.sourceApplications||[],f=a.event.schema,w=s?mt(a.event.source):xn(e,a,a.event.source),h=a.entities?.tracked||[],m=h.map(({source:D,schema:S,minCardinality:E})=>({original:xn(e,a,D),propertyRule:S,minCardinality:E}));return{eventSpecification:{name:d||"",id:o,dataProductId:a.dataProductId||"",dataProductName:""},version:u||0,eventSchema:w,entitiesSchemas:m,entities:h,triggers:c,propertyRules:f,sourceApplicationIds:g,metadata:r.metadata}}).flat()}}async function Tn(e){return await Promise.all(e.map(async n=>JSON.parse(await qt({schema:n}))))}async function Ln(e,t){return await Promise.all(t.map(i=>e.getSchemaVersion({schema:i})))}function Fn(e,t){return t.flatMap(({eventSpecification:{dataProductId:r}})=>r?[r]:[]).map(r=>e.getDataProductById(r)).map(r=>r.data[0]&&{...r.data[0],sourceApplications:(r.includes.sourceApplications||[]).filter(a=>a!==void 0)}).filter(Fo)}function $n(e,t){let n=e.reduce((o,r)=>(o[r.id]={...r},o),{});return t.map(o=>{let r=n[o.eventSpecification.dataProductId],a=o.sourceApplicationIds.flatMap(p=>r?.sourceApplications.find(s=>s.id===p)||[]);return{...o,eventSpecification:{id:o.eventSpecification.id,name:o.eventSpecification.name,dataProductId:r?.id||"",dataProductName:r?.name||"",...r?.domain?{dataProductDomain:r.domain}:{}},sourceApplications:a}})}function Fo(e){return!!e}function xn(e,t,n){let i=t.event?.schema?.properties?.type?.enum?.[0];return n.match(je)?{self:_(n),isEcomTemplateSchema:i}:e.getSchemaVersion({schema:n})}function Rn(e){return e.reduce((n,i)=>{let o=i.eventSpecification.id;return i.entities.forEach(({source:r,minCardinality:a,maxCardinality:p})=>{if(typeof a<"u"||typeof p<"u"){let s={minCardinality:a,maxCardinality:p};n[o]=n[o]||{},n[o][r]=s}}),n},{})}function mt(e){return{self:{..._(e)}}}function Nn(e,t,n){return e.filter(i=>{let{data:o}=t.getEventSpecificationById(i),r=t.getAllSchemaDraftVersion(),a=o.event?r.has(o.event.source):!1,p=o.entities?.tracked?o.entities.tracked.filter(s=>r.has(s.source)):[];if(a||p.length>0){let s=[];if(a&&o.event&&s.push(`Event DS: ${o.event.source}`),p.length>0){let c=p.map(d=>d.source).join(", ");s.push(`Entity DS: [${c}]`)}return n.warn(`Event specification with ID "${i}" has been excluded because it contains draft data structures - ${s.join(" | ")}`),!1}else return!0})}function Mn(e,t,n){return e.filter(i=>{let o=t.getAllSchemaDraftVersion().has(i);return o&&n.warn(`DS ${i} is skipped because it is draft`),!o})}var $o="SNOWPLOW_CONSOLE_API_KEY_ID",Ro="SNOWPLOW_CONSOLE_API_KEY";function Wn(e){return e.length!==0}function ut(e){return JSON.stringify(e,null,2)}function _n(e){let t={organizationId:e.organizationId,tracker:e.tracker,language:e.language,outpath:e.outpath};return Object.assign({igluCentralSchemas:[],dataStructures:[],repositories:[],localDataProducts:[],eventSpecificationIds:[],dataProductIds:[]},t)}function No(e){switch(e){case"typescript":return`${ue}${Ne}`;case"javascript":return`${ue}${Re}`;case"json":return`${ue}${Me}`;default:return""}}var jn=e=>(0,x.existsSync)(e)&&!(0,x.lstatSync)(e).isDirectory(),Mo=e=>ue+e,jo=e=>({isTS:e.endsWith(Ne),isJSON:e.endsWith(Me),isJS:e.endsWith(Re)}),gt=e=>({configDir:(0,U.dirname)(e),configPath:e,...jo(e)});function F(e){let t=(0,U.isAbsolute)(e)?e:(0,U.resolve)(process.cwd(),e);if(jn(t))return gt(t);if(!(0,x.existsSync)(t))throw new Error(`Can't find a root directory while resolving a config file path.
41
+ Provided path to resolve: ${e}
42
+ cwd: ${process.cwd()}`);let[n]=Xt.map(i=>(0,U.resolve)(t,Mo(i))).filter(jn);return gt(typeof n!="string"?t:n)}function He(e,t){let n=K.getFormat(),i=No(n),o=(0,U.resolve)(t,i),r=`const config = ${ft.default.inspect(e,!1,null)}
43
+ `,a='import { SnowtypeConfig } from "@snowplow/snowtype/types";',p=`const config: SnowtypeConfig = ${ft.default.inspect(e,!1,null)}
44
+ `,s="module.exports = config;",c="export default config;";return n==="json"?(0,x.writeFileSync)(o,ut(e)):(0,x.writeFileSync)(o,(n==="typescript"?[a,p,c]:[r,s]).join(`
45
+ `))}function $(e){let t=(0,x.statSync)(e,{throwIfNoEntry:!1});return t===void 0?!1:t.isFile()}function St(e){return(0,x.readFileSync)(e,{encoding:"utf-8"})}var Vo=async e=>(await(0,ht.require)(e,__filename)).default;async function R(e){let{configPath:t,isJS:n,isJSON:i,isTS:o}=F(e),r;return o?(r=await Vo(t),K.setFormat("typescript")):n?(r=(await import(t)).default,K.setFormat("javascript")):i&&(r=JSON.parse(St(t)),K.setFormat("json")),typeof r=="function"&&(r=await r()),r}function ie(e){try{return JSON.parse(St(e))}catch(t){throw new Te(t instanceof Error?t.message:String(t))}}async function Un(e,t){e.debug("Checking for existing configuration.."),await vt(!0,t),e.success("Valid configuration found")}async function vt(e,t){let{configPath:n,isJS:i,isJSON:o,isTS:r}=F(t),a=o===!0||r===!0||i===!0,p=r===!1&&i===!1&&o===!1,s;if(r?s=(await(0,ht.require)(n,__filename)).default:i?s=(await import(n)).default:o&&(s=JSON.parse(St(n))),typeof s=="function"&&(s=await s()),e){if(p)throw new De;ne(s)}else if(a)try{throw ne(s),new de}catch(c){if(c instanceof de)throw c}}function Gn(e){return{javascript:".js","javascript-gtm":".js",typescript:".ts",kotlin:".kt",swift:".swift",go:".go",dart:".dart",java:".java"}[e]||""}function zn(e,t){let n={eventSpecifications:{}};e.forEach(i=>{n.eventSpecifications[i.eventSpecification.id]=i.version});try{(0,x.writeFileSync)(t,JSON.stringify(n,null,2))}catch{throw new ee}}function Bn(e,t){let n=ie(t),i={...n,eventSpecifications:{...n.eventSpecifications,...e}};try{(0,x.writeFileSync)(t,JSON.stringify(i,null,2))}catch{throw new ee}}function Hn(e,t){return e.reduce((n,i)=>(i in t.eventSpecifications?(n.lockedIds.push(i),n.batchSpecs.push({id:i,version:t.eventSpecifications[i]})):n.skippedIds.push(i),n),{lockedIds:[],skippedIds:[],batchSpecs:[]})}function Jn(e,t){if(!$(t))return[];let n=ie(t),i=new Set(e),o=[];for(let r of Object.keys(n.eventSpecifications))i.has(r)||(o.push(r),delete n.eventSpecifications[r]);if(o.length===0)return[];try{(0,x.writeFileSync)(t,JSON.stringify(n,null,2))}catch{throw new ee}return o}function Kn(e,t,n){let i=Object.entries(e);i.length>0&&n.success("Available Event Specification Updates"),i.forEach(([o,r])=>{n.diff(r.isNew?`${o}: (new)`:`${o}: version ${r.previous}`,`${o}: version ${r.next}`),r.devOnlySchema.length>0&&(n.warn("This Event Specification uses schema that are not in production."),n.warn(r.devOnlySchema.join(" ")))}),t.length>0&&n.success("Available Data Structures Updates"),t.forEach(o=>{let r=`${o.previous}`,a=`${o.next}`;if(n.diff(r,a),o.nextReason==="patch"&&n.warn("The most recent version of this schema has been patched. Possible update required."),o.nextEnv==="DEV"){let p=o.next.split("/").pop();n.warn(`This data structure version (${p}) is not in production.`)}})}function qn(e){let t=e.optsWithGlobals();return{...t,apiKeyId:t.apiKeyId||process.env[$o],apiKey:t.apiKey||process.env[Ro]}}function L(e){return!!(Array.isArray(e)&&!e.length)}function X(e){return[...new Set(e)]}function Je(e){let t=X(e);return t.sort(),t}function Wo(e){return e.flatMap(t=>{let n=(0,Be.joinIgluSchemaUrlParts)(t.eventSchema.self),i=t.entities.map(o=>o.source);return[n,...i]})}async function Xn(e,t,n,i){let o=e.map(p=>(0,Be.joinIgluSchemaUrlParts)(p.self)),r=Wo(t),a=await pt(n,X([...o,...r]));if(a.length>0&&(console.log(`
46
+ `,ze(`Generating code using schemas in DEV environment, tracking against those will result in failed events. Schemas in DEV:
45
47
  `+a.join(`
46
48
  `)),`
47
- `),i))throw new St}function Kt(t){return Ie.includes(t)}function sn({self:t}){let e=(0,bt.joinIgluSchemaUrlParts)(t);return Kt(e)}function yn(t){return{standardEventSpecs:t.filter(e=>sn(e.eventSchema)),customEventSpecs:t.filter(e=>!sn(e.eventSchema))}}function wn(t,e,n){if(typeof t=="string"&&typeof e=="string"&&t&&e)return{apiKeyId:t,apiKey:e};throw n.error(new vt),new Error}function In(t){let e=!C(t.configDataStructures),n=!C(t.igluCentralSchemas),i=!C(t.repositories),o=!C(t.eventSpecificationIds),r=!C(t.dataProductIds);return(e||n||i)&&(!o&&!r)}var zi=["javascript","json","typescript"];function En(t){return t in nt}function Pn(t,e){let n=nt[t];return Array.isArray(n)?n.map(o=>o.value).includes(e):!1}function Cn(t){return zi.includes(t)}function xn(){return{withVerbosity:e=>({success:i=>{console.log(Me(i))},warn:i=>{console.log(Dt(i))},log:i=>{console.log(_e(i))},diff:(i,o)=>{console.log(ze(i,o))},debug:i=>{e===!0&&console.log(Ue(JSON.stringify(i)))},error:i=>{console.log(Ge(i.message)),e===!0&&console.log(i)}})}}function b(t,e){return async(n,i)=>{let o=Sn(i),r=xn(),a=Ve(),s=r.withVerbosity(o.verbose),{apiKeyId:c,apiKey:p}=wn(o.apiKeyId,o.apiKey,s);if(e!=="init")try{let d=n.config||process.cwd();await un(s,d)}catch(d){An(d,s,a)}return t({apiKeyId:c,apiKey:p},s,a,n).then(()=>Dn(a)).catch(d=>{An(d,s,a)})}}function An(t,e,n){throw Dn(n),e.error(t),t}function Dn(t){t.isSpinning()===!0&&t.stop(!0)}var Bi={type:"password",message:"Enter your Snowplow organization ID:",mask:!0,validate:cn},Hi={type:"select",message:"Select the Snowplow Tracker to use:",choices:[{value:"google-tag-manager",name:"Google Tag Manager"},{value:"@snowplow/javascript-tracker",name:"JavaScript Tracker"},{value:"@snowplow/browser-tracker",name:"Browser Tracker"},{value:"@snowplow/node-tracker",name:"Node Tracker"},{value:"snowplow-android-tracker",name:"Android Tracker"},{value:"snowplow-ios-tracker",name:"iOS Tracker"},{value:"snowplow-golang-tracker",name:"Golang Tracker"},{value:"@snowplow/react-native-tracker",name:"React Native Tracker"},{value:"snowplow-flutter-tracker",name:"Flutter Tracker"},{value:"snowplow-java-tracker",name:"Java Tracker"}]},Ji={type:"select",message:"Select the format to use:",choices:[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"},{value:"json",name:"JSON"}]},Ki={type:"input",message:"Enter the directory for Snowtype output:",default:"./snowtype"},qi=t=>({type:"select",message:"Select the language to use:",choices:t});async function Xi(t,e){e.debug("Checking for existing configuration file.."),await Qt(!1,process.cwd());let{password:n,select:i,input:o}=await import("@inquirer/prompts"),r=t.organizationId||await n(Bi),a=t.tracker||await i(Hi);if(!En(a))throw new B("tracker",a);let s=nt[a],c;if(s.length===1){let l=s[0];if(typeof l>"u")throw new gt("Missing language entry.");c=l.value}else c=t.language||await i(qi(s));if(!Pn(a,c))throw new B("language",c);let p=await i(Ji);if(!Cn(p))throw new B("format",p);W.setFormat(p);let d=t.outpath||await o(Ki);return e.debug("Assembling initialization options.."),{organizationId:r,tracker:a,language:c,format:p,outpath:d}}async function Yi(t,e,n,i){let o=await Xi(i,e);n.setSpinnerTitle("Initialising..."),n.isSpinning()===!1&&n.start(),e.debug("Creating configuration with options: ".concat(JSON.stringify(o)));let r=pn(o);if(K(r),!await A.createLazy({...t,organizationId:r.organizationId}).authenticate())throw new O;e.success("Authentication succeeded"),Ot(r,process.cwd()),e.success("Configuration created")}var te=b(Yi,"init");var Jn=require("path");var Hn=require("@snowplow/snowtype-core");var Tt=require("path"),bn=require("mkdirp"),ne=require("fs"),Ft=require("@snowplow/snowtype-core");var Zi="instructions.md",On="assets";async function kn(t,e,n,i,o){bn.mkdirp.sync((0,Tt.resolve)(i,On));let r=[],a=no(e,n,o),s=[];await Promise.all(e.map(async p=>{let d={triggers:await Xe(t,p.triggers),instructionsHeading:ee(p.eventSpecification.name)};s.push(ee(p.eventSpecification.name));let l=oo(p.propertyRules),S=ro(p.entities);to(p.eventSpecification.id,d,i),r.push(Qi({eventStructure:p.eventSchema.self,entitiesStructures:p.entitiesSchemas?.map(m=>m.original.self)||[],name:p.eventSpecification.name,id:p.eventSpecification.id,dataProductId:p.eventSpecification.dataProductId,version:p.version,triggerInstructions:d.triggers,linkToCode:a[p.eventSpecification.id],formattedPropertyRules:l,formattedCardinalityRules:S,organizationId:t.organizationId,sourceApplications:p.sourceApplications,...p.eventSpecification?.dataProductDomain?{dataProductDomain:p.eventSpecification?.dataProductDomain}:{}}))}));let c=`
49
+ `),i))throw new Fe}function M(e){return Zt.includes(e)}function Vn({self:e}){let t=(0,Be.joinIgluSchemaUrlParts)(e);return M(t)}function Yn(e){return{standardEventSpecs:e.filter(t=>Vn(t.eventSchema)),customEventSpecs:e.filter(t=>!Vn(t.eventSchema))}}function Ke({dataStructures:e,eventSpecificationIds:t,dataProductIds:n,localDataProducts:i}){let o=r=>(r?.length??0)>0;return!o(i)||o(e)||o(t)||o(n)}function Zn(e,t,n){if(typeof e=="string"&&typeof t=="string"&&e&&t)return{apiKeyId:e,apiKey:t};throw n.error(new $e),new Error}function Qn(e){let t=!L(e.configDataStructures),n=!L(e.igluCentralSchemas),i=!L(e.repositories)||(e.localDataProducts?.length??0)>0,o=!L(e.eventSpecificationIds),r=!L(e.dataProductIds);return(t||n||i)&&(!o&&!r)}var _o=["javascript","json","typescript"];function ei(e){return e in le}function ti(e,t){let n=le[e];return Array.isArray(n)?n.map(o=>o.value).includes(t):!1}function ni(e){return _o.includes(e)}function ii(){return{withVerbosity:t=>({success:i=>{console.log(Sn(i))},warn:i=>{console.log(ze(i))},log:i=>{console.log(vn(i))},diff:(i,o)=>{console.log(In(i,o))},debug:i=>{t===!0&&console.log(wn(JSON.stringify(i)))},error:i=>{console.log(yn(i.message)),t===!0&&console.log(i)}})}}function b(e,t){return async(n,i)=>{let o=qn(i),r=ii(),a=gn(),p=r.withVerbosity(o.verbose),s=n.config||process.cwd(),{apiKeyId:c,apiKey:d}=await Uo(t,s)?Zn(o.apiKeyId,o.apiKey,p):{apiKeyId:"",apiKey:""};if(t!=="init")try{await Un(p,s)}catch(u){oi(u,p,a)}return e({apiKeyId:c,apiKey:d},p,a,n).then(()=>ri(a)).catch(u=>{oi(u,p,a)})}}async function Uo(e,t){if(e!=="generate"&&e!=="check")return!0;try{return Ke(await R(t))}catch{return!0}}function oi(e,t,n){throw ri(n),t.error(e),e}function ri(e){e.isSpinning()===!0&&e.stop(!0)}var Go={type:"password",message:"Enter your Snowplow organization ID:",mask:!0,validate:Wn},zo={type:"select",message:"Select the Snowplow Tracker to use:",choices:[{value:"google-tag-manager",name:"Google Tag Manager"},{value:"@snowplow/javascript-tracker",name:"JavaScript Tracker"},{value:"@snowplow/browser-tracker",name:"Browser Tracker"},{value:"@snowplow/node-tracker",name:"Node Tracker"},{value:"snowplow-android-tracker",name:"Android Tracker"},{value:"snowplow-ios-tracker",name:"iOS Tracker"},{value:"snowplow-golang-tracker",name:"Golang Tracker"},{value:"@snowplow/react-native-tracker",name:"React Native Tracker"},{value:"snowplow-flutter-tracker",name:"Flutter Tracker"},{value:"snowplow-java-tracker",name:"Java Tracker"}]},Bo={type:"select",message:"Select the format to use:",choices:[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"},{value:"json",name:"JSON"}]},Ho={type:"input",message:"Enter the directory for Snowtype output:",default:"./snowtype"},Jo=e=>({type:"select",message:"Select the language to use:",choices:e});async function Ko(e,t){t.debug("Checking for existing configuration file.."),await vt(!1,process.cwd());let{password:n,select:i,input:o}=await import("@inquirer/prompts"),r=e.organizationId||await n(Go),a=e.tracker||await i(zo);if(!ei(a))throw new Q("tracker",a);let p=le[a],s;if(p.length===1){let u=p[0];if(typeof u>"u")throw new be("Missing language entry.");s=u.value}else s=e.language||await i(Jo(p));if(!ti(a,s))throw new Q("language",s);let c=await i(Bo);if(!ni(c))throw new Q("format",c);K.setFormat(c);let d=e.outpath||await o(Ho);return t.debug("Assembling initialization options.."),{organizationId:r,tracker:a,language:s,format:c,outpath:d}}async function qo(e,t,n,i){let o=await Ko(i,t);n.setSpinnerTitle("Initialising..."),n.isSpinning()===!1&&n.start(),t.debug("Creating configuration with options: ".concat(JSON.stringify(o)));let r=_n(o);if(ne(r),!await T.createLazy({...e,organizationId:r.organizationId}).authenticate())throw new V;t.success("Authentication succeeded"),He(r,process.cwd()),t.success("Configuration created")}var wt=b(qo,"init");var ji=require("path");var Ni=require("@snowplow/snowtype-core");var oe=require("path"),ai=require("mkdirp"),It=require("fs"),qe=require("@snowplow/snowtype-core");var si="instructions.md",Pt="assets";function ci(e){return[(0,oe.resolve)(e,si),(0,oe.resolve)(e,Pt)]}async function pi(e,t,n,i,o){ai.mkdirp.sync((0,oe.resolve)(i,Pt));let r=[],a=Qo(t,n,o),p=[];await Promise.all(t.map(async c=>{let d={triggers:await bn(e,c.triggers),instructionsHeading:yt(c.eventSpecification.name)};p.push(yt(c.eventSpecification.name));let u=tr(c.propertyRules),g=nr(c.entities);Yo(c.eventSpecification.id,d,i),r.push(Xo({eventStructure:c.eventSchema.self,entitiesStructures:c.entitiesSchemas?.map(f=>f.original.self)||[],name:c.eventSpecification.name,id:c.eventSpecification.id,dataProductId:c.eventSpecification.dataProductId,version:c.version,triggerInstructions:d.triggers,linkToCode:a[c.eventSpecification.id],formattedPropertyRules:u,formattedCardinalityRules:g,organizationId:e.organizationId,sourceApplications:c.sourceApplications,...c.eventSpecification?.dataProductDomain?{dataProductDomain:c.eventSpecification?.dataProductDomain}:{}}))}));let s=`
48
50
  # Implementation instructions
49
51
 
50
52
  _A guide on how to implement tracking for the generated Event Specifications._
51
53
 
52
54
  **Table of contents:**
53
- ${s.map(p=>`- [${p.instructionsTitle}](#${p.instructionsLink})`).join(`
55
+ ${p.map(c=>`- [${c.instructionsTitle}](#${c.instructionsLink})`).join(`
54
56
  `)}
55
57
 
56
58
  ${r.join(`
57
59
  `)}
58
- `;(0,ne.writeFileSync)((0,Tt.resolve)(i,Zi),c,"utf-8")}function Qi({eventStructure:t,entitiesStructures:e,name:n,id:i,dataProductId:o,version:r,triggerInstructions:a,linkToCode:s,formattedPropertyRules:c,formattedCardinalityRules:p,organizationId:d,sourceApplications:l,dataProductDomain:S}){let m="_N/A_";return`
59
- ## [${ee(n).instructionsTitle}](${eo(d,o,i)})
60
+ `;(0,It.writeFileSync)((0,oe.resolve)(i,si),s,"utf-8")}function Xo({eventStructure:e,entitiesStructures:t,name:n,id:i,dataProductId:o,version:r,triggerInstructions:a,linkToCode:p,formattedPropertyRules:s,formattedCardinalityRules:c,organizationId:d,sourceApplications:u,dataProductDomain:g}){let f="_N/A_",w=yt(n).instructionsTitle;return`
61
+ ## ${d===void 0||d===""?w:`[${w}](${Zo(d,o,i)})`}
60
62
 
61
63
  | | |
62
64
  | ----------- | ----------- |
63
65
  | **Id** | ${i} |
64
66
  | **Version** | ${r} |
65
67
  | **Data Product Id** | ${o} |
66
- | **Source Application/s** | ${l.length?l.map(g=>g.name).join(", "):"None selected"} |
67
- | **Event Data Structure** | ${t.name}/${t.version} |
68
- | **Entity Data Structures** | ${e.map(g=>`${g.name}/${g.version}`).sort().join(", ")} |
69
- | **Code** | ${s} |
70
- | **Data Product Domain** | ${S&&S.length>0?S:m} |
68
+ | **Source Application/s** | ${u.length?u.map(m=>m.name).join(", "):"None selected"} |
69
+ | **Event Data Structure** | ${e.name}/${e.version} |
70
+ | **Entity Data Structures** | ${t.map(m=>`${m.name}/${m.version}`).sort().join(", ")} |
71
+ | **Code** | ${p} |
72
+ | **Data Product Domain** | ${g&&g.length>0?g:f} |
71
73
 
72
- ${c.length>0?`### Implementation Instructions for ${t.name} event properties
74
+ ${s.length>0?`### Implementation Instructions for ${e.name} event properties
73
75
 
74
76
  #### Property Rules
75
77
  | Name | Required | Description | Exact value(s) expected |
76
78
  | ----------- | ----------- | ----------- | ----------- |
77
- ${c.map(g=>Object.values(g).join(" | ")).join(`
79
+ ${s.map(m=>Object.values(m).join(" | ")).join(`
78
80
  `)}
79
81
  `:""}
80
- ${p.length>0?`
82
+ ${c.length>0?`
81
83
  #### Entity Cardinality Rules
82
84
  | Name | Required | Number of entities |
83
85
  | ----------- | ----------- | ----------- |
84
- ${p.map(g=>Object.values(g).join(" | ")).join(`
86
+ ${c.map(m=>Object.values(m).join(" | ")).join(`
85
87
  `)}
86
88
  `:""}
87
89
 
88
- ${a.map((g,f,x)=>`
89
- ### Trigger ${x.length!==1?f+1:""}
90
+ ${a.map((m,D,S)=>`
91
+ ### Trigger ${S.length!==1?D+1:""}
90
92
 
91
93
  #### Screenshot
92
- ${g.imageBuffer?`[<img src="./assets/${i}_${f}.${g.imageExtension}" width="550"/>](./assets/${i}_${f}.${g.imageExtension})`:m}
94
+ ${m.imageBuffer?`[<img src="./assets/${i}_${D}.${m.imageExtension}" width="550"/>](./assets/${i}_${D}.${m.imageExtension})`:f}
93
95
 
94
96
  #### In which application(s) does this trigger apply?
95
97
 
96
- ${g.appIds&&g.appIds.length?g.appIds.map(G=>"`"+G+"` "):m}
98
+ ${m.appIds&&m.appIds.length?m.appIds.map(E=>"`"+E+"` "):f}
97
99
 
98
100
  #### The URL of the page on which this event specification triggers:
99
101
 
100
- ${g.url||m}
102
+ ${m.url||f}
101
103
 
102
104
  #### Notes
103
105
 
104
- ${g.description||m}
105
- `).join("")}`}function to(t,e,n){e.triggers.forEach((i,o)=>{i.imageBuffer&&(0,ne.writeFileSync)((0,Tt.resolve)(n,On,t+"_"+o+"."+i.imageExtension),i.imageBuffer,"binary")})}function eo(t,e,n){return`https://console.snowplowanalytics.com/${t}/data-products/${e}/event-specifications/${n}`}function no(t,e,n){let i=t.reduce((o,{eventSpecification:{id:r}})=>(o[r]="",o),{});return Object.keys(i).forEach(o=>{let r=e.findIndex(a=>a.match((0,Ft.createEventSpecificationInstructionsIdentifier)(o)));i[o]=r!==-1?`[Link](./${n+"#L"+r})`:"N/A"}),i}function ee(t){let e=t;return{instructionsTitle:e,instructionsLink:io(e)}}function io(t){return t.toLowerCase().replace(/[^a-z\d\s-]/g," ").replace(/\s+/g," ").trim().replace(/-{2,}|\s/g,"-")}function oo(t){return t?Object.entries(t.properties||{}).map(e=>{let[n,i]=e,o=t.required?.includes(n)?"\u2705":"\u274C",r=i.description||"-",a=i.enum?i.enum.map(s=>`\`${s}\``).join(" or "):"-";return{name:n,isRequired:o,description:r,expectedValues:a}}):[]}function ro(t){return t?t.map(({source:e,minCardinality:n,maxCardinality:i})=>{let{name:o}=(0,Ft.splitIgluSchemaUrlParts)(e),r=typeof n<"u"&&n>0?"\u2705":"\u274C",a=ao(n,i);return{name:o,isRequired:r,formattedCardinalityValues:a}}):[]}function ao(t,e){return typeof t>"u"?"`any`":typeof e<"u"?t===e?`Exactly \`${t}\``:`Between \`${t}\` and \`${e}\``:`At least \`${t}\``}var Fn=require("fs"),Ln=require("path"),Rn=h(require("util"));function $n(t,e,n,i){let o=e==="typescript"?"ts":"js";(0,Fn.writeFileSync)((0,Ln.resolve)(t,`validations.${o}`),`${o==="ts"?`
106
+ ${m.description||f}
107
+ `).join("")}`}function Yo(e,t,n){t.triggers.forEach((i,o)=>{i.imageBuffer&&(0,It.writeFileSync)((0,oe.resolve)(n,Pt,e+"_"+o+"."+i.imageExtension),i.imageBuffer,"binary")})}function Zo(e,t,n){return`https://console.snowplowanalytics.com/${e}/data-products/${t}/event-specifications/${n}`}function Qo(e,t,n){let i=e.reduce((o,{eventSpecification:{id:r}})=>(o[r]="",o),{});return Object.keys(i).forEach(o=>{let r=t.findIndex(a=>a.match((0,qe.createEventSpecificationInstructionsIdentifier)(o)));i[o]=r!==-1?`[Link](./${n+"#L"+r})`:"N/A"}),i}function yt(e){let t=e;return{instructionsTitle:t,instructionsLink:er(t)}}function er(e){return e.toLowerCase().replace(/[^a-z\d\s-]/g," ").replace(/\s+/g," ").trim().replace(/-{2,}|\s/g,"-")}function tr(e){return e?Object.entries(e.properties||{}).map(t=>{let[n,i]=t,o=e.required?.includes(n)?"\u2705":"\u274C",r=i.description||"-",a=i.enum?i.enum.map(p=>`\`${p}\``).join(" or "):"-";return{name:n,isRequired:o,description:r,expectedValues:a}}):[]}function nr(e){return e?e.map(({source:t,minCardinality:n,maxCardinality:i})=>{let{name:o}=(0,qe.splitIgluSchemaUrlParts)(t),r=typeof n<"u"&&n>0?"\u2705":"\u274C",a=ir(n,i);return{name:o,isRequired:r,formattedCardinalityValues:a}}):[]}function ir(e,t){return typeof e>"u"?"`any`":typeof t<"u"?e===t?`Exactly \`${e}\``:`Between \`${e}\` and \`${t}\``:`At least \`${e}\``}var ui=require("path"),li=y(require("util"));function mi({outDir:e,language:t}){return(0,ui.resolve)(e,`validations.${t==="typescript"?"ts":"js"}`)}function gi({language:e,validationSchemas:t,cardinalityRules:n}){let i=e==="typescript"?"ts":"js";return`${i==="ts"?`
106
108
  import { AnySchema } from "ajv";
107
109
  export type CardinalityRule = { minCardinality?: number; maxCardinality?: number };
108
110
  type IgluUrl = string;
109
111
  type EventSpecificationId = string;
110
112
  `:""}
111
- export const entityRules${o==="ts"?": Record<EventSpecificationId, Record<IgluUrl, CardinalityRule>>":""} = ${Tn(i)}
112
- export const schemasObject${o==="ts"?": Record<IgluUrl | EventSpecificationId, AnySchema | Record<IgluUrl, AnySchema>>":""} = ${Tn(n)}`,"utf-8")}function Tn(t){return Rn.default.inspect(t,{showHidden:!1,depth:null,maxArrayLength:null})}function ie(t){return Object.values(t).some(e=>so(e)?co(e):ie(e))}function so(t){return typeof t=="object"&&t!==null&&Object.hasOwn(t,"$schema")}function co(t){return t.properties?Object.values(t.properties).some(e=>Object.hasOwn(e||{},"pattern")):!1}function Nn(t,e){let n=uo(t);po(n,e)}function po(t,e){Object.entries(t).map(([n,i])=>e.warn(`Event Specification ${n} includes entities that are also present in it's application context: ${i.join(", ")}`))}function uo(t){let e={};return t.forEach(n=>{let i=n.entities.map(r=>r.source),o=n.sourceApplications.flatMap(r=>[...r.entities.enriched.map(a=>a.source),...r.entities.tracked.map(a=>a.source)]);i.forEach(r=>{o.includes(r)&&(e[n.eventSpecification.id]?e[n.eventSpecification.id]?.push(r):e[n.eventSpecification.id]=[r])})}),e}var Lt=h(require("fs/promises")),Rt=h(require("path")),Vn=require("yaml");async function jn(t,e=[]){let n=[];for(let i of e){let o=Rt.default.resolve(t,i),r=await Wn(o),a=await lo(r);n.push(...a)}return n}async function lo(t){let e=[];for(let n of t){let{isJson:i}=Mn(n),o=await Lt.default.readFile(n,{encoding:"utf-8"}),r=i?JSON.parse(o):(0,Vn.parse)(o);go(r)&&e.push(r.data)}return e}async function Wn(t,e=[]){let n=await Lt.default.readdir(t);for(let i of n){let o=Rt.default.join(t,i),r=await Lt.default.stat(o),{isJson:a,isYaml:s}=Mn(i);r.isDirectory()?e=await Wn(o,e):(a||s)&&e.push(o)}return e}function go(t){return typeof t=="object"&&t!==null&&"apiVersion"in t&&typeof t.apiVersion=="string"&&"resourceType"in t&&t.resourceType==="data-structure"}function Mn(t){let e=Rt.default.extname(t);return e.match(/\.yml|\.yaml/)?{isYaml:!0,isJson:!1}:e.match(".json")?{isYaml:!1,isJson:!0}:{isYaml:!1,isJson:!1}}var X=require("path"),oe=require("fs"),re=require("mkdirp"),_n=h(require("fs-extra"));function Un({codeLines:t,outFilePath:e,language:n}){if(n==="java"){let i="// SNOWTYPE START: ",o="// SNOWTYPE END: ",r=(0,X.resolve)((0,X.dirname)(e),"com","snowplowanalytics","snowplow","snowtype");re.mkdirp.sync(r);let a="",s=!1,c="";for(let p of t)p===o+a&&((0,oe.writeFileSync)((0,X.resolve)(r,a),c),c="",s=!1),s&&(c+=p+`
113
- `),p.startsWith(i)&&(a=p.slice(i.length),s=!0)}else{let i=t.join(`
114
- `);(0,oe.writeFileSync)(e,i)}}function Gn(t){_n.default.removeSync((0,X.resolve)(t)),re.mkdirp.sync(t)}var Nt=require("path");var zn=require("path"),$t=require("fs-extra"),Y=2e4,mo=({code:t,codeMinified:e})=>t.length>Y&&e.length<=Y?`Warning: The content exceeds the GTM limit of ${Y} characters. Please use the minified version.`:e.length>Y&&e.length>Y?`Warning: The content exceeds the GTM limit of ${Y} characters.`:"";async function Bn({defaultFileName:t,outDir:e,codeLines:n}){let i=(0,zn.resolve)(e,t+".minified.js"),o=n.join(`
115
- `),{minify:r}=await import("terser"),a=await r(o,{mangle:!1,ecma:5});a.code?(console.warn(mo({code:o,codeMinified:a.code})),await(0,$t.remove)(i),await(0,$t.writeFile)(i,a.code)):console.error("Minification failed: Terser did not generate any code.")}async function fo(t){let{config:e,...n}=t,i=await R(e||process.cwd());return k(i),i.options.commands.generate={...i.options.commands.generate,...n},i}async function st(t,e,n,i){let{dataProductIds:o,dataStructures:r,igluCentralSchemas:a,eventSpecificationIds:s,repositories:c,language:p,tracker:d,outpath:l,organizationId:S,namespace:m,options:{commands:{generate:g}}}=await fo(i),{configDir:f}=D(i.config||process.cwd()),x=C(r),G=C(a),v=C(s),E=C(o),N=C(c);x&&G&&v&&E&&N&&(e.warn("Data structures, schemas, and event specifications are empty."),e.warn("Code generation has been interrupted."),process.exit(1)),n.setSpinnerTitle("Generating..."),n.isSpinning()===!1&&n.start();let Zn=In({configDataStructures:r,igluCentralSchemas:a,repositories:c,eventSpecificationIds:s,dataProductIds:o}),P=await A.create({...t,organizationId:S,enableSupportForNonDataProductsTier:Zn});if(!await P.authenticate())throw new O;let Qn=U(P,o),jt=kt([...Qn,...s]),ct=(0,Nt.resolve)(f,J);if(L(ct)){let Q=q(ct),{lockedIds:Mt,skippedIds:me,batchSpecs:fe}=mn(jt,Q);me.length>0&&e.warn(`Skipping ${me.length} event specification(s) not found in lock file. Run 'update --yes' to add new entries.`),fe.length>0&&await P.batchFetchEventSpecifications(fe),jt=Mt}let ti=on(jt,P,e),{eventSpecificationsWithId:z}=Ye(P,ti,e),Wt=Be(z);g.deprecateOnlyOnProdAvailableUpdates&&(Wt=await Je(Wt,P));let ei=tn(P,z),pt=en(ei,z);Nn(pt,e);let{customEventSpecs:ni,standardEventSpecs:ii}=yn(pt),oi=ii.flatMap(Q=>Q.entities.map(Mt=>Mt.source));be(z)&&d==="@snowplow/browser-tracker"&&e.log("You are generating Snowplow Ecommerce events. You would need to install `@snowplow/browser-plugin-snowplow-ecommerce`."),g.validations&&e.log("For validations to work properly you would need to install `ajv@8`, `ajv-formats@2` and `ajv-draft-04@1` on your project.");let ri=await Ze(a),ai=rn(r,P,e),ue=await Qe(P,[...ai,...oi]),si=await jn(f,c),de=!!(d==="@snowplow/browser-tracker"&&p.match(/javascript|typescript/));await vn(ue,pt,P,g.disallowDevSchemas);let ci=[...si,...ri,...ue],le={language:p,tracker:d,schemas:ci,eventSpecifications:ni,validations:de&&g.validations,eventSpecificationsInputMetadata:Wt,namespace:m},V=await(0,Hn.generate)(le);if(n.stop(!0),!V)throw new ut;e.success("Code generated, writing...");let Z=(0,Nt.resolve)(f,l),pi=dn(p),ge=_t+pi,ui=(0,Nt.resolve)(Z,ge);if(Gn(Z),Un({codeLines:V.lines,outFilePath:ui,language:p}),le.language==="javascript-gtm"&&await Bn({defaultFileName:_t,outDir:Z,codeLines:V.lines}),L(ct)||ln(z,ct),de&&g.validations&&V.validationsSchemaObject){let Q=nn(z);$n(Z,p,V.validationsSchemaObject,Q),ie(V.validationsSchemaObject)&&e.warn("Some schemas appear to have attributes that can have inconsistent validations between the pipeline and client-side validation. Read more at https://docs.snowplow.io/docs/collecting-data/code-generation/client-side-validation/#divergence-with-pipeline-validation")}g.instructions&&await kn(P,pt,V.lines,Z,ge)}var ae=b(st,"generate");async function ho(t){let e=await R(t||process.cwd());return k(e),e}async function So(t,e,n,i){let o=await ho(i.config),{options:{commands:{update:{maximumBump:r,showOnlyProdUpdates:a,regenerateOnUpdate:s},generate:c}}}=o;e.debug("Starting update process with options: ".concat(JSON.stringify(i)));let{configDir:p}=D(i.config||process.cwd()),d=(0,Jn.resolve)(p,J),l=await A.create({...t,organizationId:o.organizationId});n.setSpinnerTitle("Checking for updates..."),n.isSpinning()===!1&&n.start();let S=i.dataProducts&&i.dataProducts.length>0||i.eventSpecs&&i.eventSpecs.length>0,m;if(S){let v=i.dataProducts||[],E=i.eventSpecs||[],N=U(l,v);m=_([...N,...E])}else{let v=U(l,o.dataProductIds);m=_([...o.eventSpecificationIds,...v])}let g=L(d)?q(d):{eventSpecifications:{}},f={};if(m.length>0&&(f=await Re(l,m,g),!i.latestDraft)){let v={};for(let[E,N]of Object.entries(f))l.getEventSpecificationById(E)?.data?.status!=="draft"&&(v[E]=N);f=v}let x=await Le(l,o.dataStructures,i.maximumBump||r,a);if((Object.entries(f).length>0||x.length>0)===!0)if(e.success("Available updates found!"),hn(f,x,e),i.yes){if(x.length>0&&(x.forEach(v=>{let E=o.dataStructures.indexOf(v.previous);o.dataStructures[E]=v.next}),Ot(o,i.config||process.cwd())),Object.keys(f).length>0){let v={};for(let[E,N]of Object.entries(f))v[E]=N.next;gn(v,d),e.success("Lock file updated with new event specification versions.")}if(e.debug("Updates applied."),s)return e.debug("Regenerating code after update..."),st(t,e,n,{...c,...i.config&&{config:i.config}})}else e.log("No updates applied"),e.log("To apply the available updates automatically run `update` with the --yes flag"),e.log("(caution: will overwrite the configuration file)");else e.success("No updates found. Everything is up-to-date!");return Promise.resolve(void 0)}var se=b(So,"update");async function vo(t){let{config:e,...n}=t;if(Object.values(n).every(o=>Array.isArray(o)&&o.length===0))throw new mt;let i=await R(e||process.cwd());return k(i),{patchOptions:n,generateOptions:i.options.commands.generate,regenerateOnPatch:i.options.commands.patch.regenerateOnPatch}}async function yo(t,e,n,i){let{isJSON:o,configPath:r}=D(i.config||process.cwd());if(o===!1)throw new ht;let{patchOptions:a,generateOptions:s,regenerateOnPatch:c}=await vo(i);return e.debug("Starting patch process with options: ".concat(JSON.stringify(a))),Object.entries(a).forEach(([d,l])=>{l.forEach(S=>{Fe(d,S,r)})}),e.success("Configuration patched"),c?st(t,e,n,s):(e.log("Code is not generated yet for the patched configuration"),Promise.resolve(void 0))}var ce=b(yo,"patch");var Kn=require("path");async function wo(t,e,n,i){let o=i.config||process.cwd(),r=await R(o);k(r);let{configDir:a}=D(o),s=(0,Kn.resolve)(a,J);if(!L(s)){e.log("No lock file found. Nothing to purge.");return}n.setSpinnerTitle("Resolving valid event specifications..."),n.isSpinning()===!1&&n.start();let c=await A.create({...t,organizationId:r.organizationId});if(!await c.authenticate())throw new O;let d=U(c,r.dataProductIds),l=kt([...r.eventSpecificationIds,...d]);n.stop(!0);let S=fn(l,s);S.length===0?e.success("Lock file is clean. No stale entries found."):(e.success(`Purged ${S.length} stale event specification(s) from lock file:`),S.forEach(m=>e.log(` - ${m}`)))}var pe=b(wo,"purge");var Vt=require("@snowplow/snowtype-core");async function Xn(){await import("dotenv/config");let t=new $.Command;t.exitOverride(),t.version(j,void 0,"Snowtype CLI version number").name("snowtype").description("The Snowtype CLI is a tool which aims to speed up tracking implementations, provide type safety and inline documentation for developers and ultimately reduce the number of erroneous events.").showHelpAfterError().configureHelp({showGlobalOptions:!0}).option("-k, --apiKey <string>","Snowplow Console API key").option("-s, --apiKeyId <string>","Snowplow Console API key ID").option("-v, --verbose","Enable verbose logging"),t.command("init").description("Initialize the setup of Snowtype code generation in a project. Creates the `snowtype.config.json` file.").option("-i, --organizationId <string>","organization ID").addOption(new $.Option("-t, --tracker <availableTrackers>","tracker to use").choices(Vt.trackerTemplates)).addOption(new $.Option("-l, --language <availableLanguages>","language to use").choices(Vt.languageIds)).option("-o, --outpath <string>","output path").action(te),t.command("update").description("Checks for latest version updates in Data Structures and Event Specifications.").option("-c, --config <string>","config file path").option("-y, --yes","updates all to latest without asking (caution: will overwrite the configuration file)").addOption(new $.Option("-m, --maximumBump <'patch' | 'minor' | 'major'>","the maximum SchemaVer update to show an available update notification. Defaults to 'major'").choices(["patch","minor","major"])).option("-d, --latestDraft","update event specifications to the latest version including drafts (default: published only)").option("-p, --dataProducts <dataProductIds...>","only update event specifications belonging to these data products").option("-e, --eventSpecs <eventSpecIds...>","only update these specific event specifications").action(se),t.command("generate").option("-c, --config <string>","config file path").option("--instructions","generate event specification instructions").option("--no-instructions","generate without instructions").option("--validations","add runtime validation using Ajv").option("--no-validations","generate without runtime validations").option("--disallowDevSchemas","disallow generation of code using schemas only deployed on DEV environment").option("--deprecateOnlyOnProdAvailableUpdates","show deprecation warnings only when there are PROD available schema updates").description("Generates tracking code based on configuration on the `snowtype.config.json` file.").action(ae),t.command("patch").option("-c, --config <string>","config file path").description("Adds new Data Structures and Event Specifications in the `snowtype.config.json` file.").option("-p, --dataProductIds <dataProductIds...>","data product ID").option("-e, --eventSpecificationIds <eventSpecificationIds...>","tracking eventSpecification ID").option("-d, --dataStructures <dataStructures...>","data structure URI").option("-i, --igluCentralSchemas <igluCentralSchemas...>","iglu central URI").option("-r, --repositories <repositories...>","repository path").action(ce),t.command("purge").description("Removes stale event specification entries from the lock file that no longer exist in the configuration.").option("-c, --config <string>","config file path").action(pe),t.addHelpText("before",We()).addHelpText("after",`
116
- `),await t.parseAsync(qn.argv).catch(e=>{Io(e)})}function Io(t){if(!(t instanceof $.CommanderError&&["commander.help","commander.version","commander.helpDisplayed"].indexOf(t.code)>-1))throw t}Xn().then(()=>{}).catch(()=>{process.exitCode=1});
113
+ export const entityRules${i==="ts"?": Record<EventSpecificationId, Record<IgluUrl, CardinalityRule>>":""} = ${di(n)}
114
+ export const schemasObject${i==="ts"?": Record<IgluUrl | EventSpecificationId, AnySchema | Record<IgluUrl, AnySchema>>":""} = ${di(t)}`}function di(e){return li.default.inspect(e,{showHidden:!1,depth:null,maxArrayLength:null})}function Et(e){return Object.values(e).some(t=>or(t)?rr(t):Et(t))}function or(e){return typeof e=="object"&&e!==null&&Object.hasOwn(e,"$schema")}function rr(e){return e.properties?Object.values(e.properties).some(t=>Object.hasOwn(t||{},"pattern")):!1}function fi(e,t){let n=sr(e);ar(n,t)}function ar(e,t){Object.entries(e).map(([n,i])=>t.warn(`Event Specification ${n} includes entities that are also present in it's application context: ${i.join(", ")}`))}function sr(e){let t={};return e.forEach(n=>{let i=n.entities.map(r=>r.source),o=n.sourceApplications.flatMap(r=>[...r.entities.enriched.map(a=>a.source),...r.entities.tracked.map(a=>a.source)]);i.forEach(r=>{o.includes(r)&&(t[n.eventSpecification.id]?t[n.eventSpecification.id]?.push(r):t[n.eventSpecification.id]=[r])})}),t}var vi=require("@snowplow/snowtype-core");var re=y(require("fs/promises")),j=y(require("path")),wi=require("yaml"),hi=2147483647;async function yi(e,t=[]){let n=[],i=new Set,o=new Map;for(let r of t){let a=j.default.resolve(e,r),p=await cr(await Ei(a),o);n.push(...p.schemas);for(let s of p.hidden)i.add(s)}return{schemas:n,hidden:i}}async function cr(e,t){let n=[],i=new Set;for(let o of e){let r=await Ct(o,t);if(fr(r)){let a=r.data;if(a?.self===void 0)throw new P(o,"a data structure needs a data section with a self description");n.push(a),r.meta?.hidden===!0&&i.add((0,vi.joinIgluSchemaUrlParts)(a.self))}}return{schemas:n,hidden:i}}async function Ii(e,t=[]){let n=[],i=new Map;for(let o of t){let r=j.default.resolve(e,o),a=await Ei(r);for(let p of a){let s=await Ct(p,i);mr(s)&&n.push(await pr(s,p,i))}}return n}async function pr(e,t,n){let i=e.data;if(!xt(i)||typeof i.name!="string")throw new P(t,"a data product needs a data section with a name");if(typeof e.resourceName!="string")throw new P(t,"a data product needs a resourceName");let o=i.name,r=[];for(let s of G({value:i.eventSpecifications,filePath:t,what:"the event specifications of a data product"})){let c=lr(s,t),d=await ur({references:s.excludedSourceApplications,filePath:t,specificationName:c.name,read:n}),u=await Promise.all(G({value:c.triggers,filePath:t,what:`the triggers of ${c.name}`}).map(g=>dr({trigger:g,filePath:t})));r.push({...c,...u.length===0?{}:{triggers:u},...d.length===0?{}:{excludedSourceApplicationIds:d}})}let a=G({value:i.sourceApplications,filePath:t,what:"the source applications of a data product"}),p=[];for(let{$ref:s}of a){if(s===void 0)continue;let c=await Pi({reference:s,filePath:t,read:n});p.push({id:c.resourceName,name:c.name,appIds:c.appIds??[],entities:{tracked:Si(c.entities?.tracked),enriched:Si(c.entities?.enriched)},...c.description===void 0?{}:{description:c.description},...c.owner===void 0?{}:{owner:c.owner}})}return{resourceName:e.resourceName,name:o,...i.domain===void 0?{}:{domain:i.domain},sourceApplications:p,eventSpecifications:r}}async function dr({trigger:e,filePath:t}){let n=e.image?.$ref;if(n===void 0)return e;let i=j.default.resolve(j.default.dirname(t),n);return await re.default.stat(i).catch(()=>{throw new P(t,`the image a trigger references is not there: ${n}`)}),{...e,imagePath:i}}async function ur({references:e,filePath:t,specificationName:n,read:i}){let o=[];for(let{$ref:r}of G({value:e,filePath:t,what:`the source applications ${n} excludes`})){if(r===void 0)continue;let a=await Pi({reference:r,filePath:t,read:i});o.push(a.resourceName)}return o}function lr(e,t){let{resourceName:n,name:i,version:o,...r}=e;if(typeof n!="string"||typeof i!="string")throw new P(t,"an event specification needs a resourceName and a name");if(o!==void 0&&(typeof o!="number"||!Number.isInteger(o)||o<0||o>hi))throw new P(t,`the version of ${i} has to be a whole number from 0 to ${hi}`);return G({value:r.entities?.tracked,filePath:t,what:`the entities ${i} tracks`}),G({value:r.entities?.enriched,filePath:t,what:`the entities ${i} enriches`}),{...r,resourceName:n,name:i,...o===void 0?{}:{version:o}}}async function Pi({reference:e,filePath:t,read:n}){let i=j.default.resolve(j.default.dirname(t),e),o=await Ct(i,n).catch(a=>{throw a instanceof P?a:new P(t,`the source application it references is not there: ${e}`)});if(!gr(o))throw new P(t,`what it references as a source application is not one: ${e}`);let r=o.data;if(!xt(r)||typeof r.name!="string")throw new P(i,"a source application needs a data section with a name");return G({value:r.entities?.tracked,filePath:i,what:"the entities a source application tracks"}),G({value:r.entities?.enriched,filePath:i,what:"the entities a source application enriches"}),{...r,name:r.name,resourceName:o.resourceName}}function Si(e=[]){return e.map(({source:t,minCardinality:n})=>({source:t,minCardinality:n??0}))}async function Ct(e,t){let n=t.get(e);if(n!==void 0)return n;let{isJson:i}=At(e),o=await re.default.readFile(e,{encoding:"utf-8"});try{let r=i?JSON.parse(o):(0,wi.parse)(o);return t.set(e,r),r}catch{throw new P(e,"it does not parse")}}async function Ei(e){if((await re.default.stat(e).catch(()=>{throw new P(e,"there is nothing there")})).isDirectory())return xi(e);let{isJson:n,isYaml:i}=At(e);if(!n&&!i)throw new P(e,"only json and yaml files hold definitions");return[e]}function G({value:e,filePath:t,what:n}){if(e===void 0)return[];if(!Array.isArray(e))throw new P(t,`${n} have to be a list`);if(!e.every(i=>xt(i)))throw new P(t,`${n} hold an entry that is not a definition`);return e}function xt(e){return typeof e=="object"&&e!==null}function mr(e){return Ci(e,"data-product")}function gr(e){return Ci(e,"source-application")}function Ci(e,t){return typeof e=="object"&&e!==null&&"apiVersion"in e&&typeof e.apiVersion=="string"&&"resourceType"in e&&e.resourceType===t}async function xi(e,t=[]){let n=(await re.default.readdir(e)).sort();for(let i of n){let o=j.default.join(e,i),r=await re.default.stat(o),{isJson:a,isYaml:p}=At(i);r.isDirectory()?t=await xi(o,t):(a||p)&&t.push(o)}return t}function fr(e){return typeof e=="object"&&e!==null&&"apiVersion"in e&&typeof e.apiVersion=="string"&&"resourceType"in e&&e.resourceType==="data-structure"}function At(e){let t=j.default.extname(e);return t.match(/\.yml|\.yaml/)?{isYaml:!0,isJson:!1}:t.match(".json")?{isYaml:!1,isJson:!0}:{isYaml:!1,isJson:!1}}var Z=require("path"),Ai=require("fs"),Xe=require("mkdirp"),Di=y(require("fs-extra"));function Dt({codeLines:e,outFilePath:t,language:n}){if(n!=="java")return new Map([[t,e.join(`
115
+ `)]]);let i="// SNOWTYPE START: ",o="// SNOWTYPE END: ",r=ki(t),a=new Map,p="",s=!1,c="";for(let d of e)d===o+p&&(a.set((0,Z.resolve)(r,p),c),c="",s=!1),s&&(c+=d+`
116
+ `),d.startsWith(i)&&(p=d.slice(i.length),s=!0);return a}function ki(e){return(0,Z.resolve)((0,Z.dirname)(e),"com","snowplowanalytics","snowplow","snowtype")}function bi({codeLines:e,outFilePath:t,language:n}){let i=Dt({codeLines:e,outFilePath:t,language:n});n==="java"&&Xe.mkdirp.sync(ki(t));for(let[o,r]of i)Xe.mkdirp.sync((0,Z.dirname)(o)),(0,Ai.writeFileSync)(o,r)}function Oi(e){Di.default.removeSync((0,Z.resolve)(e)),Xe.mkdirp.sync(e)}var ae=require("@snowplow/snowtype-core");function N({self:e}){return(0,ae.joinIgluSchemaUrlParts)(e)}function hr(e){return new Map(e.map(t=>[N(t),t]))}function Li({dataProducts:e,schemas:t}){let n=hr(t),o=e.flatMap(s=>s.eventSpecifications.filter(c=>c.event!==void 0).map(c=>({dataProduct:s,eventSpecification:c}))).map(({dataProduct:s,eventSpecification:c})=>Sr({dataProduct:s,eventSpecification:c,available:n})).sort((s,c)=>s.eventSpecification.id.localeCompare(c.eventSpecification.id)),r=o.filter(({eventSchema:s})=>M(N(s))).map(({eventSpecification:s})=>s.name),a=new Set(o.filter(({eventSchema:s})=>M(N(s))).flatMap(({entitiesSchemas:s})=>(s??[]).map(({original:c})=>N(c)))),p=new Set(o.filter(({eventSchema:s})=>!M(N(s))).flatMap(({eventSchema:s,entitiesSchemas:c})=>[N(s),...(c??[]).map(({original:d})=>N(d))]).filter(s=>!a.has(s)));return{eventSpecifications:o,consumedSchemas:p,standardEventSpecifications:r}}function Sr({dataProduct:e,eventSpecification:t,available:n}){let{version:i,name:o,resourceName:r,event:a,entities:p,triggers:s,excludedSourceApplicationIds:c}=t,d=a?.source!==void 0&&M(a.source);if(i===void 0&&!d)throw new Ce(o);let u=p?.tracked??[],g=wr(a?.schema),f=e.sourceApplications.filter(({id:w})=>!(c??[]).includes(w));return{eventSpecification:{id:r,name:o,dataProductId:e.resourceName,dataProductName:e.name,...e.domain===void 0?{}:{dataProductDomain:e.domain}},version:i??0,eventSchema:Ti({available:n,source:a?.source,eventSpecificationName:o,ecomEventType:g}),entitiesSchemas:u.map(({source:w,minCardinality:h,schema:m})=>({original:Ti({available:n,source:w,eventSpecificationName:o,ecomEventType:g}),propertyRule:m,minCardinality:h})),entities:u,...s===void 0?{}:{triggers:s.map(vr)},...a?.schema===void 0?{}:{propertyRules:a.schema},sourceApplicationIds:f.map(({id:w})=>w),sourceApplications:f}}function vr({description:e,appIds:t,url:n,imagePath:i}){return{description:e,...t===void 0?{}:{appIds:t},...n===void 0?{}:{url:n},...i===void 0?{}:{imagePath:i}}}function wr(e){let t=e?.properties?.type;if(typeof t!="object"||t===null||!("enum"in t))return;let n=t.enum,i=Array.isArray(n)?n[0]:void 0;return typeof i=="string"&&yr(i)?i:void 0}function yr(e){return Object.prototype.hasOwnProperty.call(ae.ecomFunctionName,e)}function Ti({available:e,source:t,eventSpecificationName:n,ecomEventType:i}){if(t!==void 0&&M(t))return mt(t);if(t?.startsWith(je))return{self:(0,ae.splitIgluSchemaUrlParts)(t),...i===void 0?{}:{isEcomTemplateSchema:i}};let o=t===void 0?void 0:e.get(t);if(o===void 0)throw new xe(n,t);return o}var Ze=require("path"),Mi=require("fs");var Fi=require("path"),se=2e4,Ye=({code:e,codeMinified:t})=>e.length>se&&t.length<=se?`Warning: The content exceeds the GTM limit of ${se} characters. Please use the minified version.`:t.length>se&&t.length>se?`Warning: The content exceeds the GTM limit of ${se} characters.`:"";function $i({defaultFileName:e,outDir:t}){return(0,Fi.resolve)(t,e+".minified.js")}async function Ri(e){let t=e.join(`
117
+ `),{minify:n}=await import("terser"),i=await n(t,{mangle:!1,ecma:5});if(i.code)return{code:t,minified:i.code}}async function Ir(e){let{config:t,...n}=e,i=await R(t||process.cwd());return W(i),i.options.commands.generate={...i.options.commands.generate,...n},i}async function kt(e,t,n,i){let{dataProductIds:o,dataStructures:r,igluCentralSchemas:a,eventSpecificationIds:p,repositories:s,localDataProducts:c=[],language:d,tracker:u,outpath:g,organizationId:f,namespace:w,options:{commands:{generate:h}}}=await Ir(i),{configDir:m}=F(i.config||process.cwd()),D=L(r),S=L(a),E=L(p),H=L(o),Rt=L(s),zi=c.length===0;D&&S&&E&&H&&Rt&&zi&&(t.warn("Data structures, schemas, and event specifications are empty."),t.warn("Code generation has been interrupted."),process.exit(1)),n.setSpinnerTitle("Generating..."),n.isSpinning()===!1&&n.start();let Nt=Qn({configDataStructures:r,igluCentralSchemas:a,repositories:s,localDataProducts:c,eventSpecificationIds:p,dataProductIds:o}),et=Ke({dataStructures:r,eventSpecificationIds:p,dataProductIds:o,localDataProducts:c}),O=et?await T.create({...e,organizationId:f,enableSupportForNonDataProductsTier:Nt}):T.createLazy({...e,organizationId:f,enableSupportForNonDataProductsTier:Nt});if(et){if(!await O.authenticate())throw new V}else t.warn("Generating from local definitions only. Schemas are not checked against the environments they are deployed to.");let Bi=Y(O,o),tt=Je([...Bi,...p]),we=(0,Ze.resolve)(m,te);if($(we)){let I=ie(we),{lockedIds:k,skippedIds:A,batchSpecs:Ht}=Hn(tt,I);A.length>0&&t.warn(`Skipping ${A.length} event specification(s) not found in lock file. Run 'update --yes' to add new entries.`),Ht.length>0&&await O.batchFetchEventSpecifications(Ht),tt=k}let Hi=Nn(tt,O,t),{eventSpecificationsWithId:ye}=On(O,Hi,t),ce=Pn(ye);h.deprecateOnlyOnProdAvailableUpdates&&(ce=await Cn(ce,O));let Ji=Fn(O,ye),Mt=$n(Ji,ye),{schemas:jt,hidden:Ki}=await yi(m,s),Vt=await Tn(a),{eventSpecifications:Ie,consumedSchemas:qi,standardEventSpecifications:Xi}=Li({dataProducts:await Ii(m,c),schemas:[...jt,...Vt]});Xi.length>0&&t.warn("Currently code will not be generated for `Standard` events. Skipping...");let Wt=I=>I.filter(k=>!qi.has(N(k))),Yi=Wt(jt),Zi=new Set(Mt.map(({eventSpecification:I})=>I.id.toString())),_t=new Set,nt=[];for(let{eventSpecification:I}of Ie){let{id:k,name:A}=I;(Zi.has(k)||_t.has(k))&&nt.push(A),_t.add(k)}if(nt.length>0)throw new Ee(nt);for(let I of Ie){let k=[I.eventSchema,...(I.entitiesSchemas??[]).map(({original:A})=>A)].map(A=>N(A)).filter(A=>Ki.has(A));k.length>0&&(ce=lt({currentMetadata:ce,eventSpecificationId:I.eventSpecification.id,newMetadata:{hiddenDsWarnings:k.map(A=>({id:A,sources:[{source:A}]})),outdatedDsWarnings:[],metrics:[]}}))}let pe=[...Mt,...Ie];fi(pe,t);let{customEventSpecs:Qi,standardEventSpecs:eo}=Yn(pe),to=new Set(Ie.map(({eventSpecification:I})=>I.id)),no=eo.filter(({eventSpecification:I})=>!to.has(I.id)).flatMap(I=>I.entities.map(k=>k.source));rn(pe)&&u==="@snowplow/browser-tracker"&&t.log("You are generating Snowplow Ecommerce events. You would need to install `@snowplow/browser-plugin-snowplow-ecommerce`."),h.validations&&t.log("For validations to work properly you would need to install `ajv@8`, `ajv-formats@2` and `ajv-draft-04@1` on your project.");let io=Mn(r,O,t),Ut=await Ln(O,[...io,...no]),Gt=!!(u==="@snowplow/browser-tracker"&&d.match(/javascript|typescript/));await Xn(Ut,pe,O,h.disallowDevSchemas);let oo=[...Yi,...Wt(Vt),...Ut],ro={language:d,tracker:u,schemas:oo,eventSpecifications:Qi,validations:Gt&&h.validations,eventSpecificationsInputMetadata:ce,namespace:w},it=await(0,Ni.generate)(ro);if(n.stop(!0),!it)throw new Pe;let ao=!$(we)&&et,ot=Gt&&h.validations?it.validationsSchemaObject:void 0;ot&&Et(ot)&&t.warn("Some schemas appear to have attributes that can have inconsistent validations between the pipeline and client-side validation. Read more at https://docs.snowplow.io/docs/collecting-data/code-generation/client-side-validation/#divergence-with-pipeline-validation");let zt=(0,Ze.resolve)(m,g),so=Gn(d),Bt=rt+so,co=(0,Ze.resolve)(zt,Bt);return{consoleApi:O,eventSpecificationsWithId:ye,eventSpecificationsWithDataProductAttributes:pe,language:d,generateOptions:h,generationOutput:it,lockPath:we,writesLockFile:ao,validationSchemas:ot,outDir:zt,outFileName:Bt,outFilePath:co}}async function bt({generationOutput:e,eventSpecificationsWithDataProductAttributes:t,language:n,outDir:i,validationSchemas:o}){let r=new Map,a=n==="javascript-gtm"?await Ri(e.lines):void 0;return a&&r.set($i({defaultFileName:rt,outDir:i}),a.minified),o&&r.set(mi({outDir:i,language:n}),gi({language:n,validationSchemas:o,cardinalityRules:Rn(t)})),{files:r,minified:a}}async function Se(e,t,n,i){let o=await kt(e,t,n,i),{consoleApi:r,eventSpecificationsWithId:a,eventSpecificationsWithDataProductAttributes:p,language:s,generateOptions:c,generationOutput:d,lockPath:u,writesLockFile:g,outDir:f,outFileName:w,outFilePath:h}=o;t.success("Code generated, writing..."),Oi(f),bi({codeLines:d.lines,outFilePath:h,language:s});let{files:m,minified:D}=await bt(o);s==="javascript-gtm"&&(D?console.warn(Ye({code:D.code,codeMinified:D.minified})):console.error("Minification failed: Terser did not generate any code.")),g&&zn(a,u);for(let[S,E]of m)(0,Mi.writeFileSync)(S,E,"utf-8");c.instructions&&await pi(r,p,d.lines,f,w)}var Ot=b(Se,"generate");async function Pr(e){let t=await R(e||process.cwd());return W(t),t}async function Er(e,t,n,i){let o=await Pr(i.config),{options:{commands:{update:{maximumBump:r,showOnlyProdUpdates:a,regenerateOnUpdate:p},generate:s}}}=o;t.debug("Starting update process with options: ".concat(JSON.stringify(i)));let{configDir:c}=F(i.config||process.cwd()),d=(0,ji.resolve)(c,te),u=await T.create({...e,organizationId:o.organizationId});n.setSpinnerTitle("Checking for updates..."),n.isSpinning()===!1&&n.start();let g=i.dataProducts&&i.dataProducts.length>0||i.eventSpecs&&i.eventSpecs.length>0,f;if(g){let S=i.dataProducts||[],E=i.eventSpecs||[],H=Y(u,S);f=X([...H,...E])}else{let S=Y(u,o.dataProductIds);f=X([...o.eventSpecificationIds,...S])}let w=$(d)?ie(d):{eventSpecifications:{}},h={};if(f.length>0&&(h=await un(u,f,w),!i.latestDraft)){let S={};for(let[E,H]of Object.entries(h))u.getEventSpecificationById(E)?.data?.status!=="draft"&&(S[E]=H);h=S}let m=await dn(u,o.dataStructures,i.maximumBump||r,a);if((Object.entries(h).length>0||m.length>0)===!0)if(t.success("Available updates found!"),Kn(h,m,t),i.yes){if(m.length>0&&(m.forEach(S=>{let E=o.dataStructures.indexOf(S.previous);o.dataStructures[E]=S.next}),He(o,i.config||process.cwd())),Object.keys(h).length>0){let S={};for(let[E,H]of Object.entries(h))S[E]=H.next;Bn(S,d),t.success("Lock file updated with new event specification versions.")}if(t.debug("Updates applied."),p)return t.debug("Regenerating code after update..."),Se(e,t,n,{...s,...i.config&&{config:i.config}})}else t.log("No updates applied"),t.log("To apply the available updates automatically run `update` with the --yes flag"),t.log("(caution: will overwrite the configuration file)");else t.success("No updates found. Everything is up-to-date!");return Promise.resolve(void 0)}var Tt=b(Er,"update");async function Cr(e){let{config:t,...n}=e;if(Object.values(n).every(o=>Array.isArray(o)&&o.length===0))throw new Oe;let i=await R(t||process.cwd());return W(i),{patchOptions:n,generateOptions:i.options.commands.generate,regenerateOnPatch:i.options.commands.patch.regenerateOnPatch}}async function xr(e,t,n,i){let{isJSON:o,configPath:r}=F(i.config||process.cwd());if(o===!1)throw new Le;let{patchOptions:a,generateOptions:p,regenerateOnPatch:s}=await Cr(i);return t.debug("Starting patch process with options: ".concat(JSON.stringify(a))),Object.entries(a).forEach(([d,u])=>{u.forEach(g=>{pn(d,g,r)})}),t.success("Configuration patched"),s?Se(e,t,n,p):(t.log("Code is not generated yet for the patched configuration"),Promise.resolve(void 0))}var Lt=b(xr,"patch");var Vi=require("path");async function Ar(e,t,n,i){let o=i.config||process.cwd(),r=await R(o);W(r);let{configDir:a}=F(o),p=(0,Vi.resolve)(a,te);if(!$(p)){t.log("No lock file found. Nothing to purge.");return}n.setSpinnerTitle("Resolving valid event specifications..."),n.isSpinning()===!1&&n.start();let s=await T.create({...e,organizationId:r.organizationId});if(!await s.authenticate())throw new V;let d=Y(s,r.dataProductIds),u=Je([...r.eventSpecificationIds,...d]);n.stop(!0);let g=Jn(u,p);g.length===0?t.success("Lock file is clean. No stale entries found."):(t.success(`Purged ${g.length} stale event specification(s) from lock file:`),g.forEach(f=>t.log(` - ${f}`)))}var Ft=b(Ar,"purge");var z=require("fs"),ve=require("path");function Wi(e,t,n=[]){let i=[...e].filter(([r,a])=>$(r)?a!==void 0&&(0,z.readFileSync)(r,"utf-8").replace(/\r\n/g,`
118
+ `)!==a:!0),o=t===void 0?[]:_i(t).filter(r=>!e.has(r)).filter(r=>!Dr(r,n));return[...i.map(([r])=>r),...o].map(r=>(0,ve.relative)(process.cwd(),r))}function _i(e){let t=(0,z.statSync)(e,{throwIfNoEntry:!1});return t===void 0||!t.isDirectory()?[]:(0,z.readdirSync)(e).flatMap(n=>{let i=(0,ve.resolve)(e,n);return(0,z.lstatSync)(i,{throwIfNoEntry:!1})?.isDirectory()===!0?_i(i):[i]})}function Dr(e,t){return t.some(n=>!(0,ve.relative)(n,e).startsWith(".."))}async function kr(e,t,n,i){let o=await kt(e,t,n,i),{language:r,generateOptions:a,generationOutput:p,outDir:s,outFilePath:c}=o;a.instructions&&t.warn("The check does not cover generated instructions.");let{files:d,minified:u}=await bt(o),g=new Map([...Dt({codeLines:p.lines,outFilePath:c,language:r}),...d]);if(r==="javascript-gtm")if(u){let w=Ye({code:u.code,codeMinified:u.minified});w!==""&&t.warn(w)}else t.warn("Minification failed: Terser did not generate any code.");let f=Wi(g,s,a.instructions?ci(s):[]);if(f.length>0)throw new Ae(f);t.success("Generated code is up to date")}var $t=b(kr,"check");var Qe=require("@snowplow/snowtype-core");async function Gi(){await import("dotenv/config");let e=new B.Command;e.exitOverride(),e.version(J,void 0,"Snowtype CLI version number").name("snowtype").description("The Snowtype CLI is a tool which aims to speed up tracking implementations, provide type safety and inline documentation for developers and ultimately reduce the number of erroneous events.").showHelpAfterError().configureHelp({showGlobalOptions:!0}).option("-k, --apiKey <string>","Snowplow Console API key").option("-s, --apiKeyId <string>","Snowplow Console API key ID").option("-v, --verbose","Enable verbose logging"),e.command("init").description("Initialize the setup of Snowtype code generation in a project. Creates the `snowtype.config.json` file.").option("-i, --organizationId <string>","organization ID").addOption(new B.Option("-t, --tracker <availableTrackers>","tracker to use").choices(Qe.trackerTemplates)).addOption(new B.Option("-l, --language <availableLanguages>","language to use").choices(Qe.languageIds)).option("-o, --outpath <string>","output path").action(wt),e.command("update").description("Checks for latest version updates in Data Structures and Event Specifications.").option("-c, --config <string>","config file path").option("-y, --yes","updates all to latest without asking (caution: will overwrite the configuration file)").addOption(new B.Option("-m, --maximumBump <'patch' | 'minor' | 'major'>","the maximum SchemaVer update to show an available update notification. Defaults to 'major'").choices(["patch","minor","major"])).option("-d, --latestDraft","update event specifications to the latest version including drafts (default: published only)").option("-p, --dataProducts <dataProductIds...>","only update event specifications belonging to these data products").option("-e, --eventSpecs <eventSpecIds...>","only update these specific event specifications").action(Tt),e.command("generate").option("-c, --config <string>","config file path").option("--instructions","generate event specification instructions").option("--no-instructions","generate without instructions").option("--validations","add runtime validation using Ajv").option("--no-validations","generate without runtime validations").option("--disallowDevSchemas","disallow generation of code using schemas only deployed on DEV environment").option("--deprecateOnlyOnProdAvailableUpdates","show deprecation warnings only when there are PROD available schema updates").description("Generates tracking code based on configuration on the `snowtype.config.json` file.").action(Ot),e.command("patch").option("-c, --config <string>","config file path").description("Adds new Data Structures and Event Specifications in the `snowtype.config.json` file.").option("-p, --dataProductIds <dataProductIds...>","data product ID").option("-e, --eventSpecificationIds <eventSpecificationIds...>","tracking eventSpecification ID").option("-d, --dataStructures <dataStructures...>","data structure URI").option("-i, --igluCentralSchemas <igluCentralSchemas...>","iglu central URI").option("-r, --repositories <repositories...>","repository path").action(Lt),e.command("purge").description("Removes stale event specification entries from the lock file that no longer exist in the configuration.").option("-c, --config <string>","config file path").action(Ft),e.command("check").option("-c, --config <string>","config file path").option("--instructions","generate event specification instructions").option("--no-instructions","generate without instructions").option("--validations","add runtime validation using Ajv").option("--no-validations","generate without runtime validations").option("--disallowDevSchemas","disallow generation of code using schemas only deployed on DEV environment").option("--deprecateOnlyOnProdAvailableUpdates","show deprecation warnings only when there are PROD available schema updates").description("Reports whether the generated code is up to date, without writing anything.").action($t),e.addHelpText("before",hn()).addHelpText("after",`
119
+ `),await e.parseAsync(Ui.argv).catch(t=>{br(t)})}function br(e){if(!(e instanceof B.CommanderError&&["commander.help","commander.version","commander.helpDisplayed"].indexOf(e.code)>-1))throw e}Gi().then(()=>{}).catch(()=>{process.exitCode=1});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowplow/snowtype",
3
- "version": "0.18.0",
3
+ "version": "0.20.0",
4
4
  "description": "A code generator CLI for faster and type-safe Snowplow tracking code",
5
5
  "author": "Peter Perlepes <peter@snowplowanalytics.com>",
6
6
  "homepage": "https://snowplow.io/",
@@ -14,7 +14,7 @@
14
14
  "dependencies": {
15
15
  "@commander-js/extra-typings": "^11.1.0",
16
16
  "@inquirer/prompts": "^8.2.0",
17
- "@snowplow/snowtype-core": "^0.18.0",
17
+ "@snowplow/snowtype-core": "^0.20.0",
18
18
  "chalk": "^4.1.2",
19
19
  "cli-spinner": "^0.2.10",
20
20
  "dotenv": "^16.3.1",
package/types.d.ts CHANGED
@@ -5,6 +5,7 @@ export type SnowtypeConfig = {
5
5
  organizationId?: string
6
6
  igluCentralSchemas?: string[]
7
7
  repositories?: string[]
8
+ localDataProducts?: string[]
8
9
  dataStructures?: string[]
9
10
  eventSpecificationIds?: string[]
10
11
  dataProductIds?: string[]