@tinacms/cli 0.60.27 → 0.61.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -70,11 +70,11 @@ var init_utils = __esm({
70
70
  });
71
71
 
72
72
  // src/server/models/media.ts
73
- var import_fs_extra5, import_path6, MediaModel;
73
+ var import_fs_extra7, import_path9, MediaModel;
74
74
  var init_media = __esm({
75
75
  "src/server/models/media.ts"() {
76
- import_fs_extra5 = __toModule(require("fs-extra"));
77
- import_path6 = __toModule(require("path"));
76
+ import_fs_extra7 = __toModule(require("fs-extra"));
77
+ import_path9 = __toModule(require("path"));
78
78
  init_utils();
79
79
  MediaModel = class {
80
80
  constructor({ publicFolder, mediaRoot }) {
@@ -83,12 +83,12 @@ var init_media = __esm({
83
83
  }
84
84
  async listMedia(args) {
85
85
  try {
86
- const folderPath = (0, import_path6.join)(this.publicFolder, this.mediaRoot, args.searchPath);
86
+ const folderPath = (0, import_path9.join)(this.publicFolder, this.mediaRoot, args.searchPath);
87
87
  const searchPath = parseMediaFolder(args.searchPath);
88
- const filesStr = await import_fs_extra5.default.readdir(folderPath);
88
+ const filesStr = await import_fs_extra7.default.readdir(folderPath);
89
89
  const filesProm = filesStr.map(async (file) => {
90
- const filePath = (0, import_path6.join)(folderPath, file);
91
- const stat = await import_fs_extra5.default.stat(filePath);
90
+ const filePath = (0, import_path9.join)(folderPath, file);
91
+ const stat = await import_fs_extra7.default.stat(filePath);
92
92
  let src = `/${file}`;
93
93
  const isFile = stat.isFile();
94
94
  if (!isFile) {
@@ -144,9 +144,9 @@ var init_media = __esm({
144
144
  }
145
145
  async deleteMedia(args) {
146
146
  try {
147
- const file = (0, import_path6.join)(this.publicFolder, this.mediaRoot, args.searchPath);
148
- await import_fs_extra5.default.stat(file);
149
- await import_fs_extra5.default.remove(file);
147
+ const file = (0, import_path9.join)(this.publicFolder, this.mediaRoot, args.searchPath);
148
+ await import_fs_extra7.default.stat(file);
149
+ await import_fs_extra7.default.remove(file);
150
150
  return { ok: true };
151
151
  } catch (error) {
152
152
  console.error(error);
@@ -158,15 +158,15 @@ var init_media = __esm({
158
158
  });
159
159
 
160
160
  // src/server/routes/index.ts
161
- var import_express, import_path7, import_multer, createMediaRouter;
161
+ var import_express, import_path10, import_multer, createMediaRouter;
162
162
  var init_routes = __esm({
163
163
  "src/server/routes/index.ts"() {
164
164
  import_express = __toModule(require("express"));
165
- import_path7 = __toModule(require("path"));
165
+ import_path10 = __toModule(require("path"));
166
166
  import_multer = __toModule(require("multer"));
167
167
  init_media();
168
168
  createMediaRouter = (config) => {
169
- const mediaFolder = (0, import_path7.join)(process.cwd(), config.publicFolder, config.mediaRoot);
169
+ const mediaFolder = (0, import_path10.join)(process.cwd(), config.publicFolder, config.mediaRoot);
170
170
  const storage = import_multer.default.diskStorage({
171
171
  destination: function(req, file, cb) {
172
172
  cb(null, mediaFolder);
@@ -293,22 +293,11 @@ var commander = __toModule(require("commander"));
293
293
 
294
294
  // package.json
295
295
  var name = "@tinacms/cli";
296
- var version = "0.60.27";
296
+ var version = "0.61.1";
297
297
 
298
- // src/cmds/query-gen/attachSchema.ts
298
+ // src/cmds/audit/audit.ts
299
299
  var import_graphql = __toModule(require("@tinacms/graphql"));
300
- var import_datalayer = __toModule(require("@tinacms/datalayer"));
301
-
302
- // src/utils/theme.ts
303
- var import_chalk = __toModule(require("chalk"));
304
- var successText = import_chalk.default.bold.green;
305
- var dangerText = import_chalk.default.bold.red;
306
- var neutralText = import_chalk.default.bold.cyan;
307
- var labelText = import_chalk.default.bold;
308
- var cmdText = import_chalk.default.inverse;
309
- var logText = import_chalk.default.italic.gray;
310
- var warnText = import_chalk.default.yellowBright.bgBlack;
311
- var CONFIRMATION_TEXT = import_chalk.default.dim("enter to confirm");
300
+ var import_path = __toModule(require("path"));
312
301
 
313
302
  // src/logger/index.ts
314
303
  var import_log4js = __toModule(require("log4js"));
@@ -321,269 +310,9 @@ import_log4js.default.configure({
321
310
  });
322
311
  logger.level = "info";
323
312
 
324
- // src/cmds/query-gen/attachSchema.ts
325
- async function attachSchema(ctx, next, options) {
326
- logger.info(logText("Building schema..."));
327
- const rootPath2 = process.cwd();
328
- const bridge = new import_datalayer.FilesystemBridge(rootPath2);
329
- const store = new import_datalayer.FilesystemStore({ rootPath: rootPath2 });
330
- const database = await (0, import_graphql.createDatabase)({ store, bridge });
331
- const schema = await (0, import_graphql.buildSchema)(rootPath2, database);
332
- ctx.schema = schema;
333
- next();
334
- }
335
-
336
- // src/cmds/query-gen/genTypes.ts
337
- var import_graphql6 = __toModule(require("graphql"));
338
- var import_fs_extra = __toModule(require("fs-extra"));
339
-
340
- // src/codegen/index.ts
341
- var import_graphql5 = __toModule(require("graphql"));
342
-
343
- // src/codegen/plugin.ts
344
- var AddGeneratedClientFunc = (_schema, _documents, _config, _info) => {
345
- return `
346
- // TinaSDK generated code
347
- import { createClient, TinaClient } from "tinacms/dist/client";
348
-
349
- const generateRequester = (client: TinaClient) => {
350
- const requester: (
351
- doc: any,
352
- vars?: any,
353
- options?: any,
354
- client
355
- ) => Promise<any> = async (doc, vars, _options) => {
356
- let data = {};
357
- try {
358
- data = await client.request({
359
- query: doc,
360
- variables: vars,
361
- });
362
- } catch (e) {
363
- // swallow errors related to document creation
364
- console.warn("Warning: There was an error when fetching data");
365
- console.warn(e);
366
- }
367
-
368
- return { data: data?.data, query: doc, variables: vars || {} };
369
- };
370
-
371
- return requester;
372
- };
373
-
374
- /**
375
- * @experimental this class can be used but may change in the future
376
- **/
377
- export const ExperimentalGetTinaClient = () =>
378
- getSdk(
379
- generateRequester(createClient({ url: "http://localhost:4001/graphql" }))
380
- );
381
-
382
- export const queries = (client: TinaClient) => {
383
- const requester = generateRequester(client);
384
- return getSdk(requester);
385
- };
386
- `;
387
- };
388
- var AddGeneratedClient = {
389
- plugin: AddGeneratedClientFunc
390
- };
391
-
392
- // src/codegen/index.ts
393
- var import_graphql_file_loader = __toModule(require("@graphql-tools/graphql-file-loader"));
394
- var import_core = __toModule(require("@graphql-codegen/core"));
395
- var import_load = __toModule(require("@graphql-tools/load"));
396
- var import_typescript_operations = __toModule(require("@graphql-codegen/typescript-operations"));
397
- var import_typescript = __toModule(require("@graphql-codegen/typescript"));
398
-
399
- // src/codegen/sdkPlugin/index.ts
400
- var import_graphql3 = __toModule(require("graphql"));
401
- var import_graphql4 = __toModule(require("graphql"));
402
- var import_path = __toModule(require("path"));
403
-
404
- // src/codegen/sdkPlugin/visitor.ts
405
- var import_visitor_plugin_common = __toModule(require("@graphql-codegen/visitor-plugin-common"));
406
- var import_auto_bind = __toModule(require("auto-bind"));
407
- var import_graphql2 = __toModule(require("graphql"));
408
- var GenericSdkVisitor = class extends import_visitor_plugin_common.ClientSideBaseVisitor {
409
- constructor(schema, fragments, rawConfig) {
410
- super(schema, fragments, rawConfig, {
411
- usingObservableFrom: rawConfig.usingObservableFrom
412
- });
413
- this._operationsToInclude = [];
414
- (0, import_auto_bind.default)(this);
415
- if (this.config.usingObservableFrom) {
416
- this._additionalImports.push(this.config.usingObservableFrom);
417
- }
418
- if (this.config.documentMode !== import_visitor_plugin_common.DocumentMode.string) {
419
- }
420
- }
421
- buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes) {
422
- if (node.name == null) {
423
- throw new Error("Plugin 'generic-sdk' cannot generate SDK for unnamed operation.\n\n" + (0, import_graphql2.print)(node));
424
- } else {
425
- this._operationsToInclude.push({
426
- node,
427
- documentVariableName,
428
- operationType,
429
- operationResultType: `{data: ${operationResultType}, variables: ${operationVariablesTypes}, query: string}`,
430
- operationVariablesTypes
431
- });
432
- }
433
- return null;
434
- }
435
- get sdkContent() {
436
- const usingObservable = !!this.config.usingObservableFrom;
437
- const allPossibleActions = this._operationsToInclude.map((o) => {
438
- const optionalVariables = !o.node.variableDefinitions || o.node.variableDefinitions.length === 0 || o.node.variableDefinitions.every((v) => v.type.kind !== import_graphql2.Kind.NON_NULL_TYPE || v.defaultValue);
439
- const returnType = usingObservable && o.operationType === "Subscription" ? "Observable" : "Promise";
440
- return `${o.node.name.value}(variables${optionalVariables ? "?" : ""}: ${o.operationVariablesTypes}, options?: C): ${returnType}<${o.operationResultType}> {
441
- return requester<${o.operationResultType}, ${o.operationVariablesTypes}>(${o.documentVariableName}, variables, options);
442
- }`;
443
- }).map((s) => (0, import_visitor_plugin_common.indentMultiline)(s, 2));
444
- return `export type Requester<C= {}> = <R, V>(doc: ${this.config.documentMode === import_visitor_plugin_common.DocumentMode.string ? "string" : "DocumentNode"}, vars?: V, options?: C) => ${usingObservable ? "Promise<R> & Observable<R>" : "Promise<R>"}
445
- export function getSdk<C>(requester: Requester<C>) {
446
- return {
447
- ${allPossibleActions.join(",\n")}
448
- };
449
- }
450
- export type Sdk = ReturnType<typeof getSdk>;`;
451
- }
452
- };
453
-
454
- // src/codegen/sdkPlugin/index.ts
455
- var plugin = (schema, documents, config) => {
456
- const allAst = (0, import_graphql4.concatAST)(documents.reduce((prev, v) => {
457
- return [...prev, v.document];
458
- }, []));
459
- const allFragments = [
460
- ...allAst.definitions.filter((d) => d.kind === import_graphql4.Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({
461
- node: fragmentDef,
462
- name: fragmentDef.name.value,
463
- onType: fragmentDef.typeCondition.name.value,
464
- isExternal: false
465
- })),
466
- ...config.externalFragments || []
467
- ];
468
- const visitor = new GenericSdkVisitor(schema, allFragments, config);
469
- const visitorResult = (0, import_graphql3.visit)(allAst, { leave: visitor });
470
- return {
471
- content: [
472
- visitor.fragments,
473
- ...visitorResult.definitions.filter((t) => typeof t === "string"),
474
- visitor.sdkContent
475
- ].join("\n")
476
- };
477
- };
478
-
479
- // src/codegen/index.ts
480
- var generateTypes = async (schema, queryPathGlob = process.cwd(), fragDocPath = process.cwd(), options = {
481
- noSDK: false,
482
- verbose: false
483
- }) => {
484
- if (options.verbose)
485
- logger.info("Generating types...");
486
- try {
487
- let docs = [];
488
- let fragDocs = [];
489
- try {
490
- if (!options.noSDK) {
491
- docs = await (0, import_load.loadDocuments)(queryPathGlob, {
492
- loaders: [new import_graphql_file_loader.GraphQLFileLoader()]
493
- });
494
- }
495
- } catch (e) {
496
- let showErrorMessage = true;
497
- const message = e.message || "";
498
- if (message.includes("Unable to find any GraphQL type definitions for the following pointers:")) {
499
- showErrorMessage = false;
500
- }
501
- if (showErrorMessage) {
502
- console.error(e);
503
- }
504
- }
505
- try {
506
- if (!options.noSDK) {
507
- fragDocs = await (0, import_load.loadDocuments)(fragDocPath, {
508
- loaders: [new import_graphql_file_loader.GraphQLFileLoader()]
509
- });
510
- }
511
- } catch (error) {
512
- console.error(error);
513
- }
514
- const res = await (0, import_core.codegen)({
515
- filename: process.cwd(),
516
- schema: (0, import_graphql5.parse)((0, import_graphql5.printSchema)(schema)),
517
- documents: [...docs, ...fragDocs],
518
- config: {},
519
- plugins: [
520
- { typescript: {} },
521
- { typescriptOperations: {} },
522
- {
523
- typescriptSdk: {}
524
- },
525
- { AddGeneratedClient: {} }
526
- ],
527
- pluginMap: {
528
- typescript: {
529
- plugin: import_typescript.plugin
530
- },
531
- typescriptOperations: {
532
- plugin: import_typescript_operations.plugin
533
- },
534
- typescriptSdk: {
535
- plugin
536
- },
537
- AddGeneratedClient
538
- }
539
- });
540
- return res;
541
- } catch (e) {
542
- console.error(e);
543
- }
544
- };
545
-
546
- // src/cmds/query-gen/genTypes.ts
547
- async function genTypes({ schema }, next, options) {
548
- const typesPath = process.cwd() + "/.tina/__generated__/types.ts";
549
- const fragPath = process.cwd() + "/.tina/__generated__/*.{graphql,gql}";
550
- const queryPathGlob = process.cwd() + "/.tina/queries/**/*.{graphql,gql}";
551
- const typescriptTypes = await generateTypes(schema, queryPathGlob, fragPath, options);
552
- await import_fs_extra.default.outputFile(typesPath, `//@ts-nocheck
553
- // DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
554
- export function gql(strings: TemplateStringsArray, ...args: string[]): string {
555
- let str = ''
556
- strings.forEach((string, i) => {
557
- str += string + (args[i] || '')
558
- })
559
- return str
560
- }
561
- ${typescriptTypes}
562
- `);
563
- logger.info(` Typescript types => ${logText(typesPath)}`);
564
- const schemaString = await (0, import_graphql6.printSchema)(schema);
565
- const schemaPath = process.cwd() + "/.tina/__generated__/schema.gql";
566
- await import_fs_extra.default.outputFile(schemaPath, `# DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
567
- ${schemaString}
568
- schema {
569
- query: Query
570
- mutation: Mutation
571
- }
572
- `);
573
- logger.info(` GraphQL types ====> ${logText(schemaPath)}
574
- `);
575
- next();
576
- }
577
-
578
- // src/cmds/audit/index.ts
579
- var import_graphql9 = __toModule(require("@tinacms/graphql"));
580
- var import_datalayer2 = __toModule(require("@tinacms/datalayer"));
581
-
582
313
  // src/cmds/audit/audit.ts
583
- var import_graphql7 = __toModule(require("@tinacms/graphql"));
584
- var import_path2 = __toModule(require("path"));
585
- var import_graphql8 = __toModule(require("@tinacms/graphql"));
586
- var import_chalk2 = __toModule(require("chalk"));
314
+ var import_graphql2 = __toModule(require("@tinacms/graphql"));
315
+ var import_chalk = __toModule(require("chalk"));
587
316
  var auditCollection = async (args) => {
588
317
  let warning = false;
589
318
  const { collection, database, rootPath: rootPath2 } = args;
@@ -606,7 +335,7 @@ var auditCollection = async (args) => {
606
335
  }
607
336
  }
608
337
  `;
609
- const result = await (0, import_graphql7.resolve)({
338
+ const result = await (0, import_graphql.resolve)({
610
339
  database,
611
340
  query,
612
341
  variables: {}
@@ -617,9 +346,9 @@ var auditCollection = async (args) => {
617
346
  const node = x.node;
618
347
  if (node._sys.extension.replace(".", "") !== format) {
619
348
  warning = true;
620
- logger.warn(import_chalk2.default.yellowBright(`WARNING: there is a file with extension \`${node._sys.extension}\` but in your schema it is defined to be \`.${format}\`
349
+ logger.warn(import_chalk.default.yellowBright(`WARNING: there is a file with extension \`${node._sys.extension}\` but in your schema it is defined to be \`.${format}\`
621
350
 
622
- location: ${import_path2.default.join(rootPath2, node._sys.path)}`));
351
+ location: ${import_path.default.join(rootPath2, node._sys.path)}`));
623
352
  }
624
353
  });
625
354
  return warning;
@@ -646,7 +375,7 @@ var auditDocuments = async (args) => {
646
375
  }
647
376
  }
648
377
  `;
649
- const result = await (0, import_graphql7.resolve)({
378
+ const result = await (0, import_graphql.resolve)({
650
379
  database,
651
380
  query,
652
381
  variables: {}
@@ -655,7 +384,7 @@ var auditDocuments = async (args) => {
655
384
  const documents = result.data.collection.documents.edges;
656
385
  for (let i = 0; i < documents.length; i++) {
657
386
  const node = documents[i].node;
658
- const fullPath = import_path2.default.join(rootPath2, node._sys.path);
387
+ const fullPath = import_path.default.join(rootPath2, node._sys.path);
659
388
  logger.info(`Checking document: ${fullPath}`);
660
389
  const documentQuery = `query {
661
390
  document(collection: "${collection.name}", relativePath: "${node._sys.relativePath}") {
@@ -665,7 +394,7 @@ var auditDocuments = async (args) => {
665
394
  }
666
395
  }
667
396
  }`;
668
- const docResult = await (0, import_graphql7.resolve)({
397
+ const docResult = await (0, import_graphql.resolve)({
669
398
  database,
670
399
  query: documentQuery,
671
400
  variables: {}
@@ -690,7 +419,7 @@ var auditDocuments = async (args) => {
690
419
  params: $params
691
420
  ){__typename}
692
421
  }`;
693
- const mutationRes = await (0, import_graphql7.resolve)({
422
+ const mutationRes = await (0, import_graphql.resolve)({
694
423
  database,
695
424
  query: mutation,
696
425
  variables: {
@@ -704,7 +433,7 @@ var auditDocuments = async (args) => {
704
433
  if (mutationRes.errors) {
705
434
  mutationRes.errors.forEach((err) => {
706
435
  error = true;
707
- logger.error(import_chalk2.default.red(err.message));
436
+ logger.error(import_chalk.default.red(err.message));
708
437
  });
709
438
  }
710
439
  }
@@ -724,7 +453,7 @@ var transformParams = (data) => {
724
453
  return data.map((item) => transformParams(item));
725
454
  }
726
455
  try {
727
- (0, import_graphql8.assertShape)(data, (yup) => yup.object({ _template: yup.string().required() }));
456
+ (0, import_graphql2.assertShape)(data, (yup) => yup.object({ _template: yup.string().required() }));
728
457
  const _a = data, { _template, __typename } = _a, rest = __objRest(_a, ["_template", "__typename"]);
729
458
  const nested = transformParams(rest);
730
459
  return { [_template]: nested };
@@ -755,7 +484,7 @@ function filterObject(obj) {
755
484
  }
756
485
 
757
486
  // src/cmds/audit/index.ts
758
- var import_chalk3 = __toModule(require("chalk"));
487
+ var import_chalk2 = __toModule(require("chalk"));
759
488
  var import_prompts = __toModule(require("prompts"));
760
489
  var import_metrics = __toModule(require("@tinacms/metrics"));
761
490
  var rootPath = process.cwd();
@@ -769,7 +498,7 @@ var audit = async (ctx, next, options) => {
769
498
  }
770
499
  });
771
500
  if (options.clean) {
772
- 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_chalk3.default.bold("clean git tree")} so unwanted changes can be undone.
501
+ 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_chalk2.default.bold("clean git tree")} so unwanted changes can be undone.
773
502
 
774
503
  `);
775
504
  const res = await (0, import_prompts.default)({
@@ -778,16 +507,14 @@ var audit = async (ctx, next, options) => {
778
507
  message: `Do you want to continue?`
779
508
  });
780
509
  if (!res.useClean) {
781
- logger.warn(import_chalk3.default.yellowBright("\u26A0\uFE0F Audit not complete"));
510
+ logger.warn(import_chalk2.default.yellowBright("\u26A0\uFE0F Audit not complete"));
782
511
  process.exit(0);
783
512
  }
784
513
  }
785
514
  if (options.useDefaultValues && !options.clean) {
786
- logger.warn(import_chalk3.default.yellowBright("WARNING: using the `--useDefaultValues` without the `--clean` flag has no effect. Please re-run audit and add the `--clean` flag"));
515
+ logger.warn(import_chalk2.default.yellowBright("WARNING: using the `--useDefaultValues` without the `--clean` flag has no effect. Please re-run audit and add the `--clean` flag"));
787
516
  }
788
- const bridge = options.clean ? new import_datalayer2.FilesystemBridge(rootPath) : new import_datalayer2.AuditFileSystemBridge(rootPath);
789
- const store = options.clean ? new import_datalayer2.FilesystemStore({ rootPath }) : new import_datalayer2.AuditFilesystemStore({ rootPath });
790
- const database = await (0, import_graphql9.createDatabase)({ store, bridge });
517
+ const database = ctx.database;
791
518
  const schema = await database.getSchema();
792
519
  const collections = schema.getCollections();
793
520
  let warning = false;
@@ -815,17 +542,17 @@ var audit = async (ctx, next, options) => {
815
542
  };
816
543
  var printFinalMessage = async (ctx, next, _options) => {
817
544
  if (ctx.error) {
818
- logger.error(import_chalk3.default.redBright(`\u203C\uFE0F Audit ${import_chalk3.default.bold("failed")} with errors`));
545
+ logger.error(import_chalk2.default.redBright(`\u203C\uFE0F Audit ${import_chalk2.default.bold("failed")} with errors`));
819
546
  } else if (ctx.warning) {
820
- logger.warn(import_chalk3.default.yellowBright("\u26A0\uFE0F Audit passed with warnings"));
547
+ logger.warn(import_chalk2.default.yellowBright("\u26A0\uFE0F Audit passed with warnings"));
821
548
  } else {
822
- logger.info(import_chalk3.default.greenBright("\u2705 Audit passed"));
549
+ logger.info(import_chalk2.default.greenBright("\u2705 Audit passed"));
823
550
  }
824
551
  next();
825
552
  };
826
553
 
827
554
  // src/cmds/init/setup-files/index.ts
828
- var import_chalk4 = __toModule(require("chalk"));
555
+ var import_chalk3 = __toModule(require("chalk"));
829
556
  var adminPage = `import { TinaAdmin } from 'tinacms';
830
557
  export default TinaAdmin;
831
558
  `;
@@ -857,65 +584,58 @@ mille rigidi sub taurum.
857
584
 
858
585
 
859
586
  `;
860
- var nextPostPage = () => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
587
+ var nextPostPage = ({
588
+ usingSrc
589
+ }) => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
861
590
  // This is a demo file once you have tina setup feel free to delete this file
862
-
863
- import { staticRequest, gql } from "tinacms";
864
- import Head from "next/head";
865
- import { createGlobalStyle } from "styled-components";
866
- import { useTina } from "tinacms/dist/edit-state";
591
+
592
+ import Head from 'next/head'
593
+ import { createGlobalStyle } from 'styled-components'
594
+ import { useTina } from 'tinacms/dist/edit-state'
867
595
  import { TinaMarkdown } from 'tinacms/dist/rich-text'
868
-
869
- const query = gql\`
870
- query BlogPostQuery($relativePath: String!) {
871
- posts(relativePath: $relativePath) {
872
- title
873
- body
874
- }
875
- }
876
- \`
877
-
596
+ import client from '${usingSrc ? "../" : ""}../../../.tina/__generated__/client'
597
+
878
598
  // Styles for markdown
879
599
  const GlobalStyle = createGlobalStyle\`
880
- h1,h2,h3,h4,h5 {
881
- margin-bottom: 1.5rem;
882
- margin-top: 1.5rem;
883
- }
884
- blockquote {
885
- background-color: rgb(209,250,229);
886
- }
887
- h1 {
888
- font-size: 45px;
889
- }
890
- h2 {
891
- font-size: 35px;
892
- }
893
- h3 {
894
- font-size: 25px;
895
- }
896
- h4 {
897
- font-size: 22px;
898
- }
899
- ul {
900
- padding-left: 0;
901
- }
902
- li {
903
- list-style-type: none;
904
- }
905
- a {
906
- font-weight: bold;
907
- color: rgb(59,130,246);
908
- text-decoration: underline;
909
- }
910
- \`;
911
-
600
+ h1,h2,h3,h4,h5 {
601
+ margin-bottom: 1.5rem;
602
+ margin-top: 1.5rem;
603
+ }
604
+ blockquote {
605
+ background-color: rgb(209,250,229);
606
+ }
607
+ h1 {
608
+ font-size: 45px;
609
+ }
610
+ h2 {
611
+ font-size: 35px;
612
+ }
613
+ h3 {
614
+ font-size: 25px;
615
+ }
616
+ h4 {
617
+ font-size: 22px;
618
+ }
619
+ ul {
620
+ padding-left: 0;
621
+ }
622
+ li {
623
+ list-style-type: none;
624
+ }
625
+ a {
626
+ font-weight: bold;
627
+ color: rgb(59,130,246);
628
+ text-decoration: underline;
629
+ }
630
+ \`
631
+
912
632
  const BlogPage = (props) => {
913
633
  const { data } = useTina({
914
- query,
634
+ query: props.query,
915
635
  variables: props.variables,
916
636
  data: props.data,
917
- });
918
-
637
+ })
638
+
919
639
  return (
920
640
  <>
921
641
  <Head>
@@ -931,15 +651,13 @@ var nextPostPage = () => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
931
651
  <div>
932
652
  <div
933
653
  style={{
934
- textAlign: "center",
654
+ textAlign: 'center',
935
655
  }}
936
656
  >
937
657
  <h1 className="text-3xl m-8 text-center leading-8 font-extrabold tracking-tight text-gray-900 sm:text-4xl">
938
- {data.posts.title}
658
+ {data.post.title}
939
659
  </h1>
940
- <ContentSection
941
- content={data.posts.body}
942
- ></ContentSection>
660
+ <ContentSection content={data.post.body}></ContentSection>
943
661
  </div>
944
662
  <div className="bg-green-100 text-center">
945
663
  Lost and looking for a place to start?
@@ -947,79 +665,65 @@ var nextPostPage = () => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
947
665
  href="https://tina.io/guides/tina-cloud/getting-started/overview/"
948
666
  className="text-blue-500 underline"
949
667
  >
950
- {" "}
668
+ {' '}
951
669
  Check out this guide
952
- </a>{" "}
670
+ </a>{' '}
953
671
  to see how add TinaCMS to an existing Next.js site.
954
672
  </div>
955
673
  </div>
956
674
  </>
957
- );
958
- };
959
-
675
+ )
676
+ }
677
+
960
678
  export const getStaticProps = async ({ params }) => {
961
- const variables = { relativePath: \`\${params.filename}.md\` }
962
679
  let data = {}
680
+ let query = {}
681
+ let variables = { relativePath: \`\${params.filename}.mdx\` }
963
682
  try {
964
- data = await staticRequest({
965
- query,
966
- variables,
967
- })
683
+ const res = await client.queries.post(variables)
684
+ query = res.query
685
+ data = res.data
686
+ variables = res.variables
968
687
  } catch {
969
688
  // swallow errors related to document creation
970
689
  }
971
-
690
+
972
691
  return {
973
692
  props: {
974
- variables,
975
- data,
976
- //myOtherProp: 'some-other-data',
977
- },
978
- }
979
- };
980
-
981
- export const getStaticPaths = async () => {
982
- const postsListData = (await staticRequest({
983
- query: gql\`
984
- query GetPostsList {
985
- postsConnection {
986
- edges {
987
- node {
988
- ...on Document {
989
- _sys {
990
- filename
991
- }
992
- }
993
- }
994
- }
995
- }
996
- }
997
- \`,
998
- }));
999
-
693
+ variables: variables,
694
+ data: data,
695
+ query: query,
696
+ //myOtherProp: 'some-other-data',
697
+ },
698
+ }
699
+ }
700
+
701
+ export const getStaticPaths = async () => {
702
+ const postsListData = await client.queries.postConnection()
703
+
1000
704
  return {
1001
- paths: postsListData.postsConnection.edges.map((post) => ({
705
+ paths: postsListData.data.postConnection.edges.map((post) => ({
1002
706
  params: { filename: post.node._sys.filename },
1003
707
  })),
1004
708
  fallback: false,
1005
- };
1006
- };
1007
-
1008
- export default BlogPage;
1009
-
1010
- const PageSection = props => {
709
+ }
710
+ }
711
+
712
+ export default BlogPage
713
+
714
+ const PageSection = (props) => {
1011
715
  return (
1012
716
  <>
1013
- <h2>{ props.heading }</h2>
1014
- <p>{ props.content }</p>
717
+ <h2>{props.heading}</h2>
718
+ <p>{props.content}</p>
1015
719
  </>
1016
720
  )
1017
721
  }
1018
-
722
+
1019
723
  const components = {
1020
724
  PageSection: PageSection,
1021
725
  }
1022
-
726
+
1023
727
  const ContentSection = ({ content }) => {
1024
728
  return (
1025
729
  <div className="relative py-16 bg-white overflow-hidden">
@@ -1128,15 +832,13 @@ var nextPostPage = () => `// THIS FILE HAS BEEN GENERATED WITH THE TINA CLI.
1128
832
  </div>
1129
833
  <div className="relative px-4 sm:px-6 lg:px-8">
1130
834
  <div className="text-lg max-w-prose mx-auto">
1131
- <TinaMarkdown components={components} content={content}/>
835
+ <TinaMarkdown components={components} content={content} />
1132
836
  <GlobalStyle />
1133
837
  </div>
1134
838
  </div>
1135
839
  </div>
1136
- );
1137
- };
1138
-
1139
- `;
840
+ )
841
+ }`;
1140
842
  var AppJsContent = (usingSrc, extraImports) => {
1141
843
  const importLine = `import Tina from '${usingSrc ? "../" : ""}../.tina/components/TinaDynamicProvider.js'`;
1142
844
  return `${importLine}
@@ -1154,15 +856,15 @@ export default App
1154
856
  `;
1155
857
  };
1156
858
  var AppJsContentPrintout = (usingSrc, extraImports) => {
1157
- const importLine = import_chalk4.default.green(`+ import Tina from '${usingSrc ? "../" : ""}../.tina/components/TinaDynamicProvider.js'`);
859
+ const importLine = import_chalk3.default.green(`+ import Tina from '${usingSrc ? "../" : ""}../.tina/components/TinaDynamicProvider.js'`);
1158
860
  return `${importLine}
1159
861
  ${extraImports || ""}
1160
862
 
1161
863
  const App = ({ Component, pageProps }) => {
1162
864
  return (
1163
- ${import_chalk4.default.green("+ <Tina>")}
865
+ ${import_chalk3.default.green("+ <Tina>")}
1164
866
  <Component {...pageProps} />
1165
- ${import_chalk4.default.green("+ </Tina>")}
867
+ ${import_chalk3.default.green("+ </Tina>")}
1166
868
  )
1167
869
  }
1168
870
 
@@ -1203,24 +905,35 @@ const DynamicTina = ({ children }) => {
1203
905
  export default DynamicTina
1204
906
  `;
1205
907
 
908
+ // src/utils/theme.ts
909
+ var import_chalk4 = __toModule(require("chalk"));
910
+ var successText = import_chalk4.default.bold.green;
911
+ var dangerText = import_chalk4.default.bold.red;
912
+ var neutralText = import_chalk4.default.bold.cyan;
913
+ var labelText = import_chalk4.default.bold;
914
+ var cmdText = import_chalk4.default.inverse;
915
+ var logText = import_chalk4.default.italic.gray;
916
+ var warnText = import_chalk4.default.yellowBright.bgBlack;
917
+ var CONFIRMATION_TEXT = import_chalk4.default.dim("enter to confirm");
918
+
1206
919
  // src/utils/script-helpers.ts
1207
920
  function generateGqlScript(scriptValue) {
1208
- return `tinacms server:start -c "${scriptValue}"`;
921
+ return `tinacms dev -c "${scriptValue}"`;
1209
922
  }
1210
923
  function extendNextScripts(scripts) {
1211
924
  return __spreadProps(__spreadValues({}, scripts), {
1212
- dev: generateGqlScript(scripts.dev || "next dev"),
1213
- build: generateGqlScript(scripts.build || "next build"),
1214
- start: generateGqlScript(scripts.start || "next start")
925
+ dev: generateGqlScript((scripts == null ? void 0 : scripts.dev) || "next dev"),
926
+ build: `tinacms build && ${(scripts == null ? void 0 : scripts.build) || "next build"}`,
927
+ start: `tinacms build && ${(scripts == null ? void 0 : scripts.start) || "next start"}`
1215
928
  });
1216
929
  }
1217
930
 
1218
931
  // src/cmds/init/index.ts
1219
- var import_fs_extra2 = __toModule(require("fs-extra"));
932
+ var import_fs_extra = __toModule(require("fs-extra"));
1220
933
  var import_progress = __toModule(require("progress"));
1221
934
  var import_metrics2 = __toModule(require("@tinacms/metrics"));
1222
935
  var import_chalk5 = __toModule(require("chalk"));
1223
- var import_path3 = __toModule(require("path"));
936
+ var import_path2 = __toModule(require("path"));
1224
937
  var import_prompts2 = __toModule(require("prompts"));
1225
938
  function execShellCommand(cmd) {
1226
939
  const exec = require("child_process").exec;
@@ -1247,7 +960,10 @@ async function initTina(ctx, next, options) {
1247
960
  var MIN_REACT_VERSION = ">=16.14.0";
1248
961
  async function checkDeps(ctx, next, options) {
1249
962
  const bar = new import_progress.default("Checking dependencies. :prog", 1);
1250
- const packageJSON = JSON.parse((await import_fs_extra2.default.readFileSync(packageJSONPath)).toString());
963
+ if (!import_fs_extra.default.existsSync(packageJSONPath)) {
964
+ throw new Error("No package.json Found. Please run tinacms init at the root of your app");
965
+ }
966
+ const packageJSON = JSON.parse((await import_fs_extra.default.readFileSync(packageJSONPath)).toString());
1251
967
  if (!checkPackage(packageJSON, "react") || !checkPackage(packageJSON, "react-dom")) {
1252
968
  const message = `Unable to initialize Tina due to outdated dependencies, try upgrading the following packages:
1253
969
  "react@${MIN_REACT_VERSION}"
@@ -1269,6 +985,9 @@ var checkPackage = (packageJSON, packageName) => {
1269
985
  strippedVersion = version2.replace(/^[^a-zA-Z0-9]*|[^a-zA-Z0-9]*$/g, "");
1270
986
  }
1271
987
  });
988
+ if (!strippedVersion) {
989
+ throw new Error(`Please add ${packageName} to your project`);
990
+ }
1272
991
  return checkVersion(strippedVersion);
1273
992
  };
1274
993
  var checkVersion = (version2) => {
@@ -1313,33 +1032,33 @@ async function installDeps(ctx, next, options) {
1313
1032
  next();
1314
1033
  }
1315
1034
  var baseDir = process.cwd();
1316
- var packageJSONPath = import_path3.default.join(baseDir, "package.json");
1317
- var blogContentPath = import_path3.default.join(baseDir, "content", "posts");
1318
- var blogPostPath = import_path3.default.join(blogContentPath, "HelloWorld.md");
1319
- var TinaFolder = import_path3.default.join(baseDir, ".tina");
1320
- var componentFolder = import_path3.default.join(TinaFolder, "components");
1321
- var TinaProviderPath = import_path3.default.join(componentFolder, "TinaProvider.js");
1322
- var TinaDynamicProvider = import_path3.default.join(componentFolder, "TinaDynamicProvider.js");
1035
+ var packageJSONPath = import_path2.default.join(baseDir, "package.json");
1036
+ var blogContentPath = import_path2.default.join(baseDir, "content", "posts");
1037
+ var blogPostPath = import_path2.default.join(blogContentPath, "HelloWorld.mdx");
1038
+ var TinaFolder = import_path2.default.join(baseDir, ".tina");
1039
+ var componentFolder = import_path2.default.join(TinaFolder, "components");
1040
+ var TinaProviderPath = import_path2.default.join(componentFolder, "TinaProvider.js");
1041
+ var TinaDynamicProvider = import_path2.default.join(componentFolder, "TinaDynamicProvider.js");
1323
1042
  async function tinaSetup(_ctx, next, _options) {
1324
- const usingSrc = !import_fs_extra2.default.pathExistsSync(import_path3.default.join(baseDir, "pages"));
1325
- if (!import_fs_extra2.default.pathExistsSync(blogPostPath)) {
1043
+ const usingSrc = !import_fs_extra.default.pathExistsSync(import_path2.default.join(baseDir, "pages"));
1044
+ if (!import_fs_extra.default.pathExistsSync(blogPostPath)) {
1326
1045
  logger.info(logText("Adding a content folder..."));
1327
- import_fs_extra2.default.mkdirpSync(blogContentPath);
1328
- import_fs_extra2.default.writeFileSync(blogPostPath, blogPost);
1046
+ import_fs_extra.default.mkdirpSync(blogContentPath);
1047
+ import_fs_extra.default.writeFileSync(blogPostPath, blogPost);
1329
1048
  }
1330
- if (!import_fs_extra2.default.existsSync(TinaProviderPath) && !import_fs_extra2.default.existsSync(TinaDynamicProvider)) {
1331
- import_fs_extra2.default.mkdirpSync(componentFolder);
1332
- import_fs_extra2.default.writeFileSync(TinaProviderPath, TinaProvider.replace(/'\.\.\/schema\.ts'/, `'../schema.${_ctx.schemaFileType || "ts"}'`));
1333
- import_fs_extra2.default.writeFileSync(TinaDynamicProvider, TinaProviderDynamic);
1049
+ if (!import_fs_extra.default.existsSync(TinaProviderPath) && !import_fs_extra.default.existsSync(TinaDynamicProvider)) {
1050
+ import_fs_extra.default.mkdirpSync(componentFolder);
1051
+ import_fs_extra.default.writeFileSync(TinaProviderPath, TinaProvider.replace(/'\.\.\/schema\.ts'/, `'../schema.${_ctx.schemaFileType || "ts"}'`));
1052
+ import_fs_extra.default.writeFileSync(TinaDynamicProvider, TinaProviderDynamic);
1334
1053
  }
1335
1054
  logger.level = "info";
1336
- const pagesPath = import_path3.default.join(baseDir, usingSrc ? "src" : "", "pages");
1337
- const appPath = import_path3.default.join(pagesPath, "_app.js");
1338
- const appPathTS = import_path3.default.join(pagesPath, "_app.tsx");
1339
- const appExtension = import_fs_extra2.default.existsSync(appPath) ? ".js" : ".tsx";
1340
- if (!import_fs_extra2.default.pathExistsSync(appPath) && !import_fs_extra2.default.pathExistsSync(appPathTS)) {
1055
+ const pagesPath = import_path2.default.join(baseDir, usingSrc ? "src" : "", "pages");
1056
+ const appPath = import_path2.default.join(pagesPath, "_app.js");
1057
+ const appPathTS = import_path2.default.join(pagesPath, "_app.tsx");
1058
+ const appExtension = import_fs_extra.default.existsSync(appPath) ? ".js" : ".tsx";
1059
+ if (!import_fs_extra.default.pathExistsSync(appPath) && !import_fs_extra.default.pathExistsSync(appPathTS)) {
1341
1060
  logger.info(logText("Adding _app.js ... \u2705"));
1342
- import_fs_extra2.default.writeFileSync(appPath, AppJsContent(usingSrc));
1061
+ import_fs_extra.default.writeFileSync(appPath, AppJsContent(usingSrc));
1343
1062
  } else {
1344
1063
  const override = await (0, import_prompts2.default)({
1345
1064
  name: "res",
@@ -1349,40 +1068,43 @@ async function tinaSetup(_ctx, next, _options) {
1349
1068
  _ctx.overrideApp = override.res;
1350
1069
  if (override.res) {
1351
1070
  logger.info(logText(`Adding _app${appExtension} ... \u2705`));
1352
- const appPathWithExtension = import_path3.default.join(pagesPath, `_app${appExtension}`);
1353
- const fileContent = import_fs_extra2.default.pathExistsSync(appPath) ? (0, import_fs_extra2.readFileSync)(appPath) : (0, import_fs_extra2.readFileSync)(appPathTS);
1071
+ const appPathWithExtension = import_path2.default.join(pagesPath, `_app${appExtension}`);
1072
+ const fileContent = import_fs_extra.default.pathExistsSync(appPath) ? (0, import_fs_extra.readFileSync)(appPath) : (0, import_fs_extra.readFileSync)(appPathTS);
1354
1073
  const matches = [
1355
1074
  ...fileContent.toString().matchAll(/^.*import.*\.css("|').*$/gm)
1356
1075
  ];
1357
1076
  const primaryMatches = matches.map((x) => x[0]);
1358
- import_fs_extra2.default.writeFileSync(appPathWithExtension, AppJsContent(usingSrc, primaryMatches.join("\n")));
1077
+ import_fs_extra.default.writeFileSync(appPathWithExtension, AppJsContent(usingSrc, primaryMatches.join("\n")));
1359
1078
  }
1360
1079
  }
1361
- const tinaBlogPagePath = import_path3.default.join(pagesPath, "demo", "blog");
1362
- const tinaBlogPagePathFile = import_path3.default.join(tinaBlogPagePath, "[filename].js");
1363
- if (!import_fs_extra2.default.pathExistsSync(tinaBlogPagePathFile)) {
1364
- import_fs_extra2.default.mkdirpSync(tinaBlogPagePath);
1365
- import_fs_extra2.default.writeFileSync(tinaBlogPagePathFile, nextPostPage());
1080
+ const tinaBlogPagePath = import_path2.default.join(pagesPath, "demo", "blog");
1081
+ const tinaBlogPagePathFile = import_path2.default.join(tinaBlogPagePath, "[filename].js");
1082
+ if (!import_fs_extra.default.pathExistsSync(tinaBlogPagePathFile)) {
1083
+ import_fs_extra.default.mkdirpSync(tinaBlogPagePath);
1084
+ import_fs_extra.default.writeFileSync(tinaBlogPagePathFile, nextPostPage({ usingSrc }));
1366
1085
  }
1367
1086
  logger.info("Adding a content folder... \u2705");
1368
- const packagePath = import_path3.default.join(baseDir, "package.json");
1369
- const pack = JSON.parse((0, import_fs_extra2.readFileSync)(packagePath).toString());
1370
- const oldScripts = pack.scripts || {};
1371
- const newPack = JSON.stringify(__spreadProps(__spreadValues({}, pack), {
1372
- scripts: extendNextScripts(oldScripts)
1373
- }), null, 2);
1374
- (0, import_fs_extra2.writeFileSync)(packagePath, newPack);
1375
- const adminPath = import_path3.default.join(pagesPath, "admin.js");
1376
- if (import_fs_extra2.default.pathExistsSync(import_path3.default.join(pagesPath, "admin"))) {
1087
+ if (!import_fs_extra.default.existsSync(packageJSONPath)) {
1088
+ throw new Error("No package.json Found. Please run tinacms init at the root of your app");
1089
+ } else {
1090
+ const pack = JSON.parse((0, import_fs_extra.readFileSync)(packageJSONPath).toString());
1091
+ const oldScripts = pack.scripts || {};
1092
+ const newPack = JSON.stringify(__spreadProps(__spreadValues({}, pack), {
1093
+ scripts: extendNextScripts(oldScripts)
1094
+ }), null, 2);
1095
+ (0, import_fs_extra.writeFileSync)(packageJSONPath, newPack);
1096
+ }
1097
+ const adminPath = import_path2.default.join(pagesPath, "admin.js");
1098
+ if (import_fs_extra.default.pathExistsSync(import_path2.default.join(pagesPath, "admin"))) {
1377
1099
  logger.warn(`Unable to add /pages/admin.js, this path already exists.
1378
1100
  Learn more about toggling edit-mode at https://tina.io/docs/tinacms-context/#manually-toggling-edit-mode`);
1379
1101
  return next();
1380
1102
  }
1381
- (0, import_fs_extra2.outputFileSync)(adminPath, adminPage);
1103
+ (0, import_fs_extra.outputFileSync)(adminPath, adminPage);
1382
1104
  next();
1383
1105
  }
1384
1106
  async function successMessage(ctx, next, options) {
1385
- const usingSrc = import_fs_extra2.default.pathExistsSync(import_path3.default.join(baseDir, "src"));
1107
+ const usingSrc = import_fs_extra.default.pathExistsSync(import_path2.default.join(baseDir, "src"));
1386
1108
  logger.info(`Tina setup ${import_chalk5.default.underline.green("done")} \u2705
1387
1109
  `);
1388
1110
  logger.info("Next Steps: \n");
@@ -1431,7 +1153,7 @@ var chain = async (cmds, options) => {
1431
1153
  var import_chalk7 = __toModule(require("chalk"));
1432
1154
 
1433
1155
  // src/cmds/start-server/errors/index.ts
1434
- var import_graphql10 = __toModule(require("@tinacms/graphql"));
1156
+ var import_graphql3 = __toModule(require("@tinacms/graphql"));
1435
1157
  var BuildSchemaError = class extends Error {
1436
1158
  constructor(message) {
1437
1159
  super(message);
@@ -1457,8 +1179,8 @@ var handleServerErrors = (e) => {
1457
1179
  logger.error(`${dangerText("ERROR: your schema was not successfully validated: see https://tina.io/docs/schema/ for instructions on how to setup a schema")}
1458
1180
  Error Message Below
1459
1181
  ${e}`);
1460
- } else if (e instanceof import_graphql10.TinaFetchError) {
1461
- (0, import_graphql10.handleFetchErrorError)(e, true);
1182
+ } else if (e instanceof import_graphql3.TinaFetchError) {
1183
+ (0, import_graphql3.handleFetchErrorError)(e, true);
1462
1184
  } else {
1463
1185
  logger.info(dangerText("Compilation failed with errors. Server has not been restarted.") + ` see error below
1464
1186
  ${e.message}`);
@@ -1466,72 +1188,78 @@ var handleServerErrors = (e) => {
1466
1188
  };
1467
1189
 
1468
1190
  // src/cmds/compile/index.ts
1469
- var import_fs_extra4 = __toModule(require("fs-extra"));
1470
- var import_path5 = __toModule(require("path"));
1191
+ var import_fs_extra3 = __toModule(require("fs-extra"));
1192
+ var import_path4 = __toModule(require("path"));
1471
1193
  var import_esbuild = __toModule(require("esbuild"));
1472
1194
 
1473
1195
  // src/cmds/compile/defaultSchema.ts
1474
1196
  var defaultSchema = `
1475
- import { defineSchema, defineConfig } from "tinacms";
1197
+ import { defineSchema, defineConfig } from 'tinacms'
1198
+ import { client } from './__generated__/client'
1199
+
1476
1200
 
1201
+ const branch =
1202
+ process.env.NEXT_PUBLIC_TINA_BRANCH ||
1203
+ process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_REF ||
1204
+ process.env.HEAD ||
1205
+ 'main'
1477
1206
  const schema = defineSchema({
1207
+ // See https://tina.io/docs/tina-cloud/connecting-site/ for more information about this config
1208
+ config: {
1209
+ token: '<Your Read Only Token>', // generated on app.tina.io,
1210
+ clientId: '<Your Client ID>', // generated on app.tina.io
1211
+ branch,
1212
+ },
1478
1213
  collections: [
1479
1214
  {
1480
- label: "Blog Posts",
1481
- name: "posts",
1482
- path: "content/posts",
1215
+ label: 'Blog Posts',
1216
+ name: 'post',
1217
+ path: 'content/posts',
1218
+ format: 'mdx',
1483
1219
  fields: [
1484
1220
  {
1485
- type: "string",
1486
- label: "Title",
1487
- name: "title",
1221
+ type: 'string',
1222
+ label: 'Title',
1223
+ name: 'title',
1488
1224
  },
1489
1225
  {
1490
- type: "rich-text",
1491
- label: "Blog Post Body",
1492
- name: "body",
1226
+ type: 'rich-text',
1227
+ label: 'Blog Post Body',
1228
+ name: 'body',
1493
1229
  isBody: true,
1494
1230
  templates: [
1495
1231
  {
1496
- name: "PageSection",
1497
- label: "Page Section",
1232
+ name: 'PageSection',
1233
+ label: 'Page Section',
1498
1234
  fields: [
1499
1235
  {
1500
- type: "string",
1501
- name: "heading",
1502
- label: "Heading",
1236
+ type: 'string',
1237
+ name: 'heading',
1238
+ label: 'Heading',
1503
1239
  },
1504
1240
  {
1505
- type: "string",
1506
- name: "content",
1507
- label: "Content",
1241
+ type: 'string',
1242
+ name: 'content',
1243
+ label: 'Content',
1508
1244
  ui: {
1509
- component: "textarea"
1510
- }
1511
- }
1245
+ component: 'textarea',
1246
+ },
1247
+ },
1512
1248
  ],
1513
1249
  },
1514
- ]
1250
+ ],
1515
1251
  },
1516
1252
  ],
1517
1253
  },
1518
1254
  ],
1519
- });
1255
+ })
1520
1256
 
1521
1257
  export default schema
1522
1258
 
1523
1259
  // Your tina config
1524
- // ==============
1525
- const branch = 'main'
1526
- // When working locally, hit our local filesystem.
1527
- // On a Vercel deployment, hit the Tina Cloud API
1528
- const apiURL =
1529
- process.env.NODE_ENV == 'development'
1530
- ? 'http://localhost:4001/graphql'
1531
- : \`https://content.tinajs.io/content/\${process.env.NEXT_PUBLIC_TINA_CLIENT_ID}/github/\${branch}\`
1532
1260
 
1533
1261
  export const tinaConfig = defineConfig({
1534
- apiURL,
1262
+ client,
1535
1263
  schema,
1536
1264
  cmsCallback: (cms) => {
1537
1265
  // add your CMS callback code here (if you want)
@@ -1540,41 +1268,42 @@ export const tinaConfig = defineConfig({
1540
1268
  /**
1541
1269
  * 1. Import \`tinacms\` and \`RouteMappingPlugin\`
1542
1270
  **/
1543
- import("tinacms").then(({ RouteMappingPlugin }) => {
1271
+ import('tinacms').then(({ RouteMappingPlugin }) => {
1544
1272
  /**
1545
1273
  * 2. Define the \`RouteMappingPlugin\` see https://tina.io/docs/tinacms-context/#the-routemappingplugin for more details
1546
1274
  **/
1547
1275
  const RouteMapping = new RouteMappingPlugin((collection, document) => {
1548
- return undefined;
1549
- });
1276
+ return undefined
1277
+ })
1550
1278
  /**
1551
1279
  * 3. Add the \`RouteMappingPlugin\` to the \`cms\`.
1552
1280
  **/
1553
- cms.plugins.add(RouteMapping);
1554
- });
1281
+ cms.plugins.add(RouteMapping)
1282
+ })
1555
1283
 
1556
- return cms;
1284
+ return cms
1557
1285
  },
1558
- });
1286
+ })
1287
+
1559
1288
  `;
1560
1289
 
1561
1290
  // src/lib/getPath.ts
1562
- var import_path4 = __toModule(require("path"));
1563
- var import_fs_extra3 = __toModule(require("fs-extra"));
1291
+ var import_path3 = __toModule(require("path"));
1292
+ var import_fs_extra2 = __toModule(require("fs-extra"));
1564
1293
  var getPath = ({
1565
1294
  projectDir,
1566
1295
  filename,
1567
1296
  allowedTypes,
1568
1297
  errorMessage
1569
1298
  }) => {
1570
- if (!import_fs_extra3.default.existsSync(projectDir)) {
1299
+ if (!import_fs_extra2.default.existsSync(projectDir)) {
1571
1300
  throw new Error(errorMessage);
1572
1301
  }
1573
- const filePaths = allowedTypes.map((ext) => import_path4.default.join(projectDir, `${filename}.${ext}`));
1302
+ const filePaths = allowedTypes.map((ext) => import_path3.default.join(projectDir, `${filename}.${ext}`));
1574
1303
  let inputFile = void 0;
1575
- filePaths.every((path4) => {
1576
- if (import_fs_extra3.default.existsSync(path4)) {
1577
- inputFile = path4;
1304
+ filePaths.every((path7) => {
1305
+ if (import_fs_extra2.default.existsSync(path7)) {
1306
+ inputFile = path7;
1578
1307
  return false;
1579
1308
  }
1580
1309
  return true;
@@ -1598,29 +1327,46 @@ var getClientPath = ({ projectDir }) => {
1598
1327
  };
1599
1328
 
1600
1329
  // src/cmds/compile/index.ts
1601
- var tinaPath = import_path5.default.join(process.cwd(), ".tina");
1602
- var packageJSONFilePath = import_path5.default.join(process.cwd(), "package.json");
1603
- var tinaGeneratedPath = import_path5.default.join(tinaPath, "__generated__");
1604
- var tinaConfigPath = import_path5.default.join(tinaGeneratedPath, "config");
1605
- var resetGeneratedFolder = async () => {
1330
+ var resetGeneratedFolder = async ({
1331
+ tinaGeneratedPath,
1332
+ usingTs
1333
+ }) => {
1606
1334
  try {
1607
- await import_fs_extra4.default.rm(tinaGeneratedPath, {
1608
- recursive: true
1609
- });
1335
+ await import_fs_extra3.default.emptyDir(tinaGeneratedPath);
1610
1336
  } catch (e) {
1611
1337
  console.log(e);
1612
1338
  }
1613
- await import_fs_extra4.default.mkdir(tinaGeneratedPath);
1614
- await import_fs_extra4.default.writeFile(import_path5.default.join(tinaGeneratedPath, "types.ts"), `
1339
+ await import_fs_extra3.default.mkdirp(tinaGeneratedPath);
1340
+ const ext = usingTs ? "ts" : "js";
1341
+ await import_fs_extra3.default.writeFile(import_path4.default.join(tinaGeneratedPath, `types.${ext}`), `
1615
1342
  export const queries = (client)=>({})
1616
1343
  `);
1617
- await import_fs_extra4.default.outputFile(import_path5.default.join(tinaGeneratedPath, ".gitignore"), "db");
1344
+ await import_fs_extra3.default.writeFile(import_path4.default.join(tinaGeneratedPath, `client.${ext}`), `
1345
+ export const client = {}
1346
+ `);
1347
+ await import_fs_extra3.default.outputFile(import_path4.default.join(tinaGeneratedPath, ".gitignore"), `db
1348
+ client.ts
1349
+ client.js
1350
+ types.ts
1351
+ types.js
1352
+ types.d.ts
1353
+ frags.gql
1354
+ queries.gql
1355
+ schema.gql
1356
+ `);
1618
1357
  };
1619
1358
  var cleanup = async ({ tinaTempPath }) => {
1620
- await import_fs_extra4.default.remove(tinaTempPath);
1359
+ await import_fs_extra3.default.remove(tinaTempPath);
1621
1360
  };
1622
1361
  var compileClient = async (ctx, next, options) => {
1623
- const tinaTempPath = import_path5.default.join(tinaGeneratedPath, "temp_client");
1362
+ const root2 = ctx.rootPath;
1363
+ if (!root2) {
1364
+ throw new Error("ctx.rootPath has not been attached");
1365
+ }
1366
+ const tinaPath = import_path4.default.join(root2, ".tina");
1367
+ const tinaGeneratedPath = import_path4.default.join(tinaPath, "__generated__");
1368
+ const packageJSONFilePath = import_path4.default.join(root2, "package.json");
1369
+ const tinaTempPath = import_path4.default.join(tinaGeneratedPath, "temp_client");
1624
1370
  if (!options.clientFileType)
1625
1371
  options = __spreadProps(__spreadValues({}, options), { clientFileType: "ts" });
1626
1372
  if (options.verbose) {
@@ -1635,8 +1381,9 @@ var compileClient = async (ctx, next, options) => {
1635
1381
  ctx.clientFileType = requestedClientFileType;
1636
1382
  }
1637
1383
  let clientExists = true;
1384
+ const projectDir = import_path4.default.join(tinaPath, "__generated__");
1638
1385
  try {
1639
- getClientPath({ projectDir: tinaPath });
1386
+ getClientPath({ projectDir });
1640
1387
  } catch {
1641
1388
  clientExists = false;
1642
1389
  }
@@ -1651,8 +1398,10 @@ var compileClient = async (ctx, next, options) => {
1651
1398
  if (!process.env.NODE_ENV) {
1652
1399
  define["process.env.NODE_ENV"] = options.dev ? '"development"' : '"production"';
1653
1400
  }
1654
- const inputFile = getClientPath({ projectDir: tinaPath });
1655
- await transpile(inputFile, "client.js", tinaTempPath, options.verbose, define);
1401
+ const inputFile = getClientPath({
1402
+ projectDir
1403
+ });
1404
+ await transpile(inputFile, "client.js", tinaTempPath, options.verbose, define, packageJSONFilePath);
1656
1405
  } catch (e) {
1657
1406
  await cleanup({ tinaTempPath });
1658
1407
  throw new BuildSchemaError(e);
@@ -1663,7 +1412,7 @@ var compileClient = async (ctx, next, options) => {
1663
1412
  }
1664
1413
  });
1665
1414
  try {
1666
- const clientFunc = require(import_path5.default.join(tinaTempPath, "client.js"));
1415
+ const clientFunc = require(import_path4.default.join(tinaTempPath, "client.js"));
1667
1416
  const client = clientFunc.default;
1668
1417
  ctx.client = client;
1669
1418
  await cleanup({ tinaTempPath });
@@ -1678,10 +1427,21 @@ var compileClient = async (ctx, next, options) => {
1678
1427
  }
1679
1428
  return next();
1680
1429
  };
1681
- var compileSchema = async (_ctx, _next, options) => {
1682
- const tinaTempPath = import_path5.default.join(tinaGeneratedPath, "temp_schema");
1683
- if (!options.schemaFileType)
1684
- options = __spreadProps(__spreadValues({}, options), { schemaFileType: "ts" });
1430
+ var compileSchema = async (ctx, _next, options) => {
1431
+ const root2 = ctx.rootPath;
1432
+ if (!root2) {
1433
+ throw new Error("ctx.rootPath has not been attached");
1434
+ }
1435
+ const tinaPath = import_path4.default.join(root2, ".tina");
1436
+ const tsConfigPath = import_path4.default.join(root2, "tsconfig.json");
1437
+ const tinaGeneratedPath = import_path4.default.join(tinaPath, "__generated__");
1438
+ const tinaTempPath = import_path4.default.join(tinaGeneratedPath, "temp_schema");
1439
+ const tinaConfigPath = import_path4.default.join(tinaGeneratedPath, "config");
1440
+ const packageJSONFilePath = import_path4.default.join(root2, "package.json");
1441
+ if (!options.schemaFileType) {
1442
+ const usingTs = await import_fs_extra3.default.pathExists(tsConfigPath);
1443
+ options = __spreadProps(__spreadValues({}, options), { schemaFileType: usingTs ? "ts" : "js" });
1444
+ }
1685
1445
  if (options.verbose) {
1686
1446
  logger.info(logText("Compiling Schema..."));
1687
1447
  }
@@ -1690,8 +1450,8 @@ var compileSchema = async (_ctx, _next, options) => {
1690
1450
  if (!schemaFileType2) {
1691
1451
  throw new Error(`Requested schema file type '${requestedSchemaFileType}' is not valid. Supported schema file types: 'ts, js, tsx, jsx'`);
1692
1452
  }
1693
- if (_ctx) {
1694
- _ctx.schemaFileType = schemaFileType2;
1453
+ if (ctx) {
1454
+ ctx.schemaFileType = schemaFileType2;
1695
1455
  }
1696
1456
  let schemaExists = true;
1697
1457
  try {
@@ -1704,9 +1464,9 @@ var compileSchema = async (_ctx, _next, options) => {
1704
1464
  .tina/schema.${schemaFileType2} not found, Creating one for you...
1705
1465
  See Documentation: https://tina.io/docs/tina-cloud/cli/#getting-started"
1706
1466
  `));
1707
- const file = import_path5.default.join(tinaPath, `schema.${schemaFileType2}`);
1708
- await import_fs_extra4.default.ensureFile(file);
1709
- await import_fs_extra4.default.writeFile(file, defaultSchema);
1467
+ const file = import_path4.default.join(tinaPath, `schema.${schemaFileType2}`);
1468
+ await import_fs_extra3.default.ensureFile(file);
1469
+ await import_fs_extra3.default.writeFile(file, defaultSchema);
1710
1470
  }
1711
1471
  try {
1712
1472
  const define = {};
@@ -1714,7 +1474,7 @@ var compileSchema = async (_ctx, _next, options) => {
1714
1474
  define["process.env.NODE_ENV"] = options.dev ? '"development"' : '"production"';
1715
1475
  }
1716
1476
  const inputFile = getSchemaPath({ projectDir: tinaPath });
1717
- await transpile(inputFile, "schema.js", tinaTempPath, options.verbose, define);
1477
+ await transpile(inputFile, "schema.js", tinaTempPath, options.verbose, define, packageJSONFilePath);
1718
1478
  } catch (e) {
1719
1479
  await cleanup({ tinaTempPath });
1720
1480
  throw new BuildSchemaError(e);
@@ -1725,104 +1485,376 @@ var compileSchema = async (_ctx, _next, options) => {
1725
1485
  }
1726
1486
  });
1727
1487
  try {
1728
- const schemaFunc = require(import_path5.default.join(tinaTempPath, "schema.js"));
1729
- const schemaObject = schemaFunc.default;
1730
- await import_fs_extra4.default.outputFile(import_path5.default.join(tinaConfigPath, "schema.json"), JSON.stringify(schemaObject, null, 2));
1731
- await cleanup({ tinaTempPath });
1732
- } catch (e) {
1733
- await cleanup({ tinaTempPath });
1734
- if (e instanceof Error) {
1735
- if (e.name === "TinaSchemaValidationError") {
1736
- throw e;
1488
+ const schemaFunc = require(import_path4.default.join(tinaTempPath, "schema.js"));
1489
+ const schemaObject = schemaFunc.default;
1490
+ ctx.schema = schemaObject;
1491
+ await import_fs_extra3.default.outputFile(import_path4.default.join(tinaConfigPath, "schema.json"), JSON.stringify(schemaObject, null, 2));
1492
+ await cleanup({ tinaTempPath });
1493
+ } catch (e) {
1494
+ await cleanup({ tinaTempPath });
1495
+ if (e instanceof Error) {
1496
+ if (e.name === "TinaSchemaValidationError") {
1497
+ throw e;
1498
+ }
1499
+ }
1500
+ throw new ExecuteSchemaError(e);
1501
+ }
1502
+ };
1503
+ var transpile = async (inputFile, outputFile, tempDir, verbose, define, packageJSONFilePath) => {
1504
+ if (verbose)
1505
+ logger.info(logText("Building javascript..."));
1506
+ const packageJSON = JSON.parse(import_fs_extra3.default.readFileSync(packageJSONFilePath).toString() || "{}");
1507
+ const deps = (packageJSON == null ? void 0 : packageJSON.dependencies) || [];
1508
+ const peerDeps = (packageJSON == null ? void 0 : packageJSON.peerDependencies) || [];
1509
+ const devDeps = (packageJSON == null ? void 0 : packageJSON.devDependencies) || [];
1510
+ const external = Object.keys(__spreadValues(__spreadValues(__spreadValues({}, deps), peerDeps), devDeps));
1511
+ const outputPath = import_path4.default.join(tempDir, outputFile);
1512
+ await (0, import_esbuild.build)({
1513
+ bundle: true,
1514
+ platform: "neutral",
1515
+ target: ["node10.4"],
1516
+ entryPoints: [inputFile],
1517
+ treeShaking: true,
1518
+ external: [...external, "./node_modules/*"],
1519
+ loader: loaders,
1520
+ outfile: outputPath,
1521
+ define
1522
+ });
1523
+ if (verbose)
1524
+ logger.info(logText(`Javascript built`));
1525
+ };
1526
+ var defineSchema = (config) => {
1527
+ return config;
1528
+ };
1529
+ var loaders = {
1530
+ ".aac": "file",
1531
+ ".css": "file",
1532
+ ".eot": "file",
1533
+ ".flac": "file",
1534
+ ".gif": "file",
1535
+ ".jpeg": "file",
1536
+ ".jpg": "file",
1537
+ ".json": "json",
1538
+ ".mp3": "file",
1539
+ ".mp4": "file",
1540
+ ".ogg": "file",
1541
+ ".otf": "file",
1542
+ ".png": "file",
1543
+ ".svg": "file",
1544
+ ".ttf": "file",
1545
+ ".wav": "file",
1546
+ ".webm": "file",
1547
+ ".webp": "file",
1548
+ ".woff": "file",
1549
+ ".woff2": "file",
1550
+ ".js": "jsx",
1551
+ ".jsx": "jsx",
1552
+ ".tsx": "tsx"
1553
+ };
1554
+
1555
+ // src/cmds/start-server/index.ts
1556
+ var import_path11 = __toModule(require("path"));
1557
+ var import_chalk6 = __toModule(require("chalk"));
1558
+ var import_chokidar = __toModule(require("chokidar"));
1559
+ var import_metrics3 = __toModule(require("@tinacms/metrics"));
1560
+
1561
+ // src/buildTina/index.ts
1562
+ var import_async_retry = __toModule(require("async-retry"));
1563
+ var import_fs_extra6 = __toModule(require("fs-extra"));
1564
+ var import_graphql10 = __toModule(require("@tinacms/graphql"));
1565
+ var import_datalayer2 = __toModule(require("@tinacms/datalayer"));
1566
+ var import_path8 = __toModule(require("path"));
1567
+
1568
+ // src/cmds/query-gen/attachSchema.ts
1569
+ var import_graphql4 = __toModule(require("@tinacms/graphql"));
1570
+ var import_datalayer = __toModule(require("@tinacms/datalayer"));
1571
+
1572
+ // src/cmds/query-gen/genTypes.ts
1573
+ var import_graphql9 = __toModule(require("graphql"));
1574
+ var import_fs_extra4 = __toModule(require("fs-extra"));
1575
+ var import_path6 = __toModule(require("path"));
1576
+
1577
+ // src/codegen/index.ts
1578
+ var import_graphql8 = __toModule(require("graphql"));
1579
+
1580
+ // src/codegen/plugin.ts
1581
+ var AddGeneratedClientFunc = (_schema, _documents, _config, _info) => {
1582
+ return `
1583
+ // TinaSDK generated code
1584
+ import { createClient, TinaClient } from "tinacms/dist/client";
1585
+
1586
+ const generateRequester = (client: TinaClient) => {
1587
+ const requester: (
1588
+ doc: any,
1589
+ vars?: any,
1590
+ options?: any,
1591
+ client
1592
+ ) => Promise<any> = async (doc, vars, _options) => {
1593
+ const data = await client.request({
1594
+ query: doc,
1595
+ variables: vars,
1596
+ });
1597
+
1598
+ return { data: data?.data, query: doc, variables: vars || {} };
1599
+ };
1600
+
1601
+ return requester;
1602
+ };
1603
+
1604
+ /**
1605
+ * @experimental this class can be used but may change in the future
1606
+ **/
1607
+ export const ExperimentalGetTinaClient = () =>
1608
+ getSdk(
1609
+ generateRequester(createClient({ url: "http://localhost:4001/graphql", queries }))
1610
+ );
1611
+
1612
+ export const queries = (client: TinaClient) => {
1613
+ const requester = generateRequester(client);
1614
+ return getSdk(requester);
1615
+ };
1616
+ `;
1617
+ };
1618
+ var AddGeneratedClient = {
1619
+ plugin: AddGeneratedClientFunc
1620
+ };
1621
+
1622
+ // src/codegen/index.ts
1623
+ var import_graphql_file_loader = __toModule(require("@graphql-tools/graphql-file-loader"));
1624
+ var import_core = __toModule(require("@graphql-codegen/core"));
1625
+ var import_load = __toModule(require("@graphql-tools/load"));
1626
+ var import_typescript_operations = __toModule(require("@graphql-codegen/typescript-operations"));
1627
+ var import_typescript = __toModule(require("@graphql-codegen/typescript"));
1628
+
1629
+ // src/codegen/sdkPlugin/index.ts
1630
+ var import_graphql6 = __toModule(require("graphql"));
1631
+ var import_graphql7 = __toModule(require("graphql"));
1632
+ var import_path5 = __toModule(require("path"));
1633
+
1634
+ // src/codegen/sdkPlugin/visitor.ts
1635
+ var import_visitor_plugin_common = __toModule(require("@graphql-codegen/visitor-plugin-common"));
1636
+ var import_auto_bind = __toModule(require("auto-bind"));
1637
+ var import_graphql5 = __toModule(require("graphql"));
1638
+ var GenericSdkVisitor = class extends import_visitor_plugin_common.ClientSideBaseVisitor {
1639
+ constructor(schema, fragments, rawConfig) {
1640
+ super(schema, fragments, rawConfig, {
1641
+ usingObservableFrom: rawConfig.usingObservableFrom
1642
+ });
1643
+ this._operationsToInclude = [];
1644
+ (0, import_auto_bind.default)(this);
1645
+ if (this.config.usingObservableFrom) {
1646
+ this._additionalImports.push(this.config.usingObservableFrom);
1647
+ }
1648
+ if (this.config.documentMode !== import_visitor_plugin_common.DocumentMode.string) {
1649
+ }
1650
+ }
1651
+ buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes) {
1652
+ if (node.name == null) {
1653
+ throw new Error("Plugin 'generic-sdk' cannot generate SDK for unnamed operation.\n\n" + (0, import_graphql5.print)(node));
1654
+ } else {
1655
+ this._operationsToInclude.push({
1656
+ node,
1657
+ documentVariableName,
1658
+ operationType,
1659
+ operationResultType: `{data: ${operationResultType}, variables: ${operationVariablesTypes}, query: string}`,
1660
+ operationVariablesTypes
1661
+ });
1662
+ }
1663
+ return null;
1664
+ }
1665
+ get sdkContent() {
1666
+ const usingObservable = !!this.config.usingObservableFrom;
1667
+ const allPossibleActions = this._operationsToInclude.map((o) => {
1668
+ const optionalVariables = !o.node.variableDefinitions || o.node.variableDefinitions.length === 0 || o.node.variableDefinitions.every((v) => v.type.kind !== import_graphql5.Kind.NON_NULL_TYPE || v.defaultValue);
1669
+ const returnType = usingObservable && o.operationType === "Subscription" ? "Observable" : "Promise";
1670
+ return `${o.node.name.value}(variables${optionalVariables ? "?" : ""}: ${o.operationVariablesTypes}, options?: C): ${returnType}<${o.operationResultType}> {
1671
+ return requester<${o.operationResultType}, ${o.operationVariablesTypes}>(${o.documentVariableName}, variables, options);
1672
+ }`;
1673
+ }).map((s) => (0, import_visitor_plugin_common.indentMultiline)(s, 2));
1674
+ return `export type Requester<C= {}> = <R, V>(doc: ${this.config.documentMode === import_visitor_plugin_common.DocumentMode.string ? "string" : "DocumentNode"}, vars?: V, options?: C) => ${usingObservable ? "Promise<R> & Observable<R>" : "Promise<R>"}
1675
+ export function getSdk<C>(requester: Requester<C>) {
1676
+ return {
1677
+ ${allPossibleActions.join(",\n")}
1678
+ };
1679
+ }
1680
+ export type Sdk = ReturnType<typeof getSdk>;`;
1681
+ }
1682
+ };
1683
+
1684
+ // src/codegen/sdkPlugin/index.ts
1685
+ var plugin = (schema, documents, config) => {
1686
+ const allAst = (0, import_graphql7.concatAST)(documents.reduce((prev, v) => {
1687
+ return [...prev, v.document];
1688
+ }, []));
1689
+ const allFragments = [
1690
+ ...allAst.definitions.filter((d) => d.kind === import_graphql7.Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({
1691
+ node: fragmentDef,
1692
+ name: fragmentDef.name.value,
1693
+ onType: fragmentDef.typeCondition.name.value,
1694
+ isExternal: false
1695
+ })),
1696
+ ...config.externalFragments || []
1697
+ ];
1698
+ const visitor = new GenericSdkVisitor(schema, allFragments, config);
1699
+ const visitorResult = (0, import_graphql6.visit)(allAst, { leave: visitor });
1700
+ return {
1701
+ content: [
1702
+ visitor.fragments,
1703
+ ...visitorResult.definitions.filter((t) => typeof t === "string"),
1704
+ visitor.sdkContent
1705
+ ].join("\n")
1706
+ };
1707
+ };
1708
+
1709
+ // src/codegen/index.ts
1710
+ var generateTypes = async (schema, queryPathGlob = process.cwd(), fragDocPath = process.cwd(), options = {
1711
+ noSDK: false,
1712
+ verbose: false
1713
+ }) => {
1714
+ if (options.verbose)
1715
+ logger.info("Generating types...");
1716
+ try {
1717
+ let docs = [];
1718
+ let fragDocs = [];
1719
+ try {
1720
+ if (!options.noSDK) {
1721
+ docs = await (0, import_load.loadDocuments)(queryPathGlob, {
1722
+ loaders: [new import_graphql_file_loader.GraphQLFileLoader()]
1723
+ });
1724
+ }
1725
+ } catch (e) {
1726
+ let showErrorMessage = true;
1727
+ const message = e.message || "";
1728
+ if (message.includes("Unable to find any GraphQL type definitions for the following pointers:")) {
1729
+ showErrorMessage = false;
1730
+ }
1731
+ if (showErrorMessage) {
1732
+ console.error(e);
1737
1733
  }
1738
1734
  }
1739
- throw new ExecuteSchemaError(e);
1735
+ try {
1736
+ if (!options.noSDK) {
1737
+ fragDocs = await (0, import_load.loadDocuments)(fragDocPath, {
1738
+ loaders: [new import_graphql_file_loader.GraphQLFileLoader()]
1739
+ });
1740
+ }
1741
+ } catch (error) {
1742
+ console.error(error);
1743
+ }
1744
+ const res = await (0, import_core.codegen)({
1745
+ filename: process.cwd(),
1746
+ schema: (0, import_graphql8.parse)((0, import_graphql8.printSchema)(schema)),
1747
+ documents: [...docs, ...fragDocs],
1748
+ config: {},
1749
+ plugins: [
1750
+ { typescript: {} },
1751
+ { typescriptOperations: {} },
1752
+ {
1753
+ typescriptSdk: {}
1754
+ },
1755
+ { AddGeneratedClient: {} }
1756
+ ],
1757
+ pluginMap: {
1758
+ typescript: {
1759
+ plugin: import_typescript.plugin
1760
+ },
1761
+ typescriptOperations: {
1762
+ plugin: import_typescript_operations.plugin
1763
+ },
1764
+ typescriptSdk: {
1765
+ plugin
1766
+ },
1767
+ AddGeneratedClient
1768
+ }
1769
+ });
1770
+ return res;
1771
+ } catch (e) {
1772
+ console.error(e);
1740
1773
  }
1741
1774
  };
1742
- var transpile = async (inputFile, outputFile, tempDir, verbose, define) => {
1743
- if (verbose)
1744
- logger.info(logText("Building javascript..."));
1745
- const packageJSON = JSON.parse(import_fs_extra4.default.readFileSync(packageJSONFilePath).toString() || "{}");
1746
- const deps = (packageJSON == null ? void 0 : packageJSON.dependencies) || [];
1747
- const peerDeps = (packageJSON == null ? void 0 : packageJSON.peerDependencies) || [];
1748
- const devDeps = (packageJSON == null ? void 0 : packageJSON.devDependencies) || [];
1749
- const external = Object.keys(__spreadValues(__spreadValues(__spreadValues({}, deps), peerDeps), devDeps));
1750
- const outputPath = import_path5.default.join(tempDir, outputFile);
1751
- await (0, import_esbuild.build)({
1752
- bundle: true,
1753
- platform: "neutral",
1754
- target: ["node10.4"],
1755
- entryPoints: [inputFile],
1756
- treeShaking: true,
1757
- external: [...external, "./node_modules/*"],
1758
- loader: loaders,
1759
- outfile: outputPath,
1760
- define
1761
- });
1762
- if (verbose)
1763
- logger.info(logText(`Javascript built`));
1764
- };
1765
- var defineSchema = (config) => {
1766
- return config;
1767
- };
1768
- var loaders = {
1769
- ".aac": "file",
1770
- ".css": "file",
1771
- ".eot": "file",
1772
- ".flac": "file",
1773
- ".gif": "file",
1774
- ".jpeg": "file",
1775
- ".jpg": "file",
1776
- ".json": "json",
1777
- ".mp3": "file",
1778
- ".mp4": "file",
1779
- ".ogg": "file",
1780
- ".otf": "file",
1781
- ".png": "file",
1782
- ".svg": "file",
1783
- ".ttf": "file",
1784
- ".wav": "file",
1785
- ".webm": "file",
1786
- ".webp": "file",
1787
- ".woff": "file",
1788
- ".woff2": "file",
1789
- ".js": "jsx",
1790
- ".jsx": "jsx",
1791
- ".tsx": "tsx"
1792
- };
1793
-
1794
- // src/cmds/start-server/index.ts
1795
- var import_datalayer3 = __toModule(require("@tinacms/datalayer"));
1796
- var import_graphql11 = __toModule(require("@tinacms/graphql"));
1797
1775
 
1798
- // src/cmds/start-server/lock.ts
1799
- var AsyncLock = class {
1800
- constructor() {
1801
- this.disable = () => {
1802
- };
1803
- this.promise = Promise.resolve();
1804
- }
1805
- enable() {
1806
- this.promise = new Promise((resolve2) => this.disable = resolve2);
1776
+ // src/cmds/query-gen/genTypes.ts
1777
+ var import_esbuild2 = __toModule(require("esbuild"));
1778
+ var TINA_HOST = "content.tinajs.io";
1779
+ var root = process.cwd();
1780
+ var generatedPath = import_path6.default.join(root, ".tina", "__generated__");
1781
+ async function genClient({
1782
+ tinaSchema,
1783
+ usingTs
1784
+ }, next, options) {
1785
+ var _a, _b, _c;
1786
+ const branch = (_a = tinaSchema == null ? void 0 : tinaSchema.config) == null ? void 0 : _a.branch;
1787
+ const clientId = (_b = tinaSchema == null ? void 0 : tinaSchema.config) == null ? void 0 : _b.clientId;
1788
+ const token = (_c = tinaSchema.config) == null ? void 0 : _c.token;
1789
+ if ((!branch || !clientId || !token) && !(options == null ? void 0 : options.local)) {
1790
+ const missing = [];
1791
+ if (!branch)
1792
+ missing.push("branch");
1793
+ if (!clientId)
1794
+ missing.push("clientId");
1795
+ if (!token)
1796
+ missing.push("token");
1797
+ throw new Error(`Client not configured properly. Missing ${missing.join(", ")}. Please visit https://tina.io/docs/tina-cloud/connecting-site/ for more information`);
1798
+ }
1799
+ const apiURL = options.local ? "http://localhost:4001/graphql" : `https://${TINA_HOST}/content/${clientId}/github/${branch}`;
1800
+ const clientPath = import_path6.default.join(generatedPath, `client.${usingTs ? "ts" : "js"}`);
1801
+ import_fs_extra4.default.writeFileSync(clientPath, `import { createClient } from "tinacms/dist/client";
1802
+ import { queries } from "./types";
1803
+ export const client = createClient({ url: '${apiURL}', token: '${token}', queries });
1804
+ export default client;
1805
+ `);
1806
+ return next();
1807
+ }
1808
+ async function genTypes({ schema, usingTs }, next, options) {
1809
+ const typesPath = process.cwd() + "/.tina/__generated__/types.ts";
1810
+ const typesJSPath = process.cwd() + "/.tina/__generated__/types.js";
1811
+ const typesDPath = process.cwd() + "/.tina/__generated__/types.d.ts";
1812
+ const fragPath = process.cwd() + "/.tina/__generated__/*.{graphql,gql}";
1813
+ const queryPathGlob = process.cwd() + "/.tina/queries/**/*.{graphql,gql}";
1814
+ const typescriptTypes = await generateTypes(schema, queryPathGlob, fragPath, options);
1815
+ const code = `//@ts-nocheck
1816
+ // DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
1817
+ export function gql(strings: TemplateStringsArray, ...args: string[]): string {
1818
+ let str = ''
1819
+ strings.forEach((string, i) => {
1820
+ str += string + (args[i] || '')
1821
+ })
1822
+ return str
1823
+ }
1824
+ ${typescriptTypes}
1825
+ `;
1826
+ if (usingTs) {
1827
+ await import_fs_extra4.default.outputFile(typesPath, code);
1828
+ logger.info(` Typescript types => ${logText(typesPath)}`);
1829
+ } else {
1830
+ await import_fs_extra4.default.outputFile(typesDPath, code);
1831
+ const jsCode = await (0, import_esbuild2.transform)(code, { loader: "ts" });
1832
+ await import_fs_extra4.default.outputFile(typesJSPath, jsCode.code);
1807
1833
  }
1808
- };
1834
+ const schemaString = await (0, import_graphql9.printSchema)(schema);
1835
+ const schemaPath = process.cwd() + "/.tina/__generated__/schema.gql";
1836
+ await import_fs_extra4.default.outputFile(schemaPath, `# DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
1837
+ ${schemaString}
1838
+ schema {
1839
+ query: Query
1840
+ mutation: Mutation
1841
+ }
1842
+ `);
1843
+ logger.info(` GraphQL types ====> ${logText(schemaPath)}
1844
+ `);
1845
+ next();
1846
+ }
1809
1847
 
1810
- // src/cmds/start-server/index.ts
1811
- var import_metrics3 = __toModule(require("@tinacms/metrics"));
1812
- var import_chalk6 = __toModule(require("chalk"));
1813
- var import_chokidar = __toModule(require("chokidar"));
1814
- var import_fs_extra6 = __toModule(require("fs-extra"));
1848
+ // src/buildTina/git.ts
1849
+ var import_fs_extra5 = __toModule(require("fs-extra"));
1815
1850
  var import_ini = __toModule(require("ini"));
1816
1851
  var import_os = __toModule(require("os"));
1817
- var import_path8 = __toModule(require("path"));
1818
- var buildLock = new AsyncLock();
1819
- var reBuildLock = new AsyncLock();
1820
- var gqlPackageFile = require.resolve("@tinacms/graphql");
1852
+ var import_path7 = __toModule(require("path"));
1821
1853
  var resolveGitRoot = async () => {
1822
- const pathParts = process.cwd().split(import_path8.default.sep);
1854
+ const pathParts = process.cwd().split(import_path7.default.sep);
1823
1855
  while (true) {
1824
- const pathToGit = pathParts.join(import_path8.default.sep);
1825
- if (await import_fs_extra6.default.pathExists(import_path8.default.join(pathToGit, ".git"))) {
1856
+ const pathToGit = pathParts.join(import_path7.default.sep);
1857
+ if (await import_fs_extra5.default.pathExists(import_path7.default.join(pathToGit, ".git"))) {
1826
1858
  return pathToGit;
1827
1859
  }
1828
1860
  if (!pathParts.length) {
@@ -1847,9 +1879,9 @@ async function makeIsomorphicOptions(fsBridge) {
1847
1879
  await fsBridge.delete(filepath);
1848
1880
  }
1849
1881
  };
1850
- const userGitConfig = `${import_os.default.homedir()}${import_path8.default.sep}.gitconfig`;
1851
- if (await import_fs_extra6.default.pathExists(userGitConfig)) {
1852
- const config = import_ini.default.parse(await import_fs_extra6.default.readFile(userGitConfig, "utf-8"));
1882
+ const userGitConfig = `${import_os.default.homedir()}${import_path7.default.sep}.gitconfig`;
1883
+ if (await import_fs_extra5.default.pathExists(userGitConfig)) {
1884
+ const config = import_ini.default.parse(await import_fs_extra5.default.readFile(userGitConfig, "utf-8"));
1853
1885
  if ((_a = config["user"]) == null ? void 0 : _a["name"]) {
1854
1886
  options.author.name = config["user"]["name"];
1855
1887
  }
@@ -1859,7 +1891,7 @@ async function makeIsomorphicOptions(fsBridge) {
1859
1891
  }
1860
1892
  let repoGitConfig = void 0;
1861
1893
  if (!options.author.name) {
1862
- repoGitConfig = import_ini.default.parse(await import_fs_extra6.default.readFile(`${gitRoot}/.git/config`, "utf-8"));
1894
+ repoGitConfig = import_ini.default.parse(await import_fs_extra5.default.readFile(`${gitRoot}/.git/config`, "utf-8"));
1863
1895
  if ((_c = repoGitConfig["user"]) == null ? void 0 : _c["name"]) {
1864
1896
  options.author.name = repoGitConfig["user"]["name"];
1865
1897
  }
@@ -1868,7 +1900,7 @@ async function makeIsomorphicOptions(fsBridge) {
1868
1900
  }
1869
1901
  }
1870
1902
  if (!options.author.email) {
1871
- repoGitConfig = repoGitConfig || import_ini.default.parse(await import_fs_extra6.default.readFile(`${gitRoot}/.git/config`, "utf-8"));
1903
+ repoGitConfig = repoGitConfig || import_ini.default.parse(await import_fs_extra5.default.readFile(`${gitRoot}/.git/config`, "utf-8"));
1872
1904
  if ((_d = repoGitConfig["user"]) == null ? void 0 : _d["email"]) {
1873
1905
  options.author.email = repoGitConfig["user"]["email"];
1874
1906
  }
@@ -1878,63 +1910,188 @@ async function makeIsomorphicOptions(fsBridge) {
1878
1910
  }
1879
1911
  return options;
1880
1912
  }
1881
- async function startServer(_ctx, next, {
1913
+
1914
+ // src/buildTina/index.ts
1915
+ var buildSetupCmdBuild = async (ctx, next, opts) => {
1916
+ const rootPath2 = ctx.rootPath;
1917
+ const { bridge, database, store } = await buildSetup(__spreadProps(__spreadValues({}, opts), {
1918
+ rootPath: rootPath2,
1919
+ useMemoryStore: true
1920
+ }));
1921
+ ctx.bridge = bridge;
1922
+ ctx.database = database;
1923
+ ctx.store = store;
1924
+ next();
1925
+ };
1926
+ var buildSetupCmdServerStart = async (ctx, next, opts) => {
1927
+ const rootPath2 = ctx.rootPath;
1928
+ const { bridge, database, store } = await buildSetup(__spreadProps(__spreadValues({}, opts), {
1929
+ rootPath: rootPath2,
1930
+ useMemoryStore: false
1931
+ }));
1932
+ ctx.bridge = bridge;
1933
+ ctx.database = database;
1934
+ ctx.store = store;
1935
+ next();
1936
+ };
1937
+ var buildSetupCmdAudit = async (ctx, next, options) => {
1938
+ const rootPath2 = ctx.rootPath;
1939
+ const bridge = options.clean ? new import_datalayer2.FilesystemBridge(rootPath2) : new import_datalayer2.AuditFileSystemBridge(rootPath2);
1940
+ const store = new import_datalayer2.LevelStore(rootPath2, false);
1941
+ const database = await (0, import_graphql10.createDatabase)({ store, bridge });
1942
+ ctx.bridge = bridge;
1943
+ ctx.database = database;
1944
+ ctx.store = store;
1945
+ next();
1946
+ };
1947
+ var buildSetup = async ({
1948
+ isomorphicGitBridge: isomorphicGitBridge2,
1949
+ experimentalData,
1950
+ rootPath: rootPath2,
1951
+ useMemoryStore
1952
+ }) => {
1953
+ const fsBridge = new import_datalayer2.FilesystemBridge(rootPath2);
1954
+ const isomorphicOptions = isomorphicGitBridge2 && await makeIsomorphicOptions(fsBridge);
1955
+ const bridge = isomorphicGitBridge2 ? new import_datalayer2.IsomorphicBridge(rootPath2, isomorphicOptions) : fsBridge;
1956
+ const store = new import_datalayer2.LevelStore(rootPath2, useMemoryStore);
1957
+ const database = await (0, import_graphql10.createDatabase)({ store, bridge });
1958
+ return { database, bridge, store };
1959
+ };
1960
+ var buildCmdBuild = async (ctx, next, options) => {
1961
+ const bridge = ctx.bridge;
1962
+ const database = ctx.database;
1963
+ const store = ctx.store;
1964
+ await build2(__spreadProps(__spreadValues({}, options), {
1965
+ bridge,
1966
+ database,
1967
+ store,
1968
+ ctx,
1969
+ skipIndex: true
1970
+ }));
1971
+ next();
1972
+ };
1973
+ var auditCmdBuild = async (ctx, next, options) => {
1974
+ const bridge = ctx.bridge;
1975
+ const database = ctx.database;
1976
+ const store = ctx.store;
1977
+ await build2(__spreadProps(__spreadValues({}, options), {
1978
+ local: true,
1979
+ verbose: true,
1980
+ bridge,
1981
+ database,
1982
+ store,
1983
+ ctx
1984
+ }));
1985
+ next();
1986
+ };
1987
+ var build2 = async ({
1988
+ noWatch,
1989
+ ctx,
1990
+ bridge,
1991
+ database,
1992
+ store,
1993
+ beforeBuild,
1994
+ afterBuild,
1995
+ dev,
1996
+ local,
1997
+ verbose,
1998
+ noSDK,
1999
+ skipIndex
2000
+ }) => {
2001
+ const rootPath2 = ctx.rootPath;
2002
+ if (!rootPath2) {
2003
+ throw new Error("Root path has not been attached");
2004
+ }
2005
+ const tinaGeneratedPath = import_path8.default.join(rootPath2, ".tina", "__generated__");
2006
+ database.clearCache();
2007
+ if (beforeBuild) {
2008
+ await beforeBuild();
2009
+ }
2010
+ try {
2011
+ await import_fs_extra6.default.mkdirp(tinaGeneratedPath);
2012
+ await store.close();
2013
+ await resetGeneratedFolder({
2014
+ tinaGeneratedPath,
2015
+ usingTs: ctx.usingTs
2016
+ });
2017
+ await store.open();
2018
+ const cliFlags = [];
2019
+ cliFlags.push("experimentalData");
2020
+ cliFlags.push("isomorphicGitBridge");
2021
+ const database2 = await (0, import_graphql10.createDatabase)({ store, bridge });
2022
+ await compileSchema(ctx, null, { verbose, dev });
2023
+ const schema = await (0, import_async_retry.default)(async () => await (0, import_graphql10.buildSchema)(rootPath2, database2, cliFlags, skipIndex));
2024
+ await genTypes({ schema, usingTs: ctx.usingTs }, () => {
2025
+ }, {
2026
+ noSDK,
2027
+ verbose
2028
+ });
2029
+ await genClient({ tinaSchema: ctx.schema, usingTs: ctx.usingTs }, () => {
2030
+ }, {
2031
+ local
2032
+ });
2033
+ } catch (error) {
2034
+ throw error;
2035
+ } finally {
2036
+ if (afterBuild) {
2037
+ await afterBuild();
2038
+ }
2039
+ }
2040
+ };
2041
+
2042
+ // src/cmds/start-server/lock.ts
2043
+ var AsyncLock = class {
2044
+ constructor() {
2045
+ this.disable = () => {
2046
+ };
2047
+ this.promise = Promise.resolve();
2048
+ }
2049
+ enable() {
2050
+ this.promise = new Promise((resolve2) => this.disable = resolve2);
2051
+ }
2052
+ };
2053
+
2054
+ // src/cmds/start-server/index.ts
2055
+ var buildLock = new AsyncLock();
2056
+ var reBuildLock = new AsyncLock();
2057
+ var gqlPackageFile = require.resolve("@tinacms/graphql");
2058
+ async function startServer(ctx, next, {
1882
2059
  port = 4001,
1883
2060
  noWatch,
1884
- experimentalData,
1885
2061
  isomorphicGitBridge: isomorphicGitBridge2,
1886
2062
  noSDK,
1887
2063
  noTelemetry,
1888
2064
  watchFolders,
1889
2065
  verbose,
1890
- dev
2066
+ dev,
2067
+ local
1891
2068
  }) {
1892
2069
  buildLock.disable();
1893
2070
  reBuildLock.disable();
1894
- const rootPath2 = process.cwd();
2071
+ const rootPath2 = ctx.rootPath;
1895
2072
  const t = new import_metrics3.Telemetry({ disabled: Boolean(noTelemetry) });
1896
2073
  t.submitRecord({
1897
2074
  event: {
1898
2075
  name: "tinacms:cli:server:start:invoke"
1899
2076
  }
1900
2077
  });
1901
- const fsBridge = new import_datalayer3.FilesystemBridge(rootPath2);
1902
- const isomorphicOptions = isomorphicGitBridge2 && await makeIsomorphicOptions(fsBridge);
1903
- const bridge = isomorphicGitBridge2 ? new import_datalayer3.IsomorphicBridge(rootPath2, isomorphicOptions) : fsBridge;
1904
- const store = experimentalData ? new import_datalayer3.LevelStore(rootPath2) : new import_datalayer3.FilesystemStore({ rootPath: rootPath2 });
2078
+ const bridge = ctx.bridge;
2079
+ const database = ctx.database;
2080
+ const store = ctx.store;
1905
2081
  const shouldBuild = bridge.supportsBuilding();
1906
- const database = await (0, import_graphql11.createDatabase)({ store, bridge });
1907
2082
  let ready = false;
1908
- const build2 = async (noSDK2) => {
1909
- database.clearCache();
1910
- await buildLock.promise;
1911
- buildLock.enable();
1912
- try {
1913
- if (!process.env.CI && !noWatch) {
1914
- await store.close();
1915
- await resetGeneratedFolder();
1916
- await store.open();
1917
- }
1918
- const cliFlags = [];
1919
- if (isomorphicGitBridge2) {
1920
- cliFlags.push("isomorphicGitBridge");
1921
- }
1922
- const database2 = await (0, import_graphql11.createDatabase)({ store, bridge });
1923
- await compileSchema(null, null, { verbose, dev });
1924
- const schema = await (0, import_graphql11.buildSchema)(rootPath2, database2, cliFlags);
1925
- await genTypes({ schema }, () => {
1926
- }, { noSDK: noSDK2, verbose });
1927
- } catch (error) {
1928
- throw error;
1929
- } finally {
1930
- buildLock.disable();
1931
- }
1932
- };
1933
2083
  const state = {
1934
2084
  server: null,
1935
2085
  sockets: []
1936
2086
  };
1937
2087
  let isReady = false;
2088
+ const beforeBuild = async () => {
2089
+ await buildLock.promise;
2090
+ buildLock.enable();
2091
+ };
2092
+ const afterBuild = async () => {
2093
+ buildLock.disable();
2094
+ };
1938
2095
  const start = async () => {
1939
2096
  await buildLock.promise;
1940
2097
  buildLock.enable();
@@ -1983,7 +2140,7 @@ or`);
1983
2140
  });
1984
2141
  });
1985
2142
  };
1986
- const foldersToWatch = (watchFolders || []).map((x) => import_path8.default.join(rootPath2, x));
2143
+ const foldersToWatch = (watchFolders || []).map((x) => import_path11.default.join(rootPath2, x));
1987
2144
  if (!noWatch && !process.env.CI) {
1988
2145
  import_chokidar.default.watch([
1989
2146
  ...foldersToWatch,
@@ -1993,14 +2150,27 @@ or`);
1993
2150
  ignored: [
1994
2151
  "**/node_modules/**/*",
1995
2152
  "**/.next/**/*",
1996
- `${import_path8.default.resolve(rootPath2)}/.tina/__generated__/**/*`
2153
+ `${import_path11.default.resolve(rootPath2)}/.tina/__generated__/**/*`
1997
2154
  ]
1998
2155
  }).on("ready", async () => {
1999
2156
  if (verbose)
2000
2157
  console.log("Generating Tina config");
2001
2158
  try {
2002
2159
  if (shouldBuild) {
2003
- await build2(noSDK);
2160
+ await build2({
2161
+ bridge,
2162
+ ctx,
2163
+ database,
2164
+ store,
2165
+ dev,
2166
+ isomorphicGitBridge: isomorphicGitBridge2,
2167
+ local: true,
2168
+ noSDK,
2169
+ noWatch,
2170
+ verbose,
2171
+ beforeBuild,
2172
+ afterBuild
2173
+ });
2004
2174
  }
2005
2175
  ready = true;
2006
2176
  isReady = true;
@@ -2018,7 +2188,20 @@ or`);
2018
2188
  logger.info("Tina change detected, regenerating config");
2019
2189
  try {
2020
2190
  if (shouldBuild) {
2021
- await build2(noSDK);
2191
+ await build2({
2192
+ bridge,
2193
+ ctx,
2194
+ database,
2195
+ store,
2196
+ dev,
2197
+ isomorphicGitBridge: isomorphicGitBridge2,
2198
+ local: true,
2199
+ noSDK,
2200
+ noWatch,
2201
+ verbose,
2202
+ beforeBuild,
2203
+ afterBuild
2204
+ });
2022
2205
  }
2023
2206
  if (isReady) {
2024
2207
  await restart();
@@ -2041,7 +2224,20 @@ or`);
2041
2224
  logger.info("Detected CI environment, omitting watch commands...");
2042
2225
  }
2043
2226
  if (shouldBuild) {
2044
- await build2(noSDK);
2227
+ await build2({
2228
+ bridge,
2229
+ ctx,
2230
+ database,
2231
+ store,
2232
+ dev,
2233
+ isomorphicGitBridge: isomorphicGitBridge2,
2234
+ local: true,
2235
+ noSDK,
2236
+ noWatch,
2237
+ verbose,
2238
+ beforeBuild,
2239
+ afterBuild
2240
+ });
2045
2241
  }
2046
2242
  await start();
2047
2243
  next();
@@ -2147,13 +2343,22 @@ stack: ${code.stack || "No stack was provided"}`);
2147
2343
  }
2148
2344
  };
2149
2345
 
2346
+ // src/buildTina/attachPath.ts
2347
+ var import_fs_extra8 = __toModule(require("fs-extra"));
2348
+ var import_path12 = __toModule(require("path"));
2349
+ var attachPath = async (ctx, next, _options) => {
2350
+ ctx.rootPath = process.cwd();
2351
+ const tinaPath = import_path12.default.join(ctx.rootPath, ".tina");
2352
+ ctx.usingTs = await (0, import_fs_extra8.pathExists)(import_path12.default.join(tinaPath, "schema.ts")) || await (0, import_fs_extra8.pathExists)(import_path12.default.join(tinaPath, "schema.tsx"));
2353
+ next();
2354
+ };
2355
+
2150
2356
  // src/cmds/baseCmds.ts
2151
- var CMD_GEN_TYPES = "schema:types";
2152
2357
  var CMD_START_SERVER = "server:start";
2153
- var CMD_COMPILE_MODELS = "schema:compile";
2154
- var CMD_WAIT_FOR_DB = "server:waitForDB";
2358
+ var CMD_DEV = "dev";
2155
2359
  var INIT = "init";
2156
2360
  var AUDIT = "audit";
2361
+ var CMD_BUILD = "build";
2157
2362
  var startServerPortOption = {
2158
2363
  name: "--port <port>",
2159
2364
  description: "Specify a port to run the server on. (default 4001)"
@@ -2207,6 +2412,17 @@ var developmentOption = {
2207
2412
  name: "--dev",
2208
2413
  description: "Uses NODE_ENV=development when compiling client and schema"
2209
2414
  };
2415
+ var localOption = {
2416
+ name: "--local",
2417
+ description: "Uses the local file system graphql server",
2418
+ defaultValue: false
2419
+ };
2420
+ var checkOptions = async (_ctx, next, options) => {
2421
+ if (options == null ? void 0 : options.experimentalData) {
2422
+ logger.warn(warnText("Warning: you are using the `--experimentalData`flag. This flag is not needed and can safely be removed. It will be deprecated in a future version"));
2423
+ }
2424
+ next();
2425
+ };
2210
2426
  var baseCmds = [
2211
2427
  {
2212
2428
  command: CMD_START_SERVER,
@@ -2221,39 +2437,62 @@ var baseCmds = [
2221
2437
  noTelemetryOption,
2222
2438
  watchFileOption,
2223
2439
  verboseOption,
2224
- developmentOption
2440
+ developmentOption,
2441
+ localOption
2225
2442
  ],
2226
- action: (options) => chain([startServer, startSubprocess], options)
2443
+ action: (options) => chain([
2444
+ attachPath,
2445
+ async (ctx, next, _) => {
2446
+ logger.warn(warnText("server:start will be deprecated in the future, please use `tinacms dev` instead"));
2447
+ next();
2448
+ },
2449
+ checkOptions,
2450
+ buildSetupCmdServerStart,
2451
+ startServer,
2452
+ startSubprocess
2453
+ ], options)
2227
2454
  },
2228
2455
  {
2229
- command: CMD_WAIT_FOR_DB,
2230
- description: "Wait for DB to finish indexing, start subprocess",
2456
+ command: CMD_DEV,
2457
+ description: "Builds tina and starts the dev server.",
2231
2458
  options: [
2459
+ startServerPortOption,
2232
2460
  subCommand,
2233
- experimentalDatalayer,
2234
2461
  isomorphicGitBridge,
2462
+ noWatchOption,
2463
+ noSDKCodegenOption,
2235
2464
  noTelemetryOption,
2236
- verboseOption,
2237
- developmentOption
2465
+ watchFileOption,
2466
+ verboseOption
2238
2467
  ],
2239
- action: (options) => chain([compileClient, waitForDB, startSubprocess], options)
2240
- },
2241
- {
2242
- command: CMD_COMPILE_MODELS,
2243
- description: "Compile schema into static files for the server",
2244
- options: [experimentalDatalayer, isomorphicGitBridge, noTelemetryOption],
2245
- action: (options) => chain([compileSchema], options)
2468
+ action: (options) => chain([
2469
+ attachPath,
2470
+ checkOptions,
2471
+ buildSetupCmdServerStart,
2472
+ startServer,
2473
+ startSubprocess
2474
+ ], options)
2246
2475
  },
2247
2476
  {
2248
- command: CMD_GEN_TYPES,
2249
- description: "Generate a GraphQL query for your site's schema, (and optionally Typescript types)",
2477
+ command: CMD_BUILD,
2478
+ description: "Build Tina",
2250
2479
  options: [
2251
2480
  experimentalDatalayer,
2252
2481
  isomorphicGitBridge,
2253
2482
  noSDKCodegenOption,
2254
- noTelemetryOption
2483
+ noTelemetryOption,
2484
+ verboseOption,
2485
+ developmentOption,
2486
+ localOption
2255
2487
  ],
2256
- action: (options) => chain([attachSchema, genTypes], options)
2488
+ action: (options) => chain([
2489
+ attachPath,
2490
+ checkOptions,
2491
+ buildSetupCmdBuild,
2492
+ buildCmdBuild,
2493
+ compileClient,
2494
+ waitForDB
2495
+ ], options)
2257
2496
  },
2258
2497
  {
2259
2498
  command: INIT,
@@ -2265,15 +2504,13 @@ var baseCmds = [
2265
2504
  ],
2266
2505
  description: "Add Tina Cloud to an existing project",
2267
2506
  action: (options) => chain([
2507
+ attachPath,
2508
+ checkOptions,
2268
2509
  checkDeps,
2269
2510
  initTina,
2270
2511
  installDeps,
2271
- async (_ctx, next, options2) => {
2272
- await compileSchema(_ctx, next, options2);
2273
- next();
2274
- },
2275
- attachSchema,
2276
- genTypes,
2512
+ buildSetupCmdBuild,
2513
+ buildCmdBuild,
2277
2514
  tinaSetup,
2278
2515
  successMessage
2279
2516
  ], options)
@@ -2283,16 +2520,9 @@ var baseCmds = [
2283
2520
  command: AUDIT,
2284
2521
  description: "Audit your schema and the files to check for errors",
2285
2522
  action: (options) => chain([
2286
- async (_ctx, next) => {
2287
- logger.level = "error";
2288
- next();
2289
- },
2290
- async (_ctx, next) => {
2291
- await compileSchema(_ctx, next, options);
2292
- next();
2293
- },
2294
- attachSchema,
2295
- genTypes,
2523
+ attachPath,
2524
+ buildSetupCmdAudit,
2525
+ auditCmdBuild,
2296
2526
  async (_ctx, next) => {
2297
2527
  logger.level = "info";
2298
2528
  logger.info(import_chalk7.default.hex("#eb6337").bgWhite("Welcome to tina audit \u{1F999}"));