@snowplow/snowtype 0.7.0 → 0.8.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 +2 -4
- package/dist/index.js +66 -52
- package/package.json +3 -4
package/README.md
CHANGED
|
@@ -12,8 +12,6 @@ Useful scripts:
|
|
|
12
12
|
| build:production | Builds project for deployment |
|
|
13
13
|
| build | Builds project for local development |
|
|
14
14
|
| fix-version | Fix version |
|
|
15
|
-
| format:fix | Fix formatting issues |
|
|
16
|
-
| format | Check for any formatting issues |
|
|
17
15
|
| lint:fix | Fix for any lint issues |
|
|
18
16
|
| lint | Check for any lint issues |
|
|
19
17
|
| prebuild:production | Remove dist folder |
|
|
@@ -41,7 +39,7 @@ Edit file `snowtype.config.ts` adding data products or event specifications.
|
|
|
41
39
|
Then run:
|
|
42
40
|
|
|
43
41
|
```bash
|
|
44
|
-
npm run snowtype generate
|
|
42
|
+
npm run snowtype generate
|
|
45
43
|
```
|
|
46
44
|
|
|
47
45
|
This will run the app and generate output code using ts-node.
|
|
@@ -59,4 +57,4 @@ Notes:
|
|
|
59
57
|
|
|
60
58
|
```bash
|
|
61
59
|
npm i -D @snowplow/browser-tracker -w @snowplow/snowtype
|
|
62
|
-
```
|
|
60
|
+
```
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`);super(s),this.response={statusCode:n,body:o}}};function
|
|
3
|
-
${
|
|
1
|
+
"use strict";var xn=Object.create;var Ht=Object.defineProperty;var Pn=Object.getOwnPropertyDescriptor;var En=Object.getOwnPropertyNames;var Cn=Object.getPrototypeOf,On=Object.prototype.hasOwnProperty;var bn=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of En(e))!On.call(t,r)&&r!==n&&Ht(t,r,{get:()=>e[r],enumerable:!(i=Pn(e,r))||i.enumerable});return t};var l=(t,e,n)=>(n=t!=null?xn(Cn(t)):{},bn(e||!t||!t.__esModule?Ht(n,"default",{value:t,enumerable:!0}):n,t));var fn=l(require("process")),V=require("@commander-js/extra-typings");var j=require("@inquirer/prompts");var Tn={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."},kn="Please report a bug.",f=class extends Error{code;constructor(e,n=""){let i=Tn[e].concat(n);super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e}},J=class extends f{constructor(){super("GenerationFailed")}},M=class extends f{constructor(){super("ConfigAlreadyExists")}},K=class extends f{constructor(){super("ConfigNotExists")}},q=class extends f{constructor(e){super("ConfigInvalid",e)}},I=class extends f{constructor(e){super("InternalError",e.concat(kn))}},T=class extends f{constructor(e,n){let i=`Value ${n} is an invalid ${e}.`;super("InvalidOption",i)}},X=class extends f{constructor(){super("MissingOptions")}},k=class extends f{constructor(){super("AuthError")}},Y=class extends f{constructor(){super("WriteLockFile")}},Z=class extends f{constructor(){super("MissingLockFile")}},Q=class extends f{constructor(){super("PatchingNotSupported")}},tt=class extends f{constructor(){super("DevNotAllowed")}};var Bt=l(require("got"));async function Jt({schema:t}){return(await(0,Bt.default)(`https://raw.githubusercontent.com/snowplow/iglu-central/master/schemas/${t.replace("iglu:","")}`)).body}var ct=l(require("got"));var Qt=require("js-sha256"),Pt=l(require("assert"));var u=l(require("joi")),ot=require("@snowplow/snowtype-core");var xt=l(require("assert"));var _="snowtype.config",et=".js",nt=".ts",it=".json",Kt=Object.freeze([et,nt,it]),rt=".snowtype-lock.json",qt="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"}]},Xt={commands:{generate:{instructions:!1,validations:!1,disallowDevSchemas:!1},update:{maximumBump:"major",regenerateOnUpdate:!1},patch:{regenerateOnPatch:!1}}};function Zt(t){let e=t.split("-");(0,xt.default)(e.length===3,"invalid SchemaVer"),(0,xt.default)(e.filter(n=>isNaN(parseInt(n))).length===0,"invalid SchemaVer")}function A(t){typeof t.options>"u"&&(t.options=Xt)}var Yt=new RegExp("^iglu:[a-zA-Z0-9-_.]+/[a-zA-Z0-9-_]+/[a-zA-Z0-9-_]+/[0-9]+-[0-9]+-[0-9]+$"),An=u.default.object().required().keys({tracker:u.default.string().required().valid(...ot.trackerTemplates),language:u.default.string().required().valid(...ot.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(Yt)),dataStructures:u.default.array().optional().items(u.default.string().regex(Yt)),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()})})})}),D=t=>{let e=An.validate(t,{abortEarly:!1,convert:!1});if(e.error)throw new q(e.error.annotate());return t};function Dn(t){let e=Qt.sha256.create();return e.update(t),e.hex()}function at(t,e){let{vendor:n,name:i,format:r}=x(t);return Dn(`${e}-${n}-${i}-${r}`)}function x(t){let e=t.replace("iglu:",""),[n,i,r,o]=e.split("/");return(0,Pt.default)(typeof n=="string"&&typeof i=="string"&&typeof r=="string"&&typeof o=="string",`invalid iglu uri ${t}`),Zt(o),{vendor:n,name:i,format:r,version:o}}function te(t,{vendor:e,name:n,format:i,version:r}){let o=t.replace("iglu:",""),[s,a,c,p]=o.split("/");return`iglu:${e||s}/${n||a}/${i||c}/${r||p}`}function ee(t){return t.some(e=>e.eventSchema.isEcomTemplateSchema)}function G(t){let[e,n,i]=t.split("-").map(r=>parseInt(r));return{model:e,revision:n,addition:i}}function ne(t,e,n=0){if(t===e&&n!==0)return"patch";let{model:i,revision:r,addition:o}=G(t),{model:s,revision:a,addition:c}=G(e);if(i!==s)return"major";if(r!==a)return"minor";if(o!==c)return"patch";(0,Pt.default)(!1,"SchemaVer checking went wrong")}var st=class extends Error{response;constructor(e){let n=e.response?.statusCode||0,{method:i,url:r}=e.options,o=e.response?.body||e.message,s=[[n,i,r].filter(Boolean).join(" "),o].filter(Boolean).join(`
|
|
2
|
+
`);super(s),this.response={statusCode:n,body:o}}};function ie(t){return!!Object.hasOwn(t||{},"response")}var F="0.8.0";var y=class{apiKey;organizationId;accessToken;apiUrl=process.env.SNOWPLOW_CONSOLE_API_URL||"https://console.snowplowanalytics.com/api/msc";constructor({apiKey:e,organizationId:n}){this.apiKey=e,this.organizationId=n}async fetchAccessToken(){if(this.accessToken)return this.accessToken;let e=`${this.apiUrl}/v1/organizations/${this.organizationId}/credentials/v2/token`,{accessToken:n}=await(0,ct.default)(e,{headers:{"X-API-Key":this.apiKey,"X-Snowtype":F}}).json();return this.accessToken=n,n}async fetchResource(e){let n=await this.fetchAccessToken();try{return await(0,ct.default)(e,{headers:{Authorization:"Bearer "+n,"X-Snowtype":F}}).json()}catch(i){throw ie(i)?new st(i):i}}fetchSchemaVersion({schema:e,env:n="DEV"}){let{version:i}=x(e),r=at(e,this.organizationId),o=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${r}/versions/${i}?env=${n}`;return this.fetchResource(o)}fetchSchemaHash({schema:e}){let n=at(e,this.organizationId),i=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${n}`;return this.fetchResource(i)}async fetchDeployments({schema:e}){let n=at(e,this.organizationId),i=25,r=[],o=!0,s=0,a=c=>`${this.apiUrl}/v1/organizations/${this.organizationId}/data-structures/v1/${n}/deployments?size=${i}&from=${c}`;for(;o;){let c=await this.fetchResource(a(s));s+=i,r=r.concat(c),c.length===0&&(o=!1)}return r}fetchEventSpecification({eventSpecificationId:e}){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/tracking-scenarios/v2/${e}`;return this.fetchResource(n)}async fetchImageVariant({imageId:e,imageVariant:n}){let i=`${this.apiUrl}/v1/organizations/${this.organizationId}/images/v1/${e}/${n}`,r=await this.fetchAccessToken();return(0,ct.default)(i,{headers:{Authorization:"Bearer "+r,"X-Snowtype":F}})}fetchDataProduct({dataProductId:e}){let n=`${this.apiUrl}/v1/organizations/${this.organizationId}/data-products/v1/${e}`;return this.fetchResource(n)}async authenticate(){try{return await this.fetchAccessToken(),!0}catch{return!1}}};var mt=require("process"),C=require("path"),v=require("fs");var kt=l(require("util")),At=require("tsx/cjs/api");var P=(()=>{let t="json";return{setFormat:i=>t=i,getFormat:()=>t}})();var O=require("@snowplow/snowtype-core");var ut=require("fs"),Et=require("path");var pt=l(require("assert"));var re=require("semver"),oe="snowtype.config.json";function Fn(t){(0,ut.writeFileSync)((0,Et.resolve)(process.cwd(),`./${oe}`),Ot(t))}function ae(t,e){try{let n=(0,ut.readFileSync)((0,Et.resolve)(process.cwd(),`./${oe}`),{encoding:"utf-8"}),i=JSON.parse(n);return i[t].some(o=>o===e)||i[t].push(e),Fn(i),!0}catch(n){return console.error(n),!1}}var $n=(t,e)=>{let{model:n,revision:i,addition:r}=G(t.version),{model:o,revision:s,addition:a}=G(e.version);return(0,pt.default)(n!==void 0&&i!==void 0&&r!==void 0&&o!==void 0&&s!==void 0&&a!==void 0,`Invalid version number comparing (${t}, ${e})`),n>o?1:n<o?-1:i>s?1:i<s?-1:r>a?1:r<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 se(t,e,n){return(await Promise.all(e.map(async r=>{let{version:o}=x(r),s=await t.fetchDeployments({schema:r}),a=Rn(s,o,n);a.sort($n);let c=a.pop();if(!c)return null;let p={previous:r,next:te(r,{version:c.version}),nextEnv:c.env};return c.version!==o?{...p,nextReason:"version"}:c.patchLevel>0&&c.env==="DEV"?{...p,nextReason:"patch"}:null}))).flatMap(r=>r===null?[]:[r])}async function Ct(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(r){if(r.response?.statusCode!==404)throw r}}return null})).then(n=>n.flatMap(i=>i!==null?[i]:[]))}async function ce(t,e,n){let{eventSpecifications:i}=n,r={};return await Promise.all(e.map(async o=>{let s=i[o];if(!s)return o;let a=(await t.fetchEventSpecification({eventSpecificationId:o})).data[0];(0,pt.default)(!!a,`failed to fetch event spec ${o}`),(0,pt.default)(!!a.version,`event spec with no version ${o}`);let c=[a.event?.source,...a.entities?.tracked?.map(d=>d.source)||[]].flatMap(d=>typeof d=="string"?[d]:[]),p=await Ct(t,c);return(a.version||0)>s&&(r[o]={previous:s,next:a.version,devOnlySchema:p}),o})),r}function Rn(t,e,n){return t.filter(i=>jn(e,i.version)!==1).filter(i=>i.version!==e||i.patchLevel).map(i=>({...i,updateType:ne(i.version,e,i.patchLevel)})).filter(Ln(n))}function Ln(t){return({updateType:e})=>{switch(t){case"major":return!0;case"minor":return e==="patch"||e==="minor";case"patch":return e==="patch"}}}function jn(t,e){let n=t.replaceAll("-","."),i=e.replaceAll("-",".");return(0,re.compare)(n,i)}var ue=require("cli-spinner"),m=l(require("chalk"));function de(){let t=new ue.Spinner;return t.setSpinnerString(18),t}var Vn="https://snowplow.io",Nn="https://docs.snowplow.io/docs/collecting-data/code-generation/",z={SUCCESS:"\u2714",LOG:"\u2139",DEBUG:"\u27A4",ERROR:"\u2717",WARN:"\u26A0"},ge={LINK:"#9911BB",OPTION:"#9911DD"};function pe(t){return m.default.hex(ge.LINK).bold(t)}function E(t){return m.default.hex(ge.OPTION).italic(t)}function dt(t,e){switch(t){case"h1":return m.default.bold.underline(e);default:return m.default.bold(e)}}function me(){return`
|
|
3
|
+
${dt("h1","CLI Help")}
|
|
4
4
|
|
|
5
|
-
For more information visit the Snowplow website ${
|
|
5
|
+
For more information visit the Snowplow website ${pe(Vn)}
|
|
6
6
|
|
|
7
|
-
For details see the CLI documentation ${
|
|
7
|
+
For details see the CLI documentation ${pe(Nn)}
|
|
8
8
|
|
|
9
|
-
${
|
|
10
|
-
1. Use ${
|
|
11
|
-
2. Use ${
|
|
12
|
-
3. Use ${
|
|
9
|
+
${dt("h2","How to get started")}
|
|
10
|
+
1. Use ${m.default.cyanBright("snowtype init")} to initialize the setup.
|
|
11
|
+
2. Use ${m.default.cyanBright("snowtype patch")} to add a Data Structure or Event Specification.
|
|
12
|
+
3. Use ${m.default.cyanBright("snowtype generate")} to generate tracking code.
|
|
13
13
|
|
|
14
|
-
${
|
|
14
|
+
${dt("h2","Available commands")}
|
|
15
15
|
To learn more about each CLI command, use the ${E("--help")} option, for example, ${E("snowtype init --help")}.
|
|
16
16
|
|
|
17
17
|
${E("snowtype init")}
|
|
@@ -26,37 +26,53 @@ To learn more about each CLI command, use the ${E("--help")} option, for example
|
|
|
26
26
|
${E("snowtype update")}
|
|
27
27
|
Checks for latest version updates in Data Structures and Event Specifications.
|
|
28
28
|
|
|
29
|
-
${
|
|
29
|
+
${dt("h2","Debug")}
|
|
30
30
|
Use the ${E("-v")} to output verbose logs
|
|
31
|
-
`}function
|
|
32
|
-
${
|
|
33
|
-
${
|
|
34
|
-
`}var
|
|
35
|
-
`));return[...e,`${["Outdated Data Structures detected:",`Event Specification Id: ${n.id}`,...
|
|
36
|
-
`)}`]},[])}function
|
|
37
|
-
`);return[...e,`${["Hidden Data Structures detected:",`Event Specification Id: ${n.id}`,
|
|
38
|
-
`)}`]},[])}function
|
|
31
|
+
`}function le(t){let e=`${z.SUCCESS}: `;return m.default.cyanBright(e)+t}function gt(t){let e=`${z.WARN} Warning: `;return m.default.hex("#FFA500")(e)+t}function fe(t){let e=`${z.LOG} ${t}`;return m.default.yellowBright(e)}function he(t){let e=`${z.DEBUG} Debug: `;return m.default.magenta(e)+t}function Se(t){let e=`${z.ERROR} Error: `;return m.default.redBright(e)+t}function ve(t,e){let n=`- ${t}`,i=`+ ${e}`;return`
|
|
32
|
+
${m.default.magenta(n)}
|
|
33
|
+
${m.default.cyanBright(i)}
|
|
34
|
+
`}var xe=l(require("mime-types"));var ye=t=>e=>{Un(e).forEach(t.warn)};function Un(t){let e=Mn(t.outdatedDsWarnings),n=_n(t.hiddenDsWarnings);return e.concat(n)}function Mn(t){return t.reduce((e,n)=>{let i=n.sources.map(r=>[`Source: ${r.source}`,`Latest Version: ${r.latestVersion}`].join(`
|
|
35
|
+
`));return[...e,`${["Outdated Data Structures detected:",`Event Specification Id: ${n.id}`,...i].join(`
|
|
36
|
+
`)}`]},[])}function _n(t){return t.reduce((e,n)=>{let i=n.sources.map(r=>`Source: ${r.source}`).join(`
|
|
37
|
+
`);return[...e,`${["Hidden Data Structures detected:",`Event Specification Id: ${n.id}`,i].join(`
|
|
38
|
+
`)}`]},[])}var we=({metadataResponse:t,accumulatorMetadataWarnings:e,eventSpecificationId:n})=>t!==void 0?bt({currentMetadata:e,eventSpecificationId:n,newMetadata:t}):bt({currentMetadata:e,eventSpecificationId:n,newMetadata:{outdatedDsWarnings:[],hiddenDsWarnings:[],metrics:[]}});var Wn=["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"],Gn="iglu:com.snowplowanalytics.snowplow.ecommerce";async function Pe(t,e){return(await Promise.all(e.map(i=>t.fetchDataProduct({dataProductId:i})))).flatMap(({data:[i]})=>i?i.trackingScenarios:[]).map(i=>i?.id).filter(i=>!!i)}function zn(t){let{original:e}=t,[n,i]=e.split("/").reverse();return{imageVariant:n,imageId:i}}async function Ee(t,e){let n=[];if(!(e&&e.length))return[];for(let i of e){let{description:r,appIds:o,url:s,variantUrls:a}=i,c={description:r,appIds:o,url:s};if(a){let{imageVariant:p,imageId:d}=zn(a),g=await t.fetchImageVariant({imageId:d,imageVariant:p});c.imageBuffer=g.rawBody,c.imageExtension=xe.default.extension(g.headers["content-type"])||""}n.push(c)}return n}function bt({currentMetadata:t,eventSpecificationId:e,newMetadata:n}){let i=(r,o)=>r.id>o.id?1:-1;return{...t,[e]:{hiddenDsWarnings:n.hiddenDsWarnings.sort(i).map(r=>({sources:r.sources})),outdatedDsWarnings:n.outdatedDsWarnings.sort(i).map(r=>({sources:r.sources}))}}}async function Ce(t,e,n){let i={};return{eventSpecificationsWithId:(await Promise.all(e.map(async o=>{let s=await t.fetchEventSpecification({eventSpecificationId:o}),a=s.data[0];if(!!s.metadata&&ye(n)(s.metadata),i=we({metadataResponse:s.metadata,accumulatorMetadataWarnings:i,eventSpecificationId:o}),typeof a>"u"||typeof a.event>"u")return[];if(Wn.includes(a.event.source))return n.warn("Currently you cannot generate code for `Standard` events. Skipping..."),[];let p=a.triggers,d=a.name,g=a.version,h=a.event.schema,S=await Ie(t,a,a.event.source),yt=a.entities?.tracked||[],wt=await Promise.all(yt.map(({source:It})=>Ie(t,a,It)));return{eventSpecification:{name:d||"",id:o,dataProductId:a.dataProductId||"",dataProductName:""},version:g||0,eventSchema:S,entitiesSchemas:wt,entities:yt,triggers:p,propertyRules:h}}))).flat(),eventSpecificationsInputMetadata:i}}async function Oe(t){return await Promise.all(t.map(async n=>JSON.parse(await Jt({schema:n}))))}async function be(t,e){return await Promise.all(e.map(i=>t.fetchSchemaVersion({schema:i})))}async function Te(t,e){let n=e.flatMap(({eventSpecification:{dataProductId:s}})=>s?[s]:[]),r=(await Promise.all(n.map(async s=>(await t.fetchDataProduct({dataProductId:s})).data[0]))).filter(Hn).reduce((s,a)=>(s[a.id]=a.name,s),{});return e.map(s=>({...s,eventSpecification:{...s.eventSpecification,dataProductName:r[s.eventSpecification.dataProductId]||""}}))}function Hn(t){return!!t}async function Ie(t,e,n){let i=e.event?.schema?.properties?.type?.enum?.[0];return n.match(Gn)?{self:x(n),isEcomTemplateSchema:i}:await t.fetchSchemaVersion({schema:n})}function ke(t){return t.reduce((n,i)=>{let r=i.eventSpecification.id;return i.entities.forEach(({source:o,minCardinality:s,maxCardinality:a})=>{if(typeof s<"u"||typeof a<"u"){let c={minCardinality:s,maxCardinality:a};n[r]=n[r]||{},n[r][o]=c}}),n},{})}function De(t){return t.length!==0}function Ot(t){return JSON.stringify(t,null,2)}function Fe(t){let e={organizationId:t.organizationId,tracker:t.tracker,language:t.language,outpath:t.outpath};return Object.assign({igluCentralSchemas:[],dataStructures:[],eventSpecificationIds:[],dataProductIds:[]},e)}function Bn(t){switch(t){case"typescript":return`${_}${nt}`;case"javascript":return`${_}${et}`;case"json":return`${_}${it}`;default:return""}}var Ae=t=>(0,v.existsSync)(t)&&!(0,v.lstatSync)(t).isDirectory(),Jn=t=>_+t,Kn=t=>({isTS:t.endsWith(nt),isJSON:t.endsWith(it),isJS:t.endsWith(et)}),Tt=t=>({configPath:t,...Kn(t)});function lt(t){let e=(0,C.isAbsolute)(t)?t:(0,C.resolve)(process.cwd(),t);if(Ae(e))return Tt(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]=Kt.map(
|
|
40
|
+
cwd: ${process.cwd()}`);let[n]=Kt.map(i=>(0,C.resolve)(e,Jn(i))).filter(Ae);return Tt(typeof n!="string"?e:n)}function ft(t){let e=P.getFormat(),n=Bn(e),i=(0,C.resolve)((0,mt.cwd)(),n),r=`const config = ${kt.default.inspect(t,!1,null)}
|
|
41
41
|
`,o=`type SnowtypeConfig = {
|
|
42
|
-
tracker: "${
|
|
43
|
-
language: "${
|
|
42
|
+
tracker: "${O.trackerTemplates.join('" | "')}";
|
|
43
|
+
language: "${O.languageIds.join('" | "')}";
|
|
44
44
|
outpath: string;
|
|
45
45
|
organizationId?: string;
|
|
46
46
|
igluCentralSchemas?: string[];
|
|
47
47
|
dataStructures?: string[];
|
|
48
48
|
eventSpecificationIds?: string[];
|
|
49
49
|
dataProductIds?: string[];
|
|
50
|
+
options?: {
|
|
51
|
+
commands: {
|
|
52
|
+
generate?: {
|
|
53
|
+
instructions?: boolean;
|
|
54
|
+
validations?: boolean;
|
|
55
|
+
disallowDevSchemas?: boolean;
|
|
56
|
+
}
|
|
57
|
+
update?: {
|
|
58
|
+
regenerateOnUpdate?: boolean
|
|
59
|
+
maximumBump?: "major" | "minor" | "patch"
|
|
60
|
+
}
|
|
61
|
+
patch?: {
|
|
62
|
+
regenerateOnPatch?: boolean
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
50
66
|
}
|
|
51
|
-
`,s=`const config: SnowtypeConfig = ${
|
|
52
|
-
`,a="module.exports = config;",c="export default config;";return e==="json"?(0,
|
|
53
|
-
`))}function
|
|
54
|
-
`,
|
|
67
|
+
`,s=`const config: SnowtypeConfig = ${kt.default.inspect(t,!1,null)}
|
|
68
|
+
`,a="module.exports = config;",c="export default config;";return e==="json"?(0,v.writeFileSync)(i,Ot(t)):(0,v.writeFileSync)(i,(e==="typescript"?[o,s,c]:[r,a]).join(`
|
|
69
|
+
`))}function Dt(t){let e=(0,v.statSync)(t,{throwIfNoEntry:!1});return e===void 0?!1:e.isFile()}function Ft(t){return(0,v.readFileSync)(t,{encoding:"utf-8"})}var qn=async t=>(await(0,At.require)(t,__filename)).default;async function $(){let{configPath:t,isJS:e,isJSON:n,isTS:i}=lt((0,mt.cwd)()),r;return i?(r=await qn(t),P.setFormat("typescript")):e?(r=(await import(t)).default,P.setFormat("javascript")):n&&(r=JSON.parse(Ft(t)),P.setFormat("json")),typeof r=="function"&&(r=await r()),r}function $e(t){return JSON.parse(Ft(t))}async function Re(t){t.debug("Checking for existing configuration.."),await $t(!0),t.success("Valid configuration found")}async function $t(t){let{configPath:e,isJS:n,isJSON:i,isTS:r}=lt(process.cwd()),o=i===!0||r===!0||n===!0,s=r===!1&&n===!1&&i===!1,a;if(r?a=(await(0,At.require)(e,__filename)).default:n?a=(await import(e)).default:i&&(a=JSON.parse(Ft(e))),typeof a=="function"&&(a=await a()),t){if(s)throw new K;D(a)}else if(o)try{throw D(a),new M}catch(c){if(c instanceof M)throw c}}function Le(t){return{javascript:".js","javascript-gtm":".js",typescript:".ts",kotlin:".kt",swift:".swift",go:".go"}[t]||""}function je(t,e){let n={eventSpecifications:{}};t.forEach(r=>{n.eventSpecifications[r.eventSpecification.id]=r.version});let i=(0,C.resolve)((0,mt.cwd)(),e,rt);try{(0,v.writeFileSync)(i,JSON.stringify(n,null,2))}catch{throw new Y}}function Ve(t,e,n){let i=Object.entries(t);i.length>0&&n.success("Available Event Specification Updates"),i.forEach(([r,o])=>{let s=`${r}: version ${o.previous}`,a=`${r}: version ${o.next}`;n.diff(s,a),o.devOnlySchema.length>0&&(n.warn("This Event Specification uses schema that are not in production."),n.warn(o.devOnlySchema.join(" ")))}),e.length>0&&n.success("Available Data Structures Updates"),e.forEach(r=>{let o=`${r.previous}`,s=`${r.next}`;if(n.diff(o,s),r.nextReason==="patch"&&n.warn("The most recent version of this schema has been patched. Possible update required."),r.nextEnv==="DEV"){let a=r.next.split("/").pop();n.warn(`This data structure version (${a}) is not in production.`)}})}function Ne(t){let e=t.optsWithGlobals();return{...e,apiKey:e.apiKey||process.env.SNOWPLOW_CONSOLE_API_KEY}}function H(t){return!!(Array.isArray(t)&&!t.length)}function Ue(t){return[...new Set(t)]}function Me(t){let e=Ue(t);return e.sort(),e}function Xn(t){return t.flatMap(e=>{let n=(0,O.joinIgluSchemaUrlParts)(e.eventSchema.self),i=e.entities.map(r=>r.source);return[n,...i]})}async function _e(t,e,n,i){let r=t.map(a=>(0,O.joinIgluSchemaUrlParts)(a.self)),o=Xn(e),s=await Ct(n,Ue([...r,...o]));if(s.length>0&&(console.log(`
|
|
70
|
+
`,gt(`Generating code using schemas in DEV environment, tracking against those will result in failed events. Schemas in DEV:
|
|
55
71
|
`+s.join(`
|
|
56
72
|
`)),`
|
|
57
|
-
`),
|
|
58
|
-
Find out more ${
|
|
59
|
-
`);let
|
|
73
|
+
`),i))throw new tt}function We(t){return t.type==="input"}function Ge(t){return t.type==="password"}function Rt(t){return t.type==="select"}var Yn=["javascript","json","typescript"],Zn=["organizationId","tracker","language","format","outpath"];function ze(t){return Zn.includes(t)}function He(t){return t in W}function Be(t,e){let n=W[t];return Array.isArray(n)?n.map(r=>r.value).includes(e):!1}function Je(t){return Yn.includes(t)}function Ke(){return{withVerbosity:e=>({success:i=>{console.log(le(i))},warn:i=>{console.log(gt(i))},log:i=>{console.log(fe(i))},diff:(i,r)=>{console.log(ve(i,r))},debug:i=>{e===!0&&console.log(he(JSON.stringify(i)))},error:i=>{console.log(Se(i.message)),e===!0&&console.log(i)}})}}function w(t,e){return async(n,i)=>{let r=Ne(i),o=Ke(),s=de(),a=o.withVerbosity(r.verbose),c=r.apiKey;if(e!=="init")try{await Re(a)}catch(p){qe(p,a,s)}return t(c,a,s,n).then(()=>Xe(s)).catch(p=>{qe(p,a,s)})}}function qe(t,e,n){throw Xe(n),e.error(t),t}function Xe(t){t.isSpinning()===!0&&t.stop(!0)}var Ye=l(require("chalk"));var R=[{type:"password",message:"Enter your Snowplow organization ID:",mask:!0,validate:De},{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"}]},{type:"select",message:"Select the language to use:"},{type:"select",message:"Select the format to use:",choices:[{value:"javascript",name:"JavaScript"},{value:"typescript",name:"TypeScript"},{value:"json",name:"JSON"}]},{type:"input",message:"Enter the directory for Snowtype output:",default:"./snowtype"}];function L(t,e,n=""){if(n)return Promise.resolve(n);if(!ze(t))throw new I("Invalid default options.");if(We(e))return(0,j.input)(e);if(Ge(e))return(0,j.password)(e);if(Rt(e))return(0,j.select)(e);throw new I("Unknown Prompt inquired.")}function Qn(t,e){return Rt(e)&&(e.choices=t),e}async function ti(t){t.debug("Checking for existing configuration file.."),await $t(!1);let e=await L("organizationId",R[0]),n=await L("tracker",R[1]);if(!He(n))throw new T("tracker",n);let i=W[n];if(!Array.isArray(i)||i.length===0)throw new I("Missing language entry.");let r;if(i.length===1){let a=i[0];if(typeof a>"u")throw new I("Missing language.");r=await L("language",R[2],a.value)}else r=await L("language",Qn(i,R[2]));if(!Be(n,r))throw new T("language",r);let o=await L("format",R[3]);if(!Je(o))throw new T("format",o);P.setFormat(o);let s=await L("outpath",R[4]);return t.debug("Assempling initialization options.."),{organizationId:e,tracker:n,language:r,format:o,outpath:s}}async function ei(t,e,n){t||e.warn(`No SNOWPLOW_CONSOLE_API_KEY detected. You might need to set this up before initializing.
|
|
74
|
+
Find out more ${Ye.default.underline("https://docs.snowplow.io/docs/collecting-data/code-generation/using-the-cli/#authenticating-with-the-console")}
|
|
75
|
+
`);let i=await ti(e);n.setSpinnerTitle("Initialising..."),n.isSpinning()===!1&&n.start(),e.debug("Creating configuration with options: ".concat(JSON.stringify(i)));let r=Fe(i);if(D(r),!await new y({apiKey:t,organizationId:r.organizationId}).authenticate())throw new k;e.success("Authentication succeeded"),ft(r),e.success("Configuration created")}var Lt=w(ei,"init");var mn=require("process"),ln=require("path");var cn=require("process"),vt=require("path"),pn=require("fs"),un=require("mkdirp"),dn=require("@snowplow/snowtype-core");var ht=require("path"),Ze=require("mkdirp"),Vt=require("fs"),St=require("@snowplow/snowtype-core");var ni="instructions.md",Qe="assets";async function tn(t,e,n,i,r){Ze.mkdirp.sync((0,ht.resolve)(i,Qe));let o=[],s=oi(e,n,r),a=[];await Promise.all(e.map(async p=>{let d={triggers:await Ee(t,p.triggers),instructionsHeading:jt(p.eventSpecification.name)};a.push(jt(p.eventSpecification.name));let g=si(p.propertyRules),h=ci(p.entities);ri(p.eventSpecification.id,d,i),o.push(ii({eventStructureName:p.eventSchema.self.name,entitiesStructureNames:p.entitiesSchemas?.map(S=>S.self.name),name:p.eventSpecification.name,id:p.eventSpecification.id,version:p.version,triggerInstructions:d.triggers,linkToCode:s[p.eventSpecification.id],formattedPropertyRules:g,formattedCardinalityRules:h}))}));let c=`
|
|
60
76
|
# Implementation instructions
|
|
61
77
|
|
|
62
78
|
_A guide on how to implement tracking for the generated Event Specifications._
|
|
@@ -67,56 +83,54 @@ ${a.map(p=>`- [${p.instructionsTitle}](#${p.instructionsLink})`).join(`
|
|
|
67
83
|
|
|
68
84
|
${o.join(`
|
|
69
85
|
`)}
|
|
70
|
-
`;(0,
|
|
71
|
-
## ${
|
|
86
|
+
`;(0,Vt.writeFileSync)((0,ht.resolve)(i,ni),c,"utf-8")}function ii({eventStructureName:t,entitiesStructureNames:e,name:n,id:i,version:r,triggerInstructions:o,linkToCode:s,formattedPropertyRules:a,formattedCardinalityRules:c}){let p="_N/A_";return`
|
|
87
|
+
## ${jt(n).instructionsTitle}
|
|
72
88
|
|
|
73
89
|
| | |
|
|
74
90
|
| ----------- | ----------- |
|
|
75
|
-
| **Id** | ${
|
|
76
|
-
| **Version** | ${
|
|
91
|
+
| **Id** | ${i} |
|
|
92
|
+
| **Version** | ${r} |
|
|
77
93
|
| **Event Data Structure** | ${t} |
|
|
78
94
|
| **Entity Data Structures** | ${e?.sort().join(", ")} |
|
|
79
95
|
| **Code** | [Link](./${s}) |
|
|
80
96
|
|
|
81
|
-
${a.length>0
|
|
97
|
+
${a.length>0?`### Implementation Instructions for ${t} event properties
|
|
82
98
|
|
|
83
|
-
${a.length>0&&`
|
|
84
99
|
| Name | Required | Description | Exact value(s) expected |
|
|
85
100
|
| ----------- | ----------- | ----------- | ----------- |
|
|
86
|
-
${a.map(
|
|
101
|
+
${a.map(d=>Object.values(d).join(" | ")).join(`
|
|
87
102
|
`)}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
${c.length>0&&`
|
|
103
|
+
`:""}
|
|
104
|
+
${c.length>0?`
|
|
91
105
|
| Name | Required | Number of entities |
|
|
92
106
|
| ----------- | ----------- | ----------- |
|
|
93
|
-
${c.map(
|
|
107
|
+
${c.map(d=>Object.values(d).join(" | ")).join(`
|
|
94
108
|
`)}
|
|
95
|
-
|
|
109
|
+
`:""}
|
|
96
110
|
|
|
97
|
-
${o.map((
|
|
98
|
-
### Trigger ${
|
|
111
|
+
${o.map((d,g,h)=>`
|
|
112
|
+
### Trigger ${h.length!==1?g+1:""}
|
|
99
113
|
|
|
100
114
|
#### Screenshot
|
|
101
|
-
${
|
|
115
|
+
${d.imageBuffer?`[<img src="./assets/${i}_${g}.${d.imageExtension}" width="550"/>](./assets/${i}_${g}.${d.imageExtension})`:p}
|
|
102
116
|
|
|
103
117
|
#### In which application(s) does this trigger apply?
|
|
104
118
|
|
|
105
|
-
${
|
|
119
|
+
${d.appIds&&d.appIds.length?d.appIds.map(S=>"`"+S+"` "):p}
|
|
106
120
|
|
|
107
121
|
#### The URL of the page on which this event specification triggers:
|
|
108
122
|
|
|
109
|
-
${
|
|
123
|
+
${d.url||p}
|
|
110
124
|
|
|
111
125
|
#### Notes
|
|
112
126
|
|
|
113
|
-
${
|
|
114
|
-
`).join("")}`}function
|
|
127
|
+
${d.description||p}
|
|
128
|
+
`).join("")}`}function ri(t,e,n){e.triggers.forEach((i,r)=>{i.imageBuffer&&(0,Vt.writeFileSync)((0,ht.resolve)(n,Qe,t+"_"+r+"."+i.imageExtension),i.imageBuffer,"binary")})}function oi(t,e,n){let i=t.reduce((r,{eventSpecification:{id:o}})=>(r[o]="",r),{});return Object.keys(i).forEach(r=>{let o=e.findIndex(s=>s.match((0,St.createEventSpecificationInstructionsIdentifier)(r)));i[r]=n+"#L"+o}),i}function jt(t){let e=t;return{instructionsTitle:e,instructionsLink:ai(e)}}function ai(t){return t.toLowerCase().replace(/[^a-z\d\s-]/g," ").replace(/\s+/g," ").trim().replace(/-{2,}|\s/g,"-")}function si(t){return t?Object.entries(t.properties||{}).map(([e,n])=>{let i=t.required?.includes(e)?"\u2705":"\u274C",r=n.description||"-",o=n.enum?n.enum.map(s=>`\`${s}\``).join(" or "):"-";return{name:e,isRequired:i,description:r,expectedValues:o}}):[]}function ci(t){return t?t.map(({source:e,minCardinality:n,maxCardinality:i})=>{let{name:r}=(0,St.splitIgluSchemaUrlParts)(e),o=typeof n<"u"&&n>0?"\u2705":"\u274C",s=pi(n,i);return{name:r,isRequired:o,formattedCardinalityValues:s}}):[]}function pi(t,e){return typeof t>"u"?"`any`":typeof e<"u"?t===e?`Exactly \`${t}\``:`Between \`${t}\` and \`${e}\``:`At least \`${t}\``}var gn=l(require("fs-extra"));var nn=require("fs"),rn=require("path"),on=l(require("util"));function an(t,e,n,i){let r=e==="typescript"?"ts":"js";(0,nn.writeFileSync)((0,rn.resolve)(t,`validations.${r}`),`${r==="ts"?`
|
|
115
129
|
import { AnySchema } from "ajv";
|
|
116
130
|
export type CardinalityRule = { minCardinality?: number; maxCardinality?: number };
|
|
117
131
|
`:""}
|
|
118
|
-
export const entityRules${
|
|
132
|
+
export const entityRules${r==="ts"?": Record<string, Record<string, CardinalityRule>>":""} = ${en(i)}
|
|
119
133
|
|
|
120
|
-
export const schemasObject${
|
|
121
|
-
`),
|
|
122
|
-
`),await t.parseAsync(
|
|
134
|
+
export const schemasObject${r==="ts"?": Record<string, AnySchema>":""} = ${en(n)}`,"utf-8")}function en(t){return on.default.inspect(t,{showHidden:!1,depth:null,maxArrayLength:null})}function sn(t){return Object.values(t).some(e=>e.properties?Object.values(e.properties).some(n=>Object.hasOwn(n||{},"pattern")):!1)}async function ui(t){let e=await $();return A(e),e.options.commands.generate={...e.options.commands.generate,...t},e}async function B(t,e,n,i){let{dataProductIds:r,dataStructures:o,igluCentralSchemas:s,eventSpecificationIds:a,language:c,tracker:p,outpath:d,organizationId:g,options:{commands:{generate:h}}}=await ui(i);n.setSpinnerTitle("Generating..."),n.isSpinning()===!1&&n.start(),H(o)&&H(s)&&H(a)&&H(r)&&e.warn("Data Structures, Schemas and Event Specifications are empty.");let S=new y({apiKey:t,organizationId:g});if(!await S.authenticate())throw new k;let wt=await Pe(S,r),It=Me([...wt,...a]),{eventSpecificationsWithId:N,eventSpecificationsInputMetadata:Sn}=await Ce(S,It,e),_t=await Te(S,N);ee(N)&&p==="@snowplow/browser-tracker"&&e.log("You are generating Snowplow Ecommerce events. You would need to install `@snowplow/browser-plugin-snowplow-ecommerce`."),h.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 vn=await Oe(s),Wt=await be(S,o),Gt=!!(p==="@snowplow/browser-tracker"&&c.match(/javascript|typescript/));await _e(Wt,_t,S,h.disallowDevSchemas);let yn={language:c,tracker:p,schemas:[...vn,...Wt],eventSpecifications:_t,validations:Gt&&h.validations,eventSpecificationsInputMetadata:Sn},b=await(0,dn.generate)(yn);if(n.stop(!0),!b)throw new J;e.success("Code generated, writing...");let wn=b.lines.join(`
|
|
135
|
+
`),U=(0,vt.resolve)((0,cn.cwd)(),d);gn.default.removeSync((0,vt.resolve)(U)),un.mkdirp.sync(U);let zt=qt+Le(c);if((0,pn.writeFileSync)((0,vt.resolve)(U,zt),wn),je(N,d),Gt&&h.validations&&b.validationsSchemaObject){let In=ke(N);an(U,c,b.validationsSchemaObject,In),sn(b.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")}h.instructions&&await tn(S,N,b.lines,U,zt)}var Nt=w(B,"generate");async function di({maximumBump:t,yes:e}){let n=await $();return A(n),n.options.commands.update={...n.options.commands.update,...typeof t<"u"&&{maximumBump:t},...typeof e<"u"&&{regenerateOnUpdate:e}},n}async function gi(t,e,n,i){let r=await di(i),{options:{commands:o}}=r;e.debug("Starting update process with options: ".concat(JSON.stringify(i)));let s=(0,ln.resolve)((0,mn.cwd)(),r.outpath,rt),a=new y({apiKey:t,organizationId:r.organizationId});n.setSpinnerTitle("Checking for updates..."),n.isSpinning()===!1&&n.start();let c={};if(!Dt(s)&&r.eventSpecificationIds.length)throw new Z;if(Dt(s)&&r.eventSpecificationIds.length){let g=$e(s);c=await ce(a,r.eventSpecificationIds,g)}let p=await se(a,r.dataStructures,o.update.maximumBump);if((Object.entries(c).length>0||p.length>0)===!0){if(e.success("Available updates found!"),Ve(c,p,e),o.update.regenerateOnUpdate===!0)return p.length>0&&(p.forEach(g=>{let h=r.dataStructures.indexOf(g.previous);r.dataStructures[h]=g.next}),ft(r)),e.debug("Applying the updates.."),B(t,e,n,o.generate);e.log("No updates applied"),e.log("To apply the available updates run update with --yes flag")}else e.success("No updates found. Everything is up-to-date!");return Promise.resolve(void 0)}var Ut=w(gi,"update");async function mi(t){if(Object.values(t).every(n=>Array.isArray(n)&&n.length===0))throw new X;let e=await $();return A(e),{patchOptions:t,generateOptions:e.options.commands.generate,regenerateOnPatch:e.options.commands.patch.regenerateOnPatch}}async function li(t,e,n,i){let{isJSON:r}=lt(process.cwd());if(r===!1)throw new Q;let{patchOptions:o,generateOptions:s,regenerateOnPatch:a}=await mi(i);return e.debug("Starting patch process with options: ".concat(JSON.stringify(o))),Object.entries(o).forEach(([p,d])=>{d.forEach(g=>{ae(p,g)})}),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 Mt=w(li,"patch");async function hn(){await import("dotenv/config");let t=new V.Command;t.exitOverride(),t.version(F,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("-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").option("-t, --tracker <string>","tracker to use").option("-l, --language <string>","language to use").option("-o, --outpath <string>","output path").action(Lt),t.command("update").description("Checks for latest version updates in Data Structures and Event Specifications.").option("-y, --yes","updates all to latest without asking").addOption(new V.Option("-m, --maximumBump <'patch' | 'minor' | 'major'>","the maximum SchemaVer update to show an available update notification. Defaults to 'major'").choices(["patch","minor","major"])).action(Ut),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(Nt),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(Mt),t.addHelpText("before",me()).addHelpText("after",`
|
|
136
|
+
`),await t.parseAsync(fn.argv).catch(e=>{fi(e)})}function fi(t){if(!(t instanceof V.CommanderError&&["commander.help","commander.version","commander.helpDisplayed"].indexOf(t.code)>-1))throw t}hn().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.8.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.8.0",
|
|
17
17
|
"chalk": "^4.1.2",
|
|
18
18
|
"cli-spinner": "^0.2.10",
|
|
19
19
|
"dotenv": "^16.3.1",
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
"js-sha256": "^0.10.1",
|
|
24
24
|
"mime-types": "^2.1.35",
|
|
25
25
|
"mkdirp": "^3.0.1",
|
|
26
|
+
"semver": "^7.6.3",
|
|
26
27
|
"tsx": "^4.9.3"
|
|
27
28
|
},
|
|
28
29
|
"devDependencies": {
|
|
@@ -46,8 +47,6 @@
|
|
|
46
47
|
"build:production": "esbuild --bundle --packages=external --platform=node --target=es2022 --outdir=dist --minify src/index.ts",
|
|
47
48
|
"build": "tsc",
|
|
48
49
|
"fix-version": "node ./scripts/version.js",
|
|
49
|
-
"format:fix": "prettier --write src",
|
|
50
|
-
"format": "prettier --check src",
|
|
51
50
|
"lint:fix": "eslint src --fix",
|
|
52
51
|
"lint": "eslint src",
|
|
53
52
|
"prebuild:production": "npm run fix-version && rimraf ./dist",
|