@dittowords/cli 5.0.0-beta.3 → 5.0.0-beta.5
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 +66 -2
- package/bin/ditto.js +63 -56
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,11 +1,75 @@
|
|
|
1
|
-
# Ditto CLI
|
|
1
|
+
# Ditto CLI v5
|
|
2
2
|
|
|
3
|
-
The Ditto CLI enables developers to access the Ditto API directly from the command line.
|
|
3
|
+
The Ditto CLI enables developers to access the Ditto API directly from the command line. The v5 version of the CLI defaults to use the new Ditto Beta by default, but still fully supports legacy configurations and projects by passing in a `--legacy` flag to all invocations.
|
|
4
4
|
|
|
5
5
|
[](https://badge.fury.io/js/@dittowords%2Fcli)
|
|
6
6
|
|
|
7
7
|
## Documentation
|
|
8
8
|
|
|
9
|
+
The official documentation can be found [here](https://dittov3.notion.site/Beta-Developer-Integrations-1d8cc8865c7a800eb13dc54d10c3d231).
|
|
10
|
+
|
|
11
|
+
## Support
|
|
12
|
+
|
|
13
|
+
- [Bug Reports](https://github.com/dittowords/cli/issues/)
|
|
14
|
+
- [Support Chat](https://www.dittowords.com)
|
|
15
|
+
- [What is Ditto?](https://www.dittowords.com/docs/what-is-ditto)
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
npm install --save-dev @dittowords/cli@beta
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
It's recommended to install the CLI as a development dependency to ensure your whole team is on the same version.
|
|
24
|
+
|
|
25
|
+
## Authentication
|
|
26
|
+
|
|
27
|
+
The first time you run the CLI, you’ll be asked to provide an API key. You can generate an API key from your [developer integrations settings](https://app.dittowords.com/account/devtools).
|
|
28
|
+
|
|
29
|
+
See the [Authentication](http://developer.dittowords.com/api-reference/authentication) page for more information on API keys.
|
|
30
|
+
|
|
31
|
+
## Configuration
|
|
32
|
+
|
|
33
|
+
By default, the CLI operates against a `ditto/` folder relative to the current working directory.
|
|
34
|
+
|
|
35
|
+
The first time you run the CLI, a `ditto/` folder will be created if it doesn't already exist. The folder will also be populated with a default `config.yml` file, which is used to control the CLI's behavior.
|
|
36
|
+
|
|
37
|
+
The default file looks like this:
|
|
38
|
+
|
|
39
|
+
```yml
|
|
40
|
+
projects: [],
|
|
41
|
+
variants: [],
|
|
42
|
+
outputs:
|
|
43
|
+
- format: json,
|
|
44
|
+
framework: i18next
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
For more information on configuring the CLI, see [this documentation section](https://dittov3.notion.site/Beta-Developer-Integrations-1d8cc8865c7a800eb13dc54d10c3d231#1d8cc8865c7a80e68ebbeb083404d8ed).
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npx @dittowords/cli
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Run the CLI to pull string data from Ditto and write it to disk.
|
|
56
|
+
|
|
57
|
+
String files are written to the `ditto` folder in a format that corresponds to your configuration. After integrating these files into development, you can execute the CLI at any time to fetch the latest strings from Ditto and update them in your application.
|
|
58
|
+
|
|
59
|
+
For more information on how files written to disk, see [this documentation section](https://dittov3.notion.site/Beta-Developer-Integrations-1d8cc8865c7a800eb13dc54d10c3d231#1d8cc8865c7a80c7bd4fe6f5f254f4d4).
|
|
60
|
+
|
|
61
|
+
See our demo projects for examples of how to integrate the Ditto CLI in different environments:
|
|
62
|
+
|
|
63
|
+
- [React web app](https://github.com/dittowords/ditto-react-demo)
|
|
64
|
+
- [iOS mobile app](https://github.com/dittowords/ditto-react-demo)
|
|
65
|
+
- [Android mobile app](https://github.com/dittowords/ditto-react-demo)
|
|
66
|
+
|
|
67
|
+
# Legacy Setup
|
|
68
|
+
|
|
69
|
+
v5 of the Ditto CLI points at the new Ditto beta experience by default. To run the CLI compatible with legacy Ditto, append the `--legacy` flag, and the CLI will work as it did in the `4.x` version. All existing legecy commands are depricated, but fully functional at this time.
|
|
70
|
+
|
|
71
|
+
## Documentation
|
|
72
|
+
|
|
9
73
|
The official documentation can be found [here](http://developer.dittowords.com/cli-reference/authentication).
|
|
10
74
|
|
|
11
75
|
## Support
|
package/bin/ditto.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";
|
|
3
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
4
|
-
var
|
|
5
|
-
`),"nl"),p={errorText:
|
|
3
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="23571d17-fe75-53c1-b0d6-409474e4a897")}catch(e){}}();
|
|
4
|
+
var Nr=Object.create;var se=Object.defineProperty;var _r=Object.getOwnPropertyDescriptor;var Mr=Object.getOwnPropertyNames;var Rr=Object.getPrototypeOf,$r=Object.prototype.hasOwnProperty;var We=t=>{throw TypeError(t)};var r=(t,e)=>se(t,"name",{value:e,configurable:!0});var Lr=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Mr(e))!$r.call(t,s)&&s!==o&&se(t,s,{get:()=>e[s],enumerable:!(n=_r(e,s))||n.enumerable});return t};var l=(t,e,o)=>(o=t!=null?Nr(Rr(t)):{},Lr(e||!t||!t.__esModule?se(o,"default",{value:t,enumerable:!0}):o,t));var He=(t,e,o)=>e.has(t)||We("Cannot "+o);var E=(t,e,o)=>(He(t,e,"read from private field"),o?o.call(t):e.get(t)),J=(t,e,o)=>e.has(t)?We("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,o),N=(t,e,o,n)=>(He(t,e,"write to private field"),n?n.call(t,o):e.set(t,o),o);var vr=l(require("@sentry/node"));var st="5.0.0-beta.5";var U=require("commander");var go=l(require("boxen")),qt=l(require("chalk"));var uo=l(require("ora"));var no=l(require("axios"));var V=l(require("fs")),Qe=l(require("path")),to=l(require("url")),at=l(require("js-yaml")),eo=l(require("@sentry/node"));var Xe=require("os"),it=l(require("path")),u=new class{get API_HOST(){return process.env.DITTO_API_HOST||"https://api.dittowords.com"}get CONFIG_FILE(){return process.env.DITTO_CONFIG_FILE||it.default.join((0,Xe.homedir)(),".config","ditto")}get PROJECT_CONFIG_FILE(){return it.default.normalize(it.default.join("ditto","config.yml"))}get TEXT_DIR(){return process.env.DITTO_TEXT_DIR||"ditto"}get TEXT_FILE(){return it.default.normalize(it.default.join(this.TEXT_DIR,"text.json"))}};function Ze(t){if(typeof t!="object")return{};let e={};for(let o in t){let n=o,s=t[n];e[n]=typeof s=="object"||Array.isArray(s)?JSON.stringify(s):s}return e}r(Ze,"createSentryContext");var Vr={sources:{components:!0},variants:!0,format:"flat"},oo=at.default.dump(Vr);function Ct(t,e){let o=Qe.default.dirname(t);V.default.existsSync(o)||V.default.mkdirSync(o),V.default.existsSync(t)||V.default.writeFileSync(t,e||"","utf-8")}r(Ct,"createFileIfMissing");function Yr(t){return typeof t=="object"}r(Yr,"jsonIsConfigYAML");function Br(t){return!!t&&typeof t=="object"&&Object.values(t).every(e=>e.every&&e.every(o=>typeof o=="object"&&Object.keys(o).includes("token")))}r(Br,"jsonIsGlobalYAML");function ie(t=u.PROJECT_CONFIG_FILE,e={}){Ct(t,oo);let o=V.default.readFileSync(t,"utf8"),n=at.default.load(o);return Yr(n)?n:e}r(ie,"readProjectConfigData");function It(t=u.CONFIG_FILE,e={}){Ct(t);let o=V.default.readFileSync(t,"utf8"),n=at.default.load(o);return Br(n)?n:e}r(It,"readGlobalConfigData");function Gr(t,e){Ct(t,oo);let o=ie(t),n={...o,...e,sources:{...o.sources,...e.sources}},s=at.default.dump(n);V.default.writeFileSync(t,s,"utf8")}r(Gr,"writeProjectConfigData");function ae(t,e){Ct(t);let o=It(t),n=at.default.dump({...o,...e});V.default.writeFileSync(t,n,"utf8")}r(ae,"writeGlobalConfigData");function Yt(t){return t.includes("://")?to.default.parse(t).hostname||"":t}r(Yt,"justTheHost");function qr(t,e){let o=It(t),n=Yt(e);o[n]=[],o[n][0]={token:""},ae(t,o)}r(qr,"deleteToken");function Ur(t,e,o){let n=It(t),s=Yt(e);n[s]=[],n[s][0]={token:o},ae(t,n)}r(Ur,"saveToken");function ro(){return process.env.DITTO_API_KEY}r(ro,"getTokenFromEnv");function zr(t,e){let o=ro();if(o)return o;let s=It(t)[Yt(e)];if(!s)return;let{length:i}=s;return s[i-1].token}r(zr,"getToken");var Ke=/-(\d+$)/;function Wr(t,e){let o=e;if(t.has(o))for(;t.has(o);){let[n,s]=o.match(Ke)||[];s&&!isNaN(parseInt(s))?o=`${o.replace(Ke,"")}-${parseInt(s)+1}`:o=`${o}-1`}return o}r(Wr,"dedupeProjectName");function Hr(t){let{sources:e,variants:o,format:n,status:s,richText:i,iosLocales:a,projects:c,components:m,disableJsDriver:y}=ie(t),f=e?.projects||[],d=new Set,S=[],x=!1;(f||[]).forEach(P=>{if(P.id&&P.name){if(P.id==="ditto_component_library"){x=!0;return}P.fileName=Wr(d,P.name),d.add(P.fileName),S.push(P)}});let C=!!e?.components,_=typeof e?.components=="object"?e.components.root:void 0,F=typeof e?.components=="object"?e.components.folders:void 0,v={hasSourceData:!!S.length||C,validProjects:S,shouldFetchComponentLibrary:C,variants:o||!1,format:n,status:s,richText:i,hasTopLevelProjectsField:!!c,hasTopLevelComponentsField:!!m,hasComponentLibraryInProjects:x,componentRoot:_,componentFolders:F,localeByVariantApiId:a?a.reduce((P,rt)=>({...P,...rt}),{}):void 0,disableJsDriver:y};return eo.setContext("config",Ze(v)),v}r(Hr,"parseSourceInformation");var w={createFileIfMissing:Ct,readProjectConfigData:ie,readGlobalConfigData:It,writeGlobalConfigData:ae,writeProjectConfigData:Gr,justTheHost:Yt,saveToken:Ur,deleteToken:qr,getToken:zr,getTokenFromEnv:ro,parseSourceInformation:Hr};function j(t){return no.default.create({baseURL:u.API_HOST,headers:{Authorization:`token ${t||w.getToken(u.CONFIG_FILE,u.API_HOST)}`,"x-ditto-cli":!0}})}r(j,"createApiClient");var G=l(require("chalk"));var Xr=r(t=>G.default.magenta(t),"errorText"),Zr=r(t=>G.default.yellow(t),"warnText"),Kr=r(t=>G.default.blueBright(t),"info"),Qr=r(t=>G.default.green(t),"success"),tn=r(t=>G.default.blueBright.underline(t),"url"),en=r(t=>G.default.grey(t),"subtle"),on=r(t=>G.default.white(t),"write"),rn=r(()=>console.log(`
|
|
5
|
+
`),"nl"),p={errorText:Xr,warnText:Zr,info:Kr,success:Qr,url:tn,subtle:en,write:on,nl:rn};var io=l(require("fs")),ao=l(require("@sentry/node")),co=l(require("chalk")),po=require("enquirer");var so=l(require("@sentry/node"));async function b(t,e=2){t&&console.log(`
|
|
6
6
|
${t}
|
|
7
|
-
`),await
|
|
8
|
-
`)}r(
|
|
9
|
-
`),w.saveToken(u.CONFIG_FILE,u.API_HOST,e),e}catch(e){if(e===""){await b("",0);return}let o=
|
|
10
|
-
|
|
11
|
-
Error ID: ${p.info(o)}`;return await b(p.errorText("Something went wrong. Please contact support or try again later.")+n)}},"collectAndSaveToken");var
|
|
12
|
-
- `+p.info(o)+" "+p.subtle(
|
|
13
|
-
`,"projectsToText"),
|
|
14
|
-
`);let n=e.map(
|
|
7
|
+
`),await so.flush(),process.exit(e)}r(b,"quit");var lo=require("axios");var ce=r((t,e=u.API_HOST)=>{if(w.getTokenFromEnv())return!1;let o=t||u.CONFIG_FILE;if(!io.default.existsSync(o))return!0;let n=w.readGlobalConfigData(o);return!n[w.justTheHost(e)]||n[w.justTheHost(e)][0].token===""},"needsToken");async function nn(t){let e=j(t),o="/token-check",n;try{n=await e.get(o)}catch(s){if(!(s instanceof lo.AxiosError))return{success:!1,output:[p.warnText("Sorry! We're having trouble reaching the Ditto API.")]};if(s.code==="ENOTFOUND")return{success:!1,output:[p.errorText(`Can't connect to API: ${p.url(u.API_HOST)}`)]};if(s.response?.status===401||s.response?.status===404)return{success:!1,output:[p.errorText("This API key isn't valid. Please try another.")]}}return typeof n=="string"?{success:!1,output:[n]}:n?.status===200?{success:!0}:{success:!1,output:[p.errorText("This API key isn't valid. Please try another.")]}}r(nn,"verifyTokenUsingTokenCheck");async function sn(t){let e=await nn(t);return e.success?!0:e.output.join(`
|
|
8
|
+
`)}r(sn,"checkToken");async function an(t){let e=p.info,o=p.url("https://app.dittowords.com/account/devtools"),n=`${co.default.bold(e("API Keys"))}`,s=t||`To get started, you'll need your Ditto API key. You can find this at: ${o} under "${n}".`;return console.log(s),(await(0,po.prompt)({type:"input",name:"token",message:"What is your API key?",validate:r(a=>sn(a),"validate")})).token}r(an,"collectToken");var ct=r(async(t=null)=>{try{let e=await an(t);return console.log(`Thanks for authenticating. We'll save the key to: ${p.info(u.CONFIG_FILE)}
|
|
9
|
+
`),w.saveToken(u.CONFIG_FILE,u.API_HOST,e),e}catch(e){if(e===""){await b("",0);return}let o=ao.captureException(e),n=`
|
|
10
|
+
|
|
11
|
+
Error ID: ${p.info(o)}`;return await b(p.errorText("Something went wrong. Please contact support or try again later.")+n)}},"collectAndSaveToken");var mo=l(require("js-yaml"));var X=r((t=u.PROJECT_CONFIG_FILE)=>w.parseSourceInformation(t).validProjects,"getSelectedProjects"),pt=r((t=u.PROJECT_CONFIG_FILE)=>w.parseSourceInformation(t).shouldFetchComponentLibrary,"getIsUsingComponents");var pe=r(t=>{let e="https://app.dittowords.com";return t==="ditto_component_library"?`${e}/components`:`${e}/doc/${t}`},"getSourceUrl"),cn=r(t=>(t||[]).reduce((e,{name:o,id:n})=>e+(`
|
|
12
|
+
- `+p.info(o)+" "+p.subtle(pe(n))),"")+`
|
|
13
|
+
`,"projectsToText"),jt=cn;var{AutoComplete:pn}=require("enquirer");function ln(t){return t.name+" "+p.subtle(t.url||pe(t.id))}r(ln,"formatProjectChoice");function mn(t){if(!t)return null;let[,e,o]=t.split(/^(.*)\s.*http.*\/(\w+).*$/);return o==="all"?{name:e,id:"ditto_component_library"}:{name:e,id:o}}r(mn,"parseResponse");var un=r(async({message:t,projects:e,limit:o=10})=>{p.write(`
|
|
14
|
+
`);let n=e.map(ln),s=new pn({name:"project",message:t,limit:o,choices:n}),i;try{i=await s.run()}catch{i=null}return mn(i)},"promptForProject"),Bt=un;function fn(t,e,o){if(o==="components"){w.writeProjectConfigData(t,{sources:{components:!0}});return}let n=[...X(t),{name:e,id:o}];w.writeProjectConfigData(t,{sources:{projects:n}})}r(fn,"saveProject");var fo=r(()=>!w.parseSourceInformation().hasSourceData,"needsSource");async function dn(){w.deleteToken(u.CONFIG_FILE,u.API_HOST),await ct("Looks like the API key you have saved no longer works. Please enter another one.")}r(dn,"askForAnotherToken");async function gn(t,e){let o=j(),n=(0,uo.default)("Fetching sources in your workspace...");n.start();let s;try{s=await o.get("/v1/projects")}catch(c){throw n.stop(),c}let i=e.reduce((c,m)=>c.add(m.id.toString()),new Set),a=s.data.filter(({id:c})=>c!=="ditto_component_library"&&!i.has(c.toString()));return n.stop(),a}r(gn,"listProjects");async function yn(t,e){let o=X(),n=pt(),s=await gn(t,o);return e&&!n&&(s=[{id:"ditto_component_library",name:"Ditto Component Library"},...s]),s?.length?Bt({projects:s,message:"Choose the source you'd like to sync text from"}):(console.log("You're currently syncing all projects in your workspace."),console.log(p.warnText("Not seeing a project that you were expecting? Verify that developer mode is enabled on that project. More info: https://www.dittowords.com/docs/ditto-developer-mode")),null)}r(yn,"collectSource");var bt=r(async({components:t=!1}={components:!1})=>{try{let e=w.getToken(u.CONFIG_FILE,u.API_HOST),o=await yn(e,t);if(!o){await b(null,0);return}console.log(`
|
|
15
15
|
Thanks for adding ${p.info(o.name)} to your selected sources.
|
|
16
16
|
We saved your updated configuration to: ${p.info(u.PROJECT_CONFIG_FILE)}
|
|
17
|
-
`),
|
|
18
|
-
`),o},"sourcesToText"),
|
|
17
|
+
`),fn(u.PROJECT_CONFIG_FILE,o.name,o.id)}catch(e){console.log(e),e.response&&e.response.status===404?(await dn(),await bt({components:t})):await b(null,2)}},"collectAndSaveSource");var hn=r((t,e)=>{let o="";return e&&(o+=`the ${p.info("Ditto Component Library")}`,(t||[]).length?o+=" and ":o+=".."),(t||[]).length&&(o+=`the following projects: ${jt(t)}
|
|
18
|
+
`),o},"sourcesToText"),Gt=hn;var yo=r(()=>ce()||fo(),"needsTokenOrSource");function xn(){let t=qt.default.white(`${qt.default.bold("Welcome to the",qt.default.magentaBright("Ditto CLI"))}.
|
|
19
19
|
|
|
20
|
-
We're glad to have you here.`);console.log((0,
|
|
20
|
+
We're glad to have you here.`);console.log((0,go.default)(t,{padding:1}))}r(xn,"welcome");var ho=r(async()=>{xn(),ce()&&await ct();let{hasSourceData:t,validProjects:e,shouldFetchComponentLibrary:o,hasTopLevelComponentsField:n,hasTopLevelProjectsField:s}=w.parseSourceInformation();if(s)return await b(`${p.errorText(`Support for ${p.warnText("projects")} as a top-level field has been removed; please configure ${p.warnText("sources.projects")} instead.`)}
|
|
21
21
|
See ${p.url("https://github.com/dittowords/cli")} for more information.`);if(n)return await b(`${p.errorText("Support for `components` as a top-level field has been removed; please configure `sources.components` instead.")}
|
|
22
|
-
See ${p.url("https://github.com/dittowords/cli")} for more information.`);if(!t){console.log(`Looks like there are no Ditto sources selected for your current directory: ${p.info(process.cwd())}.`),await
|
|
22
|
+
See ${p.url("https://github.com/dittowords/cli")} for more information.`);if(!t){console.log(`Looks like there are no Ditto sources selected for your current directory: ${p.info(process.cwd())}.`),await bt({initialize:!0,components:!0});return}let i="You're currently set up to sync text from "+Gt(e,o);console.log(i)},"init");var Z=l(require("fs")),lt=l(require("path")),Oo=l(require("ora")),Po=l(require("@sentry/node"));var le=l(require("fs")),me=l(require("path"));function q(t){let e=t.split(/\s{1,}/g);return e=e.map(o=>o.replace(/[^a-zA-Z0-9-_.]/g,"").toLowerCase()),e=e.filter(o=>o!==""),e.join("-")}r(q,"cleanFileName");var Ut=l(require("fs")),zt=l(require("path"));function xo(t=process.cwd()){let e=Tn(t);return Sn(e)}r(xo,"determineModuleType");function Tn(t){if(process.env.DITTO_MODULE_TYPE)return process.env.DITTO_MODULE_TYPE;for(;t;){let e=zt.join(t,"package.json");if(Ut.existsSync(e)){let o=Ut.readFileSync(e,"utf8");try{let n=JSON.parse(o);if(n?.type)return n.type}catch{}return null}if(t==="/")break;t=zt.dirname(t)}return null}r(Tn,"getRawTypeFromPackageJson");function Sn(t){let e=t?.toLowerCase()||"";return e==="commonjs"||e==="module"?e:"commonjs"}r(Sn,"getTypeOrDefault");var To=l(require("fs")),So=l(require("path"));function wn(t){switch(t){case"flat":return"IJSONFlat";case"nested":return"IJSONNested";case"structured":return"IJSONStructured";case"icu":return"IJSONICU";default:return"_JSON"}}r(wn,"getFormatString");function vn(t,e){return e==="commonjs"?`export = ${t};`:`export default ${t};`}r(vn,"getExportString");function Cn(t){return`
|
|
23
23
|
interface IJSONFlat {
|
|
24
24
|
[key: string]: string;
|
|
25
25
|
}
|
|
@@ -41,21 +41,21 @@ type _JSON = IJSONFlat | IJSONStructured | IJSONNested;
|
|
|
41
41
|
|
|
42
42
|
interface IDriverFile {
|
|
43
43
|
[sourceKey: string]: {
|
|
44
|
-
[variantKey: string]: ${
|
|
44
|
+
[variantKey: string]: ${wn(t.format)};
|
|
45
45
|
};
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
declare const driver: IDriverFile;
|
|
49
49
|
|
|
50
|
-
${
|
|
51
|
-
`.trim()}r(
|
|
52
|
-
`,"utf8")}r(
|
|
50
|
+
${vn("driver",t.moduleType)}
|
|
51
|
+
`.trim()}r(Cn,"getTypesString");function wo(t){let e=Cn(t);To.default.writeFileSync(So.default.resolve(u.TEXT_DIR,"index.d.ts"),e+`
|
|
52
|
+
`,"utf8")}r(wo,"generateJsDriverTypeFile");var In=r(t=>t==="ditto_component_library"?t:`project_${t}`,"stringifySourceId");function vo(t,e){let o=xo(),n=jn(t),s=bn(),i=[],a={},c={};n.forEach(f=>{var S;let d;if(f.type==="components")d=s.generate(f.fileName.split(".")[0]);else{let x=f.fileName.split(".")[0];d=s.generate(x.split("__")[0])}if(i.push(On(f.fileName,d,o)),f.type==="project"){let{variantApiId:x}=f,C=In(f.projectId);a[C]??(a[C]={}),a[C][x]=`{...${d}}`}else c[S=f.variantApiId]??(c[S]=[]),c[f.variantApiId].push(`...${d}`)}),Object.keys(c).forEach(f=>{a.ditto_component_library??(a.ditto_component_library={});let d="{";c[f].forEach((S,x)=>{d+=S,x<c[f].length-1&&(d+=", ")}),d+="}",a.ditto_component_library[f]=d});let m="";m+=i.join(`
|
|
53
53
|
`)+`
|
|
54
54
|
|
|
55
|
-
`,m+=`${
|
|
55
|
+
`,m+=`${Fn(o)}`,m+=`${JSON.stringify(a,null,2)}`.replace(/"\{/g,"{").replace(/\}"/g,"}");let y=me.default.resolve(u.TEXT_DIR,"index.js");return le.default.writeFileSync(y,m,{encoding:"utf8"}),wo({format:e,moduleType:o}),`Generated .js SDK driver at ${p.info(y)}`}r(vo,"generateJsDriver");function jn(t){let e=new Map;return t.forEach(n=>{!n.fileName||n.type==="components"||e.set(q(n.fileName),n.id)}),le.default.readdirSync(u.TEXT_DIR).filter(n=>me.default.extname(n)===".json").map(n=>{let s=n.split("__");if(s.length===3){let[,i,a]=s,[c]=a.split(".");return{type:"components",variantApiId:c,folderApiId:i,fileName:n}}if(s.length===2){let[i,a]=s,[c]=a.split("."),m=q(n.split("__")[0]);return{type:"project",projectId:e.get(m)||"",projectName:i,variantApiId:c,fileName:n}}throw new Error("Invalid JSON file generated: "+n)})}r(jn,"getFullyQualifiedJSONSources");function bn(){let t=new Set;return{generate:r(e=>{let o=e.replace(/(\W|-)/g,"_"),n=o,s=1;for(;t.has(n);)n=`${o}${s}`,s++;return t.add(n),n},"generate")}}r(bn,"createVariableNameGenerator");function Fn(t){if(t==="commonjs")return"module.exports = ";if(t==="module")return"export default ";throw new Error("Unknown module type: "+t)}r(Fn,"getExportPrefix");function On(t,e,o){if(o==="commonjs")return`const ${e} = require('./${t}');`;if(o==="module")return`import ${e} from './${t}';`;throw new Error("Unknown module type: "+o)}r(On,"getImportStatement");async function Co(t,e={}){let o=j();if(!t.variants)return null;let{shouldFetchComponentLibrary:n,validProjects:s}=t,i={params:{...e?.meta,showSampleData:e.includeSampleData}};s.length&&!n&&(i.params.projectIds=s.map(({id:c})=>c));let{data:a}=await o.get("/v1/variants",i);return a}r(Co,"fetchVariants");var Eo=require("axios");async function Wt(t={}){let e=j(),o="/v1/component-folders";t.showSampleData===!0&&(o+="?showSampleData=true");let{data:n}=await e.get(o,{});return n}r(Wt,"fetchComponentFolders");var Io=l(require("path"));async function jo(t){let e=j(),o={variants:t.variants,localeByVariantId:t.localeByVariantApiId};t.componentFolders||t.componentRoot?(o.components={},t.componentFolders&&(o.components.folders=t.componentFolders),t.componentRoot&&(o.components.root=t.componentRoot)):t.shouldFetchComponentLibrary&&(o.components=!0),t.validProjects&&(o.projects=t.validProjects);let{data:n}=await e.post("/v1/ios/swift-driver",o),s=Io.default.join(u.TEXT_DIR,"Ditto.swift");return await Ft(s,n),`Successfully saved Swift driver to ${p.info("Ditto.swift")}`}r(jo,"generateSwiftDriver");var Ht=l(require("path")),O=l(require("fs"));var Pn=/\.(strings|stringsdict)$/;async function bo(t){let e=O.default.readdirSync(u.TEXT_DIR),o={};for(let n of e){if(!Pn.test(n))continue;let[s,i]=n.split(".");if(!s.length)continue;let a=s.split("__"),c=a[0],m=a[a.length-1];if(!(c&&m))continue;let y=t&&t[m]?t[m]:m,f=`${y}.lproj`,d=Ht.default.join(u.TEXT_DIR,f);O.default.existsSync(d)||O.default.mkdirSync(d);let S=Ht.default.join(u.TEXT_DIR,n),x=Ht.default.join(d,`${c}.${i}`);En(c,i,S,x),o[f]={mappedVariant:m===y?void 0:m}}return Object.keys(o).map(n=>{let s=`Successfully generated iOS bundle ${p.info(n)}`,i=o[n].mappedVariant;return i&&(s+=` ${p.subtle(`(mapped to variant '${i}')`)}`),s}).join(`
|
|
56
56
|
`)+`
|
|
57
|
-
`}r(
|
|
58
|
-
`+o;O.default.writeFileSync(e,s),O.default.unlinkSync(t)}r(
|
|
57
|
+
`}r(bo,"generateIOSBundles");function En(t,e,o,n){if(!O.default.existsSync(n))return O.default.renameSync(o,n);if(t!=="components")throw new Error("Bundle path for "+t+" already exists");if(e==="strings")return kn(o,n);if(e==="stringsdict")return Dn(o,n);throw new Error("Unsupported extension "+e)}r(En,"handleBundleGeneration");function kn(t,e){let o=O.default.readFileSync(t,"utf-8"),s=O.default.readFileSync(e,"utf-8")+`
|
|
58
|
+
`+o;O.default.writeFileSync(e,s),O.default.unlinkSync(t)}r(kn,"appendStringsFile");function Dn(t,e){let n=O.default.readFileSync(t,"utf-8").split(`
|
|
59
59
|
`).slice(3,-4),a=`<?xml version="1.0" encoding="utf-8"?>
|
|
60
60
|
<plist version="1.0">
|
|
61
61
|
<dict>
|
|
@@ -64,57 +64,64 @@ ${[O.default.readFileSync(e,"utf-8").split(`
|
|
|
64
64
|
`)}
|
|
65
65
|
</dict>
|
|
66
66
|
</plist>
|
|
67
|
-
`;O.default.writeFileSync(e,a),O.default.unlinkSync(t)}r(
|
|
68
|
-
`),"ensureEndsWithNewLine"),
|
|
69
|
-
`}r(
|
|
70
|
-
`}r(
|
|
71
|
-
Fetching the latest text from ${
|
|
72
|
-
`;let
|
|
73
|
-
|
|
74
|
-
`,
|
|
75
|
-
|
|
76
|
-
${p.success("Done")}!`,P.stop(),console.log(
|
|
77
|
-
Choose others using the ${p.info("project")} command, or update your API key.`,console.log(
|
|
78
|
-
Please choose different projects using the ${p.info("project")} command, or turn on Developer Mode for all selected projects. Learn more here: ${p.subtle("https://www.dittowords.com/docs/ditto-developer-mode")}.`,console.log(
|
|
79
|
-
Choose others using the ${p.info("project")} command.`,console.log(
|
|
80
|
-
|
|
81
|
-
Error ID: ${p.info(a)}`;return i instanceof
|
|
82
|
-
You're currently syncing text from the ${p.info("Component Library")} and from the following projects: ${
|
|
67
|
+
`;O.default.writeFileSync(e,a),O.default.unlinkSync(t)}r(Dn,"appendStringsDictFile");var An=r(t=>t+(/[\r\n]$/.test(t)?"":`
|
|
68
|
+
`),"ensureEndsWithNewLine"),Ft=r((t,e)=>new Promise(o=>Z.default.writeFile(t,An(e),o)),"writeFile"),Nn=["flat","nested","structured","android","ios-strings","ios-stringsdict","icu"],_n=["ios-strings","ios-stringsdict"],ko=["flat","nested","structured","icu"],Mn=r(t=>{let e=t.filter(o=>ko.includes(o));return e[e.length-1]||"flat"},"getJsonFormat"),Rn={flat:".json",nested:".json",structured:".json",android:".xml","ios-strings":".strings","ios-stringsdict":".stringsdict",icu:".json"},Xt=r(t=>{try{return Object.keys(JSON.parse(t)).some(e=>!e.startsWith("__variant"))}catch{return!1}},"getJsonFormatIsValid"),ue={flat:Xt,nested:Xt,structured:Xt,icu:Xt,android:r(t=>t.includes("<string"),"android"),"ios-strings":r(t=>t.includes('" = "'),"ios-strings"),"ios-stringsdict":r(t=>t.includes("<key>"),"ios-stringsdict")},$n=r(t=>{let e=(Array.isArray(t)?t:[t]).filter(o=>Nn.includes(o));return e.length?e:["flat"]},"getFormat"),fe=r(t=>Rn[t],"getFormatExtension"),Ln=["projects","exported_at"],Jn=r(t=>{let e=Object.keys(t).filter(n=>!Ln.includes(n)).length>0,o=t.projects&&Object.keys(t.projects).length>0;return e||o},"hasVariantData");async function Vn(){w.deleteToken(u.CONFIG_FILE,u.API_HOST),await ct("Looks like the API key you have saved no longer works. Please enter another one.")}r(Vn,"askForAnotherToken");async function Fo(t,e){let{projects:o,format:n,status:s,richText:i,token:a}=e,c=j(),m={variant:t};return n&&(m.format=n),i&&(m.includeRichText=i.toString()),s&&(m.status=s),(await Promise.all(o.map(async f=>{let d={...m};f.status&&(d.status=f.status),f.exclude_components&&(d.exclude_components=String(f.exclude_components));let{data:S}=await c.get(`/v1/projects/${f.id}`,{params:d,headers:{Authorization:`token ${a}`}});if(!Jn(S))return"";let x=fe(n),C=q(f.fileName+("__"+(t||"base"))+x),_=lt.default.join(u.TEXT_DIR,C),F=S;x===".json"&&(F=JSON.stringify(S,null,2));let M=ue[n];return M(F)?(await Ft(_,F),de(C)):""}))).join("")}r(Fo,"downloadAndSaveVariant");async function Yn(t){return(await Promise.all([Fo(null,t),...t.variants.map(({apiID:o})=>Fo(o,t))])).join("")}r(Yn,"downloadAndSaveVariants");async function Bn(t){let{projects:e,format:o,status:n,richText:s,token:i,options:a}=t,c=j(),m={...a?.meta};return o&&(m.format=o),s&&(m.includeRichText=s.toString()),n&&(m.status=n),(await Promise.all(e.map(async f=>{let d={...m};f.status&&(d.status=f.status),f.exclude_components&&(d.exclude_components=String(f.exclude_components));let{data:S}=await c.get(`/v1/projects/${f.id}`,{params:d,headers:{Authorization:`token ${i}`}}),x=fe(o),C=q(`${f.fileName}__base${x}`),_=lt.default.join(u.TEXT_DIR,C),F=S;x===".json"&&(F=JSON.stringify(S,null,2));let M=ue[o];return M(F)?(await Ft(_,F),de(C)):""}))).join("")}r(Bn,"downloadAndSaveBase");function de(t){return`Successfully saved to ${p.info(t)}
|
|
69
|
+
`}r(de,"getSavedMessage");function Gn(){return Z.default.existsSync(u.TEXT_DIR)||Z.default.mkdirSync(u.TEXT_DIR),Z.default.readdirSync(u.TEXT_DIR,{withFileTypes:!0}).forEach(e=>{if(e.isDirectory()&&/\.lproj$/.test(e.name))return Z.default.rmSync(lt.default.resolve(u.TEXT_DIR,e.name),{recursive:!0,force:!0});if(e.isFile()&&/\.js(on)?|\.ts|\.xml|\.strings(dict)?$|\.swift$/.test(e.name))return Z.default.unlinkSync(lt.default.resolve(u.TEXT_DIR,e.name))}),`Cleaning old output files..
|
|
70
|
+
`}r(Gn,"cleanOutputFiles");async function qn(t,e,o){let n=j(),{validProjects:s,format:i,shouldFetchComponentLibrary:a,status:c,richText:m,componentFolders:y,componentRoot:f,localeByVariantApiId:d,disableJsDriver:S}=t,x=$n(i),C=x.some(I=>ko.includes(I)),F=x.some(I=>_n.includes(I))&&d,M=!F,v="",P=(0,Oo.default)(v);P.start();let[rt,Cr]=await Promise.all([Co(t,o),Wt({})]),Be=Object.entries(Cr).reduce((I,[A,$])=>I.concat([{id:A,name:$}]),[]);try{v+=Gn(),v+=`
|
|
71
|
+
Fetching the latest text from ${Gt(s,a)}
|
|
72
|
+
`;let I=o?o.meta:{},A={id:"__root__",name:"Root",status:typeof t.componentRoot=="object"?t.componentRoot.status:void 0},$=[];if(y)switch(f){case void 0:case!1:$.push(...y);break;default:$.push(...y),$.push(A);break}else switch(f){case void 0:$.push(...Be),$.push(A);break;case!1:$.push(...Be);break;default:$.push(A);break}let Ge=[];async function Ir(R){let wt=[{apiID:void 0},...rt||[]],vt=new URLSearchParams;o?.meta&&Object.entries(o.meta).forEach(([nt,H])=>vt.append(nt,H)),R&&vt.append("format",R),m&&vt.append("includeRichText",m.toString()),c&&vt.append("status",c);let qe=[];wt.forEach(({apiID:nt})=>{qe.push(...$.map(async H=>{let oe=new URLSearchParams(vt);nt&&oe.append("variant",nt),H.status&&oe.append("status",H.status);let Or=H.id==="__root__"?"/v1/components?root_only=true":`/v1/component-folders/${H.id}/components`,{data:Ue}=await n.get(Or,{params:oe}),ze=fe(R),Pr="components",Er=`__${q(H.name)}`,kr=`__${nt||"base"}`,re=q(`${Pr}${Er}${kr}${ze}`),Dr=lt.default.join(u.TEXT_DIR,re),ne=Ue;ze===".json"&&(ne=JSON.stringify(Ue,null,2));let Ar=ue[R];return Ar(ne)?(await Ft(Dr,ne),Ge.push({type:"components",id:"ditto_component_library",name:"ditto_component_library",fileName:re,variant:nt||"base"}),de(re)):""}))});let Fr=await Promise.all(qe);M&&(v+=Fr.join(""))}if(r(Ir,"fetchComponentLibrary"),a)for(let R of x)await Ir(R);async function jr(R){let wt="";rt?wt=await Yn({variants:rt,projects:s,format:R,status:c,richText:m,token:e}):wt=await Bn({projects:s,format:R,status:c,richText:m,token:e,options:{meta:I}}),M&&(v+=wt)}if(r(jr,"fetchProjects"),s.length)for(let R of x)await jr(R);let br=[...s,...Ge];return C&&!S&&(v+=vo(br,Mn(x))),F&&(v+=`iOS locale information detected, generating bundles..
|
|
73
|
+
|
|
74
|
+
`,v+=await bo(d),v+=await jo(t)),v+=`
|
|
75
|
+
|
|
76
|
+
${p.success("Done")}!`,P.stop(),console.log(v)}catch(I){console.error(I),P.stop();let A=I.message;if(I.response&&I.response.status===404){await Vn(),ge();return}return I.response&&I.response.status===401?(A="You don't have access to the selected projects",v=`${p.errorText(A)}.
|
|
77
|
+
Choose others using the ${p.info("project")} command, or update your API key.`,console.log(v)):I.response&&I.response.status===403?(A="One or more of the requested projects don't have Developer Mode enabled",v=`${p.errorText(A)}.
|
|
78
|
+
Please choose different projects using the ${p.info("project")} command, or turn on Developer Mode for all selected projects. Learn more here: ${p.subtle("https://www.dittowords.com/docs/ditto-developer-mode")}.`,console.log(v)):(I.response&&I.response.status===400&&(A="projects not found"),v=`We hit an error fetching text from the projects: ${p.errorText(A)}.
|
|
79
|
+
Choose others using the ${p.info("project")} command.`,console.log(v))}}r(qn,"downloadAndSave");var ge=r(async t=>{let e=t?t.meta:{},o=t?.includeSampleData||!1,n=w.getToken(u.CONFIG_FILE,u.API_HOST),s=w.parseSourceInformation();try{return await qn(s,n,{meta:e,includeSampleData:o})}catch(i){let a=Po.captureException(i),c=`
|
|
80
|
+
|
|
81
|
+
Error ID: ${p.info(a)}`;return i instanceof Eo.AxiosError?await b(p.errorText("Something went wrong connecting to Ditto servers. Please contact support or try again later.")+c):await b(p.errorText("Something went wrong. Please contact support or try again later.")+c)}},"pull");var Un=r(async()=>{let t=X(),e=pt();try{e?t.length?console.log(`
|
|
82
|
+
You're currently syncing text from the ${p.info("Component Library")} and from the following projects: ${jt(t)}`):console.log(`
|
|
83
83
|
You're currently only syncing text from the ${p.info("Component Library")}`):t.length&&console.log(`
|
|
84
|
-
You're currently set up to sync text from the following projects: ${
|
|
85
|
-
Sorry, there was an error adding a project to your workspace: `,o),await b("Project selection was not updated.")}},"addProject"),
|
|
84
|
+
You're currently set up to sync text from the following projects: ${jt(t)}`),await bt({components:!1})}catch(o){console.log(`
|
|
85
|
+
Sorry, there was an error adding a project to your workspace: `,o),await b("Project selection was not updated.")}},"addProject"),Do=Un;async function zn(){let t=X(),e=pt();if(!t.length&&!e){console.log(`
|
|
86
86
|
No projects found in your current configuration.
|
|
87
87
|
Try adding one with: ${p.info("ditto-cli project add")}
|
|
88
|
-
`);return}let o=await
|
|
88
|
+
`);return}let o=await Bt({projects:t,message:"Select a project to remove"});o&&(w.writeProjectConfigData(u.PROJECT_CONFIG_FILE,{components:e&&o.id!=="components",projects:t.filter(({id:n})=>n!==o.id)}),console.log(`
|
|
89
89
|
${p.info(o.name)} has been removed from your selected projects.
|
|
90
90
|
We saved your updated configuration to: ${p.info(u.PROJECT_CONFIG_FILE)}
|
|
91
|
-
`))}r(
|
|
92
|
-
`);if(!m.node.loc)continue;let _=m.node.loc.start.line+
|
|
93
|
-
`)[_-1],
|
|
94
|
-
`),"ensureEndsWithNewLine");var
|
|
91
|
+
`))}r(zn,"removeProject");var Ao=zn;var Ot=l(require("fs")),No=require("@babel/parser"),_o=l(require("@babel/traverse")),k=l(require("@babel/types")),Mo=require("@babel/core");async function Wn(t,e,o){let n=await new Promise((a,c)=>Ot.default.readFile(t,"utf-8",(m,y)=>{m?c(m):a(y)})),s=(0,No.parse)(n,{sourceType:"module",plugins:["jsx","typescript"]});(0,_o.default)(s,{JSXText(a){let{searchString:c,replaceWith:m}=e,y=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(y,"gi").test(a.node.value)){if(o.lineNumbers&&a.node.loc&&!o.lineNumbers.includes(a.node.loc.start.line))return;let d=Hn(a.node.value,y),S=[];d.forEach(x=>{if(x.toLowerCase()===c.toLowerCase()){let C=k.jsxIdentifier("DittoComponent"),_=k.jsxAttribute(k.jsxIdentifier("componentId"),k.stringLiteral(m)),F=k.jsxOpeningElement(C,[_],!0),M=k.jsxElement(F,void 0,[],!0);S.push(M)}else S.push(k.jsxText(x))}),a.replaceWithMultiple(S)}}});let{code:i}=(0,Mo.transformFromAst)(s,n,{configFile:!1});await new Promise((a,c)=>Ot.default.writeFile(t,i,m=>{m?c(m):a(null)}))}r(Wn,"replaceJSXTextInFile");function Hn(t,e){return t.split(new RegExp(`(${e})`,"gi")).filter(o=>o!=="")}r(Hn,"splitByCaseInsensitive");function Ro(t,e){let o,n,s;try{let i=Xn(t);o=i.filePath,n=i.searchString,s=i.replaceWith}catch(i){console.error(i),console.error("Usage for replace: ditto-cli replace <file path> <search string> <replace with>");return}Wn(o,{searchString:n,replaceWith:s},e)}r(Ro,"replace");function Xn(t){if(t.length!==3)throw new Error("The options array must contain <file path> <search string> <replace with>.");let e=t[0];if(!(Ot.default.existsSync(e)&&Ot.default.lstatSync(e).isFile()))throw new Error(`${e} is not a valid file path.`);return{filePath:e,searchString:t[1],replaceWith:t[2]}}r(Xn,"parseOptions");var Lo=l(require("fs")),Jo=l(require("glob")),Vo=require("@babel/parser"),Yo=l(require("@babel/traverse"));async function $o(t={}){let e=j();if(t.componentFolder)try{let{data:o}=await e.get(`/v1/component-folders/${t.componentFolder}/components`,{});return o}catch{return console.log(`Failed to get components for ${t.componentFolder}. Please verify the folder's API ID.`),{}}else{let{data:o}=await e.get("/v1/components?format=structured",{});return o}}r($o,"fetchComponents");async function Bo(t){let e=await $o({...t.componentFolder?{componentFolder:t.componentFolder}:{}}),o=t.directory||".",n=await Zn({directory:o,files:t.files,components:e});console.log(JSON.stringify(n,null,2))}r(Bo,"generateSuggestions");async function Zn(t){let e={},o=t.files||Jo.default.sync(`${t.directory}/**/*.+(jsx|tsx)`,{ignore:"**/node_modules/**"}),n=[];async function s(i){let a=await new Promise((m,y)=>Lo.default.readFile(i,"utf-8",(f,d)=>{f?y(f):m(d)})),c=(0,Vo.parse)(a,{sourceType:"module",plugins:["jsx","typescript"]});(0,Yo.default)(c,{JSXText(m){for(let[y,f]of Object.entries(t.components)){if(e[y]||(e[y]={apiId:y,...f,occurrences:{}}),!/^\s*$/.test(m.node.value)&&!/^\s*$/.test(f.text)&&m.node.value.includes(f.text)){let d=f.text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),S=new RegExp(d,"g"),x;for(;(x=S.exec(m.node.value))!==null;){let C=m.node.value.slice(0,x.index).split(`
|
|
92
|
+
`);if(!m.node.loc)continue;let _=m.node.loc.start.line+C.length-1,M=a.split(`
|
|
93
|
+
`)[_-1],v=Kn(M,x.index,f.text,`${f.text}`);e[y].occurrences[i]||(e[y].occurrences[i]=[]),e[y].occurrences[i].push({lineNumber:_,preview:v})}}Object.keys(e[y].occurrences).length===0&&delete e[y]}}})}r(s,"handleFile");for(let i of o)n.push(s(i));return await Promise.all(n),e}r(Zn,"findComponentsInJSXFiles");function Kn(t,e,o,n){return t.substring(0,e)+t.substring(e,t.length).replace(o,n)}r(Kn,"replaceAt");var Qn=r(t=>{let e={};return Array.isArray(t)&&t.forEach(o=>{let[n,s]=o.split(":");e[n]=s}),e},"processMetaOption"),Go=Qn;var qo=l(require("form-data")),ye=l(require("fs"));async function Uo(t,e){let o=j();if(!ye.default.existsSync(t))return console.error("Failed to import file: couldn't find file at path "+t),{componentsInserted:0,firstImportedId:"null"};let n=new qo.default;n.append("import",ye.default.createReadStream(t));let s={method:"POST",url:"/v1/components/file",params:{...e.csvColumnMapping?.name?{name:`[${e.csvColumnMapping.name}]`}:{},...e.csvColumnMapping?.text?{text:e.csvColumnMapping.text}:{},...e.csvColumnMapping?.notes?{notes:e.csvColumnMapping.notes}:{},...e.csvColumnMapping?.status?{status:e.csvColumnMapping.status}:{},...e.csvColumnMapping?.tags?{tags:e.csvColumnMapping.tags}:{},...e.csvColumnMapping?.componentId?{componentId:e.csvColumnMapping.componentId}:{}},headers:{"content-type":"multipart/form-data"},data:n};try{let{data:i}=await o(s);return i}catch(i){return console.error("Failed to import file."),console.error(i.response?.data?.message||i.message),{componentsInserted:0,firstImportedId:"null"}}}r(Uo,"importComponents");async function zo(t,e){if(t.endsWith(".csv")&&(!e.csvColumnMapping?.name||!e.csvColumnMapping?.text))throw new Error(".csv files require the --component-name and --text flags.");let o=await Uo(t,e);console.log(JSON.stringify(o))}r(zo,"importComponents");async function Wo(t){let e=await Wt(t);console.log(JSON.stringify(e))}r(Wo,"showComponentFolders");var ts=["pull","none","project","project add","project remove"],es=[{name:"pull",description:"Sync copy from Ditto into the current working directory",flags:{"--sample-data":{description:"Include sample data. Currently only supports variants."}}},{name:"project",description:"Add a Ditto project to sync copy from",commands:[{name:"add",description:"Add a Ditto project to sync copy from"},{name:"remove",description:"Stop syncing copy from a Ditto project"}]},{name:"component-folders",description:"List component folders in your workspace. More information about component folders can be found here: https://www.dittowords.com/docs/component-folders.",flags:{"-s, --sample-data":{description:"Includes the sample components folder in the output"}}},{name:"generate-suggestions",description:"Find text that can be potentially replaced with Ditto text",flags:{"-d, --directory [value]":{description:"Directory to search for text"},"-f, --files [value]":{description:"Files to search for text (will override -d)",processor:r(t=>t.split(","),"processor")},"-cf, --component-folder [value]":{description:"Component folder to search for matches"}}},{name:"replace",description:"Find and replace Ditto text with code",flags:{"-ln, --line-numbers [value]":{description:"Only replace text on a specific line number",processor:r(t=>t.split(",").map(Number),"processor")}}},{name:"import-components",description:"Import components via a file. For more information please see: https://www.dittowords.com/docs/importing-string-files.",flags:{"-t, --text [value]":{description:"Text column index (.csv format only)"},"-n, --component-name [value]":{description:"Name column indexes (comma separated) (.csv format only)"},"-no, --notes [value]":{description:"Notes column index (.csv format only)"},"-t, --tags [value]":{description:"Tags column index (.csv format only)"},"-s, --status [value]":{description:"Status column index (.csv format only)"},"-c, --component-id [value]":{description:"Component ID column index (.csv format only)"}}}],os=r(()=>{U.program.name("ditto-cli"),es.forEach(t=>{let e=U.program.command(t.name).description(t.description).action(o=>he(t.name,o));t.flags&&Object.entries(t.flags).forEach(([o,{description:n,processor:s}])=>{s?e.option(o,n,s):e.option(o,n)}),"commands"in t&&t.commands&&t.commands.forEach(o=>{e.command(o.name).description(o.description).action((n,s)=>{if(t.name==="project"){let i=`${t.name} ${o.name}`;return he(i,s)}})})})},"setupCommands"),rs=r(()=>{U.program.option("-l, --legacy","Run in legacy mode"),U.program.option("-m, --meta <data...>","Include arbitrary data in requests to the Ditto API. Ex: -m githubActionRequest:true trigger:manual"),U.program.version(st,"-v, --version","Output the current version")},"setupOptions"),he=r(async(t,e)=>{let o=ts.includes(t)&&yo();if(o)try{await ho()}catch{await b("Exiting Ditto CLI...");return}let{meta:n}=U.program.opts();switch(t){case"none":case"pull":return ge({meta:Go(n),includeSampleData:e.sampleData||!1});case"project":case"project add":return o?void 0:Do();case"project remove":return Ao();case"component-folders":return Wo({showSampleData:e.sampleData});case"generate-suggestions":return Bo({directory:e.directory,files:e.files,componentFolder:e.componentFolder});case"replace":return Ro(e.args,{...e?.lineNumbers?{lineNumbers:e.lineNumbers}:{}});case"import-components":{if(e.args.length===0){console.info("Please provide a file path.");return}return zo(e.args[0],{csvColumnMapping:{name:e.componentName,text:e.text,notes:e.notes,tags:e.tags,status:e.status,componentId:e.componentId}})}default:{await b("Exiting Ditto CLI...");return}}},"executeCommand"),ns=r(async()=>{if(os(),rs(),process.argv.length<=2&&process.argv[1].includes("ditto-cli")){await he("none",[]);return}U.program.parse(process.argv)},"legacyAppEntry"),Ho=ns;var Sr=l(require("@sentry/node")),St=require("commander");var sr=require("os"),ut=l(require("path")),ir=l(require("crypto"));var or=require("zod"),rr=l(require("fs"));var mt=l(require("path")),z=l(require("fs")),xe=l(require("fs/promises"));function Pt(t,e=""){let o=mt.default.dirname(t);return z.default.existsSync(o)||z.default.mkdirSync(o),z.default.existsSync(t)?!1:(ss(t,e),!0)}r(Pt,"createFileIfMissingSync");function ss(t,e){z.default.existsSync(mt.default.dirname(t))||z.default.mkdirSync(mt.default.dirname(t),{recursive:!0}),z.default.writeFileSync(t,e,"utf-8")}r(ss,"writeFileSync");async function Xo(t,e){z.default.existsSync(mt.default.dirname(t))||await xe.default.mkdir(mt.default.dirname(t),{recursive:!0}),await xe.default.writeFile(t,e,"utf-8")}r(Xo,"writeFile");var Zo=r(t=>t+(/[\r\n]$/.test(t)?"":`
|
|
94
|
+
`),"ensureEndsWithNewLine");var ve=l(require("js-yaml"));var Y=require("zod"),Zt=Y.z.object({projects:Y.z.array(Y.z.object({id:Y.z.string()})).optional(),variants:Y.z.array(Y.z.object({id:Y.z.string()})).optional(),outDir:Y.z.string().optional()});var Qo=require("zod");var L=require("zod");var Te=Zt.extend({format:L.z.literal("json"),framework:L.z.undefined()}).strict(),is=Te.extend({framework:L.z.literal("i18next"),type:L.z.literal("module").or(L.z.literal("commonjs")).optional()}).strict(),as=Te.extend({framework:L.z.literal("vue-i18n"),type:L.z.literal("module").or(L.z.literal("commonjs")).optional()}).strict(),Ko=L.z.discriminatedUnion("framework",[Te,is,as]);var tr=Qo.z.union([...Ko.options]);var we=class we extends Error{constructor({type:e,message:o,exitCode:n,data:s}){let i=o||"Something went wrong. Please contact support or try again later.";super(i),this.exitCode=n,this.type=e,this.data=s}};r(we,"DittoError");var K=we;function er(t){return t instanceof K}r(er,"isDittoError");function Se(t,e){return t.type===e}r(Se,"isDittoErrorType");var ps=Zt.extend({outputs:or.z.array(tr)}).strict(),Ce={projects:[],variants:[],outputs:[{format:"json",framework:"i18next"}]};async function nr(t){let e=ls(t.config);h.setProjectConfig(e)}r(nr,"initProjectConfig");function ls(t=h.projectConfigFile,e=Ce){let o=e;try{Pt(t,ve.default.dump(e));let s=rr.default.readFileSync(t,"utf8");o=ve.default.load(s)}catch(s){throw new K({type:"ConfigYamlLoadError",data:{rawErrorMessage:s.message},message:"Could not load the project config file. Please check the file path and that it is a valid YAML file."})}let n=ps.safeParse(o);if(!n.success)throw new K({type:"ConfigParseError",data:{formattedError:JSON.stringify(n.error.flatten(),null,2),messagePrefix:"There is an error in your project config file."}});return n.data}r(ls,"readProjectConfigData");var ft,W,Et,kt,dt,Dt,Q,At,je=class je{constructor(){J(this,ft);J(this,W);J(this,Et);J(this,kt);J(this,dt);J(this,Dt);J(this,Q);J(this,At);N(this,ft,process.env.DITTO_API_HOST||"https://api.dittowords.com"),N(this,W,process.env.DITTO_TOKEN),N(this,Et,process.env.DITTO_CONFIG_FILE||ut.default.join((0,sr.homedir)(),".config","ditto")),N(this,dt,process.env.DITTO_PROJECT_CONFIG_FILE||ut.default.normalize(ut.default.join("ditto","config.yml"))),N(this,kt,ut.default.normalize(ut.default.dirname(E(this,dt)))),N(this,Dt,ir.default.randomUUID()),N(this,Q,Ce),N(this,At,process.env.DITTO_OUT_DIR||this.projectConfigDir)}get apiHost(){return E(this,ft)}set apiHost(e){N(this,ft,e)}get apiToken(){return E(this,W)}get apiTokenOrThrow(){if(!E(this,W))throw new Error("No API Token found.");return E(this,W)}get configFile(){return E(this,Et)}get projectConfigFile(){return E(this,dt)}get clientId(){return E(this,Dt)}setApiToken(e){N(this,W,e)}get projectConfig(){return E(this,Q)}setProjectConfig(e){N(this,Q,e)}get selectedProjectConfigOutputs(){return E(this,Q).outputs}get projectConfigDir(){return E(this,kt)}get outDir(){return this.projectConfig.outDir||E(this,At)}};ft=new WeakMap,W=new WeakMap,Et=new WeakMap,kt=new WeakMap,dt=new WeakMap,Dt=new WeakMap,Q=new WeakMap,At=new WeakMap,r(je,"AppContext");var Ie=je,ms=new Ie,h=ms;var ar=l(require("axios"));function be(t){return function(e){return e.baseURL=h.apiHost,e.headers["x-ditto-client-id"]=h.clientId,e.headers["x-ditto-app"]="cli",e.headers.Authorization=t||h.apiToken,e}}r(be,"defaultInterceptor");var cr=ar.default.create({});cr.interceptors.request.use(be());var Kt=cr;var pr=require("axios"),D=require("zod");var us=D.z.array(D.z.object({id:D.z.string(),text:D.z.string(),status:D.z.string(),notes:D.z.string(),tags:D.z.array(D.z.string()),variableIds:D.z.array(D.z.string()),projectId:D.z.string(),variantId:D.z.string().nullable()}));async function Fe(t){try{let e=await Kt.get("/v2/textItems",{params:{filter:JSON.stringify(t)}});return us.parse(e.data)}catch(e){throw e instanceof pr.AxiosError?e.response?.status===400?new Error("Invalid filters. Please check your filters and try again."):e:new Error("Sorry! We're having trouble reaching the Ditto API. Please try again later.")}}r(Fe,"fetchText");var lr=require("axios"),g=require("zod");var Nt=g.z.object({id:g.z.string(),name:g.z.string()}),fs=Nt.merge(g.z.object({type:g.z.literal("number"),data:g.z.object({example:g.z.union([g.z.number(),g.z.string()]),fallback:g.z.union([g.z.number(),g.z.string()]).optional()})})),ds=Nt.merge(g.z.object({type:g.z.literal("string"),data:g.z.object({example:g.z.string(),fallback:g.z.string().optional()})})),gs=Nt.merge(g.z.object({type:g.z.literal("hyperlink"),data:g.z.object({text:g.z.string(),url:g.z.string()})})),ys=Nt.merge(g.z.object({type:g.z.literal("list"),data:g.z.array(g.z.string())})),hs=Nt.merge(g.z.object({type:g.z.literal("map"),data:g.z.record(g.z.string())})),xs=g.z.discriminatedUnion("type",[ds,fs,gs,ys,hs]),Ts=g.z.array(xs);async function Oe(){try{let t=await Kt.get("/v2/variables");return Ts.parse(t.data)}catch(t){throw t instanceof lr.AxiosError?t:new Error("Sorry! We're having trouble reaching the Ditto API. Please try again later.")}}r(Oe,"fetchVariables");var B=l(require("chalk"));var Ss=r(t=>B.default.magenta(t),"errorText"),ws=r(t=>B.default.yellow(t),"warnText"),vs=r(t=>B.default.blueBright(t),"info"),Cs=r(t=>B.default.green(t),"success"),Is=r(t=>B.default.blueBright.underline(t),"url"),js=r(t=>B.default.grey(t),"subtle"),bs=r(t=>B.default.white(t),"write"),Fs=r(t=>B.default.bold(t),"bold"),Os=r(t=>console.log(t),"writeLine"),T={errorText:Ss,warnText:ws,info:vs,success:Cs,url:Is,subtle:js,write:bs,writeLine:Os,bold:Fs};var Pe=class Pe{constructor(e,o){this.output=e,this.projectConfig=o,this.outDir=e.outDir??h.outDir}async fetchAPIData(){return{}}async transformAPIData(e){return[]}async format(){let e=await this.fetchAPIData(),o=await this.transformAPIData(e);await this.writeFiles(o)}async writeFiles(e){await Promise.all(e.map(o=>Xo(o.fullPath,o.formattedContent).then(()=>{T.writeLine(`Successfully saved to ${T.info(o.fullPath)}`)})))}};r(Pe,"BaseFormatter");var _t=Pe;var Ee=class Ee{constructor(e){this.filename=e.filename,this.path=e.path,this.extension=e.extension,this.content=e.content,this.metadata=e.metadata??{}}get fullPath(){return`${this.path}/${this.filename}.${this.extension}`}get filenameWithExtension(){return`${this.filename}.${this.extension}`}get formattedContent(){throw new Error("Not implemented")}};r(Ee,"OutputFile");var tt=Ee;var ke=class ke extends tt{constructor(e){super({filename:e.filename,path:e.path,extension:"json",content:e.content??{},metadata:e.metadata??{}})}get formattedContent(){return JSON.stringify(this.content,null,2)}};r(ke,"JSONOutputFile");var gt=ke;function yt(t,...e){if(e.length>5)throw new Error("Maximum of 5 mixins supported");return e.reduce((o,n)=>n(o),t)}r(yt,"applyMixins");var De=class De extends tt{constructor(o){super({filename:o.filename,path:o.path,extension:"js",content:o.content??"",metadata:o.metadata??{}});this.indentSpaces=2}get formattedContent(){return Zo(this.content??"")}};r(De,"JavascriptOutputFile");var et=De;function Mt(t){var e;return e=class extends t{constructor(){super(...arguments);this.indentSpaces=2}sanitizeStringForJSVariableName(s){return s.replace(/[^a-zA-Z0-9]/g,"_")}formatNamedModules(s){return s.map(i=>i.alias?`${i.name} as ${i.alias}`:i.name).sort().join(", ")}codegenNamedImport(s,i){return`import { ${this.formatNamedModules(s)} } from "${i}";
|
|
95
95
|
`}codegenNamedRequire(s,i){return`const { ${this.formatNamedModules(s)} } = require("${i}");
|
|
96
96
|
`}codegenDefaultImport(s,i){return`import ${s} from "${i}";
|
|
97
97
|
`}codegenDefaultRequire(s,i){return`const ${s} = require("${i}");
|
|
98
|
-
`}codegenDefaultExport(s){return`export default ${s};`}codegenCommonJSModuleExports(s){return`module.exports = ${s};`}codegenPad(s){return" ".repeat(s*this.indentSpaces)}},r(e,"JavascriptCodegenHelpers"),e}r(
|
|
98
|
+
`}codegenDefaultExport(s){return`export default ${s};`}codegenCommonJSModuleExports(s){return`module.exports = ${s};`}codegenPad(s){return" ".repeat(s*this.indentSpaces)}},r(e,"JavascriptCodegenHelpers"),e}r(Mt,"javascriptCodegenMixin");var Ae=class Ae{constructor(e){this.output=e,this.outDir=e.outDir??h.outDir}get framework(){return this.output.framework}process(...e){throw new Error("Not implemented")}};r(Ae,"BaseFramework");var ot=Ae;var Ne=class Ne extends yt(ot,Mt){process(e){let o="commonjs";"type"in this.output&&this.output.type&&(o=this.output.type);let n=new et({filename:"index",path:this.outDir}),s=Object.values(e).reduce((i,a)=>{let c=a.metadata.variantId;return i[c]??(i[c]=[]),i[c].push(a),i},{});return o==="module"?(n.content+=this.generateImportStatements(e),n.content+=`
|
|
99
99
|
`,n.content+=this.codegenDefaultExport(this.generateExportedObjectString(s))):(n.content+=this.generateRequireStatements(e),n.content+=`
|
|
100
100
|
`,n.content+=this.codegenCommonJSModuleExports(this.generateExportedObjectString(s))),[n]}generateImportStatements(e){let o="";for(let n of Object.values(e))o+=this.codegenDefaultImport(this.sanitizeStringForJSVariableName(n.filename),`./${n.filenameWithExtension}`);return o}generateRequireStatements(e){let o="";for(let n of Object.values(e))o+=this.codegenDefaultRequire(this.sanitizeStringForJSVariableName(n.filename),`./${n.filenameWithExtension}`);return o}generateExportedObjectString(e){let o=Object.keys(e),n=`{
|
|
101
101
|
`;for(let s=0;s<o.length;s++){let i=o[s],a=e[i];n+=`${this.codegenPad(1)}"${i}": {
|
|
102
102
|
`;for(let c of a)n+=`${this.codegenPad(2)}...${this.sanitizeStringForJSVariableName(c.filename)},
|
|
103
103
|
`;n+=`${this.codegenPad(1)}}${s<o.length-1?`,
|
|
104
104
|
`:`
|
|
105
|
-
`}`}return n+="}",n}};r(
|
|
105
|
+
`}`}return n+="}",n}};r(Ne,"I18NextFramework");var Rt=Ne;var _e=class _e extends yt(ot,Mt){process(e){for(let i of Object.values(e))for(let a in i.content){let c=i.content[a];typeof c=="string"&&(i.content[a]=c.replaceAll(/{{/g,"{").replaceAll(/}}/g,"}"))}let o="commonjs";"type"in this.output&&this.output.type&&(o=this.output.type);let n=new et({filename:"index",path:this.outDir}),s=Object.values(e).reduce((i,a)=>{let c=a.metadata.variantId;return i[c]??(i[c]=[]),i[c].push(a),i},{});return o==="module"?(n.content+=this.generateImportStatements(e),n.content+=`
|
|
106
|
+
`,n.content+=this.codegenDefaultExport(this.generateExportedObjectString(s))):(n.content+=this.generateRequireStatements(e),n.content+=`
|
|
107
|
+
`,n.content+=this.codegenCommonJSModuleExports(this.generateExportedObjectString(s))),[n]}generateImportStatements(e){let o="";for(let n of Object.values(e))o+=this.codegenDefaultImport(this.sanitizeStringForJSVariableName(n.filename),`./${n.filenameWithExtension}`);return o}generateRequireStatements(e){let o="";for(let n of Object.values(e))o+=this.codegenDefaultRequire(this.sanitizeStringForJSVariableName(n.filename),`./${n.filenameWithExtension}`);return o}generateExportedObjectString(e){let o=Object.keys(e),n=`{
|
|
108
|
+
`;for(let s=0;s<o.length;s++){let i=o[s],a=e[i];n+=`${this.codegenPad(1)}"${i}": {
|
|
109
|
+
`;for(let c of a)n+=`${this.codegenPad(2)}...${this.sanitizeStringForJSVariableName(c.filename)},
|
|
110
|
+
`;n+=`${this.codegenPad(1)}}${s<o.length-1?`,
|
|
111
|
+
`:`
|
|
112
|
+
`}`}return n+="}",n}};r(_e,"VueI18nFramework");var $t=_e;function mr(t){if(!t.framework)throw new Error("Only call this function with a framework output");let e=t.framework;switch(e){case"i18next":return new Rt(t);case"vue-i18n":return new $t(t);default:throw new Error(`Unsupported JSON framework: ${e}`)}}r(mr,"getFrameworkProcessor");var Me=class Me extends yt(_t){async fetchAPIData(){let e=this.generatePullFilter(),o=await Fe(e),s=(await Oe()).reduce((i,a)=>(i[a.id]=a,i),{});return{textItems:o,variablesById:s}}async transformAPIData(e){let o={},n=new gt({filename:"variables",path:this.outDir});for(let i=0;i<e.textItems.length;i++){let a=e.textItems[i],c=`${a.projectId}___${a.variantId||"base"}`;o[c]??(o[c]=new gt({filename:c,path:this.outDir,metadata:{variantId:a.variantId||"base"}})),o[c].content[a.id]=a.text;for(let m of a.variableIds){let y=e.variablesById[m];n.content[m]=y.data}}let s=[...Object.values(o),n];return this.output.framework&&s.push(...mr(this.output).process(o)),s}generatePullFilter(){let e={projects:this.projectConfig.projects,variants:this.projectConfig.variants};return this.output.projects&&(e.projects=this.output.projects),this.output.variants&&(e.variants=this.output.variants),e}};r(Me,"JSONFormatter");var Lt=Me;function Re(t,e){switch(t.format){case"json":return new Lt(t,e).format();default:throw new Error(`Unsupported output format: ${t}`)}}r(Re,"handleOutput");var ur=r(async()=>{for(let t of h.selectedProjectConfigOutputs)await Re(t,h.projectConfig)},"pull");var fr=l(require("@sentry/node"));async function ht(t,e=2){t&&T.writeLine(`
|
|
106
113
|
${t}
|
|
107
|
-
`),await
|
|
108
|
-
`)||"Invalid API key"},"validate");async function
|
|
109
|
-
`);let o
|
|
114
|
+
`),await fr.flush(),process.exit(e)}r(ht,"quit");var Tr=l(require("fs"));var $e=l(require("fs")),Le=l(require("js-yaml")),xt=require("zod");var Ps=xt.z.record(xt.z.string(),xt.z.array(xt.z.object({token:xt.z.string()})));function Qt(t=h.configFile){Pt(t);let e=$e.default.readFileSync(t,"utf8"),o=Le.default.load(e),n=Ps.safeParse(o);return n.success?n.data:{}}r(Qt,"readGlobalConfigData");function Es(t,e){Pt(t);let o=Qt(t),n=Le.default.dump({...o,...e});$e.default.writeFileSync(t,n,"utf8")}r(Es,"writeGlobalConfigData");function dr(t,e,o){let n=Qt(t);n[e]=[{token:o}],Es(t,n)}r(dr,"saveToken");var xr=l(require("@sentry/node"));var te=l(require("axios"));async function Jt(t){try{let e=te.default.create({});return e.interceptors.request.use(be(t)),(await e.get("/token-check")).status===200?{success:!0}:{success:!1,output:[T.errorText("This API key isn't valid. Please try another.")]}}catch(e){return e instanceof te.AxiosError?e.code==="ENOTFOUND"?{success:!1,output:[T.errorText(`Can't connect to API: ${T.url(h.apiHost)}`)]}:e.response?.status===401||e.response?.status===404?{success:!1,output:[T.errorText("This API key isn't valid. Please try another.")]}:{success:!1,output:[T.errorText("Sorry! We're having trouble reaching the Ditto API. Please try again later.")]}:{success:!1,output:[T.warnText("Sorry! We're having trouble reaching the Ditto API. Please try again later.")]}}}r(Jt,"checkToken");var yr=require("enquirer");var ks=r(async t=>{let e=await Jt(t);return e.success?!0:e.output?.join(`
|
|
115
|
+
`)||"Invalid API key"},"validate");async function Je(){return await(0,yr.prompt)({type:"input",name:"token",message:"What is your API key?",validate:ks})}r(Je,"promptForApiToken");async function Ve(){let t=T.url("https://app.dittowords.com/account/devtools"),e=T.bold(T.info("API Keys")),o=`To get started, you'll need your Ditto API key. You can find this at: ${t} under "${e}".`;return T.writeLine(o),(await Je()).token}r(Ve,"collectToken");var hr=l(require("url"));function Vt(t){return t.includes("://")?hr.default.parse(t).hostname||"":t}r(Vt,"getURLHostname");async function Tt(t=h.apiHost){try{let e=await Ve();T.writeLine(`Thanks for authenticating. We'll save the key to: ${T.info(h.configFile)}
|
|
116
|
+
`);let o=Vt(t);return dr(h.configFile,o,e),h.setApiToken(e),e}catch(e){if(e==="")return await ht("",0),"";let o=xr.captureException(e),n=`
|
|
110
117
|
|
|
111
|
-
Error ID: ${T.info(o)}`;return await
|
|
112
|
-
`),o);let n,s,i="Something went wrong. Please contact support or try again later.";
|
|
118
|
+
Error ID: ${T.info(o)}`;return await ht(T.errorText("Something went wrong. Please contact support or try again later.")+n),""}}r(Tt,"collectAndSaveToken");async function ee(t){return(await Jt(t)).success?t:await Tt()}r(ee,"validateToken");async function Ye(){if(h.apiToken)return await ee(h.apiToken);if(!Tr.default.existsSync(h.configFile))return await Tt();let t=Qt(h.configFile),e=Vt(h.apiHost);return!t[e]||!t[e][0]||t[e][0].token===""?await Tt(e):await ee(t[e][0].token)}r(Ye,"initAPIToken");var Ds=[{name:"pull",description:"Sync copy from Ditto",flags:{"-c, --config [value]":{description:"Relative path to the project config file. Defaults to `./ditto/config.yml`. Alternatively, you can set the DITTO_PROJECT_CONFIG_FILE environment variable."}}}],As=r(()=>{St.program.name("ditto-cli"),Ds.forEach(t=>{let e=St.program.command(t.name).description(t.description).action(o=>_s(t.name,o));t.flags&&Object.entries(t.flags).forEach(([o,{description:n,processor:s}])=>{s?e.option(o,n,s):e.option(o,n)})})},"setupCommands"),Ns=r(()=>{St.program.option("-l, --legacy","Run in legacy mode"),St.program.version(st,"-v, --version","Output the current version")},"setupOptions"),_s=r(async(t,e)=>{try{let o=e.opts(),n=await Ye();switch(h.setApiToken(n),await nr(o),t){case"none":case"pull":return await ur();default:{await ht(`Invalid command: ${t}. Exiting Ditto CLI...`);return}}}catch(o){process.env.DEBUG==="true"&&console.error(T.info(`Development stack trace:
|
|
119
|
+
`),o);let n,s,i="Something went wrong. Please contact support or try again later.";er(o)&&(s=o.exitCode,Se(o,"ConfigYamlLoadError")?i=o.message:Se(o,"ConfigParseError")&&(i=`${o.data.messagePrefix}
|
|
113
120
|
|
|
114
|
-
${o.data.formattedError}`),n={extra:{message:i,...o.data||{}}});let a=
|
|
121
|
+
${o.data.formattedError}`),n={extra:{message:i,...o.data||{}}});let a=Sr.captureException(o,n),c=`
|
|
115
122
|
|
|
116
|
-
Error ID: ${T.info(a)}`;return await
|
|
123
|
+
Error ID: ${T.info(a)}`;return await ht(T.errorText(i)+c,s)}},"executeCommand"),Ms=r(async()=>{As(),Ns(),St.program.parse(process.argv)},"appEntry"),wr=Ms;var Rs="production";vr.init({dsn:"https://9c1d99fa4267f54c6b914f720b4ed3a2@o979374.ingest.sentry.io/4505705213919232",environment:Rs,release:st});var $s=r(async()=>{process.argv.includes("--legacy")?(console.log(T.warnText(`
|
|
117
124
|
Ditto CLI is running in legacy mode. This mode is deprecated and will be removed in a future release.
|
|
118
|
-
`)),
|
|
125
|
+
`)),Ho()):wr()},"main");$s();
|
|
119
126
|
|
|
120
|
-
//# debugId=
|
|
127
|
+
//# debugId=23571d17-fe75-53c1-b0d6-409474e4a897
|