@tinacms/cli 0.58.2 → 0.60.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/CHANGELOG.md CHANGED
@@ -1,5 +1,60 @@
1
1
  # tinacms-cli
2
2
 
3
+ ## 0.60.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 35884152b: Adds and audit command that checks files for errors.
8
+
9
+ ### Patch Changes
10
+
11
+ - 083aa8ec6: Rebuild database every save while in local mode
12
+ - Updated dependencies [b66aefde1]
13
+ - Updated dependencies [35884152b]
14
+ - Updated dependencies [4948beec6]
15
+ - @tinacms/graphql@0.59.4
16
+
17
+ ## 0.59.0
18
+
19
+ ### Minor Changes
20
+
21
+ - 70da62fe8: deprecated the use of `getStaticPropsForTina`
22
+
23
+ ### Patch Changes
24
+
25
+ - 80732bd97: Create a @tinacms/datalayer package which houses the logic for data management for the GraphQL API. This simplifies the @tinacms/graphql package and allows for a clearer separation.
26
+ - Updated dependencies [34cd3a44a]
27
+ - Updated dependencies [b006a5ab9]
28
+ - Updated dependencies [a324b9c37]
29
+ - Updated dependencies [80732bd97]
30
+ - Updated dependencies [0bec208e2]
31
+ - Updated dependencies [5c070a83f]
32
+ - @tinacms/graphql@0.59.3
33
+ - @tinacms/datalayer@0.0.1
34
+
35
+ ## 0.58.5
36
+
37
+ ### Patch Changes
38
+
39
+ - Updated dependencies [212685fc3]
40
+ - @tinacms/graphql@0.59.2
41
+
42
+ ## 0.58.4
43
+
44
+ ### Patch Changes
45
+
46
+ - 118524507: Fixed typo in admin link
47
+ - Updated dependencies [f46c6f987]
48
+ - @tinacms/graphql@0.59.1
49
+
50
+ ## 0.58.3
51
+
52
+ ### Patch Changes
53
+
54
+ - Updated dependencies [bd4e1f802]
55
+ - Updated dependencies [62bea7019]
56
+ - @tinacms/graphql@0.59.0
57
+
3
58
  ## 0.58.2
4
59
 
5
60
  ### Patch Changes
package/README.md CHANGED
@@ -19,20 +19,23 @@ yarn add --dev @tinacms/cli
19
19
  ## Usage
20
20
 
21
21
  ```
22
- Usage: command [options]
22
+ Usage: @tinacms/cli command [options]
23
23
 
24
24
  Options:
25
- -V, --version output the version number
26
- -h, --help display help for command
25
+ -V, --version output the version number
26
+ -h, --help display help for command
27
27
 
28
28
  Commands:
29
- server:start [options] Start Filesystem Graphql Server
30
- schema:compile Compile schema into static files for the server
31
- schema:types Generate a GraphQL query for your site's schema, (and
32
- optionally Typescript types)
33
- help [command] display help for command
29
+ server:start [options] Start Filesystem Graphql Server
30
+ schema:compile [options] Compile schema into static files for the server
31
+ schema:types [options] Generate a GraphQL query for your site's schema, (and optionally Typescript types)
32
+ init [options] Add Tina Cloud to an existing project
33
+ audit [options] Audit your schema and the files to check for errors
34
+ help [command] display help for command
34
35
  ```
35
36
 
37
+ [See our docs](https://tina.io/docs/cli-overview/) for more information about the commands.
38
+
36
39
  ## Getting started
37
40
 
38
41
  The simplest way to get started is to add a `.tina/schema.ts` file
@@ -228,3 +231,8 @@ getPostsDocument(relativePath: "voteForPedro.md") {
228
231
  To learn how to work with this data on a Tina-enabled site, check out the [client documentation](https://tina.io/docs/tina-cloud/client/)
229
232
 
230
233
  > This API is currently somewhat limited. Specifically there's no support for filtering and sorting "list" queries. We have plans to tackle that in upcoming cycles
234
+
235
+
236
+ ## API Docs
237
+
238
+ See [our doc page](https://tina.io/docs/cli-overview/) for specific API docs
@@ -0,0 +1,31 @@
1
+ /**
2
+ Copyright 2021 Forestry.io Holdings, Inc.
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, software
8
+ distributed under the License is distributed on an "AS IS" BASIS,
9
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ See the License for the specific language governing permissions and
11
+ limitations under the License.
12
+ */
13
+ import type { Database, TinaCloudCollection } from '@tinacms/graphql';
14
+ declare type AuditArgs = {
15
+ collection: TinaCloudCollection;
16
+ database: Database;
17
+ rootPath: string;
18
+ useDefaultValues: boolean;
19
+ };
20
+ export declare const auditCollection: (args: AuditArgs) => Promise<boolean>;
21
+ export declare const auditDocuments: (args: AuditArgs) => Promise<boolean>;
22
+ export declare const transformDocumentIntoMutationRequestPayload: (document: {
23
+ [key: string]: unknown;
24
+ _collection: string;
25
+ __typename?: string;
26
+ _template: string;
27
+ }, instructions: {
28
+ includeCollection?: boolean;
29
+ includeTemplate?: boolean;
30
+ }, defaults?: any) => any;
31
+ export {};
@@ -0,0 +1,14 @@
1
+ /**
2
+ Copyright 2021 Forestry.io Holdings, Inc.
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, software
8
+ distributed under the License is distributed on an "AS IS" BASIS,
9
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ See the License for the specific language governing permissions and
11
+ limitations under the License.
12
+ */
13
+ export declare const audit: (ctx: any, next: () => void, options: any) => Promise<void>;
14
+ export declare const printFinalMessage: (ctx: any, next: () => void, _options: any) => Promise<void>;
@@ -15,4 +15,5 @@ export declare const CMD_GEN_TYPES = "schema:types";
15
15
  export declare const CMD_START_SERVER = "server:start";
16
16
  export declare const CMD_COMPILE_MODELS = "schema:compile";
17
17
  export declare const INIT = "init";
18
+ export declare const AUDIT = "audit";
18
19
  export declare const baseCmds: Command[];
@@ -11,6 +11,6 @@ See the License for the specific language governing permissions and
11
11
  limitations under the License.
12
12
  */
13
13
  export declare const adminPage = "import { TinaAdmin } from 'tinacms';\nexport default TinaAdmin;\n";
14
- export declare const blogPost = "---\ntitle: Vote For Pedro\n---\n# Welcome to the blog.\n\n> To edit this site head over to the [` /\n admin`](/admin) route. Then click the pencil icon in the bottom lefthand corner to start editing \uD83E\uDD99. \n\n\n# Dixi gaude Arethusa\n\n## Oscula mihi\n\nLorem markdownum numerabilis armentorum platanus, cultros coniunx sibi per\nsilvas, nostris clausit sequemur diverso scopulosque. Fecit tum alta sed non\nfalcato murmura, geminas donata Amyntore, quoque Nox. Invitam inquit, modo\nnocte; ut ignis faciemque manes in imagine sinistra ut mucrone non ramos\nsepulcro supplex. Crescentesque populos motura, fit cumque. Verumque est; retro\nsibi tristia bracchia Aetola telae caruerunt et.\n\n\n## Mutato fefellimus sit demisit aut alterius sollicito\n\nPhaethonteos vestes quem involvite iuvenca; furiali anne: sati totumque,\n**corpora** cum rapacibus nunc! Nervis repetatne, miserabile doleas, deprensum\nhunc, fluctus Threicio, ad urbes, magicaeque, quid. Per credensque series adicis\npoteram [quidem](#)! Iam uni mensas victrix\nvittas ut flumina Satyri adulter; bellum iacet domitae repercusso truncis urnis\nmille rigidi sub taurum.\n\n\n";
14
+ export declare const blogPost = "---\ntitle: Vote For Pedro\n---\n# Welcome to the blog.\n\n> To edit this site head over to the [`/admin`](/admin) route. Then click the pencil icon in the bottom lefthand corner to start editing \uD83E\uDD99. \n\n# Dixi gaude Arethusa\n\n## Oscula mihi\n\nLorem markdownum numerabilis armentorum platanus, cultros coniunx sibi per\nsilvas, nostris clausit sequemur diverso scopulosque. Fecit tum alta sed non\nfalcato murmura, geminas donata Amyntore, quoque Nox. Invitam inquit, modo\nnocte; ut ignis faciemque manes in imagine sinistra ut mucrone non ramos\nsepulcro supplex. Crescentesque populos motura, fit cumque. Verumque est; retro\nsibi tristia bracchia Aetola telae caruerunt et.\n\n\n## Mutato fefellimus sit demisit aut alterius sollicito\n\nPhaethonteos vestes quem involvite iuvenca; furiali anne: sati totumque,\n**corpora** cum rapacibus nunc! Nervis repetatne, miserabile doleas, deprensum\nhunc, fluctus Threicio, ad urbes, magicaeque, quid. Per credensque series adicis\npoteram [quidem](#)! Iam uni mensas victrix\nvittas ut flumina Satyri adulter; bellum iacet domitae repercusso truncis urnis\nmille rigidi sub taurum.\n\n\n";
15
15
  export declare const nextPostPage: () => string;
16
16
  export declare const AppJsContent: (extraImports?: string) => string;
package/dist/index.js CHANGED
@@ -30,7 +30,7 @@ var server_exports = {};
30
30
  __export(server_exports, {
31
31
  default: () => server_default
32
32
  });
33
- var import_cors, import_http, import_express, import_altair_express_middleware, import_body_parser, GITHUB_ACCESS_TOKEN, gqlServer, server_default;
33
+ var import_cors, import_http, import_express, import_altair_express_middleware, import_body_parser, gqlServer, server_default;
34
34
  var init_server = __esm({
35
35
  "pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/start-server/server.ts"() {
36
36
  import_cors = __toModule(require("cors"));
@@ -38,7 +38,6 @@ var init_server = __esm({
38
38
  import_express = __toModule(require("express"));
39
39
  import_altair_express_middleware = __toModule(require("altair-express-middleware"));
40
40
  import_body_parser = __toModule(require("body-parser"));
41
- GITHUB_ACCESS_TOKEN = process.env.GITHUB_PERSONAL_ACCESS_TOKEN;
42
41
  gqlServer = async (database) => {
43
42
  const gqlPackage = require("@tinacms/graphql");
44
43
  const app = (0, import_express.default)();
@@ -71,36 +70,6 @@ var init_server = __esm({
71
70
  });
72
71
  return res.json(result);
73
72
  });
74
- app.get("/list-branches", async (req, res) => {
75
- try {
76
- const { query } = req;
77
- const { owner, repo } = query;
78
- const result = await gqlPackage.listBranches({
79
- auth: GITHUB_ACCESS_TOKEN,
80
- owner,
81
- repo
82
- });
83
- return res.json(result.data);
84
- } catch (error) {
85
- console.error("There was a problem fetching the branches.", error);
86
- }
87
- });
88
- app.post("/create-branch", async (req, res) => {
89
- try {
90
- const { owner, repo, name: name2, baseBranch } = req.body;
91
- const result = await gqlPackage.createBranch({
92
- auth: GITHUB_ACCESS_TOKEN,
93
- owner,
94
- repo,
95
- baseBranch,
96
- name: name2
97
- });
98
- return res.json(result);
99
- } catch (error) {
100
- res.end();
101
- console.error("There was a problem creating a new branch.", error);
102
- }
103
- });
104
73
  return server;
105
74
  };
106
75
  server_default = gqlServer;
@@ -116,7 +85,7 @@ var commander = __toModule(require("commander"));
116
85
 
117
86
  // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/package.json
118
87
  var name = "@tinacms/cli";
119
- var version = "0.58.2";
88
+ var version = "0.59.0";
120
89
 
121
90
  // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/utils/theme.ts
122
91
  var import_chalk = __toModule(require("chalk"));
@@ -150,6 +119,7 @@ var chain = async (cmds, options) => {
150
119
 
151
120
  // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/query-gen/attachSchema.ts
152
121
  var import_graphql = __toModule(require("@tinacms/graphql"));
122
+ var import_datalayer = __toModule(require("@tinacms/datalayer"));
153
123
 
154
124
  // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/logger/index.ts
155
125
  var import_log4js = __toModule(require("log4js"));
@@ -165,11 +135,11 @@ logger.level = "info";
165
135
  // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/query-gen/attachSchema.ts
166
136
  async function attachSchema(ctx, next, options) {
167
137
  logger.info(logText("Building schema..."));
168
- const rootPath = process.cwd();
169
- const bridge = new import_graphql.FilesystemBridge(rootPath);
170
- const store = new import_graphql.FilesystemStore({ rootPath });
138
+ const rootPath2 = process.cwd();
139
+ const bridge = new import_datalayer.FilesystemBridge(rootPath2);
140
+ const store = new import_datalayer.FilesystemStore({ rootPath: rootPath2 });
171
141
  const database = await (0, import_graphql.createDatabase)({ store, bridge });
172
- const schema = await (0, import_graphql.buildSchema)(rootPath, database);
142
+ const schema = await (0, import_graphql.buildSchema)(rootPath2, database);
173
143
  ctx.schema = schema;
174
144
  next();
175
145
  }
@@ -184,16 +154,26 @@ var import_typescript_operations = __toModule(require("@graphql-codegen/typescri
184
154
  var AddGeneratedClientFunc = (_schema, _documents, _config, _info) => {
185
155
  return `
186
156
  // TinaSDK generated code
187
- import { getStaticPropsForTina } from 'tinacms'
157
+ import { staticRequest } from 'tinacms'
188
158
  const requester: (doc: any, vars?: any, options?: any) => Promise<any> = async (
189
159
  doc,
190
160
  vars,
191
161
  _options
192
162
  ) => {
193
- // const data = await tinaClient.request(doc, { variables: vars });
194
- const res = await await getStaticPropsForTina({query: doc, variables: vars})
195
- return res
196
- };
163
+ let data = {}
164
+ try {
165
+ data = await staticRequest({
166
+ query: doc,
167
+ variables: vars,
168
+ })
169
+ } catch (e) {
170
+ // swallow errors related to document creation
171
+ console.warn('Warning: There was an error when fetching data')
172
+ console.warn(e)
173
+ }
174
+
175
+ return { data, query: doc, variables: vars || {} }
176
+ }
197
177
 
198
178
  /**
199
179
  * @experimental this class can be used but may change in the future
@@ -366,7 +346,7 @@ async function genTypes({ schema }, next, options) {
366
346
  // DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
367
347
  ${typescriptTypes}
368
348
  `);
369
- logger.info(`Typescript types => ${successText(typesPath)}`);
349
+ logger.info(`Typescript types => ${logText(typesPath)}`);
370
350
  const schemaString = await (0, import_graphql6.printSchema)(schema);
371
351
  const schemaPath = process.cwd() + "/.tina/__generated__/schema.gql";
372
352
  await import_fs_extra.default.outputFile(schemaPath, `# DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
@@ -376,7 +356,7 @@ schema {
376
356
  mutation: Mutation
377
357
  }
378
358
  `);
379
- logger.info(`GraphQL types ====> ${successText(schemaPath)}`);
359
+ logger.info(`GraphQL types ====> ${logText(schemaPath)}`);
380
360
  next();
381
361
  }
382
362
 
@@ -384,6 +364,7 @@ schema {
384
364
  var import_child_process = __toModule(require("child_process"));
385
365
  var import_path3 = __toModule(require("path"));
386
366
  var import_graphql7 = __toModule(require("@tinacms/graphql"));
367
+ var import_datalayer2 = __toModule(require("@tinacms/datalayer"));
387
368
 
388
369
  // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/compile/index.ts
389
370
  var import_fast_glob = __toModule(require("fast-glob"));
@@ -486,12 +467,12 @@ var defineSchema = (config) => {
486
467
  var import_chokidar = __toModule(require("chokidar"));
487
468
  var gqlPackageFile = require.resolve("@tinacms/graphql");
488
469
  async function startServer(_ctx, _next, { port = 4001, command, noWatch, experimentalData, noSDK }) {
489
- const rootPath = process.cwd();
470
+ const rootPath2 = process.cwd();
490
471
  if (!process.env.CI && !noWatch) {
491
472
  await resetGeneratedFolder();
492
473
  }
493
- const bridge = new import_graphql7.FilesystemBridge(rootPath);
494
- const store = experimentalData ? new import_graphql7.LevelStore(rootPath) : new import_graphql7.FilesystemStore({ rootPath });
474
+ const bridge = new import_datalayer2.FilesystemBridge(rootPath2);
475
+ const store = experimentalData ? new import_datalayer2.LevelStore(rootPath2) : new import_datalayer2.FilesystemStore({ rootPath: rootPath2 });
495
476
  const shouldBuild = bridge.supportsBuilding();
496
477
  const database = await (0, import_graphql7.createDatabase)({ store, bridge });
497
478
  const startSubprocess = () => {
@@ -518,8 +499,8 @@ stack: ${code.stack || "No stack was provided"}`);
518
499
  };
519
500
  let ready = false;
520
501
  if (!noWatch && !process.env.CI) {
521
- import_chokidar.default.watch([`${rootPath}/**/*.{ts,gql,graphql}`], {
522
- ignored: `${import_path3.default.resolve(rootPath)}/.tina/__generated__/**/*`
502
+ import_chokidar.default.watch([`${rootPath2}/**/*.{ts,gql,graphql}`], {
503
+ ignored: `${import_path3.default.resolve(rootPath2)}/.tina/__generated__/**/*`
523
504
  }).on("ready", async () => {
524
505
  console.log("Generating Tina config");
525
506
  try {
@@ -548,8 +529,14 @@ stack: ${code.stack || "No stack was provided"}`);
548
529
  });
549
530
  }
550
531
  const build = async (noSDK2) => {
532
+ if (!process.env.CI && !noWatch) {
533
+ await resetGeneratedFolder();
534
+ }
535
+ const bridge2 = new import_datalayer2.FilesystemBridge(rootPath2);
536
+ const store2 = experimentalData ? new import_datalayer2.LevelStore(rootPath2) : new import_datalayer2.FilesystemStore({ rootPath: rootPath2 });
537
+ const database2 = await (0, import_graphql7.createDatabase)({ store: store2, bridge: bridge2 });
551
538
  await compile(null, null);
552
- const schema = await (0, import_graphql7.buildSchema)(rootPath, database);
539
+ const schema = await (0, import_graphql7.buildSchema)(rootPath2, database2);
553
540
  await genTypes({ schema }, () => {
554
541
  }, { noSDK: noSDK2 });
555
542
  };
@@ -623,9 +610,7 @@ title: Vote For Pedro
623
610
  ---
624
611
  # Welcome to the blog.
625
612
 
626
- > To edit this site head over to the [\` /
627
- admin\`](/admin) route. Then click the pencil icon in the bottom lefthand corner to start editing \u{1F999}.
628
-
613
+ > To edit this site head over to the [\`/admin\`](/admin) route. Then click the pencil icon in the bottom lefthand corner to start editing \u{1F999}.
629
614
 
630
615
  # Dixi gaude Arethusa
631
616
 
@@ -653,7 +638,7 @@ mille rigidi sub taurum.
653
638
  var nextPostPage = () => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
654
639
  // This is a demo file once you have tina setup feel free to delete this file
655
640
 
656
- import { staticRequest, gql, getStaticPropsForTina } from "tinacms";
641
+ import { staticRequest, gql } from "tinacms";
657
642
  import Head from "next/head";
658
643
  import { createGlobalStyle } from "styled-components";
659
644
 
@@ -744,24 +729,35 @@ var nextPostPage = () => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
744
729
  };
745
730
 
746
731
  export const getStaticProps = async ({ params }) => {
747
- const tinaProps = await getStaticPropsForTina({
748
- query: gql\`
749
- query BlogPostQuery($relativePath: String!) {
750
- getPostsDocument(relativePath: $relativePath) {
751
- data {
752
- title
753
- body
754
- }
732
+ const query = gql\`
733
+ query BlogPostQuery($relativePath: String!) {
734
+ getPostsDocument(relativePath: $relativePath) {
735
+ data {
736
+ title
737
+ body
755
738
  }
756
739
  }
757
- \`,
758
- variables: { relativePath: \`\${params.filename}.md\` },
759
- });
740
+ }
741
+ \`
742
+ const variables = { relativePath: \`\${params.filename}.md\` }
743
+ let data = {}
744
+ try {
745
+ data = await staticRequest({
746
+ query,
747
+ variables,
748
+ })
749
+ } catch {
750
+ // swallow errors related to document creation
751
+ }
752
+
760
753
  return {
761
754
  props: {
762
- ...tinaProps,
755
+ query,
756
+ variables,
757
+ data,
758
+ //myOtherProp: 'some-other-data',
763
759
  },
764
- };
760
+ }
765
761
  };
766
762
 
767
763
  export const getStaticPaths = async () => {
@@ -943,12 +939,12 @@ export default App
943
939
  var import_chalk2 = __toModule(require("chalk"));
944
940
  function execShellCommand(cmd) {
945
941
  const exec = require("child_process").exec;
946
- return new Promise((resolve, reject) => {
942
+ return new Promise((resolve2, reject) => {
947
943
  exec(cmd, (error, stdout, stderr) => {
948
944
  if (error) {
949
945
  console.warn(error);
950
946
  }
951
- resolve(stdout ? stdout : stderr);
947
+ resolve2(stdout ? stdout : stderr);
952
948
  });
953
949
  });
954
950
  }
@@ -1050,11 +1046,252 @@ Enjoy Tina \u{1F999} !
1050
1046
  next();
1051
1047
  }
1052
1048
 
1049
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/audit/index.ts
1050
+ var import_graphql10 = __toModule(require("@tinacms/graphql"));
1051
+ var import_datalayer3 = __toModule(require("@tinacms/datalayer"));
1052
+
1053
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/audit/audit.ts
1054
+ var import_graphql8 = __toModule(require("@tinacms/graphql"));
1055
+ var import_path5 = __toModule(require("path"));
1056
+ var import_graphql9 = __toModule(require("@tinacms/graphql"));
1057
+ var import_chalk3 = __toModule(require("chalk"));
1058
+ var auditCollection = async (args) => {
1059
+ let warning = false;
1060
+ const { collection, database, rootPath: rootPath2 } = args;
1061
+ logger.info(`Checking collection ${collection.name}`);
1062
+ const query = `query {
1063
+ getCollection(collection: "${collection.name}") {
1064
+ format
1065
+ documents {
1066
+ edges {
1067
+ node {
1068
+ ...on Document {
1069
+ sys {
1070
+ extension
1071
+ path
1072
+ }
1073
+ }
1074
+ }
1075
+ }
1076
+ }
1077
+ }
1078
+ }
1079
+ `;
1080
+ const result = await (0, import_graphql8.resolve)({
1081
+ database,
1082
+ query,
1083
+ variables: {}
1084
+ });
1085
+ const format = result.data.getCollection.format;
1086
+ const docs = result.data.getCollection.documents.edges;
1087
+ docs.forEach((x) => {
1088
+ const node = x.node;
1089
+ if (node.sys.extension.replace(".", "") !== format) {
1090
+ warning = true;
1091
+ logger.warn(import_chalk3.default.yellowBright(`WARNING: there is a file with extension \`${node.sys.extension}\` but in your schema it is defined to be \`.${format}\`
1092
+
1093
+ location: ${import_path5.default.join(rootPath2, node.sys.path)}`));
1094
+ }
1095
+ });
1096
+ return warning;
1097
+ };
1098
+ var auditDocuments = async (args) => {
1099
+ const { collection, database, rootPath: rootPath2, useDefaultValues } = args;
1100
+ const query = `query {
1101
+ getCollection(collection: "${collection.name}") {
1102
+ format
1103
+ slug
1104
+ documents {
1105
+ edges {
1106
+ node {
1107
+ ...on Document {
1108
+ sys {
1109
+ extension
1110
+ path
1111
+ relativePath
1112
+ }
1113
+ }
1114
+ }
1115
+ }
1116
+ }
1117
+ }
1118
+ }
1119
+ `;
1120
+ const result = await (0, import_graphql8.resolve)({
1121
+ database,
1122
+ query,
1123
+ variables: {}
1124
+ });
1125
+ let error = false;
1126
+ const documents = result.data.getCollection.documents.edges;
1127
+ for (let i = 0; i < documents.length; i++) {
1128
+ const node = documents[i].node;
1129
+ const fullPath = import_path5.default.join(rootPath2, node.sys.path);
1130
+ logger.info(`Checking document: ${fullPath}`);
1131
+ const documentQuery = `query {
1132
+ getDocument(collection: "${collection.name}", relativePath: "${node.sys.relativePath}") {
1133
+ __typename
1134
+ ...on Document {
1135
+ values
1136
+ }
1137
+ }
1138
+ }`;
1139
+ const docResult = await (0, import_graphql8.resolve)({
1140
+ database,
1141
+ query: documentQuery,
1142
+ variables: {}
1143
+ });
1144
+ const topLevelDefaults = {};
1145
+ if (useDefaultValues && typeof collection.fields !== "string") {
1146
+ collection.fields.filter((x) => !x.list).forEach((x) => {
1147
+ const value = x.ui;
1148
+ if (typeof value !== "undefined") {
1149
+ topLevelDefaults[x.name] = value.defaultValue;
1150
+ }
1151
+ });
1152
+ }
1153
+ const params = transformDocumentIntoMutationRequestPayload(docResult.data.getDocument.values, {
1154
+ includeCollection: true,
1155
+ includeTemplate: typeof collection.templates !== "undefined"
1156
+ }, topLevelDefaults);
1157
+ const mutation = `mutation($collection: String!, $relativePath: String!, $params: DocumentMutation!) {
1158
+ updateDocument(
1159
+ collection: $collection,
1160
+ relativePath: $relativePath,
1161
+ params: $params
1162
+ ){__typename}
1163
+ }`;
1164
+ const mutationRes = await (0, import_graphql8.resolve)({
1165
+ database,
1166
+ query: mutation,
1167
+ variables: {
1168
+ params,
1169
+ collection: collection.name,
1170
+ relativePath: node.sys.relativePath
1171
+ },
1172
+ silenceErrors: true
1173
+ });
1174
+ if (mutationRes.errors) {
1175
+ mutationRes.errors.forEach((err) => {
1176
+ error = true;
1177
+ logger.error(import_chalk3.default.red(err.message));
1178
+ });
1179
+ }
1180
+ }
1181
+ return error;
1182
+ };
1183
+ var transformDocumentIntoMutationRequestPayload = (document, instructions, defaults) => {
1184
+ const { _collection, __typename, _template, ...rest } = document;
1185
+ const params = transformParams(rest);
1186
+ const paramsWithTemplate = instructions.includeTemplate ? { [_template]: params } : params;
1187
+ return instructions.includeCollection ? { [_collection]: { ...defaults, ...filterObject(paramsWithTemplate) } } : { ...defaults, ...filterObject(paramsWithTemplate) };
1188
+ };
1189
+ var transformParams = (data) => {
1190
+ if (["string", "number", "boolean"].includes(typeof data)) {
1191
+ return data;
1192
+ }
1193
+ if (Array.isArray(data)) {
1194
+ return data.map((item) => transformParams(item));
1195
+ }
1196
+ try {
1197
+ (0, import_graphql9.assertShape)(data, (yup) => yup.object({ _template: yup.string().required() }));
1198
+ const { _template, __typename, ...rest } = data;
1199
+ const nested = transformParams(rest);
1200
+ return { [_template]: nested };
1201
+ } catch (e) {
1202
+ if (e.message === "Failed to assertShape - _template is a required field") {
1203
+ if (!data) {
1204
+ return void 0;
1205
+ return [];
1206
+ }
1207
+ const accum = {};
1208
+ Object.entries(data).map(([keyName, value]) => {
1209
+ accum[keyName] = transformParams(value);
1210
+ });
1211
+ return accum;
1212
+ } else {
1213
+ if (!data) {
1214
+ return void 0;
1215
+ return [];
1216
+ }
1217
+ throw e;
1218
+ }
1219
+ }
1220
+ };
1221
+ function filterObject(obj) {
1222
+ const ret = {};
1223
+ Object.keys(obj).filter((key) => obj[key] !== void 0).forEach((key) => ret[key] = obj[key]);
1224
+ return ret;
1225
+ }
1226
+
1227
+ // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/audit/index.ts
1228
+ var import_chalk4 = __toModule(require("chalk"));
1229
+ var import_prompts2 = __toModule(require("prompts"));
1230
+ var rootPath = process.cwd();
1231
+ var audit = async (ctx, next, options) => {
1232
+ if (options.clean) {
1233
+ logger.info(`You are using the \`--clean\` option. This will modify your content as if a user is submitting a form. Before running this you should have a ${import_chalk4.default.bold("clean git tree")} so unwanted changes can be undone.
1234
+
1235
+ `);
1236
+ const res = await (0, import_prompts2.default)({
1237
+ name: "useClean",
1238
+ type: "confirm",
1239
+ message: `Do you want to continue?`
1240
+ });
1241
+ if (!res.useClean) {
1242
+ logger.warn(import_chalk4.default.yellowBright("\u26A0\uFE0F Audit not complete"));
1243
+ process.exit(0);
1244
+ }
1245
+ }
1246
+ if (options.useDefaultValues && !options.clean) {
1247
+ logger.warn(import_chalk4.default.yellowBright("WARNING: using the `--useDefaultValues` without the `--clean` flag has no effect. Please re-run audit and add the `--clean` flag"));
1248
+ }
1249
+ const bridge = options.clean ? new import_datalayer3.FilesystemBridge(rootPath) : new import_datalayer3.AuditFileSystemBridge(rootPath);
1250
+ const store = options.clean ? new import_datalayer3.FilesystemStore({ rootPath }) : new import_datalayer3.AuditFilesystemStore({ rootPath });
1251
+ const database = await (0, import_graphql10.createDatabase)({ store, bridge });
1252
+ const schema = await database.getSchema();
1253
+ const collections = schema.getCollections();
1254
+ let warning = false;
1255
+ let error = false;
1256
+ for (let i = 0; i < collections.length; i++) {
1257
+ const collection = collections[i];
1258
+ const returnWarning = await auditCollection({
1259
+ collection,
1260
+ database,
1261
+ rootPath,
1262
+ useDefaultValues: options.useDefaultValues
1263
+ });
1264
+ const returnError = await auditDocuments({
1265
+ collection,
1266
+ database,
1267
+ rootPath,
1268
+ useDefaultValues: options.useDefaultValues
1269
+ });
1270
+ warning = warning || returnWarning;
1271
+ error = error || returnError;
1272
+ }
1273
+ ctx.warning = warning;
1274
+ ctx.error = error;
1275
+ next();
1276
+ };
1277
+ var printFinalMessage = async (ctx, next, _options) => {
1278
+ if (ctx.error) {
1279
+ logger.error(import_chalk4.default.redBright(`\u203C\uFE0F Audit ${import_chalk4.default.bold("failed")} with errors`));
1280
+ } else if (ctx.warning) {
1281
+ logger.warn(import_chalk4.default.yellowBright("\u26A0\uFE0F Audit passed with warnings"));
1282
+ } else {
1283
+ logger.info(import_chalk4.default.greenBright("\u2705 Audit passed"));
1284
+ }
1285
+ next();
1286
+ };
1287
+
1053
1288
  // pnp:/Users/jeffsee/code/tinacms/packages/@tinacms/cli/src/cmds/baseCmds.ts
1289
+ var import_chalk5 = __toModule(require("chalk"));
1054
1290
  var CMD_GEN_TYPES = "schema:types";
1055
1291
  var CMD_START_SERVER = "server:start";
1056
1292
  var CMD_COMPILE_MODELS = "schema:compile";
1057
1293
  var INIT = "init";
1294
+ var AUDIT = "audit";
1058
1295
  var startServerPortOption = {
1059
1296
  name: "--port <port>",
1060
1297
  description: "Specify a port to run the server on. (default 4001)"
@@ -1075,6 +1312,14 @@ var noSDKCodegenOption = {
1075
1312
  name: "--noSDK",
1076
1313
  description: "Don't generate the generated client SDK"
1077
1314
  };
1315
+ var cleanOption = {
1316
+ name: "--clean",
1317
+ description: "Submit gql mutation to all files to git rid of any data that is not defined in the `schema.ts`"
1318
+ };
1319
+ var useDefaultValuesOption = {
1320
+ name: "--useDefaultValues",
1321
+ description: "Adds default values to the graphQL mutation so that default values can be filled into existing documents (useful for adding a field with `required: true`)"
1322
+ };
1078
1323
  var baseCmds = [
1079
1324
  {
1080
1325
  command: CMD_START_SERVER,
@@ -1116,6 +1361,30 @@ var baseCmds = [
1116
1361
  tinaSetup,
1117
1362
  successMessage
1118
1363
  ], options)
1364
+ },
1365
+ {
1366
+ options: [cleanOption, useDefaultValuesOption],
1367
+ command: AUDIT,
1368
+ description: "Audit your schema and the files to check for errors",
1369
+ action: (options) => chain([
1370
+ async (_ctx, next) => {
1371
+ logger.level = "error";
1372
+ next();
1373
+ },
1374
+ async (_ctx, next) => {
1375
+ await compile(_ctx, next);
1376
+ next();
1377
+ },
1378
+ attachSchema,
1379
+ genTypes,
1380
+ async (_ctx, next) => {
1381
+ logger.level = "info";
1382
+ logger.info(import_chalk5.default.hex("#eb6337").bgWhite("Welcome to tina audit \u{1F999}"));
1383
+ next();
1384
+ },
1385
+ audit,
1386
+ printFinalMessage
1387
+ ], options)
1119
1388
  }
1120
1389
  ];
1121
1390
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinacms/cli",
3
- "version": "0.58.2",
3
+ "version": "0.60.0",
4
4
  "main": "dist/index.js",
5
5
  "typings": "dist/index.d.ts",
6
6
  "files": [
@@ -56,7 +56,8 @@
56
56
  "@graphql-codegen/visitor-plugin-common": "^2.4.0",
57
57
  "@graphql-tools/graphql-file-loader": "^7.2.0",
58
58
  "@graphql-tools/load": "^7.3.2",
59
- "@tinacms/graphql": "0.58.2",
59
+ "@tinacms/datalayer": "0.0.1",
60
+ "@tinacms/graphql": "0.59.4",
60
61
  "ajv": "^6.12.3",
61
62
  "altair-express-middleware": "4.0.6",
62
63
  "auto-bind": "^4.0.0",