@snowplow/snowtype 0.8.4 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/index.js +38 -39
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -22,6 +22,7 @@ Useful scripts:
|
|
|
22
22
|
Add a `.env` file in the `packages/cli` folder with the following content:
|
|
23
23
|
|
|
24
24
|
```bash
|
|
25
|
+
SNOWPLOW_CONSOLE_API_KEY_ID=YOUR_KEY_ID_HERE
|
|
25
26
|
SNOWPLOW_CONSOLE_API_KEY=YOUR_KEY_HERE
|
|
26
27
|
SNOWPLOW_CONSOLE_API_URL=https://next.console.snowplowanalytics.com/api/msc
|
|
27
28
|
```
|
package/dist/index.js
CHANGED
|
@@ -1,43 +1,43 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);super(s),this.response={statusCode:n,body:r}}};function
|
|
3
|
-
${
|
|
1
|
+
"use strict";var Dn=Object.create;var Zt=Object.defineProperty;var $n=Object.getOwnPropertyDescriptor;var Ln=Object.getOwnPropertyNames;var Fn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var jn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ln(e))!Rn.call(t,o)&&o!==n&&Zt(t,o,{get:()=>e[o],enumerable:!(i=$n(e,o))||i.enumerable});return t};var S=(t,e,n)=>(n=t!=null?Dn(Fn(t)):{},jn(e||!t||!t.__esModule?Zt(n,"default",{value:t,enumerable:!0}):n,t));var En=S(require("process")),O=require("@commander-js/extra-typings");var A=require("@inquirer/prompts");var Vn={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.",MissingLockFile:"Missing lockfile. You might need to run `snowtype generate` first.",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"},Nn="Please report a bug.",f=class extends Error{code;constructor(e,n=""){let i=Vn[e].concat(n);super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e}},K=class extends f{constructor(){super("GenerationFailed")}},M=class extends f{constructor(){super("ConfigAlreadyExists")}},q=class extends f{constructor(){super("ConfigNotExists")}},X=class extends f{constructor(e){super("ConfigInvalid",e)}},Y=class extends f{constructor(e){super("InternalError",e.concat(Nn))}},L=class extends f{constructor(e,n){let i=`Value ${n} is an invalid ${e}.`;super("InvalidOption",i)}},Z=class extends f{constructor(){super("MissingOptions")}},F=class extends f{constructor(){super("AuthError")}},Q=class extends f{constructor(){super("WriteLockFile")}},tt=class extends f{constructor(){super("MissingLockFile")}},et=class extends f{constructor(){super("PatchingNotSupported")}},nt=class extends f{constructor(){super("DevNotAllowed")}},it=class extends f{constructor(){super("AuthCredentialsMissing")}};var Qt=S(require("got"));async function te({schema:t}){return(await(0,Qt.default)(`https://raw.githubusercontent.com/snowplow/iglu-central/master/schemas/${t.replace("iglu:","")}`)).body}var lt=S(require("got"));var ce=require("js-sha256"),kt=S(require("assert"));var u=S(require("joi")),ct=require("@snowplow/snowtype-core");var Tt=S(require("assert"));var U="snowtype.config",ot=".js",rt=".ts",at=".json",ee=Object.freeze([ot,rt,at]),st=".snowtype-lock.json",ne="snowplow";var W={"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"}]},ie={commands:{generate:{instructions:!1,validations:!1,disallowDevSchemas:!1},update:{maximumBump:"major",regenerateOnUpdate:!1,showOnlyProdUpdates:!1},patch:{regenerateOnPatch:!1}}},oe=["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"],re="iglu:com.snowplowanalytics.snowplow.ecommerce";var pt=require("lodash");function se(t){let e=t.split("-");(0,Tt.default)(e.length===3,"invalid SchemaVer"),(0,Tt.default)(e.filter(n=>isNaN(parseInt(n))).length===0,"invalid SchemaVer")}function R(t){t.options=(0,pt.merge)((0,pt.cloneDeep)(ie),t.options||{})}var ae=new RegExp("^iglu:[a-zA-Z0-9-_.]+/[a-zA-Z0-9-_]+/[a-zA-Z0-9-_]+/[0-9]+-[0-9]+-[0-9]+$"),_n=u.default.object().required().keys({tracker:u.default.string().required().valid(...ct.trackerTemplates),language:u.default.string().required().valid(...ct.languageIds),outpath:u.default.string().required(),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(ae)),dataStructures:u.default.array().optional().items(u.default.string().regex(ae)),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()}),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()})})})}),j=t=>{let e=_n.validate(t,{abortEarly:!1,convert:!1});if(e.error)throw new X(e.error.annotate());return t};function Mn(t){let e=ce.sha256.create();return e.update(t),e.hex()}function ut(t,e){let{vendor:n,name:i,format:o}=E(t);return Mn(`${e}-${n}-${i}-${o}`)}function E(t){let e=t.replace("iglu:",""),[n,i,o,r]=e.split("/");return(0,kt.default)(typeof n=="string"&&typeof i=="string"&&typeof o=="string"&&typeof r=="string",`invalid iglu uri ${t}`),se(r),{vendor:n,name:i,format:o,version:r}}function pe(t,{vendor:e,name:n,format:i,version:o}){let r=t.replace("iglu:",""),[s,a,p,c]=r.split("/");return`iglu:${e||s}/${n||a}/${i||p}/${o||c}`}function ue(t){return t.some(e=>e.eventSchema.isEcomTemplateSchema)}function G(t){let[e,n,i]=t.split("-").map(o=>parseInt(o));return{model:e,revision:n,addition:i}}function de(t,e,n=0){if(t===e&&n!==0)return"patch";let{model:i,revision:o,addition:r}=G(t),{model:s,revision:a,addition:p}=G(e);if(i!==s)return"major";if(o!==a)return"minor";if(r!==p)return"patch";(0,kt.default)(!1,"SchemaVer checking went wrong")}var dt=class extends Error{response;constructor(e){let n=e.response?.statusCode||0,{method:i,url:o}=e.options,r=e.response?.body||e.message,s=[[n,i,o].filter(Boolean).join(" "),r].filter(Boolean).join(`
|
|
2
|
+
`);super(s),this.response={statusCode:n,body:r}}};function le(t){return!!Object.hasOwn(t||{},"response")}var V="0.10.0";var x=class{apiKeyId;apiKey;organizationId;accessToken;apiUrl=process.env.SNOWPLOW_CONSOLE_API_URL||"https://console.snowplowanalytics.com/api/msc";constructor({apiKeyId:e,apiKey:n,organizationId:i}){this.apiKeyId=e,this.apiKey=n,this.organizationId=i}async fetchAccessToken(){if(this.accessToken)return this.accessToken;let e=`${this.apiUrl}/v1/organizations/${this.organizationId}/credentials/v3/token`,{accessToken:n}=await(0,lt.default)(e,{headers:{"X-API-Key-Id":this.apiKeyId,"X-API-Key":this.apiKey,"X-Snowtype":V}}).json();return this.accessToken=n,n}async fetchResource(e){let n=await this.fetchAccessToken();try{return await(0,lt.default)(e,{headers:{Authorization:"Bearer "+n,"X-Snowtype":V}}).json()}catch(i){throw le(i)?new dt(i):i}}fetchSchemaVersion({schema:e,env:n="DEV"}){let{version:i}=E(e),o=ut(e,this.organizationId),r=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${o}/versions/${i}?env=${n}`;return this.fetchResource(r)}fetchSchemaHash({schema:e}){let n=ut(e,this.organizationId),i=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${n}`;return this.fetchResource(i)}async fetchDeployments({schema:e,deploymentEnv:n}){let i=ut(e,this.organizationId),o=25,r=[],s=!0,a=0,p=c=>`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${i}/deployments?size=${o}&from=${c}${n?`&env=${n}`:""}`;for(;s;){let c=await this.fetchResource(p(a));a+=o,r=r.concat(c),c.length===0&&(s=!1)}return r}fetchEventSpecification({eventSpecificationId:e}){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/event-specs/v1/${e}`;return this.fetchResource(n)}async fetchImageVariant({imageId:e,imageVariant:n}){let i=`${this.apiUrl}/v1/organizations/${this.organizationId}/images/v1/${e}/${n}`,o=await this.fetchAccessToken();return(0,lt.default)(i,{headers:{Authorization:"Bearer "+o,"X-Snowtype":V}})}fetchDataProduct({dataProductId:e}){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-products/v2/${e}`;return this.fetchResource(n)}async authenticate(){try{return await this.fetchAccessToken(),!0}catch{return!1}}};var vt=require("process"),k=require("path"),v=require("fs");var Vt=S(require("util")),Nt=require("tsx/cjs/api");var b=(()=>{let t="json";return{setFormat:i=>t=i,getFormat:()=>t}})();var C=require("@snowplow/snowtype-core");var mt=require("fs"),Dt=require("path");var gt=S(require("assert"));var ge=require("semver"),me="snowtype.config.json";function Un(t){(0,mt.writeFileSync)((0,Dt.resolve)(process.cwd(),`./${me}`),Lt(t))}function fe(t,e){try{let n=(0,mt.readFileSync)((0,Dt.resolve)(process.cwd(),`./${me}`),{encoding:"utf-8"}),i=JSON.parse(n);return i[t].some(r=>r===e)||i[t].push(e),Un(i),!0}catch(n){return console.error(n),!1}}var Wn=(t,e)=>{let{model:n,revision:i,addition:o}=G(t.version),{model:r,revision:s,addition:a}=G(e.version);return(0,gt.default)(n!==void 0&&i!==void 0&&o!==void 0&&r!==void 0&&s!==void 0&&a!==void 0,`Invalid version number comparing (${t}, ${e})`),n>r?1:n<r?-1:i>s?1:i<s?-1:o>a?1:o<a?-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 he(t,e,n,i){return(await Promise.all(e.map(async r=>{let{version:s}=E(r),a=await t.fetchDeployments({schema:r,...i&&{deploymentEnv:"PROD"}}),p=Gn(a,s,n);p.sort(Wn);let c=p.pop();if(!c)return null;let l={previous:r,next:pe(r,{version:c.version}),nextEnv:c.env};return c.version!==s?{...l,nextReason:"version"}:c.patchLevel>0&&c.env==="DEV"?{...l,nextReason:"patch"}:null}))).flatMap(r=>r===null?[]:[r])}async function $t(t,e){return Promise.all(e.map(async n=>{try{await t.fetchSchemaVersion({schema:n,env:"PROD"})}catch(i){if(i.response?.statusCode===404)try{return await t.fetchSchemaVersion({schema:n,env:"DEV"}),n}catch(o){if(o.response?.statusCode!==404)throw o}}return null})).then(n=>n.flatMap(i=>i!==null?[i]:[]))}async function Se(t,e,n){let{eventSpecifications:i}=n,o={};return await Promise.all(e.map(async r=>{let s=i[r];if(!s)return r;let a=(await t.fetchEventSpecification({eventSpecificationId:r})).data[0];(0,gt.default)(!!a,`failed to fetch event spec ${r}`),(0,gt.default)(!!a.version,`event spec with no version ${r}`);let p=[a.event?.source,...a.entities?.tracked?.map(l=>l.source)||[]].flatMap(l=>typeof l=="string"?[l]:[]),c=await $t(t,p);return(a.version||0)>s&&(o[r]={previous:s,next:a.version,devOnlySchema:c}),r})),o}function Gn(t,e,n){return t.filter(i=>zn(e,i.version)!==1).filter(i=>i.version!==e||i.patchLevel).map(i=>({...i,updateType:de(i.version,e,i.patchLevel)})).filter(Hn(n))}function Hn(t){return({updateType:e})=>{switch(t){case"major":return!0;case"minor":return e==="patch"||e==="minor";case"patch":return e==="patch"}}}function zn(t,e){let n=t.replaceAll("-","."),i=e.replaceAll("-",".");return(0,ge.compare)(n,i)}var ye=require("cli-spinner"),h=S(require("chalk"));function we(){let t=new ye.Spinner;return t.setSpinnerString(18),t}var Bn="https://snowplow.io",Jn="https://docs.snowplow.io/docs/collecting-data/code-generation/",H={SUCCESS:"\u2714",LOG:"\u2139",DEBUG:"\u27A4",ERROR:"\u2717",WARN:"\u26A0"},Ie={LINK:"#9911BB",OPTION:"#9911DD"};function ve(t){return h.default.hex(Ie.LINK).bold(t)}function T(t){return h.default.hex(Ie.OPTION).italic(t)}function ft(t,e){switch(t){case"h1":return h.default.bold.underline(e);default:return h.default.bold(e)}}function Ee(){return`
|
|
3
|
+
${ft("h1","CLI Help")}
|
|
4
4
|
|
|
5
|
-
For more information visit the Snowplow website ${
|
|
5
|
+
For more information visit the Snowplow website ${ve(Bn)}
|
|
6
6
|
|
|
7
|
-
For details see the CLI documentation ${
|
|
7
|
+
For details see the CLI documentation ${ve(Jn)}
|
|
8
8
|
|
|
9
|
-
${
|
|
10
|
-
1. Use ${
|
|
11
|
-
2. Use ${
|
|
12
|
-
3. Use ${
|
|
9
|
+
${ft("h2","How to get started")}
|
|
10
|
+
1. Use ${h.default.cyanBright("snowtype init")} to initialize the setup.
|
|
11
|
+
2. Use ${h.default.cyanBright("snowtype patch")} to add a Data Structure or Event Specification.
|
|
12
|
+
3. Use ${h.default.cyanBright("snowtype generate")} to generate tracking code.
|
|
13
13
|
|
|
14
|
-
${
|
|
15
|
-
To learn more about each CLI command, use the ${
|
|
14
|
+
${ft("h2","Available commands")}
|
|
15
|
+
To learn more about each CLI command, use the ${T("--help")} option, for example, ${T("snowtype init --help")}.
|
|
16
16
|
|
|
17
|
-
${
|
|
17
|
+
${T("snowtype init")}
|
|
18
18
|
Initialize the setup of Snowtype code generation in a project. Creates the \`snowtype.config.json\` file.
|
|
19
19
|
|
|
20
|
-
${
|
|
20
|
+
${T("snowtype patch")}
|
|
21
21
|
Adds new Data Structures and Event Specifications in the \`snowtype.config.json\` file.
|
|
22
22
|
|
|
23
|
-
${
|
|
23
|
+
${T("snowtype generate")}
|
|
24
24
|
Generates tracking code based on configuration on the \`snowtype.config.json\` file.
|
|
25
25
|
|
|
26
|
-
${
|
|
26
|
+
${T("snowtype update")}
|
|
27
27
|
Checks for latest version updates in Data Structures and Event Specifications.
|
|
28
28
|
|
|
29
|
-
${
|
|
30
|
-
Use the ${
|
|
31
|
-
`}function
|
|
32
|
-
${
|
|
33
|
-
${
|
|
34
|
-
`}var
|
|
29
|
+
${ft("h2","Debug")}
|
|
30
|
+
Use the ${T("-v")} to output verbose logs
|
|
31
|
+
`}function xe(t){let e=`${H.SUCCESS}: `;return h.default.cyanBright(e)+t}function ht(t){let e=`${H.WARN} Warning: `;return h.default.hex("#FFA500")(e)+t}function Ce(t){let e=`${H.LOG} ${t}`;return h.default.yellowBright(e)}function Pe(t){let e=`${H.DEBUG} Debug: `;return h.default.magenta(e)+t}function Ae(t){let e=`${H.ERROR} Error: `;return h.default.redBright(e)+t}function Oe(t,e){let n=`- ${t}`,i=`+ ${e}`;return`
|
|
32
|
+
${h.default.magenta(n)}
|
|
33
|
+
${h.default.cyanBright(i)}
|
|
34
|
+
`}var De=S(require("mime-types"));var be=t=>(e,n)=>{Kn(e,n||"").forEach(t.warn)};function Kn(t,e){let n=qn(t.outdatedDsWarnings,e),i=Xn(t.hiddenDsWarnings,e);return n.concat(i)}function qn(t,e){return t.reduce((n,i)=>{let o=i.sources.map(r=>[`Source: ${r.source}`,`Latest Version: ${r.latestVersion}`].join(`
|
|
35
35
|
`));return[...n,`${["Outdated Data Structures detected:",`Data Product Id: ${e}`,`Event Specification Id: ${i.id}`,...o].join(`
|
|
36
|
-
`)}`]},[])}function
|
|
36
|
+
`)}`]},[])}function Xn(t,e){return t.reduce((n,i)=>{let o=i.sources.map(r=>`Source: ${r.source}`).join(`
|
|
37
37
|
`);return[...n,`${["Hidden Data Structures detected:",`Data Product Id: ${e}`,`Event Specification Id: ${i.id}`,o].join(`
|
|
38
|
-
`)}`]},[])}var
|
|
38
|
+
`)}`]},[])}var Te=({metadataResponse:t,accumulatorMetadataWarnings:e,eventSpecificationId:n})=>t!==void 0?Ft({currentMetadata:e,eventSpecificationId:n,newMetadata:t}):Ft({currentMetadata:e,eventSpecificationId:n,newMetadata:{outdatedDsWarnings:[],hiddenDsWarnings:[],metrics:[]}});async function St(t,e){return(await Promise.all(e.map(i=>t.fetchDataProduct({dataProductId:i})))).flatMap(({data:[i]})=>i?i.eventSpecs:[]).map(i=>i.id)}function Yn(t){let{original:e}=t,[n,i]=e.split("/").reverse();return{imageVariant:n,imageId:i}}async function $e(t,e){let n=[];if(!(e&&e.length))return[];for(let i of e){let{description:o,appIds:r,url:s,variantUrls:a}=i,p={description:o,appIds:r,url:s};if(a){let{imageVariant:c,imageId:l}=Yn(a),m=await t.fetchImageVariant({imageId:l,imageVariant:c});p.imageBuffer=m.rawBody,p.imageExtension=De.default.extension(m.headers["content-type"])||""}n.push(p)}return n}function Ft({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}))}}}async function Le(t,e,n){let i={};return{eventSpecificationsWithId:(await Promise.all(e.map(async r=>{let s=await t.fetchEventSpecification({eventSpecificationId:r}),a=s.data[0];if(typeof a>"u"||typeof a.event>"u")return[];!!s.metadata&&be(n)(s.metadata,a.dataProductId),i=Te({metadataResponse:s.metadata,accumulatorMetadataWarnings:i,eventSpecificationId:r});let c=Rt(a.event.source);c&&n.warn("Currently code will not be generated for `Standard` events. Skipping...");let l=a.triggers,m=a.name,g=a.version,d=a.sourceApplications||[],y=a.event.schema,D=c?Qn(a.event.source):await ke(t,a,a.event.source),w=a.entities?.tracked||[],I=await Promise.all(w.map(async({source:At,schema:Ot})=>({original:await ke(t,a,At),propertyRule:Ot})));return{eventSpecification:{name:m||"",id:r,dataProductId:a.dataProductId||"",dataProductName:""},version:g||0,eventSchema:D,entitiesSchemas:I,entities:w,triggers:l,propertyRules:y,sourceApplicationIds:d}}))).flat(),eventSpecificationsInputMetadata:i}}async function Fe(t){return await Promise.all(t.map(async n=>JSON.parse(await te({schema:n}))))}async function Re(t,e){return await Promise.all(e.map(i=>t.fetchSchemaVersion({schema:i})))}async function je(t,e){let n=e.flatMap(({eventSpecification:{dataProductId:r}})=>r?[r]:[]);return(await Promise.all(n.map(r=>t.fetchDataProduct({dataProductId:r})))).map(r=>r.data[0]&&{...r.data[0],sourceApplications:r.includes.sourceApplications||[]}).filter(Zn)}function Ve(t,e){let n=t.reduce((o,r)=>(o[r.id]={...r},o),{});return e.map(o=>{let r=n[o.eventSpecification.dataProductId],s=o.sourceApplicationIds.flatMap(a=>r?.sourceApplications.find(p=>p.id===a)||[]);return{...o,eventSpecification:{...o.eventSpecification,dataProductName:r?.name||""},sourceApplications:s}})}function Zn(t){return!!t}async function ke(t,e,n){let i=e.event?.schema?.properties?.type?.enum?.[0];return n.match(re)?{self:E(n),isEcomTemplateSchema:i}:await t.fetchSchemaVersion({schema:n})}function Ne(t){return t.reduce((n,i)=>{let o=i.eventSpecification.id;return i.entities.forEach(({source:r,minCardinality:s,maxCardinality:a})=>{if(typeof s<"u"||typeof a<"u"){let p={minCardinality:s,maxCardinality:a};n[o]=n[o]||{},n[o][r]=p}}),n},{})}function Qn(t){return{self:{...E(t)}}}var ti="SNOWPLOW_CONSOLE_API_KEY_ID",ei="SNOWPLOW_CONSOLE_API_KEY";function Ue(t){return t.length!==0}function Lt(t){return JSON.stringify(t,null,2)}function We(t){let e={organizationId:t.organizationId,tracker:t.tracker,language:t.language,outpath:t.outpath};return Object.assign({igluCentralSchemas:[],dataStructures:[],eventSpecificationIds:[],dataProductIds:[]},e)}function ni(t){switch(t){case"typescript":return`${U}${rt}`;case"javascript":return`${U}${ot}`;case"json":return`${U}${at}`;default:return""}}var _e=t=>(0,v.existsSync)(t)&&!(0,v.lstatSync)(t).isDirectory(),ii=t=>U+t,oi=t=>({isTS:t.endsWith(rt),isJSON:t.endsWith(at),isJS:t.endsWith(ot)}),jt=t=>({configPath:t,...oi(t)});function yt(t){let e=(0,k.isAbsolute)(t)?t:(0,k.resolve)(process.cwd(),t);if(_e(e))return jt(e);if(!(0,v.existsSync)(e))throw new Error(`Can't find a root directory while resolving a config file path.
|
|
39
39
|
Provided path to resolve: ${t}
|
|
40
|
-
cwd: ${process.cwd()}`);let[n]=
|
|
40
|
+
cwd: ${process.cwd()}`);let[n]=ee.map(i=>(0,k.resolve)(e,ii(i))).filter(_e);return jt(typeof n!="string"?e:n)}function wt(t){let e=b.getFormat(),n=ni(e),i=(0,k.resolve)((0,vt.cwd)(),n),o=`const config = ${Vt.default.inspect(t,!1,null)}
|
|
41
41
|
`,r=`type SnowtypeConfig = {
|
|
42
42
|
tracker: "${C.trackerTemplates.join('" | "')}";
|
|
43
43
|
language: "${C.languageIds.join('" | "')}";
|
|
@@ -65,15 +65,13 @@ cwd: ${process.cwd()}`);let[n]=Zt.map(i=>(0,k.resolve)(e,ti(i))).filter(je);retu
|
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
|
-
`,s=`const config: SnowtypeConfig = ${
|
|
69
|
-
`,a="module.exports = config;",p="export default config;";return e==="json"?(0,v.writeFileSync)(i,
|
|
70
|
-
`))}function
|
|
71
|
-
`,
|
|
68
|
+
`,s=`const config: SnowtypeConfig = ${Vt.default.inspect(t,!1,null)}
|
|
69
|
+
`,a="module.exports = config;",p="export default config;";return e==="json"?(0,v.writeFileSync)(i,Lt(t)):(0,v.writeFileSync)(i,(e==="typescript"?[r,s,p]:[o,a]).join(`
|
|
70
|
+
`))}function _t(t){let e=(0,v.statSync)(t,{throwIfNoEntry:!1});return e===void 0?!1:e.isFile()}function Mt(t){return(0,v.readFileSync)(t,{encoding:"utf-8"})}var ri=async t=>(await(0,Nt.require)(t,__filename)).default;async function N(){let{configPath:t,isJS:e,isJSON:n,isTS:i}=yt((0,vt.cwd)()),o;return i?(o=await ri(t),b.setFormat("typescript")):e?(o=(await import(t)).default,b.setFormat("javascript")):n&&(o=JSON.parse(Mt(t)),b.setFormat("json")),typeof o=="function"&&(o=await o()),o}function Ge(t){return JSON.parse(Mt(t))}async function He(t){t.debug("Checking for existing configuration.."),await Ut(!0),t.success("Valid configuration found")}async function Ut(t){let{configPath:e,isJS:n,isJSON:i,isTS:o}=yt(process.cwd()),r=i===!0||o===!0||n===!0,s=o===!1&&n===!1&&i===!1,a;if(o?a=(await(0,Nt.require)(e,__filename)).default:n?a=(await import(e)).default:i&&(a=JSON.parse(Mt(e))),typeof a=="function"&&(a=await a()),t){if(s)throw new q;j(a)}else if(r)try{throw j(a),new M}catch(p){if(p instanceof M)throw p}}function ze(t){return{javascript:".js","javascript-gtm":".js",typescript:".ts",kotlin:".kt",swift:".swift",go:".go"}[t]||""}function Be(t,e){let n={eventSpecifications:{}};t.forEach(o=>{n.eventSpecifications[o.eventSpecification.id]=o.version});let i=(0,k.resolve)((0,vt.cwd)(),e,st);try{(0,v.writeFileSync)(i,JSON.stringify(n,null,2))}catch{throw new Q}}function Je(t,e,n){let i=Object.entries(t);i.length>0&&n.success("Available Event Specification Updates"),i.forEach(([o,r])=>{let s=`${o}: version ${r.previous}`,a=`${o}: version ${r.next}`;n.diff(s,a),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}`,s=`${o.next}`;if(n.diff(r,s),o.nextReason==="patch"&&n.warn("The most recent version of this schema has been patched. Possible update required."),o.nextEnv==="DEV"){let a=o.next.split("/").pop();n.warn(`This data structure version (${a}) is not in production.`)}})}function Ke(t){let e=t.optsWithGlobals();return{...e,apiKeyId:e.apiKeyId||process.env[ti],apiKey:e.apiKey||process.env[ei]}}function z(t){return!!(Array.isArray(t)&&!t.length)}function It(t){return[...new Set(t)]}function qe(t){let e=It(t);return e.sort(),e}function ai(t){return t.flatMap(e=>{let n=(0,C.joinIgluSchemaUrlParts)(e.eventSchema.self),i=e.entities.map(o=>o.source);return[n,...i]})}async function Xe(t,e,n,i){let o=t.map(a=>(0,C.joinIgluSchemaUrlParts)(a.self)),r=ai(e),s=await $t(n,It([...o,...r]));if(s.length>0&&(console.log(`
|
|
71
|
+
`,ht(`Generating code using schemas in DEV environment, tracking against those will result in failed events. Schemas in DEV:
|
|
72
72
|
`+s.join(`
|
|
73
73
|
`)),`
|
|
74
|
-
`),i))throw new nt}function
|
|
75
|
-
Find out more ${en.default.underline("https://docs.snowplow.io/docs/collecting-data/code-generation/using-the-cli/#authenticating-with-the-console")}
|
|
76
|
-
`);let o=await ui(i,e);n.setSpinnerTitle("Initialising..."),n.isSpinning()===!1&&n.start(),e.debug("Creating configuration with options: ".concat(JSON.stringify(o)));let r=Me(o);if(j(r),!await new x({apiKey:t,organizationId:r.organizationId}).authenticate())throw new R;e.success("Authentication succeeded"),yt(r),e.success("Configuration created")}var Ut=P(di,"init");var vn=require("process"),yn=require("path");var gn=require("process"),xt=require("path"),mn=require("fs"),fn=require("mkdirp"),hn=require("@snowplow/snowtype-core");var It=require("path"),nn=require("mkdirp"),Wt=require("fs"),Et=require("@snowplow/snowtype-core");var li="instructions.md",on="assets";async function rn(t,e,n,i,o){nn.mkdirp.sync((0,It.resolve)(i,on));let r=[],s=hi(e,n,o),a=[];await Promise.all(e.map(async c=>{let l={triggers:await be(t,c.triggers),instructionsHeading:_t(c.eventSpecification.name)};a.push(_t(c.eventSpecification.name));let m=vi(c.propertyRules),g=yi(c.entities);mi(c.eventSpecification.id,l,i),r.push(gi({eventStructure:c.eventSchema.self,entitiesStructures:c.entitiesSchemas?.map(d=>d.self)||[],name:c.eventSpecification.name,id:c.eventSpecification.id,dataProductId:c.eventSpecification.dataProductId,version:c.version,triggerInstructions:l.triggers,linkToCode:s[c.eventSpecification.id],formattedPropertyRules:m,formattedCardinalityRules:g,organizationId:t.organizationId,sourceApplications:c.sourceApplications}))}));let p=`
|
|
74
|
+
`),i))throw new nt}function Rt(t){return oe.includes(t)}function Me({self:t}){let e=(0,C.joinIgluSchemaUrlParts)(t);return Rt(e)}function Ye(t){return{standardEventSpecs:t.filter(e=>Me(e.eventSchema)),customEventSpecs:t.filter(e=>!Me(e.eventSchema))}}function Ze(t,e,n){if(typeof t=="string"&&typeof e=="string"&&t&&e)return{apiKeyId:t,apiKey:e};throw n.error(new it),new Error}var si=["javascript","json","typescript"];function Qe(t){return t in W}function tn(t,e){let n=W[t];return Array.isArray(n)?n.map(o=>o.value).includes(e):!1}function en(t){return si.includes(t)}function nn(){return{withVerbosity:e=>({success:i=>{console.log(xe(i))},warn:i=>{console.log(ht(i))},log:i=>{console.log(Ce(i))},diff:(i,o)=>{console.log(Oe(i,o))},debug:i=>{e===!0&&console.log(Pe(JSON.stringify(i)))},error:i=>{console.log(Ae(i.message)),e===!0&&console.log(i)}})}}function P(t,e){return async(n,i)=>{let o=Ke(i),r=nn(),s=we(),a=r.withVerbosity(o.verbose),{apiKeyId:p,apiKey:c}=Ze(o.apiKeyId,o.apiKey,a);if(e!=="init")try{await He(a)}catch(l){on(l,a,s)}return t({apiKeyId:p,apiKey:c},a,s,n).then(()=>rn(s)).catch(l=>{on(l,a,s)})}}function on(t,e,n){throw rn(n),e.error(t),t}function rn(t){t.isSpinning()===!0&&t.stop(!0)}var ci={type:"password",message:"Enter your Snowplow organization ID:",mask:!0,validate:Ue},pi={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"}]},ui={type:"select",message:"Select the format to use:",choices:[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"},{value:"json",name:"JSON"}]},di={type:"input",message:"Enter the directory for Snowtype output:",default:"./snowtype"},li=t=>({type:"select",message:"Select the language to use:",choices:t});async function gi(t,e){e.debug("Checking for existing configuration file.."),await Ut(!1);let n=t.organizationId||await(0,A.password)(ci),i=t.tracker||await(0,A.select)(pi);if(!Qe(i))throw new L("tracker",i);let o=W[i],r;if(o.length===1){let p=o[0];if(typeof p>"u")throw new Y("Missing language entry.");r=p.value}else r=t.language||await(0,A.select)(li(o));if(!tn(i,r))throw new L("language",r);let s=await(0,A.select)(ui);if(!en(s))throw new L("format",s);b.setFormat(s);let a=t.outpath||await(0,A.input)(di);return e.debug("Assembling initialization options.."),{organizationId:n,tracker:i,language:r,format:s,outpath:a}}async function mi(t,e,n,i){let o=await gi(i,e);n.setSpinnerTitle("Initialising..."),n.isSpinning()===!1&&n.start(),e.debug("Creating configuration with options: ".concat(JSON.stringify(o)));let r=We(o);if(j(r),!await new x({...t,organizationId:r.organizationId}).authenticate())throw new F;e.success("Authentication succeeded"),wt(r),e.success("Configuration created")}var Wt=P(mi,"init");var wn=require("process"),In=require("path");var fn=require("process"),Ct=require("path"),hn=require("fs"),Sn=require("mkdirp"),vn=require("@snowplow/snowtype-core");var Et=require("path"),an=require("mkdirp"),Ht=require("fs"),xt=require("@snowplow/snowtype-core");var fi="instructions.md",sn="assets";async function cn(t,e,n,i,o){an.mkdirp.sync((0,Et.resolve)(i,sn));let r=[],s=yi(e,n,o),a=[];await Promise.all(e.map(async c=>{let l={triggers:await $e(t,c.triggers),instructionsHeading:Gt(c.eventSpecification.name)};a.push(Gt(c.eventSpecification.name));let m=Ii(c.propertyRules),g=Ei(c.entities);Si(c.eventSpecification.id,l,i),r.push(hi({eventStructure:c.eventSchema.self,entitiesStructures:c.entitiesSchemas?.map(d=>d.original.self)||[],name:c.eventSpecification.name,id:c.eventSpecification.id,dataProductId:c.eventSpecification.dataProductId,version:c.version,triggerInstructions:l.triggers,linkToCode:s[c.eventSpecification.id],formattedPropertyRules:m,formattedCardinalityRules:g,organizationId:t.organizationId,sourceApplications:c.sourceApplications}))}));let p=`
|
|
77
75
|
# Implementation instructions
|
|
78
76
|
|
|
79
77
|
_A guide on how to implement tracking for the generated Event Specifications._
|
|
@@ -84,8 +82,8 @@ ${a.map(c=>`- [${c.instructionsTitle}](#${c.instructionsLink})`).join(`
|
|
|
84
82
|
|
|
85
83
|
${r.join(`
|
|
86
84
|
`)}
|
|
87
|
-
`;(0,
|
|
88
|
-
## [${
|
|
85
|
+
`;(0,Ht.writeFileSync)((0,Et.resolve)(i,fi),p,"utf-8")}function hi({eventStructure:t,entitiesStructures:e,name:n,id:i,dataProductId:o,version:r,triggerInstructions:s,linkToCode:a,formattedPropertyRules:p,formattedCardinalityRules:c,organizationId:l,sourceApplications:m}){let g="_N/A_";return`
|
|
86
|
+
## [${Gt(n).instructionsTitle}](${vi(l,o,i)})
|
|
89
87
|
|
|
90
88
|
| | |
|
|
91
89
|
| ----------- | ----------- |
|
|
@@ -130,12 +128,13 @@ ${d.url||g}
|
|
|
130
128
|
#### Notes
|
|
131
129
|
|
|
132
130
|
${d.description||g}
|
|
133
|
-
`).join("")}`}function
|
|
131
|
+
`).join("")}`}function Si(t,e,n){e.triggers.forEach((i,o)=>{i.imageBuffer&&(0,Ht.writeFileSync)((0,Et.resolve)(n,sn,t+"_"+o+"."+i.imageExtension),i.imageBuffer,"binary")})}function vi(t,e,n){return`https://console.snowplowanalytics.com/${t}/data-products/${e}/event-specifications/${n}`}function yi(t,e,n){let i=t.reduce((o,{eventSpecification:{id:r}})=>(o[r]="",o),{});return Object.keys(i).forEach(o=>{let r=e.findIndex(s=>s.match((0,xt.createEventSpecificationInstructionsIdentifier)(o)));i[o]=r!==-1?`[Link](./${n+"#L"+r})`:"N/A"}),i}function Gt(t){let e=t;return{instructionsTitle:e,instructionsLink:wi(e)}}function wi(t){return t.toLowerCase().replace(/[^a-z\d\s-]/g," ").replace(/\s+/g," ").trim().replace(/-{2,}|\s/g,"-")}function Ii(t){return t?Object.entries(t.properties||{}).map(e=>{let[n,i]=e,o=t.required?.includes(n)?"\u2705":"\u274C",r=i.description||"-",s=i.enum?i.enum.map(a=>`\`${a}\``).join(" or "):"-";return{name:n,isRequired:o,description:r,expectedValues:s}}):[]}function Ei(t){return t?t.map(({source:e,minCardinality:n,maxCardinality:i})=>{let{name:o}=(0,xt.splitIgluSchemaUrlParts)(e),r=typeof n<"u"&&n>0?"\u2705":"\u274C",s=xi(n,i);return{name:o,isRequired:r,formattedCardinalityValues:s}}):[]}function xi(t,e){return typeof t>"u"?"`any`":typeof e<"u"?t===e?`Exactly \`${t}\``:`Between \`${t}\` and \`${e}\``:`At least \`${t}\``}var yn=S(require("fs-extra"));var un=require("fs"),dn=require("path"),ln=S(require("util"));function gn(t,e,n,i){let o=e==="typescript"?"ts":"js";(0,un.writeFileSync)((0,dn.resolve)(t,`validations.${o}`),`${o==="ts"?`
|
|
134
132
|
import { AnySchema } from "ajv";
|
|
135
133
|
export type CardinalityRule = { minCardinality?: number; maxCardinality?: number };
|
|
134
|
+
type IgluUrl = string;
|
|
135
|
+
type EventSpecificationId = string;
|
|
136
136
|
`:""}
|
|
137
|
-
export const entityRules${o==="ts"?": Record<
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
`),
|
|
141
|
-
`),await t.parseAsync(wn.argv).catch(e=>{Ti(e)})}function Ti(t){if(!(t instanceof O.CommanderError&&["commander.help","commander.version","commander.helpDisplayed"].indexOf(t.code)>-1))throw t}In().then(()=>{}).catch(()=>{process.exitCode=1});
|
|
137
|
+
export const entityRules${o==="ts"?": Record<EventSpecificationId, Record<IgluUrl, CardinalityRule>>":""} = ${pn(i)}
|
|
138
|
+
export const schemasObject${o==="ts"?": Record<IgluUrl | EventSpecificationId, AnySchema | Record<IgluUrl, AnySchema>>":""} = ${pn(n)}`,"utf-8")}function pn(t){return ln.default.inspect(t,{showHidden:!1,depth:null,maxArrayLength:null})}function zt(t){return Object.values(t).some(e=>Ci(e)?Pi(e):zt(e))}function Ci(t){return typeof t=="object"&&t!==null&&Object.hasOwn(t,"$schema")}function Pi(t){return t.properties?Object.values(t.properties).some(e=>Object.hasOwn(e||{},"pattern")):!1}function mn(t,e){let n=Oi(t);Ai(n,e)}function Ai(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 Oi(t){let e={};return t.forEach(n=>{let i=n.entities.map(r=>r.source),o=n.sourceApplications.flatMap(r=>[...r.entities.enriched.map(s=>s.source),...r.entities.tracked.map(s=>s.source)]);i.forEach(r=>{o.includes(r)&&(e[n.eventSpecification.id]?e[n.eventSpecification.id]?.push(r):e[n.eventSpecification.id]=[r])})}),e}async function bi(t){let e=await N();return R(e),e.options.commands.generate={...e.options.commands.generate,...t},e}async function B(t,e,n,i){let{dataProductIds:o,dataStructures:r,igluCentralSchemas:s,eventSpecificationIds:a,language:p,tracker:c,outpath:l,organizationId:m,options:{commands:{generate:g}}}=await bi(i);n.setSpinnerTitle("Generating..."),n.isSpinning()===!1&&n.start(),z(r)&&z(s)&&z(a)&&z(o)&&e.warn("Data Structures, Schemas and Event Specifications are empty.");let d=new x({...t,organizationId:m});if(!await d.authenticate())throw new F;let D=await St(d,o),w=qe([...D,...a]),{eventSpecificationsWithId:I,eventSpecificationsInputMetadata:At}=await Le(d,w,e),Ot=await je(d,I),J=Ve(Ot,I);mn(J,e);let{customEventSpecs:Cn,standardEventSpecs:Pn}=Ye(J),An=Pn.flatMap(bt=>bt.entities.map(kn=>kn.source));ue(I)&&c==="@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 On=await Fe(s),qt=await Re(d,[...r,...An]),Xt=!!(c==="@snowplow/browser-tracker"&&p.match(/javascript|typescript/));await Xe(qt,J,d,g.disallowDevSchemas);let bn={language:p,tracker:c,schemas:[...On,...qt],eventSpecifications:Cn,validations:Xt&&g.validations,eventSpecificationsInputMetadata:At},$=await(0,vn.generate)(bn);if(n.stop(!0),!$)throw new K;e.success("Code generated, writing...");let Tn=$.lines.join(`
|
|
139
|
+
`),_=(0,Ct.resolve)((0,fn.cwd)(),l);yn.default.removeSync((0,Ct.resolve)(_)),Sn.mkdirp.sync(_);let Yt=ne+ze(p);if((0,hn.writeFileSync)((0,Ct.resolve)(_,Yt),Tn),Be(I,l),Xt&&g.validations&&$.validationsSchemaObject){let bt=Ne(I);gn(_,p,$.validationsSchemaObject,bt),zt($.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 cn(d,J,$.lines,_,Yt)}var Bt=P(B,"generate");async function Ti(){let t=await N();return R(t),t}async function ki(t,e,n,i){let o=await Ti(),{options:{commands:{update:{maximumBump:r,regenerateOnUpdate:s,showOnlyProdUpdates:a},generate:p}}}=o;e.debug("Starting update process with options: ".concat(JSON.stringify(i)));let c=(0,In.resolve)((0,wn.cwd)(),o.outpath,st),l=new x({...t,organizationId:o.organizationId});n.setSpinnerTitle("Checking for updates..."),n.isSpinning()===!1&&n.start();let m=await St(l,o.dataProductIds),g=It([...o.eventSpecificationIds,...m]),d={};if(!_t(c)&&g.length>0)throw new tt;if(_t(c)&&g.length>0){let w=Ge(c);d=await Se(l,g,w)}let y=await he(l,o.dataStructures,i.maximumBump||r,a);if((Object.entries(d).length>0||y.length>0)===!0){if(e.success("Available updates found!"),Je(d,y,e),i.yes||s)return y.length>0&&(y.forEach(w=>{let I=o.dataStructures.indexOf(w.previous);o.dataStructures[I]=w.next}),wt(o)),e.debug("Applying the updates.."),B(t,e,n,p);e.log("No updates applied"),e.log("To apply the available updates automatically run `update` with the --yes flag"),e.log("(caution: will ovewrite the configuration file)")}else e.success("No updates found. Everything is up-to-date!");return Promise.resolve(void 0)}var Jt=P(ki,"update");async function Di(t){if(Object.values(t).every(n=>Array.isArray(n)&&n.length===0))throw new Z;let e=await N();return R(e),{patchOptions:t,generateOptions:e.options.commands.generate,regenerateOnPatch:e.options.commands.patch.regenerateOnPatch}}async function $i(t,e,n,i){let{isJSON:o}=yt(process.cwd());if(o===!1)throw new et;let{patchOptions:r,generateOptions:s,regenerateOnPatch:a}=await Di(i);return e.debug("Starting patch process with options: ".concat(JSON.stringify(r))),Object.entries(r).forEach(([c,l])=>{l.forEach(m=>{fe(c,m)})}),e.success("Configuration patched"),a?B(t,e,n,s):(e.log("Code is not generated yet for the patched configuration"),Promise.resolve(void 0))}var Kt=P($i,"patch");var Pt=require("@snowplow/snowtype-core");async function xn(){await import("dotenv/config");let t=new O.Command;t.exitOverride(),t.version(V,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 O.Option("-t, --tracker <availableTrackers>","tracker to use").choices(Pt.trackerTemplates)).addOption(new O.Option("-l, --language <availableLanguages>","language to use").choices(Pt.languageIds)).option("-o, --outpath <string>","output path").action(Wt),t.command("update").description("Checks for latest version updates in Data Structures and Event Specifications.").option("-y, --yes","updates all to latest without asking (caution: will ovewrite the configuration file)").addOption(new O.Option("-m, --maximumBump <'patch' | 'minor' | 'major'>","the maximum SchemaVer update to show an available update notification. Defaults to 'major'").choices(["patch","minor","major"])).action(Jt),t.command("generate").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").description("Generates tracking code based on configuration on the `snowtype.config.json` file.").action(Bt),t.command("patch").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").action(Kt),t.addHelpText("before",Ee()).addHelpText("after",`
|
|
140
|
+
`),await t.parseAsync(En.argv).catch(e=>{Li(e)})}function Li(t){if(!(t instanceof O.CommanderError&&["commander.help","commander.version","commander.helpDisplayed"].indexOf(t.code)>-1))throw t}xn().then(()=>{}).catch(()=>{process.exitCode=1});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@snowplow/snowtype",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.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/",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"dependencies": {
|
|
14
14
|
"@commander-js/extra-typings": "^11.1.0",
|
|
15
15
|
"@inquirer/prompts": "^3.3.0",
|
|
16
|
-
"@snowplow/snowtype-core": "^0.
|
|
16
|
+
"@snowplow/snowtype-core": "^0.10.0",
|
|
17
17
|
"chalk": "^4.1.2",
|
|
18
18
|
"cli-spinner": "^0.2.10",
|
|
19
19
|
"dotenv": "^16.3.1",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"prebuild:production": "npm run fix-version && rimraf ./dist",
|
|
56
56
|
"prebuild": "npm run fix-version",
|
|
57
57
|
"test": "jest --testPathIgnorePatterns e2e/",
|
|
58
|
-
"test:e2e": "jest e2e/"
|
|
58
|
+
"test:e2e": "npm run build:production && jest e2e/"
|
|
59
59
|
},
|
|
60
60
|
"engines": {
|
|
61
61
|
"node": ">=18"
|