@tinacms/cli 1.3.2 → 1.4.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.
Files changed (54) hide show
  1. package/bin/tinacms +3 -1
  2. package/dist/cmds/forestry-migrate/util/index.d.ts +14 -14
  3. package/dist/cmds/init/index.d.ts +4 -1
  4. package/dist/index.d.ts +3 -2
  5. package/dist/index.js +2229 -2070
  6. package/dist/logger/index.d.ts +16 -3
  7. package/dist/logger/is-unicode-supported.d.ts +1 -0
  8. package/dist/next/codegen/codegen/index.d.ts +5 -0
  9. package/dist/{codegen → next/codegen/codegen}/plugin.d.ts +2 -2
  10. package/dist/{codegen → next/codegen/codegen}/sdkPlugin/index.d.ts +1 -1
  11. package/dist/next/codegen/index.d.ts +30 -0
  12. package/dist/{cmds/audit → next/commands/audit-command}/audit.d.ts +7 -5
  13. package/dist/next/commands/audit-command/index.d.ts +12 -0
  14. package/dist/next/commands/build-command/index.d.ts +23 -0
  15. package/dist/next/commands/build-command/server.d.ts +3 -0
  16. package/dist/next/commands/build-command/tailwind.d.ts +2 -0
  17. package/dist/next/commands/build-command/waitForDB.d.ts +7 -0
  18. package/dist/next/commands/codemod-command/index.d.ts +9 -0
  19. package/dist/next/commands/codemod-command/server/index.d.ts +2 -0
  20. package/dist/next/commands/dev-command/html.d.ts +1 -0
  21. package/dist/next/commands/dev-command/index.d.ts +21 -0
  22. package/dist/next/commands/dev-command/server/index.d.ts +3 -0
  23. package/dist/next/commands/dev-command/server/media.d.ts +45 -0
  24. package/dist/next/commands/dev-command/tailwind.d.ts +2 -0
  25. package/dist/next/commands/init-command/index.d.ts +9 -0
  26. package/dist/next/config-manager.d.ts +54 -0
  27. package/dist/next/database.d.ts +4 -0
  28. package/dist/next/vite/index.d.ts +12 -0
  29. package/dist/next/vite/tailwind.d.ts +2 -0
  30. package/dist/utils/sleep.d.ts +4 -0
  31. package/dist/utils/start-subprocess.d.ts +5 -0
  32. package/package.json +17 -6
  33. package/dist/buildTina/attachDatabase.d.ts +0 -8
  34. package/dist/buildTina/attachPath.d.ts +0 -5
  35. package/dist/buildTina/git.d.ts +0 -13
  36. package/dist/buildTina/index.d.ts +0 -71
  37. package/dist/cmds/audit/index.d.ts +0 -5
  38. package/dist/cmds/baseCmds.d.ts +0 -11
  39. package/dist/cmds/compile/defaultSchema.d.ts +0 -4
  40. package/dist/cmds/compile/index.d.ts +0 -24
  41. package/dist/cmds/query-gen/genTypes.d.ts +0 -16
  42. package/dist/cmds/query-gen/index.d.ts +0 -4
  43. package/dist/cmds/start-server/errors/index.d.ts +0 -10
  44. package/dist/cmds/start-server/index.d.ts +0 -27
  45. package/dist/cmds/start-server/lock.d.ts +0 -9
  46. package/dist/cmds/start-server/server.d.ts +0 -5
  47. package/dist/cmds/startSubprocess/index.d.ts +0 -8
  48. package/dist/cmds/statusChecks/checkClientInformation.d.ts +0 -32
  49. package/dist/cmds/statusChecks/waitForIndexing.d.ts +0 -11
  50. package/dist/codegen/index.d.ts +0 -8
  51. package/dist/command.d.ts +0 -19
  52. package/dist/middleware.d.ts +0 -4
  53. /package/dist/{codegen → next/codegen/codegen}/sdkPlugin/config.d.ts +0 -0
  54. /package/dist/{codegen → next/codegen/codegen}/sdkPlugin/visitor.d.ts +0 -0
package/dist/index.js CHANGED
@@ -4,9 +4,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __getProtoOf = Object.getPrototypeOf;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __esm = (fn, res) => function __init() {
8
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
- };
10
7
  var __export = (target, all) => {
11
8
  for (var name2 in all)
12
9
  __defProp(target, name2, { get: all[name2], enumerable: true });
@@ -25,282 +22,43 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
22
  ));
26
23
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
24
 
28
- // src/utils/index.ts
29
- var parseMediaFolder;
30
- var init_utils = __esm({
31
- "src/utils/index.ts"() {
32
- parseMediaFolder = (str) => {
33
- let returnString = str;
34
- if (returnString.startsWith("/"))
35
- returnString = returnString.substr(1);
36
- if (returnString.endsWith("/"))
37
- returnString = returnString.substr(0, returnString.length - 1);
38
- return returnString;
39
- };
40
- }
41
- });
42
-
43
- // src/server/models/media.ts
44
- var import_fs_extra6, import_path6, MediaModel;
45
- var init_media = __esm({
46
- "src/server/models/media.ts"() {
47
- import_fs_extra6 = __toESM(require("fs-extra"));
48
- import_path6 = require("path");
49
- init_utils();
50
- MediaModel = class {
51
- constructor({ rootPath: rootPath2, publicFolder, mediaRoot }) {
52
- this.rootPath = rootPath2;
53
- this.mediaRoot = mediaRoot;
54
- this.publicFolder = publicFolder;
55
- }
56
- async listMedia(args) {
57
- try {
58
- const folderPath = (0, import_path6.join)(
59
- this.rootPath,
60
- this.publicFolder,
61
- this.mediaRoot,
62
- args.searchPath
63
- );
64
- const searchPath = parseMediaFolder(args.searchPath);
65
- const filesStr = await import_fs_extra6.default.readdir(folderPath);
66
- const filesProm = filesStr.map(async (file) => {
67
- const filePath = (0, import_path6.join)(folderPath, file);
68
- const stat = await import_fs_extra6.default.stat(filePath);
69
- let src = `/${file}`;
70
- const isFile = stat.isFile();
71
- if (!isFile) {
72
- return {
73
- isFile,
74
- size: stat.size,
75
- src,
76
- filename: file
77
- };
78
- }
79
- if (searchPath) {
80
- src = `/${searchPath}${src}`;
81
- }
82
- if (this.mediaRoot) {
83
- src = `/${this.mediaRoot}${src}`;
84
- }
85
- return {
86
- isFile,
87
- size: stat.size,
88
- src,
89
- filename: file
90
- };
91
- });
92
- const offset = Number(args.cursor) || 0;
93
- const limit = Number(args.limit) || 20;
94
- const rawItems = await Promise.all(filesProm);
95
- const sortedItems = rawItems.sort((a, b) => {
96
- if (a.isFile && !b.isFile) {
97
- return 1;
98
- }
99
- if (!a.isFile && b.isFile) {
100
- return -1;
101
- }
102
- return 0;
103
- });
104
- const limitItems = sortedItems.slice(offset, offset + limit);
105
- const files = limitItems.filter((x) => x.isFile);
106
- const directories = limitItems.filter((x) => !x.isFile).map((x) => x.src);
107
- const cursor = rawItems.length > offset + limit ? String(offset + limit) : null;
108
- return {
109
- files,
110
- directories,
111
- cursor
112
- };
113
- } catch (error) {
114
- console.error(error);
115
- return {
116
- files: [],
117
- directories: [],
118
- error: error == null ? void 0 : error.toString()
119
- };
120
- }
121
- }
122
- async deleteMedia(args) {
123
- try {
124
- const file = (0, import_path6.join)(
125
- this.rootPath,
126
- this.publicFolder,
127
- this.mediaRoot,
128
- args.searchPath
129
- );
130
- await import_fs_extra6.default.stat(file);
131
- await import_fs_extra6.default.remove(file);
132
- return { ok: true };
133
- } catch (error) {
134
- console.error(error);
135
- return { ok: false, message: error == null ? void 0 : error.toString() };
136
- }
137
- }
138
- };
139
- }
140
- });
141
-
142
- // src/server/routes/index.ts
143
- var import_express, import_path7, import_multer, createMediaRouter;
144
- var init_routes = __esm({
145
- "src/server/routes/index.ts"() {
146
- import_express = require("express");
147
- import_path7 = require("path");
148
- import_multer = __toESM(require("multer"));
149
- init_media();
150
- createMediaRouter = (config2) => {
151
- const mediaFolder = (0, import_path7.join)(
152
- config2.rootPath,
153
- config2.publicFolder,
154
- config2.mediaRoot
155
- );
156
- const storage = import_multer.default.diskStorage({
157
- destination: function(req, file, cb) {
158
- cb(null, mediaFolder);
159
- },
160
- filename: function(req, _file, cb) {
161
- const file = req.params[0];
162
- cb(null, file);
163
- }
164
- });
165
- const upload = (0, import_multer.default)({ storage });
166
- const uploadRoute = upload.single("file");
167
- const mediaModel = new MediaModel(config2);
168
- const mediaRouter = (0, import_express.Router)();
169
- mediaRouter.get("/list/*", async (req, res) => {
170
- const folder = req.params[0];
171
- const cursor = req.query.cursor;
172
- const limit = req.query.limit;
173
- const media = await mediaModel.listMedia({
174
- searchPath: folder,
175
- cursor,
176
- limit
177
- });
178
- res.json(media);
179
- });
180
- mediaRouter.delete("/*", async (req, res) => {
181
- const file = req.params[0];
182
- const didDelete = await mediaModel.deleteMedia({ searchPath: file });
183
- res.json(didDelete);
184
- });
185
- mediaRouter.post("/upload/*", async function(req, res) {
186
- await uploadRoute(req, res, (err) => {
187
- if (err instanceof import_multer.default.MulterError) {
188
- res.status(500).json({ message: err.message });
189
- } else if (err) {
190
- res.status(500).json({ message: err.message });
191
- } else {
192
- res.json({ success: true });
193
- }
194
- });
195
- });
196
- return mediaRouter;
197
- };
198
- }
199
- });
200
-
201
- // src/server/server.ts
202
- var import_cors, import_http, import_express2, import_altair_express_middleware, import_body_parser, gqlServer;
203
- var init_server = __esm({
204
- "src/server/server.ts"() {
205
- import_cors = __toESM(require("cors"));
206
- import_http = __toESM(require("http"));
207
- import_express2 = __toESM(require("express"));
208
- import_altair_express_middleware = require("altair-express-middleware");
209
- import_body_parser = __toESM(require("body-parser"));
210
- init_routes();
211
- init_utils();
212
- gqlServer = async (database, verbose) => {
213
- var _a, _b, _c;
214
- const gqlPackage = require("@tinacms/graphql");
215
- const app = (0, import_express2.default)();
216
- const server = import_http.default.createServer(app);
217
- app.use((0, import_cors.default)());
218
- app.use(import_body_parser.default.json());
219
- app.use(
220
- "/altair",
221
- (0, import_altair_express_middleware.altairExpress)({
222
- endpointURL: "/graphql",
223
- initialQuery: `# Welcome to Tina!
224
- # We've got a simple query set up for you to get started
225
- # but there's plenty more for you to explore on your own!
226
- query MyQuery {
227
- collections {
228
- documents {
229
- id
230
- sys {
231
- filename
232
- extension
233
- }
234
- }
235
- }
236
- }`
237
- })
238
- );
239
- app.post("/graphql", async (req, res) => {
240
- const { query, variables } = req.body;
241
- const config2 = {
242
- useRelativeMedia: true
243
- };
244
- const result = await gqlPackage.resolve({
245
- config: config2,
246
- database,
247
- query,
248
- variables,
249
- verbose
250
- });
251
- return res.json(result);
252
- });
253
- const db = database;
254
- const schema = await db.getSchema();
255
- const mediaPaths = (_c = (_b = (_a = schema == null ? void 0 : schema.schema) == null ? void 0 : _a.config) == null ? void 0 : _b.media) == null ? void 0 : _c.tina;
256
- app.use(
257
- "/media",
258
- createMediaRouter({
259
- rootPath: db.bridge.rootPath,
260
- publicFolder: parseMediaFolder((mediaPaths == null ? void 0 : mediaPaths.publicFolder) || ""),
261
- mediaRoot: parseMediaFolder((mediaPaths == null ? void 0 : mediaPaths.mediaRoot) || "")
262
- })
263
- );
264
- return server;
265
- };
266
- }
267
- });
268
-
269
- // src/server/index.ts
270
- var init_server2 = __esm({
271
- "src/server/index.ts"() {
272
- init_server();
273
- }
274
- });
275
-
276
- // src/cmds/start-server/server.ts
277
- var server_exports = {};
278
- __export(server_exports, {
279
- default: () => server_default
280
- });
281
- var server_default;
282
- var init_server3 = __esm({
283
- "src/cmds/start-server/server.ts"() {
284
- init_server2();
285
- server_default = gqlServer;
286
- }
287
- });
288
-
289
25
  // src/index.ts
290
26
  var src_exports = {};
291
27
  __export(src_exports, {
292
- defineSchema: () => defineSchema,
293
- init: () => init
28
+ default: () => src_default
294
29
  });
295
30
  module.exports = __toCommonJS(src_exports);
296
- var commander = __toESM(require("commander"));
31
+ var import_clipanion5 = require("clipanion");
297
32
 
298
33
  // package.json
299
- var name = "@tinacms/cli";
300
- var version = "1.3.2";
34
+ var version = "1.4.0";
301
35
 
302
- // src/cmds/audit/audit.ts
303
- var import_graphql = require("@tinacms/graphql");
36
+ // src/next/commands/dev-command/index.ts
37
+ var import_clipanion = require("clipanion");
38
+ var import_fs_extra4 = __toESM(require("fs-extra"));
39
+ var import_path6 = __toESM(require("path"));
40
+ var import_chokidar = __toESM(require("chokidar"));
41
+ var import_graphql8 = require("@tinacms/graphql");
42
+
43
+ // src/next/config-manager.ts
44
+ var import_fs_extra = __toESM(require("fs-extra"));
45
+ var import_path = __toESM(require("path"));
46
+ var import_os = __toESM(require("os"));
47
+ var esbuild = __toESM(require("esbuild"));
48
+ var url = __toESM(require("url"));
49
+ var dotenv = __toESM(require("dotenv"));
50
+ var import_normalize_path = __toESM(require("normalize-path"));
51
+
52
+ // src/logger/index.ts
53
+ var import_chalk = __toESM(require("chalk"));
54
+
55
+ // src/logger/is-unicode-supported.ts
56
+ function isUnicodeSupported() {
57
+ if (process.platform !== "win32") {
58
+ return process.env.TERM !== "linux";
59
+ }
60
+ return Boolean(process.env.CI) || Boolean(process.env.WT_SESSION) || Boolean(process.env.TERMINUS_SUBLIME) || process.env.ConEmuTask === "{cmd::Cmder}" || process.env.TERM_PROGRAM === "Terminus-Sublime" || process.env.TERM_PROGRAM === "vscode" || process.env.TERM === "xterm-256color" || process.env.TERM === "alacritty" || process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
61
+ }
304
62
 
305
63
  // src/logger/index.ts
306
64
  var import_log4js = __toESM(require("log4js"));
@@ -312,658 +70,947 @@ import_log4js.default.configure({
312
70
  categories: { default: { appenders: ["out"], level: "info" } }
313
71
  });
314
72
  logger.level = "info";
315
-
316
- // src/cmds/audit/audit.ts
317
- var import_graphql2 = require("@tinacms/graphql");
318
- var import_chalk = __toESM(require("chalk"));
319
- var auditDocuments = async (args) => {
320
- const { collection, database, useDefaultValues, documents } = args;
321
- let error = false;
322
- for (let i = 0; i < documents.length; i++) {
323
- const node = documents[i].node;
324
- const relativePath = node.path.replace(`${collection.path}/`, "");
325
- const documentQuery = `query {
326
- document(collection: "${collection.name}", relativePath: "${relativePath}") {
327
- __typename
328
- ...on Document {
329
- _values
330
- }
331
- }
332
- }`;
333
- const docResult = await (0, import_graphql.resolve)({
334
- database,
335
- query: documentQuery,
336
- variables: {},
337
- silenceErrors: true,
338
- verbose: args.verbose || false,
339
- isAudit: true
73
+ function ansiRegex() {
74
+ const pattern = [
75
+ "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
76
+ "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
77
+ ].join("|");
78
+ return new RegExp(pattern, "g");
79
+ }
80
+ var bar = "\u2502";
81
+ var strip = (str) => str.replace(ansiRegex(), "");
82
+ var note = (message = "", title = "") => {
83
+ const lines = `
84
+ ${message}
85
+ `.split("\n");
86
+ const len = lines.reduce((sum, ln) => {
87
+ ln = strip(ln);
88
+ return ln.length > sum ? ln.length : sum;
89
+ }, 0) + 2;
90
+ const msg = lines.map(
91
+ (ln) => `${import_chalk.default.gray(bar)} ${import_chalk.default.white(ln)}${" ".repeat(
92
+ len - strip(ln).length
93
+ )}${import_chalk.default.gray(bar)}`
94
+ ).join("\n");
95
+ process.stdout.write(
96
+ `${import_chalk.default.gray(bar)}
97
+ ${import_chalk.default.green("\u25CB")} ${import_chalk.default.reset(
98
+ title
99
+ )} ${import_chalk.default.gray(
100
+ "\u2500".repeat(len - title.length - 1) + "\u256E"
101
+ )}
102
+ ${msg}
103
+ ${import_chalk.default.gray("\u251C" + "\u2500".repeat(len + 2) + "\u256F")}
104
+ `
105
+ );
106
+ };
107
+ var summary = (content2) => {
108
+ const outString = [];
109
+ let longestKey = 0;
110
+ content2.items.forEach((item) => {
111
+ item.subItems.forEach((subItem) => {
112
+ if (subItem.key.length > longestKey) {
113
+ longestKey = subItem.key.length;
114
+ }
340
115
  });
341
- if (docResult.errors) {
342
- error = true;
343
- docResult.errors.forEach((err) => {
344
- logger.error(import_chalk.default.red(err.message));
345
- if (err.originalError.originalError) {
346
- logger.error(
347
- import_chalk.default.red(` ${err.originalError.originalError.message}`)
348
- );
349
- }
350
- });
116
+ });
117
+ content2.items.forEach((item) => {
118
+ outString.push(`${item.emoji} ${import_chalk.default.cyan(item.heading)}`);
119
+ item.subItems.forEach((subItem) => {
120
+ const spaces = longestKey - subItem.key.length + 4;
121
+ outString.push(
122
+ ` ${subItem.key}:${[...Array(spaces)].join(" ")}${import_chalk.default.cyan(
123
+ subItem.value
124
+ )}`
125
+ );
126
+ });
127
+ outString.push(``);
128
+ });
129
+ if (process.env.CI) {
130
+ logger.info(JSON.stringify(content2, null, 2));
131
+ } else {
132
+ note(outString.join("\n"), content2.heading);
133
+ }
134
+ };
135
+ var unicode = isUnicodeSupported();
136
+ var s = (c, fallback) => unicode ? c : fallback;
137
+ var S_STEP_ACTIVE = s("\u25C6", "*");
138
+ var S_STEP_CANCEL = s("\u25A0", "x");
139
+ var S_STEP_ERROR = s("\u25B2", "x");
140
+ var S_STEP_SUBMIT = s("\u25C7", "o");
141
+ var S_BAR_START = s("\u250C", "T");
142
+ var S_BAR = s("\u2502", "|");
143
+ var S_BAR_END = s("\u2514", "\u2014");
144
+ var S_RADIO_ACTIVE = s("\u25CF", ">");
145
+ var S_RADIO_INACTIVE = s("\u25CB", " ");
146
+ var S_CHECKBOX_ACTIVE = s("\u25FB", "[\u2022]");
147
+ var S_CHECKBOX_SELECTED = s("\u25FC", "[+]");
148
+ var S_CHECKBOX_INACTIVE = s("\u25FB", "[ ]");
149
+ var S_PASSWORD_MASK = s("\u25AA", "\u2022");
150
+ var S_BAR_H = s("\u2500", "-");
151
+ var S_CORNER_TOP_RIGHT = s("\u256E", "+");
152
+ var S_CONNECT_LEFT = s("\u251C", "+");
153
+ var S_CORNER_BOTTOM_RIGHT = s("\u256F", "+");
154
+ var S_INFO = s("\u25CF", "\u2022");
155
+ var S_SUCCESS = s("\u25C6", "*");
156
+ var S_WARN = s("\u25B2", "!");
157
+ var S_ERROR = s("\u25A0", "x");
158
+
159
+ // src/next/config-manager.ts
160
+ var TINA_FOLDER = "tina";
161
+ var LEGACY_TINA_FOLDER = ".tina";
162
+ var GENERATED_FOLDER = "__generated__";
163
+ var GRAPHQL_JSON_FILE = "_graphql.json";
164
+ var GRAPHQL_GQL_FILE = "schema.gql";
165
+ var SCHEMA_JSON_FILE = "_schema.json";
166
+ var LOOKUP_JSON_FILE = "_lookup.json";
167
+ var ConfigManager = class {
168
+ constructor(rootPath = process.cwd(), tinaGraphQLVersion) {
169
+ this.rootPath = (0, import_normalize_path.default)(rootPath);
170
+ this.tinaGraphQLVersionFromCLI = tinaGraphQLVersion;
171
+ }
172
+ isUsingTs() {
173
+ return [".ts", ".tsx"].includes(import_path.default.extname(this.tinaConfigFilePath));
174
+ }
175
+ hasSelfHostedConfig() {
176
+ return !!this.selfHostedDatabaseFilePath;
177
+ }
178
+ hasSeparateContentRoot() {
179
+ return this.rootPath !== this.contentRootPath;
180
+ }
181
+ async processConfig() {
182
+ this.tinaFolderPath = await this.getTinaFolderPath(this.rootPath);
183
+ this.envFilePath = import_path.default.resolve(
184
+ import_path.default.join(this.tinaFolderPath, "..", ".env")
185
+ );
186
+ dotenv.config({ path: this.envFilePath });
187
+ this.tinaConfigFilePath = await this.getPathWithExtension(
188
+ import_path.default.join(this.tinaFolderPath, "config")
189
+ );
190
+ if (!this.tinaConfigFilePath) {
191
+ throw new Error(
192
+ `Unable to find confg file in ${this.tinaFolderPath}. Looking for a file named "config.{ts,tsx,js,jsx}"`
193
+ );
194
+ }
195
+ this.selfHostedDatabaseFilePath = await this.getPathWithExtension(
196
+ import_path.default.join(this.tinaFolderPath, "database")
197
+ );
198
+ this.generatedFolderPath = import_path.default.join(this.tinaFolderPath, GENERATED_FOLDER);
199
+ this.config = await this.loadConfigFile(
200
+ this.generatedFolderPath,
201
+ this.tinaConfigFilePath
202
+ );
203
+ this.generatedGraphQLGQLPath = import_path.default.join(
204
+ this.generatedFolderPath,
205
+ GRAPHQL_GQL_FILE
206
+ );
207
+ this.generatedGraphQLJSONPath = import_path.default.join(
208
+ this.generatedFolderPath,
209
+ GRAPHQL_JSON_FILE
210
+ );
211
+ this.generatedSchemaJSONPath = import_path.default.join(
212
+ this.generatedFolderPath,
213
+ SCHEMA_JSON_FILE
214
+ );
215
+ this.generatedLookupJSONPath = import_path.default.join(
216
+ this.generatedFolderPath,
217
+ LOOKUP_JSON_FILE
218
+ );
219
+ this.generatedQueriesFilePath = import_path.default.join(
220
+ this.generatedFolderPath,
221
+ "queries.gql"
222
+ );
223
+ this.generatedFragmentsFilePath = import_path.default.join(
224
+ this.generatedFolderPath,
225
+ "frags.gql"
226
+ );
227
+ const fullLocalContentPath = import_path.default.join(
228
+ this.tinaFolderPath,
229
+ this.config.localContentPath || ""
230
+ );
231
+ if (this.config.localContentPath && await import_fs_extra.default.existsSync(fullLocalContentPath)) {
232
+ logger.info(`Using separate content repo at ${fullLocalContentPath}`);
233
+ this.contentRootPath = fullLocalContentPath;
351
234
  } else {
352
- const topLevelDefaults = {};
353
- if (useDefaultValues && typeof collection.fields !== "string") {
354
- collection.fields.filter((x) => !x.list).forEach((x) => {
355
- const value = x.ui;
356
- if (typeof value !== "undefined") {
357
- topLevelDefaults[x.name] = value.defaultValue;
358
- }
359
- });
360
- }
361
- const params = transformDocumentIntoMutationRequestPayload(
362
- docResult.data.document._values,
363
- {
364
- includeCollection: true,
365
- includeTemplate: typeof collection.templates !== "undefined"
366
- },
367
- topLevelDefaults
235
+ this.contentRootPath = this.rootPath;
236
+ }
237
+ this.generatedTypesTSFilePath = import_path.default.join(
238
+ this.generatedFolderPath,
239
+ "types.ts"
240
+ );
241
+ this.generatedTypesJSFilePath = import_path.default.join(
242
+ this.generatedFolderPath,
243
+ "types.js"
244
+ );
245
+ this.generatedTypesDFilePath = import_path.default.join(
246
+ this.generatedFolderPath,
247
+ "types.d.ts"
248
+ );
249
+ this.userQueriesAndFragmentsGlob = import_path.default.join(
250
+ this.tinaFolderPath,
251
+ "queries/**/*.{graphql,gql}"
252
+ );
253
+ this.generatedQueriesAndFragmentsGlob = import_path.default.join(
254
+ this.generatedFolderPath,
255
+ "*.{graphql,gql}"
256
+ );
257
+ this.generatedClientTSFilePath = import_path.default.join(
258
+ this.generatedFolderPath,
259
+ "client.ts"
260
+ );
261
+ this.generatedClientJSFilePath = import_path.default.join(
262
+ this.generatedFolderPath,
263
+ "client.js"
264
+ );
265
+ this.publicFolderPath = import_path.default.join(
266
+ this.rootPath,
267
+ this.config.build.publicFolder
268
+ );
269
+ this.outputFolderPath = import_path.default.join(
270
+ this.publicFolderPath,
271
+ this.config.build.outputFolder
272
+ );
273
+ this.outputHTMLFilePath = import_path.default.join(this.outputFolderPath, "index.html");
274
+ this.outputGitignorePath = import_path.default.join(this.outputFolderPath, ".gitignore");
275
+ this.spaHTMLPath = url.pathToFileURL(
276
+ require.resolve("@tinacms/app")
277
+ ).pathname;
278
+ this.spaRootPath = this.spaHTMLPath.replace("/index.html", "");
279
+ this.spaMainPath = import_path.default.join(this.spaRootPath, "src", "main.tsx");
280
+ }
281
+ async getTinaFolderPath(rootPath) {
282
+ const tinaFolderPath = import_path.default.join(rootPath, TINA_FOLDER);
283
+ const tinaFolderExists = await import_fs_extra.default.pathExists(tinaFolderPath);
284
+ if (tinaFolderExists) {
285
+ this.isUsingLegacyFolder = false;
286
+ return tinaFolderPath;
287
+ }
288
+ const legacyFolderPath = import_path.default.join(rootPath, LEGACY_TINA_FOLDER);
289
+ const legacyFolderExists = await import_fs_extra.default.pathExists(legacyFolderPath);
290
+ if (legacyFolderExists) {
291
+ this.isUsingLegacyFolder = true;
292
+ return legacyFolderPath;
293
+ }
294
+ throw new Error(
295
+ `Unable to find Tina folder, if you're working in folder outside of the Tina config be sure to specify --rootPath`
296
+ );
297
+ }
298
+ getTinaGraphQLVersion() {
299
+ var _a, _b;
300
+ if (this.tinaGraphQLVersionFromCLI) {
301
+ return this.tinaGraphQLVersionFromCLI;
302
+ }
303
+ const generatedSchema = import_fs_extra.default.readJSONSync(this.generatedSchemaJSONPath);
304
+ if (!generatedSchema || !(typeof (generatedSchema == null ? void 0 : generatedSchema.version) !== "undefined") || !(typeof ((_a = generatedSchema == null ? void 0 : generatedSchema.version) == null ? void 0 : _a.major) === "string") || !(typeof ((_b = generatedSchema == null ? void 0 : generatedSchema.version) == null ? void 0 : _b.minor) === "string")) {
305
+ throw new Error(
306
+ `Can not find Tina GraphQL version in ${this.generatedSchemaJSONPath}`
368
307
  );
369
- const mutation = `mutation($collection: String!, $relativePath: String!, $params: DocumentUpdateMutation!) {
370
- updateDocument(
371
- collection: $collection,
372
- relativePath: $relativePath,
373
- params: $params
374
- ){__typename}
375
- }`;
376
- const mutationRes = await (0, import_graphql.resolve)({
377
- database,
378
- query: mutation,
379
- variables: {
380
- params,
381
- collection: collection.name,
382
- relativePath
383
- },
384
- isAudit: true,
385
- silenceErrors: true,
386
- verbose: args.verbose || false
387
- });
388
- if (mutationRes.errors) {
389
- mutationRes.errors.forEach((err) => {
390
- error = true;
391
- logger.error(import_chalk.default.red(err.message));
392
- });
393
- }
394
308
  }
309
+ return `${generatedSchema.version.major}.${generatedSchema.version.minor}`;
395
310
  }
396
- return error;
397
- };
398
- var transformDocumentIntoMutationRequestPayload = (document, instructions, defaults) => {
399
- const { _collection, __typename, _template, ...rest } = document;
400
- const params = transformParams(rest);
401
- const paramsWithTemplate = instructions.includeTemplate ? { [_template]: params } : params;
402
- return instructions.includeCollection ? { [_collection]: { ...defaults, ...filterObject(paramsWithTemplate) } } : { ...defaults, ...filterObject(paramsWithTemplate) };
403
- };
404
- var transformParams = (data) => {
405
- if (["string", "number", "boolean"].includes(typeof data)) {
406
- return data;
311
+ printGeneratedClientFilePath() {
312
+ if (this.isUsingTs()) {
313
+ return this.generatedClientTSFilePath.replace(`${this.rootPath}/`, "");
314
+ }
315
+ return this.generatedClientJSFilePath.replace(`${this.rootPath}/`, "");
407
316
  }
408
- if (Array.isArray(data)) {
409
- return data.map((item) => transformParams(item));
317
+ printGeneratedTypesFilePath() {
318
+ return this.generatedTypesTSFilePath.replace(`${this.rootPath}/`, "");
410
319
  }
411
- try {
412
- (0, import_graphql2.assertShape)(
413
- data,
414
- (yup) => yup.object({ _template: yup.string().required() })
415
- );
416
- const { _template, __typename, ...rest } = data;
417
- const nested = transformParams(rest);
418
- return { [_template]: nested };
419
- } catch (e) {
420
- if (e.message === "Failed to assertShape - _template is a required field") {
421
- if (!data) {
422
- return void 0;
423
- return [];
424
- }
425
- const accum = {};
426
- Object.entries(data).map(([keyName, value]) => {
427
- accum[keyName] = transformParams(value);
428
- });
429
- return accum;
430
- } else {
431
- if (!data) {
432
- return void 0;
433
- return [];
434
- }
435
- throw e;
320
+ printoutputHTMLFilePath() {
321
+ return this.outputHTMLFilePath.replace(`${this.publicFolderPath}/`, "");
322
+ }
323
+ printRelativePath(filename) {
324
+ if (filename) {
325
+ return filename.replace(`${this.rootPath}/`, "");
436
326
  }
327
+ throw `No path provided to print`;
437
328
  }
438
- };
439
- function filterObject(obj) {
440
- const ret = {};
441
- Object.keys(obj).filter((key) => obj[key] !== void 0).forEach((key) => ret[key] = obj[key]);
442
- return ret;
443
- }
444
-
445
- // src/cmds/audit/index.ts
446
- var import_chalk3 = __toESM(require("chalk"));
447
- var import_prompts = __toESM(require("prompts"));
448
- var import_metrics = require("@tinacms/metrics");
329
+ printContentRelativePath(filename) {
330
+ if (filename) {
331
+ return filename.replace(`${this.contentRootPath}/`, "");
332
+ }
333
+ throw `No path provided to print`;
334
+ }
335
+ async getPathWithExtension(filepath) {
336
+ const extensions = ["tsx", "ts", "jsx", "js"];
337
+ let result;
338
+ await Promise.all(
339
+ extensions.map(async (ext) => {
340
+ if (result) {
341
+ return;
342
+ }
343
+ const filepathWithExtension = `${filepath}.${ext}`;
344
+ const exists = await import_fs_extra.default.existsSync(filepathWithExtension);
345
+ if (exists) {
346
+ result = filepathWithExtension;
347
+ }
348
+ })
349
+ );
350
+ return result;
351
+ }
352
+ async loadDatabaseFile() {
353
+ const tmpdir = import_path.default.join(import_os.default.tmpdir(), Date.now().toString());
354
+ const outfile = import_path.default.join(tmpdir, "database.build.js");
355
+ await esbuild.build({
356
+ entryPoints: [this.selfHostedDatabaseFilePath],
357
+ bundle: true,
358
+ platform: "node",
359
+ outfile
360
+ });
361
+ const result = require(outfile);
362
+ await import_fs_extra.default.removeSync(outfile);
363
+ return result.default;
364
+ }
365
+ async loadConfigFile(generatedFolderPath, configFilePath) {
366
+ const tmpdir = import_path.default.join(import_os.default.tmpdir(), Date.now().toString());
367
+ const outfile = import_path.default.join(tmpdir, "config.build.jsx");
368
+ const outfile2 = import_path.default.join(tmpdir, "config.build.js");
369
+ const tempTSConfigFile = import_path.default.join(tmpdir, "tsconfig.json");
370
+ await import_fs_extra.default.outputFileSync(tempTSConfigFile, "{}");
371
+ await esbuild.build({
372
+ entryPoints: [configFilePath],
373
+ bundle: true,
374
+ target: ["es2020"],
375
+ platform: "node",
376
+ outfile
377
+ });
378
+ await esbuild.build({
379
+ entryPoints: [outfile],
380
+ bundle: true,
381
+ platform: "node",
382
+ outfile: outfile2
383
+ });
384
+ const result = require(outfile2);
385
+ await import_fs_extra.default.removeSync(outfile);
386
+ await import_fs_extra.default.removeSync(outfile2);
387
+ return result.default;
388
+ }
389
+ };
390
+
391
+ // src/next/commands/dev-command/html.ts
392
+ var devHTML = (port) => `<!DOCTYPE html>
393
+ <html lang="en">
394
+ <head>
395
+ <meta charset="UTF-8" />
396
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
397
+ <title>TinaCMS</title>
398
+ </head>
399
+
400
+ <!-- if development -->
401
+ <script type="module">
402
+ import RefreshRuntime from 'http://localhost:${port}/@react-refresh'
403
+ RefreshRuntime.injectIntoGlobalHook(window)
404
+ window.$RefreshReg$ = () => {}
405
+ window.$RefreshSig$ = () => (type) => type
406
+ window.__vite_plugin_react_preamble_installed__ = true
407
+ <\/script>
408
+ <script type="module" src="http://localhost:${port}/@vite/client"><\/script>
409
+ <script
410
+ type="module"
411
+ src="http://localhost:${port}/src/main.tsx"
412
+ ><\/script>
413
+ <body class="tina-tailwind">
414
+ <div id="root"></div>
415
+ </body>
416
+ </html>`;
417
+
418
+ // src/next/commands/dev-command/server/index.ts
419
+ var import_body_parser = __toESM(require("body-parser"));
420
+ var import_path5 = __toESM(require("path"));
421
+ var import_cors = __toESM(require("cors"));
422
+ var import_vite2 = require("vite");
423
+ var import_graphql = require("@tinacms/graphql");
449
424
 
450
- // src/utils/theme.ts
451
- var import_chalk2 = __toESM(require("chalk"));
452
- var successText = import_chalk2.default.bold.green;
453
- var focusText = import_chalk2.default.bold;
454
- var dangerText = import_chalk2.default.bold.red;
455
- var neutralText = import_chalk2.default.bold.cyan;
456
- var linkText = import_chalk2.default.bold.cyan;
457
- var labelText = import_chalk2.default.bold;
458
- var cmdText = import_chalk2.default.inverse;
459
- var indentedCmd = (str) => {
460
- return ` \u2503 ` + str;
461
- };
462
- var logText = import_chalk2.default.italic.gray;
463
- var warnText = import_chalk2.default.yellowBright.bgBlack;
464
- var titleText = import_chalk2.default.bgHex("d2f1f8").hex("ec4816");
465
- var CONFIRMATION_TEXT = import_chalk2.default.dim("enter to confirm");
466
-
467
- // src/cmds/audit/index.ts
468
- var rootPath = process.cwd();
469
- var audit = async (ctx, next, options) => {
470
- const telemetry = new import_metrics.Telemetry({ disabled: options.noTelemetry });
471
- await telemetry.submitRecord({
472
- event: {
473
- name: "tinacms:cli:audit:invoke",
474
- clean: Boolean(options.clean),
475
- useDefaults: Boolean(options.useDefaultValues)
476
- }
477
- });
478
- if (options.clean) {
479
- logger.info(
480
- `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(
481
- "clean git tree"
482
- )} so unwanted changes can be undone.
483
-
484
- `
485
- );
486
- const res = await (0, import_prompts.default)({
487
- name: "useClean",
488
- type: "confirm",
489
- message: `Do you want to continue?`
425
+ // src/next/commands/dev-command/server/media.ts
426
+ var import_fs_extra2 = __toESM(require("fs-extra"));
427
+ var import_path2 = __toESM(require("path"));
428
+ var import_busboy = __toESM(require("busboy"));
429
+ var createMediaRouter = (config3) => {
430
+ const mediaFolder = import_path2.default.join(
431
+ config3.rootPath,
432
+ config3.publicFolder,
433
+ config3.mediaRoot
434
+ );
435
+ const mediaModel = new MediaModel(config3);
436
+ const handleList = async (req, res) => {
437
+ const requestURL = new URL(req.url, config3.apiURL);
438
+ const folder = requestURL.pathname.replace("/media/list/", "");
439
+ const limit = requestURL.searchParams.get("limit");
440
+ const cursor = requestURL.searchParams.get("cursor");
441
+ const media = await mediaModel.listMedia({
442
+ searchPath: folder,
443
+ cursor,
444
+ limit
490
445
  });
491
- if (!res.useClean) {
492
- logger.warn(import_chalk3.default.yellowBright("\u26A0\uFE0F Audit not complete"));
493
- process.exit(0);
494
- }
495
- }
496
- if (options.useDefaultValues && !options.clean) {
497
- logger.warn(
498
- import_chalk3.default.yellowBright(
499
- "WARNING: using the `--useDefaultValues` without the `--clean` flag has no effect. Please re-run audit and add the `--clean` flag"
500
- )
501
- );
502
- }
503
- const database = ctx.database;
504
- const schema = await database.getSchema();
505
- const collections = schema.getCollections();
506
- let error = false;
507
- for (let i = 0; i < collections.length; i++) {
508
- const collection = collections[i];
509
- const docs = await database.query(
510
- { collection: collection.name, first: -1, filterChain: [] },
511
- (item) => ({ path: item })
512
- );
513
- logger.info(
514
- `Checking ${neutralText(collection.name)} collection. ${docs.edges.length} Documents`
515
- );
516
- const returnError = await auditDocuments({
517
- collection,
518
- database,
519
- rootPath,
520
- useDefaultValues: options.useDefaultValues,
521
- documents: docs.edges,
522
- verbose: ctx.verbose
446
+ res.end(JSON.stringify(media));
447
+ };
448
+ const handleDelete = async (req, res) => {
449
+ const file = decodeURIComponent(req.url.slice("/media/".length));
450
+ const didDelete = await mediaModel.deleteMedia({ searchPath: file });
451
+ res.end(JSON.stringify(didDelete));
452
+ };
453
+ const handlePost = async function(req, res) {
454
+ const bb = (0, import_busboy.default)({ headers: req.headers });
455
+ bb.on("file", (name2, file, info) => {
456
+ const saveTo = import_path2.default.join(mediaFolder, info.filename);
457
+ file.pipe(import_fs_extra2.default.createWriteStream(saveTo));
523
458
  });
524
- error = error || returnError;
525
- }
526
- ctx.error = error;
527
- next();
528
- };
529
- var printFinalMessage = async (ctx, next, _options) => {
530
- if (ctx.error) {
531
- logger.error(
532
- import_chalk3.default.redBright(`\u203C\uFE0F Audit ${import_chalk3.default.bold("failed")} with errors`)
533
- );
534
- } else if (ctx.warning) {
535
- logger.warn(import_chalk3.default.yellowBright("\u26A0\uFE0F Audit passed with warnings"));
536
- } else {
537
- logger.info(import_chalk3.default.greenBright("\u2705 Audit passed"));
538
- }
539
- next();
540
- };
541
-
542
- // src/cmds/baseCmds.ts
543
- var import_config2 = require("dotenv/config");
544
-
545
- // src/middleware.ts
546
- var chain = async (cmds, options) => {
547
- const ctx = {};
548
- const next = async (middlewareIndex) => {
549
- if (middlewareIndex >= cmds.length) {
550
- process.exit(0);
551
- }
459
+ bb.on("error", (error) => {
460
+ res.statusCode = 500;
461
+ if (error instanceof Error) {
462
+ res.end(JSON.stringify({ message: error }));
463
+ } else {
464
+ res.end(JSON.stringify({ message: "Unknown error while uploading" }));
465
+ }
466
+ });
467
+ bb.on("close", () => {
468
+ res.statusCode = 200;
469
+ res.end(JSON.stringify({ success: true }));
470
+ });
471
+ req.pipe(bb);
472
+ };
473
+ return { handleList, handleDelete, handlePost };
474
+ };
475
+ var parseMediaFolder = (str) => {
476
+ let returnString = str;
477
+ if (returnString.startsWith("/"))
478
+ returnString = returnString.substr(1);
479
+ if (returnString.endsWith("/"))
480
+ returnString = returnString.substr(0, returnString.length - 1);
481
+ return returnString;
482
+ };
483
+ var MediaModel = class {
484
+ constructor({ rootPath, publicFolder, mediaRoot }) {
485
+ this.rootPath = rootPath;
486
+ this.mediaRoot = mediaRoot;
487
+ this.publicFolder = publicFolder;
488
+ }
489
+ async listMedia(args) {
552
490
  try {
553
- await cmds[middlewareIndex](
554
- ctx,
555
- () => next(middlewareIndex + 1),
556
- options || {}
491
+ const folderPath = (0, import_path2.join)(
492
+ this.rootPath,
493
+ this.publicFolder,
494
+ this.mediaRoot,
495
+ args.searchPath
557
496
  );
558
- } catch (err) {
559
- console.error(` ${dangerText(err)}`);
560
- if (err.stack) {
561
- console.log(err.stack);
562
- }
563
- process.exit(1);
497
+ const searchPath = parseMediaFolder(args.searchPath);
498
+ const filesStr = await import_fs_extra2.default.readdir(folderPath);
499
+ const filesProm = filesStr.map(async (file) => {
500
+ const filePath = (0, import_path2.join)(folderPath, file);
501
+ const stat = await import_fs_extra2.default.stat(filePath);
502
+ let src = `/${file}`;
503
+ const isFile = stat.isFile();
504
+ if (!isFile) {
505
+ return {
506
+ isFile,
507
+ size: stat.size,
508
+ src,
509
+ filename: file
510
+ };
511
+ }
512
+ if (searchPath) {
513
+ src = `/${searchPath}${src}`;
514
+ }
515
+ if (this.mediaRoot) {
516
+ src = `/${this.mediaRoot}${src}`;
517
+ }
518
+ return {
519
+ isFile,
520
+ size: stat.size,
521
+ src,
522
+ filename: file
523
+ };
524
+ });
525
+ const offset = Number(args.cursor) || 0;
526
+ const limit = Number(args.limit) || 20;
527
+ const rawItems = await Promise.all(filesProm);
528
+ const sortedItems = rawItems.sort((a, b) => {
529
+ if (a.isFile && !b.isFile) {
530
+ return 1;
531
+ }
532
+ if (!a.isFile && b.isFile) {
533
+ return -1;
534
+ }
535
+ return 0;
536
+ });
537
+ const limitItems = sortedItems.slice(offset, offset + limit);
538
+ const files = limitItems.filter((x) => x.isFile);
539
+ const directories = limitItems.filter((x) => !x.isFile).map((x) => x.src);
540
+ const cursor = rawItems.length > offset + limit ? String(offset + limit) : null;
541
+ return {
542
+ files,
543
+ directories,
544
+ cursor
545
+ };
546
+ } catch (error) {
547
+ console.error(error);
548
+ return {
549
+ files: [],
550
+ directories: [],
551
+ error: error == null ? void 0 : error.toString()
552
+ };
564
553
  }
565
- };
566
- if (cmds.length > 0) {
567
- await next(0);
568
- }
569
- };
570
-
571
- // src/cmds/baseCmds.ts
572
- var import_chalk4 = __toESM(require("chalk"));
573
-
574
- // src/cmds/start-server/index.ts
575
- var import_path8 = __toESM(require("path"));
576
- var import_chokidar = __toESM(require("chokidar"));
577
- var import_metrics2 = require("@tinacms/metrics");
578
-
579
- // src/cmds/start-server/lock.ts
580
- var AsyncLock = class {
581
- constructor() {
582
- this.disable = () => {
583
- };
584
- this.promise = Promise.resolve();
585
- }
586
- enable() {
587
- this.promise = new Promise((resolve2) => this.disable = resolve2);
588
- }
589
- };
590
-
591
- // src/cmds/start-server/errors/index.ts
592
- var import_graphql3 = require("@tinacms/graphql");
593
- var BuildSchemaError = class extends Error {
594
- constructor(message) {
595
- super(message);
596
- this.name = "BuildSchemaError";
597
- }
598
- };
599
- var ExecuteSchemaError = class extends Error {
600
- constructor(message) {
601
- super(message);
602
- this.name = "ExecuteSchemaError";
603
554
  }
604
- };
605
- var handleServerErrors = (e) => {
606
- if (e.name === "BuildSchemaError") {
607
- logger.error(`${dangerText(
608
- "ERROR: your schema was not successfully built: see https://tina.io/docs/errors/esbuild-error/ for more details"
609
- )}
610
- Error Message Below
611
- ${e}`);
612
- } else if (e.name === "ExecuteSchemaError") {
613
- logger.error(`${dangerText(
614
- "ERROR: your schema was not successfully executed: see https://tina.io/docs/errors/esbuild-error/ for more details"
615
- )}
616
- Error Message Below
617
- ${e}`);
618
- } else if (e.name === "TinaSchemaValidationError") {
619
- logger.error(`${dangerText(
620
- "ERROR: your schema was not successfully validated: see https://tina.io/docs/schema/ for instructions on how to setup a schema"
621
- )}
622
- Error Message Below
623
- ${e}`);
624
- } else if (e instanceof import_graphql3.TinaFetchError) {
625
- (0, import_graphql3.handleFetchErrorError)(e, true);
626
- } else {
627
- logger.info(
628
- dangerText(
629
- "Compilation failed with errors. Server has not been restarted."
630
- ) + ` see error below
631
- ${e.message}`
632
- );
555
+ async deleteMedia(args) {
556
+ try {
557
+ const file = (0, import_path2.join)(
558
+ this.rootPath,
559
+ this.publicFolder,
560
+ this.mediaRoot,
561
+ args.searchPath
562
+ );
563
+ await import_fs_extra2.default.stat(file);
564
+ await import_fs_extra2.default.remove(file);
565
+ return { ok: true };
566
+ } catch (error) {
567
+ console.error(error);
568
+ return { ok: false, message: error == null ? void 0 : error.toString() };
569
+ }
633
570
  }
634
571
  };
635
572
 
636
- // src/buildTina/index.ts
637
- var import_fs_extra5 = __toESM(require("fs-extra"));
638
- var import_graphql9 = require("@tinacms/graphql");
639
- var import_datalayer = require("@tinacms/datalayer");
640
- var import_memory_level = require("memory-level");
641
- var import_path5 = __toESM(require("path"));
642
-
643
- // src/cmds/compile/index.ts
644
- var _ = __toESM(require("lodash"));
645
- var import_fs_extra2 = __toESM(require("fs-extra"));
646
- var import_path2 = __toESM(require("path"));
573
+ // src/next/commands/dev-command/server/index.ts
647
574
  var import_esbuild = require("esbuild");
648
575
 
649
- // src/lib/getPath.ts
650
- var import_path = __toESM(require("path"));
651
- var import_fs_extra = __toESM(require("fs-extra"));
652
- var fileExists = ({
653
- projectDir,
654
- filename,
655
- allowedTypes
656
- }) => {
657
- if (!import_fs_extra.default.existsSync(projectDir)) {
658
- return false;
659
- }
660
- const filePaths = allowedTypes.map(
661
- (ext) => import_path.default.join(projectDir, `${filename}.${ext}`)
662
- );
663
- let inputFile = void 0;
664
- filePaths.every((path11) => {
665
- if (import_fs_extra.default.existsSync(path11)) {
666
- inputFile = path11;
667
- return false;
576
+ // src/next/vite/index.ts
577
+ var import_path4 = __toESM(require("path"));
578
+ var import_vite = require("vite");
579
+
580
+ // src/next/vite/tailwind.ts
581
+ var import_tailwindcss = __toESM(require("tailwindcss"));
582
+ var import_postcss_nested = __toESM(require("postcss-nested/index.js"));
583
+ var import_nesting = __toESM(require("tailwindcss/nesting/index.js"));
584
+ var import_defaultTheme = __toESM(require("tailwindcss/defaultTheme.js"));
585
+ var import_typography = __toESM(require("@tailwindcss/typography"));
586
+ var import_line_clamp = __toESM(require("@tailwindcss/line-clamp"));
587
+ var import_aspect_ratio = __toESM(require("@tailwindcss/aspect-ratio"));
588
+ var import_path3 = __toESM(require("path"));
589
+ var tinaTailwind = (spaPath, configFilePath) => {
590
+ return {
591
+ name: "vite-plugin-tina",
592
+ config: (viteConfig) => {
593
+ const plugins = [];
594
+ const content2 = [
595
+ import_path3.default.join(spaPath, "src/**/*.{vue,js,ts,jsx,tsx,svelte}"),
596
+ import_path3.default.join(configFilePath)
597
+ ];
598
+ const tw = (0, import_tailwindcss.default)({
599
+ important: ".tina-tailwind",
600
+ theme: {
601
+ columns: {
602
+ auto: "auto",
603
+ 1: "1",
604
+ 2: "2",
605
+ 3: "3",
606
+ 4: "4",
607
+ 5: "5",
608
+ 6: "6",
609
+ 7: "7",
610
+ 8: "8",
611
+ 9: "9",
612
+ 10: "10",
613
+ 11: "11",
614
+ 12: "12",
615
+ "3xs": "256px",
616
+ "2xs": "288px",
617
+ xs: "320px",
618
+ sm: "384px",
619
+ md: "448px",
620
+ lg: "512px",
621
+ xl: "576px",
622
+ "2xl": "672px",
623
+ "3xl": "768px",
624
+ "4xl": "896px",
625
+ "5xl": "1024px",
626
+ "6xl": "1152px",
627
+ "7xl": "1280px"
628
+ },
629
+ spacing: {
630
+ px: "1px",
631
+ 0: "0px",
632
+ 0.5: "2px",
633
+ 1: "4px",
634
+ 1.5: "6px",
635
+ 2: "8px",
636
+ 2.5: "10px",
637
+ 3: "12px",
638
+ 3.5: "14px",
639
+ 4: "16px",
640
+ 5: "20px",
641
+ 6: "24px",
642
+ 7: "28px",
643
+ 8: "32px",
644
+ 9: "36px",
645
+ 10: "40px",
646
+ 11: "44px",
647
+ 12: "48px",
648
+ 14: "56px",
649
+ 16: "64px",
650
+ 18: "72px",
651
+ 20: "80px",
652
+ 24: "96px",
653
+ 28: "114px",
654
+ 32: "128px",
655
+ 36: "144px",
656
+ 40: "160px",
657
+ 44: "176px",
658
+ 48: "192px",
659
+ 52: "208px",
660
+ 56: "224px",
661
+ 60: "240px",
662
+ 64: "256px",
663
+ 72: "288px",
664
+ 80: "320px",
665
+ 96: "384px"
666
+ },
667
+ borderRadius: {
668
+ none: "0px",
669
+ sm: "2px",
670
+ DEFAULT: "4px",
671
+ md: "6px",
672
+ lg: "8px",
673
+ xl: "12px",
674
+ "2xl": "16px",
675
+ "3xl": "24px",
676
+ full: "9999px"
677
+ },
678
+ borderWidth: {
679
+ DEFAULT: "1px",
680
+ 0: "0",
681
+ 2: "2px",
682
+ 3: "3px",
683
+ 4: "4px",
684
+ 6: "6px",
685
+ 8: "8px"
686
+ },
687
+ fontSize: {
688
+ xs: ["13px", { lineHeight: "1.33" }],
689
+ sm: ["14px", { lineHeight: "1.43" }],
690
+ base: ["16px", { lineHeight: "1.5" }],
691
+ md: ["16px", { lineHeight: "1.5" }],
692
+ lg: ["18px", { lineHeight: "1.55" }],
693
+ xl: ["20px", { lineHeight: "1.4" }],
694
+ "2xl": ["24px", { lineHeight: "1.33" }],
695
+ "3xl": ["30px", { lineHeight: "1.2" }],
696
+ "4xl": ["36px", { lineHeight: "1.1" }],
697
+ "5xl": ["48px", { lineHeight: "1" }],
698
+ "6xl": ["60px", { lineHeight: "1" }],
699
+ "7xl": ["72px", { lineHeight: "1" }],
700
+ "8xl": ["96px", { lineHeight: "1" }],
701
+ "9xl": ["128px", { lineHeight: "1" }]
702
+ },
703
+ opacity: {
704
+ 0: "0",
705
+ 5: ".05",
706
+ 7: ".07",
707
+ 10: ".1",
708
+ 15: ".15",
709
+ 20: ".2",
710
+ 25: ".25",
711
+ 30: ".3",
712
+ 40: ".4",
713
+ 50: ".5",
714
+ 60: ".6",
715
+ 70: ".7",
716
+ 75: ".75",
717
+ 80: ".8",
718
+ 90: ".9",
719
+ 100: "1"
720
+ },
721
+ zIndex: {
722
+ "-1": "-1",
723
+ base: "9000",
724
+ panel: "9400",
725
+ menu: "9800",
726
+ chrome: "10200",
727
+ overlay: "10600",
728
+ modal: "10800",
729
+ 0: "0",
730
+ 10: "10",
731
+ 20: "20",
732
+ 30: "30",
733
+ 40: "40",
734
+ 25: "25",
735
+ 50: "50",
736
+ 75: "75",
737
+ 100: "100",
738
+ auto: "auto"
739
+ },
740
+ extend: {
741
+ scale: {
742
+ 97: ".97",
743
+ 103: "1.03"
744
+ },
745
+ transitionDuration: {
746
+ 0: "0ms",
747
+ 2e3: "2000ms"
748
+ },
749
+ boxShadow: {
750
+ xs: "0 0 0 1px rgba(0, 0, 0, 0.05)",
751
+ outline: "0 0 0 3px rgba(66, 153, 225, 0.5)"
752
+ },
753
+ colors: {
754
+ blue: {
755
+ 50: "#DCEEFF",
756
+ 100: "#B4DBFF",
757
+ 200: "#85C5FE",
758
+ 300: "#4EABFE",
759
+ 400: "#2296fe",
760
+ 500: "#0084FF",
761
+ 600: "#0574e4",
762
+ 700: "#0D5DBD",
763
+ 800: "#144696",
764
+ 900: "#1D2C6C",
765
+ 1e3: "#241748"
766
+ },
767
+ gray: {
768
+ 50: "#F6F6F9",
769
+ 100: "#EDECF3",
770
+ 150: "#E6E3EF",
771
+ 200: "#E1DDEC",
772
+ 250: "#C9C5D5",
773
+ 300: "#b2adbe",
774
+ 400: "#918c9e",
775
+ 500: "#716c7f",
776
+ 600: "#565165",
777
+ 700: "#433e52",
778
+ 800: "#363145",
779
+ 900: "#252336",
780
+ 1e3: "#1c1b2e"
781
+ },
782
+ orange: {
783
+ 400: "#EB6337",
784
+ 500: "#EC4815",
785
+ 600: "#DC4419"
786
+ }
787
+ },
788
+ fontFamily: {
789
+ sans: ["Inter", ...import_defaultTheme.default.fontFamily.sans]
790
+ },
791
+ lineHeight: {
792
+ 3: "12px",
793
+ 4: "16px",
794
+ 5: "20px",
795
+ 6: "24px",
796
+ 7: "28px",
797
+ 8: "32px",
798
+ 9: "36px",
799
+ 10: "40px"
800
+ },
801
+ maxWidth: {
802
+ form: "900px"
803
+ },
804
+ screens: {
805
+ xs: "320px",
806
+ sm: "560px",
807
+ md: "720px",
808
+ lg: "1030px"
809
+ }
810
+ }
811
+ },
812
+ content: content2,
813
+ plugins: [
814
+ (0, import_typography.default)({ className: "tina-prose" }),
815
+ import_line_clamp.default,
816
+ import_aspect_ratio.default
817
+ ]
818
+ });
819
+ plugins.push(import_nesting.default);
820
+ plugins.push(import_postcss_nested.default);
821
+ plugins.push(tw);
822
+ return {
823
+ css: {
824
+ postcss: {
825
+ plugins
826
+ }
827
+ }
828
+ };
668
829
  }
669
- return true;
670
- });
671
- return Boolean(inputFile);
830
+ };
672
831
  };
673
- var getPath = ({
674
- projectDir,
675
- filename,
676
- allowedTypes,
677
- errorMessage
678
- }) => {
679
- if (!import_fs_extra.default.existsSync(projectDir)) {
680
- if (errorMessage) {
681
- throw new Error(errorMessage);
682
- } else {
683
- throw new Error(`Could not find ${projectDir}`);
684
- }
685
- }
686
- const filePaths = allowedTypes.map(
687
- (ext) => import_path.default.join(projectDir, `${filename}.${ext}`)
688
- );
689
- let inputFile = void 0;
690
- filePaths.every((path11) => {
691
- if (import_fs_extra.default.existsSync(path11)) {
692
- inputFile = path11;
693
- return false;
694
- }
695
- return true;
696
- });
697
- if (!inputFile && errorMessage) {
698
- throw new Error(errorMessage);
699
- }
700
- return inputFile;
701
- };
702
-
703
- // src/cmds/compile/index.ts
704
- var generatedFilesToRemove = [
705
- "_graphql.json",
706
- "__lookup.json",
707
- "__schema.json",
708
- "frags.gql",
709
- "queries.gql",
710
- "schema.gql",
711
- "db"
712
- ];
713
- var resetGeneratedFolder = async ({
714
- tinaGeneratedPath,
715
- usingTs,
716
- isBuild
832
+
833
+ // src/next/vite/index.ts
834
+ var import_normalize_path2 = __toESM(require("normalize-path"));
835
+ var createConfig = async ({
836
+ configManager,
837
+ database,
838
+ apiURL,
839
+ plugins = [],
840
+ noSDK,
841
+ noWatch,
842
+ rollupOptions
717
843
  }) => {
718
- try {
719
- if (isBuild) {
720
- await import_fs_extra2.default.emptyDir(tinaGeneratedPath);
721
- } else {
722
- for (let index = 0; index < generatedFilesToRemove.length; index++) {
723
- const file = generatedFilesToRemove[index];
724
- if (file === "db") {
725
- try {
726
- await import_fs_extra2.default.remove(import_path2.default.join(tinaGeneratedPath, file));
727
- } catch (_e) {
728
- }
844
+ const publicEnv = {};
845
+ Object.keys(process.env).forEach((key) => {
846
+ if (key.startsWith("TINA_PUBLIC_") || key.startsWith("NEXT_PUBLIC_") || key === "NODE_ENV" || key === "HEAD") {
847
+ try {
848
+ if (typeof process.env[key] === "string") {
849
+ publicEnv[key] = process.env[key];
729
850
  } else {
730
- await import_fs_extra2.default.remove(import_path2.default.join(tinaGeneratedPath, file));
851
+ publicEnv[key] = JSON.stringify(process.env[key]);
731
852
  }
853
+ } catch (error) {
854
+ console.warn(
855
+ `Could not stringify public env process.env.${key} env variable`
856
+ );
857
+ console.warn(error);
732
858
  }
733
859
  }
734
- } catch (e) {
735
- console.log(e);
736
- }
737
- await import_fs_extra2.default.mkdirp(tinaGeneratedPath);
738
- const ext = usingTs ? "ts" : "js";
739
- if (!await import_fs_extra2.default.pathExists(import_path2.default.join(tinaGeneratedPath, `types.${ext}`))) {
740
- await import_fs_extra2.default.writeFile(
741
- import_path2.default.join(tinaGeneratedPath, `types.${ext}`),
742
- `
743
- export const queries = (client)=>({})
744
- `
745
- );
746
- }
747
- if (!await import_fs_extra2.default.pathExists(import_path2.default.join(tinaGeneratedPath, `client.${ext}`))) {
748
- await import_fs_extra2.default.writeFile(
749
- import_path2.default.join(tinaGeneratedPath, `client.${ext}`),
750
- `
751
- export const client = ()=>{}
752
- export default client
753
- `
754
- );
755
- }
756
- await import_fs_extra2.default.outputFile(
757
- import_path2.default.join(tinaGeneratedPath, ".gitignore"),
758
- `app
759
- db
760
- prebuild
761
- client.ts
762
- client.js
763
- types.ts
764
- types.js
765
- types.d.ts
766
- frags.gql
767
- queries.gql
768
- schema.gql
769
- out.jsx
770
- `
771
- );
772
- };
773
- var cleanup = async ({ tinaTempPath }) => {
774
- await import_fs_extra2.default.remove(tinaTempPath);
775
- };
776
- var compileFile = async (options, fileName) => {
777
- const root = options.rootPath;
778
- if (!root) {
779
- throw new Error("ctx.rootPath has not been attached");
780
- }
781
- const tinaPath = import_path2.default.join(root, ".tina");
782
- const tsConfigPath = import_path2.default.join(root, "tsconfig.json");
783
- const tinaGeneratedPath = import_path2.default.join(tinaPath, "__generated__");
784
- const tinaTempPath = import_path2.default.join(tinaGeneratedPath, `temp_${fileName}`);
785
- const packageJSONFilePath = import_path2.default.join(root, "package.json");
786
- if (!options.schemaFileType) {
787
- const usingTs = await import_fs_extra2.default.pathExists(tsConfigPath);
788
- options = { ...options, schemaFileType: usingTs ? "ts" : "js" };
789
- }
790
- if (options.verbose) {
791
- logger.info(logText(`Compiling ${fileName}...`));
792
- }
793
- const { schemaFileType: requestedSchemaFileType = "ts" } = options;
794
- const schemaFileType2 = (requestedSchemaFileType === "ts" || requestedSchemaFileType === "tsx") && "ts" || (requestedSchemaFileType === "js" || requestedSchemaFileType === "jsx") && "js";
795
- if (!schemaFileType2) {
796
- throw new Error(
797
- `Requested schema file type '${requestedSchemaFileType}' is not valid. Supported schema file types: 'ts, js, tsx, jsx'`
798
- );
799
- }
800
- try {
801
- const define = {};
802
- if (!process.env.NODE_ENV) {
803
- define["process.env.NODE_ENV"] = options.dev ? '"development"' : '"production"';
804
- }
805
- const inputFile = getPath({
806
- projectDir: tinaPath,
807
- filename: fileName,
808
- allowedTypes: ["js", "jsx", "tsx", "ts"],
809
- errorMessage: `Must provide a ${fileName}.{js,jsx,tsx,ts}`
810
- });
811
- await transpile(
812
- inputFile,
813
- `${fileName}.cjs`,
814
- tinaTempPath,
815
- options.verbose,
816
- define,
817
- packageJSONFilePath
818
- );
819
- } catch (e) {
820
- await cleanup({ tinaTempPath });
821
- throw new BuildSchemaError(e);
822
- }
823
- Object.keys(require.cache).map((key) => {
824
- if (key.startsWith(tinaTempPath)) {
825
- delete require.cache[require.resolve(key)];
826
- }
827
- });
828
- let returnObject = {};
829
- try {
830
- const schemaFunc = require(import_path2.default.join(tinaTempPath, `${fileName}.cjs`));
831
- returnObject = schemaFunc.default;
832
- await cleanup({ tinaTempPath });
833
- } catch (e) {
834
- await cleanup({ tinaTempPath });
835
- if (e instanceof Error) {
836
- if (e.name === "TinaSchemaValidationError") {
837
- throw e;
838
- }
839
- }
840
- throw new ExecuteSchemaError(e);
841
- }
842
- return returnObject;
843
- };
844
- var compileSchema = async (options) => {
845
- const root = options.rootPath;
846
- const tinaPath = import_path2.default.join(root, ".tina");
847
- const tinaGeneratedPath = import_path2.default.join(tinaPath, "__generated__");
848
- const tinaConfigPath = import_path2.default.join(tinaGeneratedPath, "config");
849
- const schemaExists = fileExists({
850
- projectDir: tinaPath,
851
- filename: "schema",
852
- allowedTypes: ["js", "jsx", "tsx", "ts"]
853
860
  });
854
- const configExists = fileExists({
855
- projectDir: tinaPath,
856
- filename: "config",
857
- allowedTypes: ["js", "jsx", "tsx", "ts"]
858
- });
859
- if (!schemaExists && !configExists) {
860
- throw new Error(
861
- "No schema or config file found in .tina folder. Please run `npx @tinacms/cli@latest init` to generate a schema file."
862
- );
863
- }
864
- let schema;
865
- if (schemaExists && !configExists) {
866
- console.warn(
867
- `schema.{ts,tsx,js,jsx} will soon be deprecated, in favor of the new config.{ts,tsx,js,jsx}
868
- See here for migration steps, see here: https://tina.io/blog/upgrading-to-iframe`
861
+ const alias = {
862
+ TINA_IMPORT: configManager.tinaConfigFilePath,
863
+ SCHEMA_IMPORT: configManager.generatedGraphQLJSONPath
864
+ };
865
+ if (noSDK) {
866
+ alias["CLIENT_IMPORT"] = import_path4.default.join(
867
+ configManager.spaRootPath,
868
+ "src",
869
+ "dummy-client.ts"
869
870
  );
870
- schema = await compileFile(options, "schema");
871
- }
872
- if (configExists) {
873
- const config2 = await compileFile(options, "config");
874
- const configCopy = _.cloneDeep(config2);
875
- delete configCopy.schema;
876
- if (config2 == null ? void 0 : config2.schema) {
877
- schema = { ...config2.schema, config: configCopy };
871
+ } else {
872
+ alias["CLIENT_IMPORT"] = configManager.isUsingTs() ? configManager.generatedTypesTSFilePath : configManager.generatedTypesJSFilePath;
873
+ }
874
+ const config3 = {
875
+ root: configManager.spaRootPath,
876
+ base: `/${(0, import_normalize_path2.default)(configManager.config.build.outputFolder)}/`,
877
+ appType: "spa",
878
+ resolve: {
879
+ alias,
880
+ dedupe: ["graphql", "tinacms", "@tinacms/toolkit", "react", "react-dom"]
881
+ },
882
+ define: {
883
+ "process.env": `new Object(${JSON.stringify(publicEnv)})`,
884
+ "process.platform": `"${process.platform}"`,
885
+ __API_URL__: `"${apiURL}"`,
886
+ __TOKEN__: `"${configManager.config.token}"`,
887
+ __TINA_GRAPHQL_VERSION__: `"${configManager.getTinaGraphQLVersion()}"`
888
+ },
889
+ optimizeDeps: {
890
+ force: true,
891
+ include: ["react/jsx-runtime", "react/jsx-dev-runtime"]
892
+ },
893
+ server: {
894
+ watch: noWatch ? {
895
+ ignored: ["**/*"]
896
+ } : void 0,
897
+ fs: {
898
+ strict: false
899
+ }
900
+ },
901
+ build: {
902
+ sourcemap: true,
903
+ outDir: configManager.outputFolderPath,
904
+ emptyOutDir: true,
905
+ rollupOptions
906
+ },
907
+ plugins: [
908
+ (0, import_vite.splitVendorChunkPlugin)(),
909
+ tinaTailwind(configManager.spaRootPath, configManager.tinaConfigFilePath),
910
+ ...plugins
911
+ ]
912
+ };
913
+ return config3;
914
+ };
915
+
916
+ // src/next/commands/dev-command/server/index.ts
917
+ var createDevServer = async (configManager, database, apiURL, noSDK, noWatch) => {
918
+ const plugins = [
919
+ {
920
+ name: "transform-tsx",
921
+ async transform(code, id) {
922
+ if (id.startsWith(configManager.rootPath)) {
923
+ const extName = import_path5.default.extname(id);
924
+ if (extName.startsWith(".tsx") || extName.startsWith(".ts")) {
925
+ const result = await (0, import_esbuild.transform)(code, { loader: "tsx" });
926
+ return {
927
+ code: result.code
928
+ };
929
+ }
930
+ }
931
+ }
932
+ },
933
+ {
934
+ name: "graphql-endpoints",
935
+ configureServer(server) {
936
+ server.middlewares.use((0, import_cors.default)());
937
+ server.middlewares.use(import_body_parser.default.json());
938
+ server.middlewares.use(async (req, res, next) => {
939
+ var _a;
940
+ const mediaPaths = (_a = configManager.config.media) == null ? void 0 : _a.tina;
941
+ const mediaRouter = createMediaRouter({
942
+ rootPath: configManager.rootPath,
943
+ apiURL,
944
+ publicFolder: parseMediaFolder((mediaPaths == null ? void 0 : mediaPaths.publicFolder) || ""),
945
+ mediaRoot: parseMediaFolder((mediaPaths == null ? void 0 : mediaPaths.mediaRoot) || "")
946
+ });
947
+ if (req.url.startsWith("/media/upload")) {
948
+ await mediaRouter.handlePost(req, res);
949
+ return;
950
+ }
951
+ if (req.url.startsWith("/media")) {
952
+ if (req.method === "DELETE") {
953
+ await mediaRouter.handleDelete(req, res);
954
+ return;
955
+ }
956
+ }
957
+ if (req.url.startsWith("/media/list")) {
958
+ await mediaRouter.handleList(req, res);
959
+ return;
960
+ }
961
+ if (req.url === "/altair") {
962
+ res.end(
963
+ JSON.stringify({
964
+ status: "The GraphQL playground has moved to <your-dev-url>/index.html#/graphql"
965
+ })
966
+ );
967
+ return;
968
+ }
969
+ if (req.url === "/graphql") {
970
+ const { query, variables } = req.body;
971
+ const result = await (0, import_graphql.resolve)({
972
+ config: {
973
+ useRelativeMedia: true
974
+ },
975
+ database,
976
+ query,
977
+ variables,
978
+ verbose: false
979
+ });
980
+ res.end(JSON.stringify(result));
981
+ return;
982
+ }
983
+ next();
984
+ });
985
+ }
878
986
  }
879
- }
880
- await import_fs_extra2.default.outputFile(
881
- import_path2.default.join(tinaConfigPath, `schema.json`),
882
- JSON.stringify(schema, null, 2)
987
+ ];
988
+ return (0, import_vite2.createServer)(
989
+ await createConfig({
990
+ configManager,
991
+ database,
992
+ apiURL,
993
+ plugins,
994
+ noSDK,
995
+ noWatch,
996
+ rollupOptions: {
997
+ input: configManager.spaMainPath
998
+ }
999
+ })
883
1000
  );
884
- return schema;
885
1001
  };
886
- var transpile = async (inputFile, outputFile, tempDir, verbose, define, packageJSONFilePath, platform = "neutral") => {
887
- if (verbose)
888
- logger.info(logText("Building javascript..."));
889
- const packageJSON = JSON.parse(
890
- import_fs_extra2.default.readFileSync(packageJSONFilePath).toString() || "{}"
891
- );
892
- const deps = (packageJSON == null ? void 0 : packageJSON.dependencies) || [];
893
- const peerDeps = (packageJSON == null ? void 0 : packageJSON.peerDependencies) || [];
894
- const devDeps = (packageJSON == null ? void 0 : packageJSON.devDependencies) || [];
895
- const external = Object.keys({ ...deps, ...peerDeps, ...devDeps });
896
- const prebuiltInputPath = import_path2.default.join(tempDir, "temp-output.jsx");
897
- await (0, import_esbuild.build)({
898
- bundle: true,
899
- platform,
900
- target: ["es2020"],
901
- entryPoints: [inputFile],
902
- treeShaking: true,
903
- external: [...external, "./node_modules/*"],
904
- loader: loaders,
905
- outfile: prebuiltInputPath,
906
- define
907
- });
908
- const tempTsConfigPath = import_path2.default.join(tempDir, "temp-tsconfig.json");
909
- await import_fs_extra2.default.outputFileSync(tempTsConfigPath, "{}");
910
- const outputPath = import_path2.default.join(tempDir, outputFile);
911
- await (0, import_esbuild.build)({
912
- bundle: true,
913
- platform,
914
- target: ["node10.4"],
915
- entryPoints: [prebuiltInputPath],
916
- format: "cjs",
917
- treeShaking: true,
918
- external: [...external, "./node_modules/*"],
919
- tsconfig: tempTsConfigPath,
920
- loader: loaders,
921
- outfile: outputPath,
922
- define
923
- });
924
- if (verbose)
925
- logger.info(logText(`Javascript built`));
926
- };
927
- var defineSchema = (config2) => {
928
- return config2;
929
- };
930
- var loaders = {
931
- ".aac": "file",
932
- ".css": "file",
933
- ".eot": "file",
934
- ".flac": "file",
935
- ".gif": "file",
936
- ".jpeg": "file",
937
- ".jpg": "file",
938
- ".json": "json",
939
- ".mp3": "file",
940
- ".mp4": "file",
941
- ".ogg": "file",
942
- ".otf": "file",
943
- ".png": "file",
944
- ".svg": "file",
945
- ".ttf": "file",
946
- ".wav": "file",
947
- ".webm": "file",
948
- ".webp": "file",
949
- ".woff": "file",
950
- ".woff2": "file",
951
- ".js": "jsx",
952
- ".jsx": "jsx",
953
- ".tsx": "tsx"
954
- };
955
-
956
- // src/cmds/query-gen/genTypes.ts
957
- var import_graphql8 = require("graphql");
1002
+
1003
+ // src/next/codegen/index.ts
958
1004
  var import_fs_extra3 = __toESM(require("fs-extra"));
959
- var import_path3 = __toESM(require("path"));
1005
+ var import_graphql6 = require("graphql");
960
1006
 
961
- // src/codegen/index.ts
962
- var import_graphql7 = require("graphql");
1007
+ // src/next/codegen/codegen/index.ts
1008
+ var import_graphql5 = require("graphql");
963
1009
 
964
- // src/codegen/plugin.ts
965
- var AddGeneratedClientFunc = (_schema, _documents, _config, _info) => {
966
- return `
1010
+ // src/next/codegen/codegen/plugin.ts
1011
+ var AddGeneratedClientFunc = (apiURL) => {
1012
+ return (_schema, _documents, _config, _info) => {
1013
+ return `
967
1014
  // TinaSDK generated code
968
1015
  import { createClient, TinaClient } from "tinacms/dist/client";
969
1016
 
@@ -990,7 +1037,7 @@ const generateRequester = (client: TinaClient) => {
990
1037
  **/
991
1038
  export const ExperimentalGetTinaClient = () =>
992
1039
  getSdk(
993
- generateRequester(createClient({ url: "http://localhost:4001/graphql", queries }))
1040
+ generateRequester(createClient({ url: "${apiURL}", queries }))
994
1041
  );
995
1042
 
996
1043
  export const queries = (client: TinaClient) => {
@@ -998,26 +1045,27 @@ export const queries = (client: TinaClient) => {
998
1045
  return getSdk(requester);
999
1046
  };
1000
1047
  `;
1048
+ };
1001
1049
  };
1002
- var AddGeneratedClient = {
1003
- plugin: AddGeneratedClientFunc
1004
- };
1050
+ var AddGeneratedClient = (apiURL) => ({
1051
+ plugin: AddGeneratedClientFunc(apiURL)
1052
+ });
1005
1053
 
1006
- // src/codegen/index.ts
1054
+ // src/next/codegen/codegen/index.ts
1007
1055
  var import_graphql_file_loader = require("@graphql-tools/graphql-file-loader");
1008
1056
  var import_core = require("@graphql-codegen/core");
1009
1057
  var import_load = require("@graphql-tools/load");
1010
1058
  var import_typescript_operations = require("@graphql-codegen/typescript-operations");
1011
1059
  var import_typescript = require("@graphql-codegen/typescript");
1012
1060
 
1013
- // src/codegen/sdkPlugin/index.ts
1014
- var import_graphql5 = require("graphql");
1015
- var import_graphql6 = require("graphql");
1061
+ // src/next/codegen/codegen/sdkPlugin/index.ts
1062
+ var import_graphql3 = require("graphql");
1063
+ var import_graphql4 = require("graphql");
1016
1064
 
1017
- // src/codegen/sdkPlugin/visitor.ts
1065
+ // src/next/codegen/codegen/sdkPlugin/visitor.ts
1018
1066
  var import_visitor_plugin_common = require("@graphql-codegen/visitor-plugin-common");
1019
1067
  var import_auto_bind = __toESM(require("auto-bind"));
1020
- var import_graphql4 = require("graphql");
1068
+ var import_graphql2 = require("graphql");
1021
1069
  var GenericSdkVisitor = class extends import_visitor_plugin_common.ClientSideBaseVisitor {
1022
1070
  constructor(schema, fragments, rawConfig) {
1023
1071
  super(schema, fragments, rawConfig, {
@@ -1034,7 +1082,7 @@ var GenericSdkVisitor = class extends import_visitor_plugin_common.ClientSideBas
1034
1082
  buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes) {
1035
1083
  if (node.name == null) {
1036
1084
  throw new Error(
1037
- "Plugin 'generic-sdk' cannot generate SDK for unnamed operation.\n\n" + (0, import_graphql4.print)(node)
1085
+ "Plugin 'generic-sdk' cannot generate SDK for unnamed operation.\n\n" + (0, import_graphql2.print)(node)
1038
1086
  );
1039
1087
  } else {
1040
1088
  this._operationsToInclude.push({
@@ -1051,13 +1099,13 @@ var GenericSdkVisitor = class extends import_visitor_plugin_common.ClientSideBas
1051
1099
  const usingObservable = !!this.config.usingObservableFrom;
1052
1100
  const allPossibleActions = this._operationsToInclude.map((o) => {
1053
1101
  const optionalVariables = !o.node.variableDefinitions || o.node.variableDefinitions.length === 0 || o.node.variableDefinitions.every(
1054
- (v) => v.type.kind !== import_graphql4.Kind.NON_NULL_TYPE || v.defaultValue
1102
+ (v) => v.type.kind !== import_graphql2.Kind.NON_NULL_TYPE || v.defaultValue
1055
1103
  );
1056
1104
  const returnType = usingObservable && o.operationType === "Subscription" ? "Observable" : "Promise";
1057
1105
  return `${o.node.name.value}(variables${optionalVariables ? "?" : ""}: ${o.operationVariablesTypes}, options?: C): ${returnType}<${o.operationResultType}> {
1058
1106
  return requester<${o.operationResultType}, ${o.operationVariablesTypes}>(${o.documentVariableName}, variables, options);
1059
1107
  }`;
1060
- }).map((s) => (0, import_visitor_plugin_common.indentMultiline)(s, 2));
1108
+ }).map((s2) => (0, import_visitor_plugin_common.indentMultiline)(s2, 2));
1061
1109
  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>"}
1062
1110
  export function getSdk<C>(requester: Requester<C>) {
1063
1111
  return {
@@ -1068,26 +1116,26 @@ var GenericSdkVisitor = class extends import_visitor_plugin_common.ClientSideBas
1068
1116
  }
1069
1117
  };
1070
1118
 
1071
- // src/codegen/sdkPlugin/index.ts
1072
- var plugin = (schema, documents, config2) => {
1073
- const allAst = (0, import_graphql6.concatAST)(
1119
+ // src/next/codegen/codegen/sdkPlugin/index.ts
1120
+ var plugin = (schema, documents, config3) => {
1121
+ const allAst = (0, import_graphql4.concatAST)(
1074
1122
  documents.reduce((prev, v) => {
1075
1123
  return [...prev, v.document];
1076
1124
  }, [])
1077
1125
  );
1078
1126
  const allFragments = [
1079
1127
  ...allAst.definitions.filter(
1080
- (d) => d.kind === import_graphql6.Kind.FRAGMENT_DEFINITION
1128
+ (d) => d.kind === import_graphql4.Kind.FRAGMENT_DEFINITION
1081
1129
  ).map((fragmentDef) => ({
1082
1130
  node: fragmentDef,
1083
1131
  name: fragmentDef.name.value,
1084
1132
  onType: fragmentDef.typeCondition.name.value,
1085
1133
  isExternal: false
1086
1134
  })),
1087
- ...config2.externalFragments || []
1135
+ ...config3.externalFragments || []
1088
1136
  ];
1089
- const visitor = new GenericSdkVisitor(schema, allFragments, config2);
1090
- const visitorResult = (0, import_graphql5.visit)(allAst, { leave: visitor });
1137
+ const visitor = new GenericSdkVisitor(schema, allFragments, config3);
1138
+ const visitorResult = (0, import_graphql3.visit)(allAst, { leave: visitor });
1091
1139
  return {
1092
1140
  content: [
1093
1141
  visitor.fragments,
@@ -1097,22 +1145,15 @@ var plugin = (schema, documents, config2) => {
1097
1145
  };
1098
1146
  };
1099
1147
 
1100
- // src/codegen/index.ts
1101
- var generateTypes = async (schema, queryPathGlob = process.cwd(), fragDocPath = process.cwd(), options = {
1102
- noSDK: false,
1103
- verbose: false
1104
- }) => {
1105
- if (options.verbose)
1106
- logger.info("Generating types...");
1148
+ // src/next/codegen/codegen/index.ts
1149
+ var generateTypes = async (schema, queryPathGlob = process.cwd(), fragDocPath = process.cwd(), apiURL) => {
1107
1150
  let docs = [];
1108
1151
  let fragDocs = [];
1109
- if (!options.noSDK) {
1110
- docs = await loadGraphQLDocuments(queryPathGlob);
1111
- fragDocs = await loadGraphQLDocuments(fragDocPath);
1112
- }
1152
+ docs = await loadGraphQLDocuments(queryPathGlob);
1153
+ fragDocs = await loadGraphQLDocuments(fragDocPath);
1113
1154
  const res = await (0, import_core.codegen)({
1114
1155
  filename: process.cwd(),
1115
- schema: (0, import_graphql7.parse)((0, import_graphql7.printSchema)(schema)),
1156
+ schema: (0, import_graphql5.parse)((0, import_graphql5.printSchema)(schema)),
1116
1157
  documents: [...docs, ...fragDocs],
1117
1158
  config: {},
1118
1159
  plugins: [
@@ -1133,7 +1174,7 @@ var generateTypes = async (schema, queryPathGlob = process.cwd(), fragDocPath =
1133
1174
  typescriptSdk: {
1134
1175
  plugin
1135
1176
  },
1136
- AddGeneratedClient
1177
+ AddGeneratedClient: AddGeneratedClient(apiURL)
1137
1178
  }
1138
1179
  });
1139
1180
  return res;
@@ -1155,66 +1196,132 @@ var loadGraphQLDocuments = async (globPath) => {
1155
1196
  return result;
1156
1197
  };
1157
1198
 
1158
- // src/cmds/query-gen/genTypes.ts
1199
+ // src/next/codegen/index.ts
1159
1200
  var import_esbuild2 = require("esbuild");
1160
1201
  var TINA_HOST = "content.tinajs.io";
1161
- async function genClient({
1162
- tinaSchema,
1163
- usingTs,
1164
- rootPath: rootPath2
1165
- }, options) {
1166
- var _a, _b, _c, _d, _e, _f, _g;
1167
- const generatedPath = import_path3.default.join(rootPath2, ".tina", "__generated__");
1168
- const branch = (_a = tinaSchema == null ? void 0 : tinaSchema.config) == null ? void 0 : _a.branch;
1169
- const clientId = (_b = tinaSchema == null ? void 0 : tinaSchema.config) == null ? void 0 : _b.clientId;
1170
- const token = (_c = tinaSchema.config) == null ? void 0 : _c.token;
1171
- const baseUrl = ((_e = (_d = tinaSchema == null ? void 0 : tinaSchema.config) == null ? void 0 : _d.tinaioConfig) == null ? void 0 : _e.contentApiUrlOverride) || `https://${TINA_HOST}`;
1172
- if ((!branch || !clientId || !token) && !(options == null ? void 0 : options.local) && !((_f = tinaSchema == null ? void 0 : tinaSchema.config) == null ? void 0 : _f.contentApiUrlOverride)) {
1173
- const missing = [];
1174
- if (!branch)
1175
- missing.push("branch");
1176
- if (!clientId)
1177
- missing.push("clientId");
1178
- if (!token)
1179
- missing.push("token");
1180
- throw new Error(
1181
- `Client not configured properly. Missing ${missing.join(
1182
- ", "
1183
- )}. Please visit https://tina.io/docs/tina-cloud/connecting-site/ for more information`
1202
+ var Codegen = class {
1203
+ constructor({
1204
+ configManager,
1205
+ port,
1206
+ schema,
1207
+ noSDK,
1208
+ queryDoc,
1209
+ fragDoc
1210
+ }) {
1211
+ this.configManager = configManager;
1212
+ this.port = port;
1213
+ this.schema = schema;
1214
+ this.noSDK = noSDK;
1215
+ this.queryDoc = queryDoc;
1216
+ this.fragDoc = fragDoc;
1217
+ }
1218
+ async removeGeneratedFilesIfExists() {
1219
+ await unlinkIfExists(this.configManager.generatedClientJSFilePath);
1220
+ await unlinkIfExists(this.configManager.generatedTypesDFilePath);
1221
+ await unlinkIfExists(this.configManager.generatedTypesJSFilePath);
1222
+ await unlinkIfExists(this.configManager.generatedTypesTSFilePath);
1223
+ await unlinkIfExists(this.configManager.generatedClientTSFilePath);
1224
+ await unlinkIfExists(this.configManager.generatedQueriesFilePath);
1225
+ await unlinkIfExists(this.configManager.generatedFragmentsFilePath);
1226
+ }
1227
+ async execute() {
1228
+ const apiURL = this.getApiURL();
1229
+ if (this.noSDK) {
1230
+ await this.removeGeneratedFilesIfExists();
1231
+ return apiURL;
1232
+ }
1233
+ await import_fs_extra3.default.outputFile(
1234
+ this.configManager.generatedQueriesFilePath,
1235
+ this.queryDoc
1184
1236
  );
1237
+ await import_fs_extra3.default.outputFile(
1238
+ this.configManager.generatedFragmentsFilePath,
1239
+ this.fragDoc
1240
+ );
1241
+ await maybeWarnFragmentSize(this.configManager.generatedFragmentsFilePath);
1242
+ const { clientString } = await this.genClient();
1243
+ const { codeString, schemaString } = await this.genTypes();
1244
+ await import_fs_extra3.default.outputFile(
1245
+ this.configManager.generatedGraphQLGQLPath,
1246
+ schemaString
1247
+ );
1248
+ if (this.configManager.isUsingTs()) {
1249
+ await import_fs_extra3.default.outputFile(
1250
+ this.configManager.generatedTypesTSFilePath,
1251
+ codeString
1252
+ );
1253
+ await import_fs_extra3.default.outputFile(
1254
+ this.configManager.generatedClientTSFilePath,
1255
+ clientString
1256
+ );
1257
+ await unlinkIfExists(this.configManager.generatedClientJSFilePath);
1258
+ await unlinkIfExists(this.configManager.generatedTypesDFilePath);
1259
+ await unlinkIfExists(this.configManager.generatedTypesJSFilePath);
1260
+ } else {
1261
+ await import_fs_extra3.default.outputFile(
1262
+ this.configManager.generatedTypesDFilePath,
1263
+ codeString
1264
+ );
1265
+ const jsCode = await (0, import_esbuild2.transform)(codeString, { loader: "ts" });
1266
+ await import_fs_extra3.default.outputFile(
1267
+ this.configManager.generatedTypesJSFilePath,
1268
+ jsCode.code
1269
+ );
1270
+ await import_fs_extra3.default.outputFile(
1271
+ this.configManager.generatedClientJSFilePath,
1272
+ clientString
1273
+ );
1274
+ await unlinkIfExists(this.configManager.generatedTypesTSFilePath);
1275
+ await unlinkIfExists(this.configManager.generatedClientTSFilePath);
1276
+ }
1277
+ return apiURL;
1185
1278
  }
1186
- let apiURL = options.local ? `http://localhost:${options.port || 4001}/graphql` : `${baseUrl}/content/${clientId}/github/${branch}`;
1187
- if ((_g = tinaSchema.config) == null ? void 0 : _g.contentApiUrlOverride) {
1188
- apiURL = tinaSchema.config.contentApiUrlOverride;
1279
+ getApiURL() {
1280
+ var _a, _b, _c, _d;
1281
+ const branch = (_a = this.configManager.config) == null ? void 0 : _a.branch;
1282
+ const clientId = (_b = this.configManager.config) == null ? void 0 : _b.clientId;
1283
+ const token = (_c = this.configManager.config) == null ? void 0 : _c.token;
1284
+ const version2 = this.configManager.getTinaGraphQLVersion();
1285
+ const baseUrl = ((_d = this.configManager.config.tinaioConfig) == null ? void 0 : _d.contentApiUrlOverride) || `https://${TINA_HOST}`;
1286
+ if ((!branch || !clientId || !token) && !this.port && !this.configManager.config.contentApiUrlOverride) {
1287
+ const missing = [];
1288
+ if (!branch)
1289
+ missing.push("branch");
1290
+ if (!clientId)
1291
+ missing.push("clientId");
1292
+ if (!token)
1293
+ missing.push("token");
1294
+ throw new Error(
1295
+ `Client not configured properly. Missing ${missing.join(
1296
+ ", "
1297
+ )}. Please visit https://tina.io/docs/tina-cloud/connecting-site/ for more information`
1298
+ );
1299
+ }
1300
+ let apiURL = this.port ? `http://localhost:${this.port}/graphql` : `${baseUrl}/${version2}/content/${clientId}/github/${branch}`;
1301
+ if (this.configManager.config.contentApiUrlOverride) {
1302
+ apiURL = this.configManager.config.contentApiUrlOverride;
1303
+ }
1304
+ return apiURL;
1189
1305
  }
1190
- const clientPath = import_path3.default.join(generatedPath, `client.${usingTs ? "ts" : "js"}`);
1191
- import_fs_extra3.default.writeFileSync(
1192
- clientPath,
1193
- `import { createClient } from "tinacms/dist/client";
1306
+ async genClient() {
1307
+ var _a;
1308
+ const token = (_a = this.configManager.config) == null ? void 0 : _a.token;
1309
+ const apiURL = this.getApiURL();
1310
+ const clientString = `import { createClient } from "tinacms/dist/client";
1194
1311
  import { queries } from "./types";
1195
1312
  export const client = createClient({ url: '${apiURL}', token: '${token}', queries });
1196
1313
  export default client;
1197
- `
1198
- );
1199
- return apiURL;
1200
- }
1201
- async function genTypes({
1202
- schema,
1203
- usingTs,
1204
- rootPath: rootPath2
1205
- }, next, options) {
1206
- const typesPath = rootPath2 + "/.tina/__generated__/types.ts";
1207
- const typesJSPath = rootPath2 + "/.tina/__generated__/types.js";
1208
- const typesDPath = rootPath2 + "/.tina/__generated__/types.d.ts";
1209
- const fragPath = rootPath2 + "/.tina/__generated__/*.{graphql,gql}";
1210
- const queryPathGlob = rootPath2 + "/.tina/queries/**/*.{graphql,gql}";
1211
- const typescriptTypes = await generateTypes(
1212
- schema,
1213
- queryPathGlob,
1214
- fragPath,
1215
- options
1216
- );
1217
- const code = `//@ts-nocheck
1314
+ `;
1315
+ return { apiURL, clientString };
1316
+ }
1317
+ async genTypes() {
1318
+ const typescriptTypes = await generateTypes(
1319
+ this.schema,
1320
+ this.configManager.userQueriesAndFragmentsGlob,
1321
+ this.configManager.generatedQueriesAndFragmentsGlob,
1322
+ this.getApiURL()
1323
+ );
1324
+ const codeString = `//@ts-nocheck
1218
1325
  // DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
1219
1326
  export function gql(strings: TemplateStringsArray, ...args: string[]): string {
1220
1327
  let str = ''
@@ -1225,31 +1332,139 @@ async function genTypes({
1225
1332
  }
1226
1333
  ${typescriptTypes}
1227
1334
  `;
1228
- if (usingTs) {
1229
- await import_fs_extra3.default.outputFile(typesPath, code);
1230
- } else {
1231
- await import_fs_extra3.default.outputFile(typesDPath, code);
1232
- const jsCode = await (0, import_esbuild2.transform)(code, { loader: "ts" });
1233
- await import_fs_extra3.default.outputFile(typesJSPath, jsCode.code);
1234
- }
1235
- const schemaString = await (0, import_graphql8.printSchema)(schema);
1236
- const schemaPath = rootPath2 + "/.tina/__generated__/schema.gql";
1237
- await import_fs_extra3.default.outputFile(
1238
- schemaPath,
1239
- `# DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
1240
- ${schemaString}
1335
+ const schemaString = `# DO NOT MODIFY THIS FILE. This file is automatically generated by Tina
1336
+ ${await (0, import_graphql6.printSchema)(this.schema)}
1241
1337
  schema {
1242
1338
  query: Query
1243
1339
  mutation: Mutation
1244
1340
  }
1245
- `
1341
+ `;
1342
+ return { codeString, schemaString };
1343
+ }
1344
+ };
1345
+ var maybeWarnFragmentSize = async (filepath) => {
1346
+ if (await (await import_fs_extra3.default.stat(filepath)).size > 100 * 1024) {
1347
+ console.warn(
1348
+ "Warning: frags.gql is very large (>100kb). Consider setting the reference depth to 1 or 0. See code snippet below."
1349
+ );
1350
+ console.log(
1351
+ `const schema = defineSchema({
1352
+ config: {
1353
+ client: {
1354
+ referenceDepth: 1,
1355
+ },
1356
+ }
1357
+ // ...
1358
+ })`
1359
+ );
1360
+ }
1361
+ };
1362
+ var unlinkIfExists = async (filepath) => {
1363
+ if (await import_fs_extra3.default.existsSync(filepath)) {
1364
+ await import_fs_extra3.default.unlinkSync(filepath);
1365
+ }
1366
+ };
1367
+
1368
+ // src/next/commands/dev-command/index.ts
1369
+ var import_chalk3 = __toESM(require("chalk"));
1370
+
1371
+ // src/utils/start-subprocess.ts
1372
+ var import_child_process = __toESM(require("child_process"));
1373
+
1374
+ // src/utils/theme.ts
1375
+ var import_chalk2 = __toESM(require("chalk"));
1376
+ var successText = import_chalk2.default.bold.green;
1377
+ var focusText = import_chalk2.default.bold;
1378
+ var dangerText = import_chalk2.default.bold.red;
1379
+ var neutralText = import_chalk2.default.bold.cyan;
1380
+ var linkText = import_chalk2.default.bold.cyan;
1381
+ var labelText = import_chalk2.default.bold;
1382
+ var cmdText = import_chalk2.default.inverse;
1383
+ var indentedCmd = (str) => {
1384
+ return ` \u2503 ` + str;
1385
+ };
1386
+ var logText = import_chalk2.default.italic.gray;
1387
+ var warnText = import_chalk2.default.yellowBright.bgBlack;
1388
+ var titleText = import_chalk2.default.bgHex("d2f1f8").hex("ec4816");
1389
+ var CONFIRMATION_TEXT = import_chalk2.default.dim("enter to confirm");
1390
+
1391
+ // src/utils/start-subprocess.ts
1392
+ var startSubprocess2 = async ({ command }) => {
1393
+ if (typeof command === "string") {
1394
+ const commands = command.split(" ");
1395
+ const firstCommand = commands[0];
1396
+ const args = commands.slice(1) || [];
1397
+ const ps = import_child_process.default.spawn(firstCommand, args, {
1398
+ stdio: "inherit",
1399
+ shell: true
1400
+ });
1401
+ ps.on("error", (code) => {
1402
+ logger.error(
1403
+ dangerText(
1404
+ `An error has occurred in the Next.js child process. Error message below`
1405
+ )
1406
+ );
1407
+ logger.error(`name: ${code.name}
1408
+ message: ${code.message}
1409
+
1410
+ stack: ${code.stack || "No stack was provided"}`);
1411
+ });
1412
+ ps.on("close", (code) => {
1413
+ logger.info(`child process exited with code ${code}`);
1414
+ process.exit(code);
1415
+ });
1416
+ return ps;
1417
+ }
1418
+ };
1419
+
1420
+ // src/next/database.ts
1421
+ var import_graphql7 = require("@tinacms/graphql");
1422
+ var import_readable_stream = require("readable-stream");
1423
+ var import_net = require("net");
1424
+ var import_many_level = require("many-level");
1425
+ var import_memory_level = require("memory-level");
1426
+ var createDBServer = () => {
1427
+ const levelHost = new import_many_level.ManyLevelHost(
1428
+ new import_memory_level.MemoryLevel({
1429
+ valueEncoding: "json"
1430
+ })
1246
1431
  );
1247
- next();
1432
+ const dbServer = (0, import_net.createServer)(function(socket) {
1433
+ return (0, import_readable_stream.pipeline)(socket, levelHost.createRpcStream(), socket, () => {
1434
+ });
1435
+ });
1436
+ dbServer.once("error", (err) => {
1437
+ if ((err == null ? void 0 : err.code) === "EADDRINUSE") {
1438
+ throw new Error(`Tina Dev server is already in use`);
1439
+ }
1440
+ });
1441
+ dbServer.listen(9e3);
1442
+ };
1443
+ async function createAndInitializeDatabase(configManager, bridgeOverride) {
1444
+ let database;
1445
+ const bridge = bridgeOverride || new import_graphql7.FilesystemBridge(configManager.rootPath, configManager.contentRootPath);
1446
+ if (configManager.hasSelfHostedConfig() && configManager.config.contentApiUrlOverride) {
1447
+ database = await configManager.loadDatabaseFile();
1448
+ database.bridge = bridge;
1449
+ } else {
1450
+ if (configManager.hasSelfHostedConfig() && !configManager.config.contentApiUrlOverride) {
1451
+ logger.warn(
1452
+ `Found a database config file at ${configManager.printRelativePath(
1453
+ configManager.selfHostedDatabaseFilePath
1454
+ )} but there was no "contentApiUrlOverride" set. Falling back to built-in datalayer`
1455
+ );
1456
+ }
1457
+ const level = new import_graphql7.TinaLevelClient();
1458
+ level.openConnection();
1459
+ database = (0, import_graphql7.createDatabase)({
1460
+ bridge,
1461
+ level,
1462
+ tinaDirectory: configManager.isUsingLegacyFolder ? LEGACY_TINA_FOLDER : TINA_FOLDER
1463
+ });
1464
+ }
1465
+ return database;
1248
1466
  }
1249
1467
 
1250
- // src/buildTina/index.ts
1251
- var import_app = require("@tinacms/app");
1252
-
1253
1468
  // src/utils/spinner.ts
1254
1469
  var import_cli_spinner = require("cli-spinner");
1255
1470
  async function localSpin({
@@ -1286,423 +1501,343 @@ function spin({
1286
1501
  }
1287
1502
  }
1288
1503
 
1289
- // src/buildTina/attachPath.ts
1290
- var import_fs_extra4 = require("fs-extra");
1291
- var import_path4 = __toESM(require("path"));
1292
- var attachPath = async (ctx, next, options) => {
1293
- ctx.rootPath = options.rootPath || process.cwd();
1294
- ctx.usingTs = await isProjectTs(ctx.rootPath);
1295
- next();
1296
- };
1297
- var isProjectTs = async (rootPath2) => {
1298
- const tinaPath = import_path4.default.join(rootPath2, ".tina");
1299
- return await (0, import_fs_extra4.pathExists)(import_path4.default.join(tinaPath, "schema.ts")) || await (0, import_fs_extra4.pathExists)(import_path4.default.join(tinaPath, "schema.tsx")) || await (0, import_fs_extra4.pathExists)(import_path4.default.join(tinaPath, "config.ts")) || await (0, import_fs_extra4.pathExists)(import_path4.default.join(tinaPath, "config.tsx"));
1300
- };
1301
-
1302
- // src/buildTina/index.ts
1303
- var buildSetupCmdBuild = async (ctx, next, opts) => {
1304
- const rootPath2 = ctx.rootPath;
1305
- await buildSetup({
1306
- ...opts,
1307
- rootPath: rootPath2
1308
- });
1309
- ctx.builder = new ConfigBuilder(ctx.database);
1310
- next();
1311
- };
1312
- var buildSetupCmdServerStart = async (ctx, next, opts) => {
1313
- const rootPath2 = ctx.rootPath;
1314
- await buildSetup({
1315
- ...opts,
1316
- rootPath: rootPath2
1317
- });
1318
- ctx.builder = new ConfigBuilder(ctx.database);
1319
- next();
1320
- };
1321
- var buildSetupCmdAudit = async (ctx, next, options) => {
1322
- const rootPath2 = ctx.rootPath;
1323
- const bridge = options.clean ? new import_datalayer.FilesystemBridge(rootPath2) : new import_datalayer.AuditFileSystemBridge(rootPath2);
1324
- await import_fs_extra5.default.ensureDirSync(import_path5.default.join(rootPath2, ".tina", "__generated__"));
1325
- const database = await (0, import_graphql9.createDatabase)({
1326
- level: new import_memory_level.MemoryLevel({
1327
- valueEncoding: "json"
1328
- }),
1329
- bridge
1330
- });
1331
- ctx.bridge = bridge;
1332
- ctx.database = database;
1333
- ctx.builder = new ConfigBuilder(ctx.database);
1334
- next();
1335
- };
1336
- var buildSetup = async ({ rootPath: rootPath2 }) => {
1337
- await import_fs_extra5.default.ensureDirSync(import_path5.default.join(rootPath2, ".tina", "__generated__"));
1338
- };
1339
- var buildCmdBuild = async (ctx, next, options) => {
1340
- const { schema, graphQLSchema, tinaSchema } = await ctx.builder.build({
1341
- rootPath: ctx.rootPath,
1342
- ...options
1343
- });
1344
- ctx.schema = schema;
1345
- ctx.graphQLSchema = graphQLSchema;
1346
- ctx.tinaSchema = tinaSchema;
1347
- const apiUrl = await ctx.builder.genTypedClient({
1348
- compiledSchema: schema,
1349
- local: options.local,
1350
- noSDK: options.noSDK,
1351
- verbose: options.verbose,
1352
- usingTs: ctx.usingTs,
1353
- rootPath: ctx.rootPath,
1354
- port: options.port
1355
- });
1356
- ctx.apiUrl = apiUrl;
1357
- await buildAdmin({
1358
- local: options.local,
1359
- rootPath: ctx.rootPath,
1360
- schema,
1361
- apiUrl
1362
- });
1363
- next();
1364
- };
1365
- var auditCmdBuild = async (ctx, next, options) => {
1366
- const { graphQLSchema, tinaSchema } = await ctx.builder.build({
1367
- rootPath: ctx.rootPath,
1368
- ...options,
1369
- verbose: true
1370
- });
1371
- await spin({
1372
- waitFor: async () => {
1373
- await ctx.database.indexContent({ graphQLSchema, tinaSchema });
1374
- },
1375
- text: "Indexing local files"
1376
- });
1377
- next();
1378
- };
1379
- var indexIntoSelfHostedDatabase = async (ctx, next) => {
1380
- if (!ctx.isSelfHostedDatabase) {
1381
- return next();
1382
- }
1383
- const { graphQLSchema, tinaSchema } = ctx;
1384
- await spin({
1385
- waitFor: async () => {
1386
- await ctx.database.indexContent({ graphQLSchema, tinaSchema });
1387
- },
1388
- text: "Indexing to self-hosted database"
1389
- });
1390
- next();
1391
- };
1392
- var ConfigBuilder = class {
1393
- constructor(database) {
1394
- this.database = database;
1395
- }
1396
- async build({ dev, verbose, rootPath: rootPath2, local }) {
1397
- var _a, _b, _c;
1398
- const usingTs = await isProjectTs(rootPath2);
1399
- if (!rootPath2) {
1400
- throw new Error("Root path has not been attached");
1401
- }
1402
- const tinaGeneratedPath = import_path5.default.join(rootPath2, ".tina", "__generated__");
1403
- this.database.clearCache();
1404
- await import_fs_extra5.default.mkdirp(tinaGeneratedPath);
1405
- await resetGeneratedFolder({
1406
- tinaGeneratedPath,
1407
- usingTs,
1408
- isBuild: !local
1409
- });
1410
- const compiledSchema = await compileSchema({
1411
- verbose,
1412
- dev,
1413
- rootPath: rootPath2
1414
- });
1415
- if (this.database.bridge.addOutputPath && ((_a = compiledSchema.config) == null ? void 0 : _a.localContentPath)) {
1416
- if ((_c = (_b = compiledSchema == null ? void 0 : compiledSchema.config) == null ? void 0 : _b.media) == null ? void 0 : _c.tina) {
1417
- throw new Error(
1418
- `"media.tina" is not supported when the "localContentPath" property is present.`
1419
- );
1420
- }
1421
- let localContentPath = compiledSchema.config.localContentPath;
1422
- if (!localContentPath.startsWith("/")) {
1423
- localContentPath = import_path5.default.join(process.cwd(), ".tina", localContentPath);
1424
- }
1425
- if (await import_fs_extra5.default.pathExists(localContentPath)) {
1426
- logger.info(logText(`Using separate content path ${localContentPath}`));
1427
- } else {
1428
- logger.warn(
1429
- warnText(
1430
- `Using separate content path ${localContentPath}
1431
- but no directory was found at that location, creating one...`
1432
- )
1433
- );
1434
- await import_fs_extra5.default.mkdir(localContentPath);
1435
- }
1436
- this.database.bridge.addOutputPath(localContentPath);
1437
- }
1438
- const { graphQLSchema, tinaSchema } = await (0, import_graphql9.buildSchema)(
1439
- rootPath2,
1440
- this.database,
1441
- ["experimentalData", "isomorphicGitBridge"]
1442
- );
1443
- return { schema: compiledSchema, graphQLSchema, tinaSchema };
1444
- }
1445
- async genTypedClient({
1446
- usingTs,
1447
- compiledSchema,
1448
- noSDK,
1449
- verbose,
1450
- local,
1451
- port,
1452
- rootPath: rootPath2
1453
- }) {
1454
- const astSchema = await (0, import_graphql9.getASTSchema)(this.database);
1455
- await genTypes({ schema: astSchema, usingTs, rootPath: rootPath2 }, () => {
1456
- }, {
1457
- noSDK,
1458
- verbose
1504
+ // src/next/commands/dev-command/index.ts
1505
+ var DevCommand = class extends import_clipanion.Command {
1506
+ constructor() {
1507
+ super(...arguments);
1508
+ this.port = import_clipanion.Option.String("-p,--port", "4001", {
1509
+ description: "Specify a port to run the server on. (default 4001)"
1510
+ });
1511
+ this.subCommand = import_clipanion.Option.String("-c,--command", {
1512
+ description: "The sub-command to run"
1513
+ });
1514
+ this.rootPath = import_clipanion.Option.String("--rootPath", {
1515
+ description: "Specify the root directory to run the CLI from (defaults to current working directory)"
1516
+ });
1517
+ this.watchFolders = import_clipanion.Option.String("-w,--watchFolders", {
1518
+ description: "DEPRECATED - a list of folders (relative to where this is being run) that the cli will watch for changes"
1519
+ });
1520
+ this.isomorphicGitBridge = import_clipanion.Option.Boolean("--isomorphicGitBridge", {
1521
+ description: "DEPRECATED - Enable Isomorphic Git Bridge Implementation"
1522
+ });
1523
+ this.experimentalDataLayer = import_clipanion.Option.Boolean("--experimentalData", {
1524
+ description: "DEPRECATED - Build the server with additional data querying capabilities"
1525
+ });
1526
+ this.verbose = import_clipanion.Option.Boolean("-v,--verbose", false, {
1527
+ description: "increase verbosity of logged output"
1528
+ });
1529
+ this.noWatch = import_clipanion.Option.Boolean("--noWatch", false, {
1530
+ description: "Don't regenerate config on file changes"
1531
+ });
1532
+ this.noSDK = import_clipanion.Option.Boolean("--noSDK", false, {
1533
+ description: "Don't generate the generated client SDK"
1534
+ });
1535
+ this.noTelemetry = import_clipanion.Option.Boolean("--noTelemetry", false, {
1536
+ description: "Disable anonymous telemetry that is collected"
1459
1537
  });
1460
- return genClient(
1461
- { tinaSchema: compiledSchema, usingTs, rootPath: rootPath2 },
1462
- {
1463
- local,
1464
- port
1465
- }
1466
- );
1467
1538
  }
1468
- };
1469
- var buildAdmin = async ({
1470
- schema,
1471
- local,
1472
- rootPath: rootPath2,
1473
- apiUrl
1474
- }) => {
1475
- var _a;
1476
- if ((_a = schema == null ? void 0 : schema.config) == null ? void 0 : _a.build) {
1477
- const buildVite = async () => {
1478
- var _a2, _b, _c, _d, _e, _f, _g;
1479
- await (0, import_app.viteBuild)({
1480
- local,
1481
- rootPath: rootPath2,
1482
- outputFolder: (_b = (_a2 = schema == null ? void 0 : schema.config) == null ? void 0 : _a2.build) == null ? void 0 : _b.outputFolder,
1483
- publicFolder: (_d = (_c = schema == null ? void 0 : schema.config) == null ? void 0 : _c.build) == null ? void 0 : _d.publicFolder,
1484
- apiUrl,
1485
- host: (_g = (_f = (_e = schema == null ? void 0 : schema.config) == null ? void 0 : _e.build) == null ? void 0 : _f.host) != null ? _g : false
1486
- });
1487
- };
1488
- if (local) {
1489
- logger.info(logText("Starting Tina asset server"));
1490
- await buildVite();
1491
- } else {
1492
- await spin({
1493
- text: logText("Building static site"),
1494
- waitFor: buildVite
1495
- });
1496
- logger.info(logText("\nDone building static site"));
1497
- }
1539
+ async catch(error) {
1540
+ logger.error("Error occured during tinacms dev");
1541
+ console.error(error);
1542
+ process.exit(1);
1498
1543
  }
1499
- };
1500
-
1501
- // src/cmds/start-server/index.ts
1502
- var buildLock = new AsyncLock();
1503
- var reBuildLock = new AsyncLock();
1504
- var gqlPackageFile = require.resolve("@tinacms/graphql");
1505
- async function startServer(ctx, next, {
1506
- port = 4001,
1507
- noWatch,
1508
- noSDK,
1509
- noTelemetry,
1510
- watchFolders,
1511
- verbose,
1512
- dev
1513
- }) {
1514
- buildLock.disable();
1515
- reBuildLock.disable();
1516
- const rootPath2 = ctx.rootPath;
1517
- const t = new import_metrics2.Telemetry({ disabled: Boolean(noTelemetry) });
1518
- t.submitRecord({
1519
- event: {
1520
- name: "tinacms:cli:server:start:invoke"
1544
+ async execute() {
1545
+ if (this.watchFolders) {
1546
+ logger.warn(
1547
+ "--watchFolders has been deprecated, imports from your Tina config file will be watched automatically. If you still need it please open a ticket at https://github.com/tinacms/tinacms/issues"
1548
+ );
1521
1549
  }
1522
- });
1523
- const bridge = ctx.bridge;
1524
- const database = ctx.database;
1525
- const shouldBuild = bridge.supportsBuilding();
1526
- let ready = false;
1527
- const state = {
1528
- server: null,
1529
- sockets: []
1530
- };
1531
- let isReady = false;
1532
- const beforeBuild = async () => {
1533
- await buildLock.promise;
1534
- buildLock.enable();
1535
- };
1536
- const afterBuild = async () => {
1537
- buildLock.disable();
1538
- };
1539
- const start = async () => {
1540
- await buildLock.promise;
1541
- buildLock.enable();
1542
- try {
1543
- const s = (init_server3(), __toCommonJS(server_exports));
1544
- state.server = await s.default(database);
1545
- await new Promise((resolve2, reject) => {
1546
- state.server.listen(port, () => {
1547
- var _a, _b;
1548
- const altairUrl = `http://localhost:${port}/altair/`;
1549
- const cmsUrl = ((_b = (_a = ctx.schema) == null ? void 0 : _a.config) == null ? void 0 : _b.build) ? `[your-development-url]/${ctx.schema.config.build.outputFolder}/index.html` : `[your-development-url]/admin`;
1550
- if (verbose)
1551
- logger.info(`Started Filesystem GraphQL server on port: ${port}`);
1552
- console.log("");
1553
- logger.info(indentedCmd(`GraphQL playground: ${linkText(altairUrl)}`));
1554
- logger.info(indentedCmd(`CMS: ${linkText(cmsUrl)}
1555
- `));
1556
- resolve2();
1557
- });
1558
- state.server.on("error", function(e) {
1559
- if (e.code === "EADDRINUSE") {
1560
- logger.error(dangerText(`Port ${port} already in use`));
1561
- }
1562
- reject(e);
1563
- });
1564
- state.server.on("connection", (socket) => {
1565
- state.sockets.push(socket);
1566
- });
1567
- });
1568
- } catch (error) {
1569
- throw error;
1570
- } finally {
1571
- buildLock.disable();
1550
+ if (this.isomorphicGitBridge) {
1551
+ logger.warn("--isomorphicGitBridge has been deprecated");
1572
1552
  }
1573
- };
1574
- const restart = async () => {
1575
- return new Promise((resolve2, reject) => {
1576
- logger.info("restarting local server...");
1577
- delete require.cache[gqlPackageFile];
1578
- state.sockets.forEach((socket) => {
1579
- if (socket.destroyed === false) {
1580
- socket.destroy();
1553
+ if (this.experimentalDataLayer) {
1554
+ logger.warn(
1555
+ "--experimentalDataLayer has been deprecated, the data layer is now built-in automatically"
1556
+ );
1557
+ }
1558
+ const configManager = new ConfigManager(this.rootPath);
1559
+ logger.info("Starting Tina Dev Server");
1560
+ createDBServer();
1561
+ let database = null;
1562
+ const setup = async ({ firstTime }) => {
1563
+ try {
1564
+ await configManager.processConfig();
1565
+ } catch (e) {
1566
+ logger.error(e.message);
1567
+ if (this.verbose) {
1568
+ console.error(e);
1581
1569
  }
1582
- });
1583
- state.sockets = [];
1584
- state.server.close(async () => {
1585
- logger.info("Server closed");
1586
- start().then((x) => resolve2(x)).catch((err) => reject(err));
1587
- });
1588
- });
1589
- };
1590
- const build2 = async () => {
1591
- var _a, _b;
1592
- logger.info(titleText(" TinaCMS ") + focusText(" - Build Started\n"));
1593
- try {
1594
- await beforeBuild();
1595
- const { schema, graphQLSchema, tinaSchema } = await ctx.builder.build({
1596
- rootPath: ctx.rootPath,
1597
- verbose,
1598
- local: true
1599
- });
1600
- ctx.schema = schema;
1601
- const missingFormat = (_b = (_a = tinaSchema == null ? void 0 : tinaSchema.schema) == null ? void 0 : _a.collections) == null ? void 0 : _b.filter((x) => !x.format).map((x) => x.name).join(", ");
1602
- if (missingFormat) {
1603
- logger.warn(
1604
- warnText(
1605
- `No format provided for collection(s) "${missingFormat}", defaulting to .md`
1606
- )
1570
+ if (firstTime) {
1571
+ logger.error(
1572
+ "Unable to start dev server, please fix your Tina config and try again"
1573
+ );
1574
+ process.exit(1);
1575
+ }
1576
+ }
1577
+ if (firstTime) {
1578
+ database = await createAndInitializeDatabase(configManager);
1579
+ } else {
1580
+ database.clearCache();
1581
+ }
1582
+ const { tinaSchema, graphQLSchema, queryDoc, fragDoc } = await (0, import_graphql8.buildSchema)(database, configManager.config);
1583
+ if (!configManager.isUsingLegacyFolder) {
1584
+ delete require.cache[configManager.generatedSchemaJSONPath];
1585
+ delete require.cache[configManager.generatedLookupJSONPath];
1586
+ delete require.cache[configManager.generatedGraphQLJSONPath];
1587
+ const schemaObject = require(configManager.generatedSchemaJSONPath);
1588
+ const lookupObject = require(configManager.generatedLookupJSONPath);
1589
+ const graphqlSchemaObject = require(configManager.generatedGraphQLJSONPath);
1590
+ await import_fs_extra4.default.writeFileSync(
1591
+ import_path6.default.join(configManager.tinaFolderPath, "tina-lock.json"),
1592
+ JSON.stringify({
1593
+ schema: schemaObject,
1594
+ lookup: lookupObject,
1595
+ graphql: graphqlSchemaObject
1596
+ })
1607
1597
  );
1608
1598
  }
1609
- const apiUrl = await ctx.builder.genTypedClient({
1610
- compiledSchema: schema,
1611
- local: true,
1612
- noSDK,
1613
- verbose,
1614
- usingTs: ctx.usingTs,
1615
- port,
1616
- rootPath: ctx.rootPath
1599
+ const codegen2 = new Codegen({
1600
+ schema: await (0, import_graphql8.getASTSchema)(database),
1601
+ configManager,
1602
+ port: Number(this.port),
1603
+ noSDK: this.noSDK,
1604
+ queryDoc,
1605
+ fragDoc
1617
1606
  });
1607
+ const apiURL2 = await codegen2.execute();
1608
+ if (!this.noWatch) {
1609
+ this.watchQueries(configManager, async () => await codegen2.execute());
1610
+ }
1611
+ const warnings = [];
1618
1612
  await spin({
1619
1613
  waitFor: async () => {
1620
- await ctx.database.indexContent({ graphQLSchema, tinaSchema });
1614
+ const res = await database.indexContent({
1615
+ graphQLSchema,
1616
+ tinaSchema
1617
+ });
1618
+ warnings.push(...res.warnings);
1621
1619
  },
1622
- text: logText("Indexing local files")
1623
- });
1624
- await buildAdmin({
1625
- local: true,
1626
- rootPath: ctx.rootPath,
1627
- schema,
1628
- apiUrl
1620
+ text: "Indexing local files"
1629
1621
  });
1630
- } catch (error) {
1631
- throw error;
1632
- } finally {
1633
- await afterBuild();
1622
+ if (warnings.length > 0) {
1623
+ logger.warn(`Indexing completed with ${warnings.length} warning(s)`);
1624
+ warnings.forEach((warning) => {
1625
+ logger.warn(warnText(`${warning}`));
1626
+ });
1627
+ }
1628
+ return { apiURL: apiURL2, database };
1629
+ };
1630
+ const { apiURL } = await setup({ firstTime: true });
1631
+ await import_fs_extra4.default.outputFile(configManager.outputHTMLFilePath, devHTML(this.port));
1632
+ await import_fs_extra4.default.outputFile(
1633
+ configManager.outputGitignorePath,
1634
+ "index.html\nassets/"
1635
+ );
1636
+ const server = await createDevServer(
1637
+ configManager,
1638
+ database,
1639
+ apiURL,
1640
+ this.noSDK,
1641
+ this.noWatch
1642
+ );
1643
+ await server.listen(Number(this.port));
1644
+ if (!this.noWatch) {
1645
+ this.watchContentFiles(configManager, database);
1634
1646
  }
1635
- };
1636
- const foldersToWatch = (watchFolders || []).map((x) => import_path8.default.join(rootPath2, x));
1637
- if (!noWatch && !process.env.CI) {
1638
- import_chokidar.default.watch(
1639
- [
1640
- ...foldersToWatch,
1641
- `${rootPath2}/.tina/**/*.{ts,gql,graphql,js,tsx,jsx}`,
1642
- gqlPackageFile
1643
- ],
1644
- {
1645
- ignored: [
1646
- "**/node_modules/**/*",
1647
- "**/.next/**/*",
1648
- `${import_path8.default.resolve(rootPath2)}/.tina/__generated__/**/*`
1649
- ]
1647
+ server.watcher.on("change", async (changedPath) => {
1648
+ if (changedPath.includes("__generated__")) {
1649
+ return;
1650
+ }
1651
+ if (changedPath.includes("@tinacms/app")) {
1652
+ return;
1653
+ }
1654
+ if (changedPath.includes("tinacms/dist")) {
1655
+ return;
1650
1656
  }
1651
- ).on("ready", async () => {
1652
- if (verbose)
1653
- console.log("Generating Tina config");
1654
1657
  try {
1655
- if (shouldBuild) {
1656
- await build2();
1657
- }
1658
- ready = true;
1659
- isReady = true;
1660
- await start();
1661
- next();
1658
+ logger.info("Tina config updated");
1659
+ await setup({ firstTime: false });
1662
1660
  } catch (e) {
1663
- handleServerErrors(e);
1664
- throw e;
1661
+ logger.error(e.message);
1665
1662
  }
1666
- }).on("all", async () => {
1667
- if (ready) {
1668
- await reBuildLock.promise;
1669
- reBuildLock.enable();
1670
- logger.info("Tina change detected, regenerating config");
1671
- try {
1672
- if (shouldBuild) {
1673
- await build2();
1674
- }
1675
- if (isReady) {
1676
- await restart();
1677
- }
1678
- } catch (e) {
1679
- handleServerErrors(e);
1680
- t.submitRecord({
1681
- event: {
1682
- name: "tinacms:cli:server:error",
1683
- errorMessage: e.message
1684
- }
1685
- });
1686
- } finally {
1687
- reBuildLock.disable();
1688
- }
1663
+ });
1664
+ const subItems = [];
1665
+ if (configManager.hasSeparateContentRoot()) {
1666
+ subItems.push({
1667
+ key: "Content repo",
1668
+ value: configManager.contentRootPath
1669
+ });
1670
+ }
1671
+ const summaryItems = [
1672
+ {
1673
+ emoji: "\u{1F999}",
1674
+ heading: "Tina Config",
1675
+ subItems: [
1676
+ {
1677
+ key: "CMS",
1678
+ value: `<your-dev-server-url>/${configManager.printoutputHTMLFilePath()}`
1679
+ },
1680
+ {
1681
+ key: "API playground",
1682
+ value: `<your-dev-server-url>/${configManager.printoutputHTMLFilePath()}#/graphql`
1683
+ },
1684
+ {
1685
+ key: "API url",
1686
+ value: apiURL
1687
+ },
1688
+ ...subItems
1689
+ ]
1689
1690
  }
1691
+ ];
1692
+ if (!this.noSDK) {
1693
+ summaryItems.push({
1694
+ emoji: "\u{1F916}",
1695
+ heading: "Auto-generated files",
1696
+ subItems: [
1697
+ {
1698
+ key: "GraphQL Client",
1699
+ value: configManager.printGeneratedClientFilePath()
1700
+ },
1701
+ {
1702
+ key: "Typescript Types",
1703
+ value: configManager.printGeneratedTypesFilePath()
1704
+ }
1705
+ ]
1706
+ });
1707
+ }
1708
+ summary({
1709
+ heading: "Tina Dev Server is running...",
1710
+ items: [
1711
+ ...summaryItems
1712
+ ]
1690
1713
  });
1691
- } else {
1692
- if (process.env.CI) {
1693
- logger.info("Detected CI environment, omitting watch commands...");
1714
+ let subProc;
1715
+ if (this.subCommand) {
1716
+ subProc = await startSubprocess2({ command: this.subCommand });
1717
+ logger.info(`Starting subprocess: ${import_chalk3.default.cyan(this.subCommand)}`);
1694
1718
  }
1695
- if (shouldBuild) {
1696
- await build2();
1719
+ function exitHandler(options, exitCode) {
1720
+ if (subProc) {
1721
+ subProc.kill();
1722
+ }
1723
+ process.exit();
1697
1724
  }
1698
- await start();
1699
- next();
1725
+ process.on("exit", exitHandler);
1726
+ process.on("SIGINT", exitHandler);
1727
+ process.on("SIGUSR1", exitHandler);
1728
+ process.on("SIGUSR2", exitHandler);
1729
+ process.on("uncaughtException", exitHandler);
1730
+ }
1731
+ watchContentFiles(configManager, database) {
1732
+ const collectionContentFiles = [];
1733
+ configManager.config.schema.collections.forEach((collection) => {
1734
+ const collectionGlob = `${import_path6.default.join(
1735
+ configManager.contentRootPath,
1736
+ collection.path
1737
+ )}/**/*.${collection.format || "md"}`;
1738
+ collectionContentFiles.push(collectionGlob);
1739
+ });
1740
+ let ready = false;
1741
+ import_chokidar.default.watch(collectionContentFiles).on("ready", () => {
1742
+ ready = true;
1743
+ }).on("add", async (addedFile) => {
1744
+ if (!ready) {
1745
+ return;
1746
+ }
1747
+ const pathFromRoot = configManager.printContentRelativePath(addedFile);
1748
+ database.indexContentByPaths([pathFromRoot]);
1749
+ }).on("change", async (changedFile) => {
1750
+ const pathFromRoot = configManager.printContentRelativePath(changedFile);
1751
+ database.indexContentByPaths([pathFromRoot]);
1752
+ }).on("unlink", async (removedFile) => {
1753
+ const pathFromRoot = configManager.printContentRelativePath(removedFile);
1754
+ database.deleteContentByPaths([pathFromRoot]);
1755
+ });
1700
1756
  }
1701
- }
1702
-
1703
- // src/cmds/statusChecks/waitForIndexing.ts
1704
- var import_progress = __toESM(require("progress"));
1705
- var import_schema_tools = require("@tinacms/schema-tools");
1757
+ watchQueries(configManager, callback) {
1758
+ let ready = false;
1759
+ import_chokidar.default.watch(configManager.userQueriesAndFragmentsGlob).on("ready", () => {
1760
+ ready = true;
1761
+ }).on("add", async (addedFile) => {
1762
+ await callback();
1763
+ }).on("change", async (changedFile) => {
1764
+ await callback();
1765
+ }).on("unlink", async (removedFile) => {
1766
+ await callback();
1767
+ });
1768
+ }
1769
+ };
1770
+ DevCommand.paths = [["dev"], ["server:start"]];
1771
+ DevCommand.usage = import_clipanion.Command.Usage({
1772
+ category: `Commands`,
1773
+ description: `Builds Tina and starts the dev server`,
1774
+ examples: [
1775
+ [`A basic example`, `$0 dev`],
1776
+ [`A second example`, `$0 dev --rootPath`]
1777
+ ]
1778
+ });
1779
+
1780
+ // src/next/commands/build-command/index.ts
1781
+ var import_node_fetch2 = __toESM(require("node-fetch"));
1782
+ var import_clipanion2 = require("clipanion");
1783
+ var import_progress2 = __toESM(require("progress"));
1784
+ var import_fs_extra5 = __toESM(require("fs-extra"));
1785
+ var import_graphql9 = require("@tinacms/graphql");
1786
+
1787
+ // src/next/commands/build-command/server.ts
1788
+ var import_vite4 = require("vite");
1789
+ var buildProductionSpa = async (configManager, database, apiURL, noSDK) => {
1790
+ const publicEnv = {};
1791
+ Object.keys(process.env).forEach((key) => {
1792
+ if (key.startsWith("TINA_PUBLIC_") || key.startsWith("NEXT_PUBLIC_") || key === "NODE_ENV" || key === "HEAD") {
1793
+ try {
1794
+ if (typeof process.env[key] === "string") {
1795
+ publicEnv[key] = process.env[key];
1796
+ } else {
1797
+ publicEnv[key] = JSON.stringify(process.env[key]);
1798
+ }
1799
+ } catch (error) {
1800
+ console.warn(
1801
+ `Could not stringify public env process.env.${key} env variable`
1802
+ );
1803
+ console.warn(error);
1804
+ }
1805
+ }
1806
+ });
1807
+ const config3 = await createConfig({
1808
+ configManager,
1809
+ database,
1810
+ apiURL,
1811
+ noSDK,
1812
+ noWatch: true
1813
+ });
1814
+ return (0, import_vite4.build)(config3);
1815
+ };
1816
+
1817
+ // src/next/commands/build-command/index.ts
1818
+ var import_schema_tools2 = require("@tinacms/schema-tools");
1819
+ var import_graphql10 = require("graphql");
1820
+ var import_core2 = require("@graphql-inspector/core");
1821
+
1822
+ // src/next/commands/build-command/waitForDB.ts
1823
+ var import_progress = __toESM(require("progress"));
1824
+ var import_schema_tools = require("@tinacms/schema-tools");
1825
+ var import_node_fetch = __toESM(require("node-fetch"));
1826
+
1827
+ // src/utils/sleep.ts
1828
+ function timeout(ms) {
1829
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1830
+ }
1831
+ async function sleepAndCallFunc({
1832
+ fn,
1833
+ ms
1834
+ }) {
1835
+ await timeout(ms);
1836
+ const res = await fn();
1837
+ return res;
1838
+ }
1839
+
1840
+ // src/next/commands/build-command/waitForDB.ts
1706
1841
  var POLLING_INTERVAL = 5e3;
1707
1842
  var STATUS_INPROGRESS = "inprogress";
1708
1843
  var STATUS_COMPLETE = "complete";
@@ -1713,30 +1848,30 @@ var IndexFailedError = class extends Error {
1713
1848
  this.name = "IndexFailedError";
1714
1849
  }
1715
1850
  };
1716
- var waitForDB = async (ctx, next, options) => {
1717
- const token = ctx.schema.config.token;
1718
- if (ctx.isSelfHostedDatabase) {
1719
- return next();
1720
- }
1721
- const { clientId, branch, isLocalClient, host } = (0, import_schema_tools.parseURL)(ctx.apiUrl);
1722
- if (isLocalClient) {
1723
- return next();
1851
+ var waitForDB = async (config3, apiUrl, verbose) => {
1852
+ const token = config3.token;
1853
+ const { clientId, branch, isLocalClient, host } = (0, import_schema_tools.parseURL)(apiUrl);
1854
+ if (isLocalClient || !host || !clientId || !branch) {
1855
+ if (verbose) {
1856
+ logger.info(logText("Not using Tina Cloud, skipping DB check"));
1857
+ }
1858
+ return;
1724
1859
  }
1725
- const bar = new import_progress.default(
1860
+ const bar2 = new import_progress.default(
1726
1861
  "Checking indexing process in Tina Cloud... :prog",
1727
1862
  1
1728
1863
  );
1729
1864
  const pollForStatus = async () => {
1730
1865
  try {
1731
- if (options.verbose) {
1866
+ if (verbose) {
1732
1867
  logger.info(logText("Polling for status..."));
1733
1868
  }
1734
- const headers = new Headers();
1869
+ const headers = new import_node_fetch.Headers();
1735
1870
  headers.append("Content-Type", "application/json");
1736
1871
  if (token) {
1737
1872
  headers.append("X-API-KEY", token);
1738
1873
  }
1739
- const response = await fetch(
1874
+ const response = await (0, import_node_fetch.default)(
1740
1875
  `https://${host}/db/${clientId}/status/${branch}`,
1741
1876
  {
1742
1877
  method: "GET",
@@ -1747,15 +1882,14 @@ var waitForDB = async (ctx, next, options) => {
1747
1882
  const { status, error } = await response.json();
1748
1883
  const statusMessage = `Indexing status: '${status}'`;
1749
1884
  if (status === STATUS_COMPLETE) {
1750
- bar.tick({
1885
+ bar2.tick({
1751
1886
  prog: "\u2705"
1752
1887
  });
1753
- return next();
1754
1888
  } else if (status === STATUS_INPROGRESS) {
1755
- if (options.verbose) {
1889
+ if (verbose) {
1756
1890
  logger.info(logText(`${statusMessage}, trying again in 5 seconds`));
1757
1891
  }
1758
- setTimeout(pollForStatus, POLLING_INTERVAL);
1892
+ await sleepAndCallFunc({ fn: pollForStatus, ms: POLLING_INTERVAL });
1759
1893
  } else if (status === STATUS_FAILED) {
1760
1894
  throw new IndexFailedError(
1761
1895
  `Attempting to index but responded with status 'failed', To retry the indexing process, click \u201CReset Repository Cache\u201D in tina cloud advance settings. ${error}`
@@ -1767,7 +1901,7 @@ var waitForDB = async (ctx, next, options) => {
1767
1901
  }
1768
1902
  } catch (e) {
1769
1903
  if (e instanceof IndexFailedError) {
1770
- bar.tick({
1904
+ bar2.tick({
1771
1905
  prog: "\u274C"
1772
1906
  });
1773
1907
  throw e;
@@ -1777,48 +1911,598 @@ var waitForDB = async (ctx, next, options) => {
1777
1911
  );
1778
1912
  }
1779
1913
  }
1780
- };
1781
- spin({
1782
- text: "Checking indexing process in Tina Cloud...",
1783
- waitFor: pollForStatus
1784
- });
1914
+ };
1915
+ await spin({
1916
+ text: "Checking indexing process in Tina Cloud...",
1917
+ waitFor: pollForStatus
1918
+ });
1919
+ };
1920
+
1921
+ // src/next/commands/build-command/index.ts
1922
+ var BuildCommand = class extends import_clipanion2.Command {
1923
+ constructor() {
1924
+ super(...arguments);
1925
+ this.rootPath = import_clipanion2.Option.String("--rootPath", {
1926
+ description: "Specify the root directory to run the CLI from (defaults to current working directory)"
1927
+ });
1928
+ this.verbose = import_clipanion2.Option.Boolean("-v,--verbose", false, {
1929
+ description: "increase verbosity of logged output"
1930
+ });
1931
+ this.noSDK = import_clipanion2.Option.Boolean("--noSDK", false, {
1932
+ description: "Don't generate the generated client SDK"
1933
+ });
1934
+ this.isomorphicGitBridge = import_clipanion2.Option.Boolean("--isomorphicGitBridge", {
1935
+ description: "DEPRECATED - Enable Isomorphic Git Bridge Implementation"
1936
+ });
1937
+ this.localOption = import_clipanion2.Option.Boolean("--local", {
1938
+ description: "DEPRECATED: Uses the local file system graphql server"
1939
+ });
1940
+ this.experimentalDataLayer = import_clipanion2.Option.Boolean("--experimentalData", {
1941
+ description: "DEPRECATED - Build the server with additional data querying capabilities"
1942
+ });
1943
+ this.noTelemetry = import_clipanion2.Option.Boolean("--noTelemetry", false, {
1944
+ description: "Disable anonymous telemetry that is collected"
1945
+ });
1946
+ this.tinaGraphQLVersion = import_clipanion2.Option.String("--tina-graphql-version", {
1947
+ description: "Specify the version of @tinacms/graphql to use (defaults to latest)"
1948
+ });
1949
+ }
1950
+ async catch(error) {
1951
+ console.error(error);
1952
+ process.exit(1);
1953
+ }
1954
+ async execute() {
1955
+ const configManager = new ConfigManager(
1956
+ this.rootPath,
1957
+ this.tinaGraphQLVersion
1958
+ );
1959
+ logger.info("Starting Tina build");
1960
+ if (this.isomorphicGitBridge) {
1961
+ logger.warn("--isomorphicGitBridge has been deprecated");
1962
+ }
1963
+ if (this.experimentalDataLayer) {
1964
+ logger.warn(
1965
+ "--experimentalDataLayer has been deprecated, the data layer is now built-in automatically"
1966
+ );
1967
+ }
1968
+ if (this.localOption) {
1969
+ logger.warn("--local has been deprecated");
1970
+ }
1971
+ try {
1972
+ await configManager.processConfig();
1973
+ } catch (e) {
1974
+ logger.error(e.message);
1975
+ logger.error("Unable to build, please fix your Tina config and try again");
1976
+ process.exit(1);
1977
+ }
1978
+ createDBServer();
1979
+ const database = await createAndInitializeDatabase(configManager);
1980
+ const { queryDoc, fragDoc } = await (0, import_graphql9.buildSchema)(
1981
+ database,
1982
+ configManager.config
1983
+ );
1984
+ const codegen2 = new Codegen({
1985
+ schema: await (0, import_graphql9.getASTSchema)(database),
1986
+ configManager,
1987
+ noSDK: this.noSDK,
1988
+ queryDoc,
1989
+ fragDoc
1990
+ });
1991
+ const apiURL = await codegen2.execute();
1992
+ await this.checkClientInfo(configManager, apiURL);
1993
+ await waitForDB(configManager.config, apiURL, false);
1994
+ await this.checkGraphqlSchema(configManager, database, apiURL);
1995
+ await buildProductionSpa(configManager, database, apiURL, this.noSDK);
1996
+ await import_fs_extra5.default.outputFile(
1997
+ configManager.outputGitignorePath,
1998
+ "index.html\nassets/"
1999
+ );
2000
+ const summaryItems = [];
2001
+ if (!this.noSDK) {
2002
+ summaryItems.push({
2003
+ emoji: "\u{1F916}",
2004
+ heading: "Auto-generated files",
2005
+ subItems: [
2006
+ {
2007
+ key: "GraphQL Client",
2008
+ value: configManager.printGeneratedClientFilePath()
2009
+ },
2010
+ {
2011
+ key: "Typescript Types",
2012
+ value: configManager.printGeneratedTypesFilePath()
2013
+ }
2014
+ ]
2015
+ });
2016
+ }
2017
+ summary({
2018
+ heading: "Tina build complete",
2019
+ items: [
2020
+ {
2021
+ emoji: "\u{1F999}",
2022
+ heading: "Tina Config",
2023
+ subItems: [
2024
+ {
2025
+ key: "API url",
2026
+ value: apiURL
2027
+ }
2028
+ ]
2029
+ },
2030
+ ...summaryItems
2031
+ ]
2032
+ });
2033
+ process.exit();
2034
+ }
2035
+ async checkClientInfo(configManager, apiURL) {
2036
+ const { config: config3 } = configManager;
2037
+ const token = config3.token;
2038
+ const { clientId, branch, host } = (0, import_schema_tools2.parseURL)(apiURL);
2039
+ const url2 = `https://${host}/db/${clientId}/status/${branch}`;
2040
+ const bar2 = new import_progress2.default("Checking clientId and token. :prog", 1);
2041
+ let branchKnown = false;
2042
+ try {
2043
+ const res = await request({
2044
+ token,
2045
+ url: url2
2046
+ });
2047
+ bar2.tick({
2048
+ prog: "\u2705"
2049
+ });
2050
+ if (!(res.status === "unknown")) {
2051
+ branchKnown = true;
2052
+ }
2053
+ } catch (e) {
2054
+ summary({
2055
+ heading: "Error when checking client information",
2056
+ items: [
2057
+ {
2058
+ emoji: "\u274C",
2059
+ heading: "You provided",
2060
+ subItems: [
2061
+ {
2062
+ key: "clientId",
2063
+ value: config3.clientId
2064
+ },
2065
+ {
2066
+ key: "token",
2067
+ value: config3.token
2068
+ }
2069
+ ]
2070
+ }
2071
+ ]
2072
+ });
2073
+ throw e;
2074
+ }
2075
+ const branchBar = new import_progress2.default("Checking branch is on Tina Cloud. :prog", 1);
2076
+ if (branchKnown) {
2077
+ branchBar.tick({
2078
+ prog: "\u2705"
2079
+ });
2080
+ return;
2081
+ }
2082
+ for (let i = 0; i <= 5; i++) {
2083
+ await sleepAndCallFunc({
2084
+ fn: async () => {
2085
+ const res = await request({
2086
+ token,
2087
+ url: url2
2088
+ });
2089
+ if (this.verbose) {
2090
+ logger.info(
2091
+ `Branch status: ${res.status}. Attempt: ${i + 1}. Trying again in 5 seconds.`
2092
+ );
2093
+ }
2094
+ if (!(res.status === "unknown")) {
2095
+ branchBar.tick({
2096
+ prog: "\u2705"
2097
+ });
2098
+ return;
2099
+ }
2100
+ },
2101
+ ms: 5e3
2102
+ });
2103
+ }
2104
+ branchBar.tick({
2105
+ prog: "\u274C"
2106
+ });
2107
+ logger.error(
2108
+ `${dangerText(
2109
+ `ERROR: Branch '${branch}' is not on Tina Cloud.`
2110
+ )} Please make sure that branch '${branch}' exists in your repository and that you have pushed your all changes to the remote. View all all branches and there current status here: ${linkText(
2111
+ `https://app.tina.io/projects/${clientId}/configuration`
2112
+ )}`
2113
+ );
2114
+ throw new Error("Branch is not on Tina Cloud");
2115
+ }
2116
+ async checkGraphqlSchema(configManager, database, apiURL) {
2117
+ const bar2 = new import_progress2.default(
2118
+ "Checking local GraphQL Schema matches server. :prog",
2119
+ 1
2120
+ );
2121
+ const { config: config3 } = configManager;
2122
+ const token = config3.token;
2123
+ const remoteSchema = await fetchRemoteGraphqlSchema({
2124
+ url: apiURL,
2125
+ token
2126
+ });
2127
+ const remoteGqlSchema = (0, import_graphql10.buildClientSchema)(remoteSchema);
2128
+ const localSchemaDocument = await database.getGraphQLSchemaFromBridge();
2129
+ const localGraphqlSchema = (0, import_graphql10.buildASTSchema)(localSchemaDocument);
2130
+ const diffResult = await (0, import_core2.diff)(localGraphqlSchema, remoteGqlSchema);
2131
+ if (diffResult.length === 0) {
2132
+ bar2.tick({
2133
+ prog: "\u2705"
2134
+ });
2135
+ } else {
2136
+ bar2.tick({
2137
+ prog: "\u274C"
2138
+ });
2139
+ let errorMessage = `The local GraphQL schema doesn't match the remote GraphQL schema. Please push up your changes to Github to update your remote GraphQL schema.`;
2140
+ if (config3 == null ? void 0 : config3.branch) {
2141
+ errorMessage += `
2142
+
2143
+ Additional info: Branch: ${config3.branch}, Client ID: ${config3.clientId} `;
2144
+ }
2145
+ throw new Error(errorMessage);
2146
+ }
2147
+ }
2148
+ };
2149
+ BuildCommand.paths = [["build"]];
2150
+ BuildCommand.usage = import_clipanion2.Command.Usage({
2151
+ category: `Commands`,
2152
+ description: `Build the CMS and autogenerated modules for usage with Tina Cloud`
2153
+ });
2154
+ async function request(args) {
2155
+ const headers = new import_node_fetch2.Headers();
2156
+ if (args.token) {
2157
+ headers.append("X-API-KEY", args.token);
2158
+ }
2159
+ headers.append("Content-Type", "application/json");
2160
+ const url2 = args == null ? void 0 : args.url;
2161
+ const res = await (0, import_node_fetch2.default)(url2, {
2162
+ method: "GET",
2163
+ headers,
2164
+ redirect: "follow"
2165
+ });
2166
+ const json = await res.json();
2167
+ if (!res.ok) {
2168
+ let additionalInfo = "";
2169
+ if (res.status === 401 || res.status === 403) {
2170
+ additionalInfo = "Please check that your client ID, URL and read only token are configured properly.";
2171
+ }
2172
+ if (json) {
2173
+ additionalInfo += `
2174
+
2175
+ Message from server: ${json.message}`;
2176
+ }
2177
+ throw new Error(
2178
+ `Server responded with status code ${res.status}, ${res.statusText}. ${additionalInfo ? additionalInfo : ""} Please see our FAQ for more information: https://tina.io/docs/errors/faq/`
2179
+ );
2180
+ }
2181
+ if (json.errors) {
2182
+ throw new Error(
2183
+ `Unable to fetch, please see our FAQ for more information: https://tina.io/docs/errors/faq/
2184
+
2185
+ Errors:
2186
+ ${json.errors.map((error) => error.message).join("\n")}`
2187
+ );
2188
+ }
2189
+ return {
2190
+ status: json == null ? void 0 : json.status,
2191
+ timestamp: json == null ? void 0 : json.timestamp
2192
+ };
2193
+ }
2194
+ var fetchRemoteGraphqlSchema = async ({
2195
+ url: url2,
2196
+ token
2197
+ }) => {
2198
+ const headers = new import_node_fetch2.Headers();
2199
+ if (token) {
2200
+ headers.append("X-API-KEY", token);
2201
+ }
2202
+ const body = JSON.stringify({ query: (0, import_graphql10.getIntrospectionQuery)(), variables: {} });
2203
+ headers.append("Content-Type", "application/json");
2204
+ const res = await (0, import_node_fetch2.default)(url2, {
2205
+ method: "POST",
2206
+ headers,
2207
+ body
2208
+ });
2209
+ const data = await res.json();
2210
+ return data == null ? void 0 : data.data;
2211
+ };
2212
+
2213
+ // src/next/commands/audit-command/index.ts
2214
+ var import_clipanion3 = require("clipanion");
2215
+ var import_graphql13 = require("@tinacms/graphql");
2216
+
2217
+ // src/next/commands/audit-command/audit.ts
2218
+ var import_prompts = __toESM(require("prompts"));
2219
+ var import_metrics = require("@tinacms/metrics");
2220
+ var import_graphql11 = require("@tinacms/graphql");
2221
+ var import_graphql12 = require("@tinacms/graphql");
2222
+ var import_chalk4 = __toESM(require("chalk"));
2223
+ var audit = async ({
2224
+ database,
2225
+ clean,
2226
+ useDefaultValues,
2227
+ noTelemetry,
2228
+ verbose
2229
+ }) => {
2230
+ const telemetry = new import_metrics.Telemetry({ disabled: noTelemetry });
2231
+ await telemetry.submitRecord({
2232
+ event: {
2233
+ name: "tinacms:cli:audit:invoke",
2234
+ clean: Boolean(clean),
2235
+ useDefaults: Boolean(useDefaultValues)
2236
+ }
2237
+ });
2238
+ if (clean) {
2239
+ logger.info(
2240
+ `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(
2241
+ "clean git tree"
2242
+ )} so unwanted changes can be undone.
2243
+
2244
+ `
2245
+ );
2246
+ const res = await (0, import_prompts.default)({
2247
+ name: "useClean",
2248
+ type: "confirm",
2249
+ message: `Do you want to continue?`
2250
+ });
2251
+ if (!res.useClean) {
2252
+ logger.warn(import_chalk4.default.yellowBright("\u26A0\uFE0F Audit not complete"));
2253
+ process.exit(0);
2254
+ }
2255
+ }
2256
+ if (useDefaultValues && !clean) {
2257
+ logger.warn(
2258
+ import_chalk4.default.yellowBright(
2259
+ "WARNING: using the `--useDefaultValues` without the `--clean` flag has no effect. Please re-run audit and add the `--clean` flag"
2260
+ )
2261
+ );
2262
+ }
2263
+ const schema = await database.getSchema();
2264
+ const collections = schema.getCollections();
2265
+ let error = false;
2266
+ for (let i = 0; i < collections.length; i++) {
2267
+ const collection = collections[i];
2268
+ const docs = await database.query(
2269
+ { collection: collection.name, first: -1, filterChain: [] },
2270
+ (item) => ({ path: item })
2271
+ );
2272
+ logger.info(
2273
+ `Checking ${neutralText(collection.name)} collection. ${docs.edges.length} Documents`
2274
+ );
2275
+ const returnError = await auditDocuments({
2276
+ collection,
2277
+ database,
2278
+ useDefaultValues,
2279
+ documents: docs.edges,
2280
+ verbose
2281
+ });
2282
+ error = error || returnError;
2283
+ }
2284
+ if (error) {
2285
+ logger.error(
2286
+ import_chalk4.default.redBright(`\u203C\uFE0F Audit ${import_chalk4.default.bold("failed")} with errors`)
2287
+ );
2288
+ } else {
2289
+ logger.info(import_chalk4.default.greenBright("\u2705 Audit passed"));
2290
+ }
2291
+ };
2292
+ var auditDocuments = async (args) => {
2293
+ const { collection, database, useDefaultValues, documents } = args;
2294
+ let error = false;
2295
+ for (let i = 0; i < documents.length; i++) {
2296
+ const node = documents[i].node;
2297
+ const relativePath = node.path.replace(`${collection.path}/`, "");
2298
+ const documentQuery = `query {
2299
+ document(collection: "${collection.name}", relativePath: "${relativePath}") {
2300
+ __typename
2301
+ ...on Document {
2302
+ _values
2303
+ }
2304
+ }
2305
+ }`;
2306
+ const docResult = await (0, import_graphql11.resolve)({
2307
+ database,
2308
+ query: documentQuery,
2309
+ variables: {},
2310
+ silenceErrors: true,
2311
+ verbose: args.verbose || false,
2312
+ isAudit: true
2313
+ });
2314
+ if (docResult.errors) {
2315
+ error = true;
2316
+ docResult.errors.forEach((err) => {
2317
+ logger.error(import_chalk4.default.red(err.message));
2318
+ if (err.originalError.originalError) {
2319
+ logger.error(
2320
+ import_chalk4.default.red(` ${err.originalError.originalError.message}`)
2321
+ );
2322
+ }
2323
+ });
2324
+ } else {
2325
+ const topLevelDefaults = {};
2326
+ if (useDefaultValues && typeof collection.fields !== "string") {
2327
+ collection.fields.filter((x) => !x.list).forEach((x) => {
2328
+ const value = x.ui;
2329
+ if (typeof value !== "undefined") {
2330
+ topLevelDefaults[x.name] = value.defaultValue;
2331
+ }
2332
+ });
2333
+ }
2334
+ const params = transformDocumentIntoMutationRequestPayload(
2335
+ docResult.data.document._values,
2336
+ {
2337
+ includeCollection: true,
2338
+ includeTemplate: typeof collection.templates !== "undefined"
2339
+ },
2340
+ topLevelDefaults
2341
+ );
2342
+ const mutation = `mutation($collection: String!, $relativePath: String!, $params: DocumentUpdateMutation!) {
2343
+ updateDocument(
2344
+ collection: $collection,
2345
+ relativePath: $relativePath,
2346
+ params: $params
2347
+ ){__typename}
2348
+ }`;
2349
+ const mutationRes = await (0, import_graphql11.resolve)({
2350
+ database,
2351
+ query: mutation,
2352
+ variables: {
2353
+ params,
2354
+ collection: collection.name,
2355
+ relativePath
2356
+ },
2357
+ isAudit: true,
2358
+ silenceErrors: true,
2359
+ verbose: args.verbose || false
2360
+ });
2361
+ if (mutationRes.errors) {
2362
+ mutationRes.errors.forEach((err) => {
2363
+ error = true;
2364
+ logger.error(import_chalk4.default.red(err.message));
2365
+ });
2366
+ }
2367
+ }
2368
+ }
2369
+ return error;
2370
+ };
2371
+ var transformDocumentIntoMutationRequestPayload = (document, instructions, defaults) => {
2372
+ const { _collection, __typename, _template, ...rest } = document;
2373
+ const params = transformParams(rest);
2374
+ const paramsWithTemplate = instructions.includeTemplate ? { [_template]: params } : params;
2375
+ return instructions.includeCollection ? { [_collection]: { ...defaults, ...filterObject(paramsWithTemplate) } } : { ...defaults, ...filterObject(paramsWithTemplate) };
2376
+ };
2377
+ var transformParams = (data) => {
2378
+ if (["string", "number", "boolean"].includes(typeof data)) {
2379
+ return data;
2380
+ }
2381
+ if (Array.isArray(data)) {
2382
+ return data.map((item) => transformParams(item));
2383
+ }
2384
+ try {
2385
+ (0, import_graphql12.assertShape)(
2386
+ data,
2387
+ (yup) => yup.object({ _template: yup.string().required() })
2388
+ );
2389
+ const { _template, __typename, ...rest } = data;
2390
+ const nested = transformParams(rest);
2391
+ return { [_template]: nested };
2392
+ } catch (e) {
2393
+ if (e.message === "Failed to assertShape - _template is a required field") {
2394
+ if (!data) {
2395
+ return void 0;
2396
+ return [];
2397
+ }
2398
+ const accum = {};
2399
+ Object.entries(data).map(([keyName, value]) => {
2400
+ accum[keyName] = transformParams(value);
2401
+ });
2402
+ return accum;
2403
+ } else {
2404
+ if (!data) {
2405
+ return void 0;
2406
+ return [];
2407
+ }
2408
+ throw e;
2409
+ }
2410
+ }
1785
2411
  };
2412
+ function filterObject(obj) {
2413
+ const ret = {};
2414
+ Object.keys(obj).filter((key) => obj[key] !== void 0).forEach((key) => ret[key] = obj[key]);
2415
+ return ret;
2416
+ }
1786
2417
 
1787
- // src/cmds/startSubprocess/index.ts
1788
- var import_child_process = __toESM(require("child_process"));
1789
- var startSubprocess = async (_ctx, next, { command }) => {
1790
- if (typeof command === "string") {
1791
- const commands = command.split(" ");
1792
- const firstCommand = commands[0];
1793
- const args = commands.slice(1) || [];
1794
- const ps = import_child_process.default.spawn(firstCommand, args, {
1795
- stdio: "inherit",
1796
- shell: true
2418
+ // src/next/commands/audit-command/index.ts
2419
+ var import_graphql14 = require("@tinacms/graphql");
2420
+ var AuditCommand = class extends import_clipanion3.Command {
2421
+ constructor() {
2422
+ super(...arguments);
2423
+ this.rootPath = import_clipanion3.Option.String("--rootPath", {
2424
+ description: "Specify the root directory to run the CLI from"
1797
2425
  });
1798
- ps.on("error", (code) => {
1799
- logger.error(
1800
- dangerText(
1801
- `An error has occurred in the Next.js child process. Error message below`
1802
- )
1803
- );
1804
- logger.error(`name: ${code.name}
1805
- message: ${code.message}
1806
-
1807
- stack: ${code.stack || "No stack was provided"}`);
2426
+ this.verbose = import_clipanion3.Option.Boolean("-v,--verbose", false, {
2427
+ description: "increase verbosity of logged output"
1808
2428
  });
1809
- ps.on("close", (code) => {
1810
- logger.info(`child process exited with code ${code}`);
1811
- process.exit(code);
2429
+ this.clean = import_clipanion3.Option.Boolean("--clean", false, {
2430
+ description: "Clean the output"
1812
2431
  });
2432
+ this.useDefaultValues = import_clipanion3.Option.Boolean("--useDefaultValues", false, {
2433
+ description: "When cleaning the output, use defaults on the config"
2434
+ });
2435
+ this.noTelemetry = import_clipanion3.Option.Boolean("--noTelemetry", false, {
2436
+ description: "Disable anonymous telemetry that is collected"
2437
+ });
2438
+ }
2439
+ async catch(error) {
2440
+ logger.error("Error occured during tinacms audit");
2441
+ if (this.verbose) {
2442
+ console.error(error);
2443
+ }
2444
+ process.exit(1);
2445
+ }
2446
+ async execute() {
2447
+ const configManager = new ConfigManager(this.rootPath);
2448
+ logger.info("Starting Tina Audit");
2449
+ try {
2450
+ await configManager.processConfig();
2451
+ } catch (e) {
2452
+ logger.error(e.message);
2453
+ process.exit(1);
2454
+ }
2455
+ createDBServer();
2456
+ const database = await createAndInitializeDatabase(
2457
+ configManager,
2458
+ this.clean ? void 0 : new import_graphql14.AuditFileSystemBridge(configManager.rootPath)
2459
+ );
2460
+ const { tinaSchema, graphQLSchema } = await (0, import_graphql13.buildSchema)(
2461
+ database,
2462
+ configManager.config
2463
+ );
2464
+ const warnings = [];
2465
+ await spin({
2466
+ waitFor: async () => {
2467
+ const res = await database.indexContent({
2468
+ graphQLSchema,
2469
+ tinaSchema
2470
+ });
2471
+ warnings.push(...res.warnings);
2472
+ },
2473
+ text: "Indexing local files"
2474
+ });
2475
+ if (warnings.length > 0) {
2476
+ logger.warn(`Indexing completed with ${warnings.length} warning(s)`);
2477
+ warnings.forEach((warning) => {
2478
+ logger.warn(warnText(`${warning}`));
2479
+ });
2480
+ }
2481
+ await audit({
2482
+ database,
2483
+ clean: this.clean,
2484
+ noTelemetry: this.noTelemetry,
2485
+ useDefaultValues: this.useDefaultValues,
2486
+ verbose: this.verbose
2487
+ });
2488
+ process.exit();
1813
2489
  }
1814
2490
  };
2491
+ AuditCommand.paths = [["audit"]];
2492
+ AuditCommand.usage = import_clipanion3.Command.Usage({
2493
+ category: `Commands`,
2494
+ description: `Audit config and content files`
2495
+ });
2496
+
2497
+ // src/next/commands/init-command/index.ts
2498
+ var import_clipanion4 = require("clipanion");
1815
2499
 
1816
2500
  // src/cmds/init/index.ts
1817
- var import_path11 = __toESM(require("path"));
2501
+ var import_path9 = __toESM(require("path"));
1818
2502
  var import_prettier = require("prettier");
1819
- var import_fs_extra9 = __toESM(require("fs-extra"));
2503
+ var import_fs_extra8 = __toESM(require("fs-extra"));
1820
2504
  var import_prompts2 = __toESM(require("prompts"));
1821
- var import_metrics3 = require("@tinacms/metrics");
2505
+ var import_metrics2 = require("@tinacms/metrics");
1822
2506
 
1823
2507
  // src/cmds/init/setup-files/index.ts
1824
2508
  var nextPostPage = ({
@@ -2159,8 +2843,8 @@ var configExamples = {
2159
2843
  };
2160
2844
 
2161
2845
  // src/cmds/forestry-migrate/util/index.ts
2162
- var import_fs_extra7 = __toESM(require("fs-extra"));
2163
- var import_path9 = __toESM(require("path"));
2846
+ var import_fs_extra6 = __toESM(require("fs-extra"));
2847
+ var import_path7 = __toESM(require("path"));
2164
2848
  var import_js_yaml = __toESM(require("js-yaml"));
2165
2849
  var import_zod = __toESM(require("zod"));
2166
2850
 
@@ -2298,7 +2982,7 @@ var FrontmatterTemplateSchema = import_zod.default.object({
2298
2982
  });
2299
2983
  var transformForestryFieldsToTinaFields = ({
2300
2984
  fields,
2301
- rootPath: rootPath2,
2985
+ rootPath,
2302
2986
  template,
2303
2987
  skipBlocks = false
2304
2988
  }) => {
@@ -2415,7 +3099,7 @@ var transformForestryFieldsToTinaFields = ({
2415
3099
  label: forestryField2.label,
2416
3100
  fields: transformForestryFieldsToTinaFields({
2417
3101
  fields: forestryField2.fields,
2418
- rootPath: rootPath2,
3102
+ rootPath,
2419
3103
  template,
2420
3104
  skipBlocks
2421
3105
  })
@@ -2430,7 +3114,7 @@ var transformForestryFieldsToTinaFields = ({
2430
3114
  fields: transformForestryFieldsToTinaFields({
2431
3115
  fields: forestryField2.fields,
2432
3116
  template,
2433
- rootPath: rootPath2,
3117
+ rootPath,
2434
3118
  skipBlocks
2435
3119
  })
2436
3120
  };
@@ -2484,9 +3168,9 @@ var transformForestryFieldsToTinaFields = ({
2484
3168
  });
2485
3169
  return tinaFields;
2486
3170
  };
2487
- var getFieldsFromTemplates = ({ tem, rootPath: rootPath2, skipBlocks = false }) => {
2488
- const templatePath = import_path9.default.join(
2489
- rootPath2,
3171
+ var getFieldsFromTemplates = ({ tem, rootPath, skipBlocks = false }) => {
3172
+ const templatePath = import_path7.default.join(
3173
+ rootPath,
2490
3174
  ".forestry",
2491
3175
  "front_matter",
2492
3176
  "templates",
@@ -2494,7 +3178,7 @@ var getFieldsFromTemplates = ({ tem, rootPath: rootPath2, skipBlocks = false })
2494
3178
  );
2495
3179
  let templateString = "";
2496
3180
  try {
2497
- templateString = import_fs_extra7.default.readFileSync(templatePath).toString();
3181
+ templateString = import_fs_extra6.default.readFileSync(templatePath).toString();
2498
3182
  } catch {
2499
3183
  throw new Error(
2500
3184
  `Could not find template ${tem} at ${templatePath}
@@ -2506,7 +3190,7 @@ var getFieldsFromTemplates = ({ tem, rootPath: rootPath2, skipBlocks = false })
2506
3190
  const template = parseTemplates({ val: templateObj });
2507
3191
  const fields = transformForestryFieldsToTinaFields({
2508
3192
  fields: template.fields,
2509
- rootPath: rootPath2,
3193
+ rootPath,
2510
3194
  template: tem,
2511
3195
  skipBlocks
2512
3196
  });
@@ -2516,9 +3200,9 @@ var parseTemplates = ({ val }) => {
2516
3200
  const template = FrontmatterTemplateSchema.parse(val);
2517
3201
  return template;
2518
3202
  };
2519
- var hasForestryConfig = async ({ rootPath: rootPath2 }) => {
2520
- const forestryPath = import_path9.default.join(rootPath2, ".forestry", "settings.yml");
2521
- const exists = await import_fs_extra7.default.pathExists(forestryPath);
3203
+ var hasForestryConfig = async ({ rootPath }) => {
3204
+ const forestryPath = import_path7.default.join(rootPath, ".forestry", "settings.yml");
3205
+ const exists = await import_fs_extra6.default.pathExists(forestryPath);
2522
3206
  return {
2523
3207
  path: forestryPath,
2524
3208
  exists
@@ -2530,11 +3214,11 @@ var parseSections = ({ val }) => {
2530
3214
  };
2531
3215
 
2532
3216
  // src/cmds/forestry-migrate/index.ts
2533
- var import_fs_extra8 = __toESM(require("fs-extra"));
2534
- var import_path10 = __toESM(require("path"));
3217
+ var import_fs_extra7 = __toESM(require("fs-extra"));
3218
+ var import_path8 = __toESM(require("path"));
2535
3219
  var import_js_yaml2 = __toESM(require("js-yaml"));
2536
3220
  var import_minimatch = __toESM(require("minimatch"));
2537
- var import_graphql10 = require("@tinacms/graphql");
3221
+ var import_graphql15 = require("@tinacms/graphql");
2538
3222
  var BODY_FIELD = {
2539
3223
  type: "rich-text",
2540
3224
  name: "body",
@@ -2546,17 +3230,17 @@ var stringifyLabel = (label) => {
2546
3230
  return label.replace(/[^a-zA-Z0-9]/g, "_").toLowerCase();
2547
3231
  };
2548
3232
  var generateAllCollections = async ({
2549
- rootPath: rootPath2
3233
+ rootPath
2550
3234
  }) => {
2551
- const allTemplates = (await import_fs_extra8.default.readdir(
2552
- import_path10.default.join(rootPath2, ".forestry", "front_matter", "templates")
2553
- )).map((tem) => import_path10.default.basename(tem, ".yml"));
3235
+ const allTemplates = (await import_fs_extra7.default.readdir(
3236
+ import_path8.default.join(rootPath, ".forestry", "front_matter", "templates")
3237
+ )).map((tem) => import_path8.default.basename(tem, ".yml"));
2554
3238
  const templateMap = /* @__PURE__ */ new Map();
2555
3239
  const proms = allTemplates.map(async (tem) => {
2556
3240
  try {
2557
3241
  const { fields, templateObj } = getFieldsFromTemplates({
2558
3242
  tem,
2559
- rootPath: rootPath2
3243
+ rootPath
2560
3244
  });
2561
3245
  templateMap.set(tem, { fields, templateObj });
2562
3246
  } catch (e) {
@@ -2570,10 +3254,10 @@ var generateAllCollections = async ({
2570
3254
  };
2571
3255
  var generateCollections = async ({
2572
3256
  forestryPath,
2573
- rootPath: rootPath2
3257
+ rootPath
2574
3258
  }) => {
2575
- const templateMap = await generateAllCollections({ rootPath: rootPath2 });
2576
- const forestryConfig = await import_fs_extra8.default.readFile(forestryPath);
3259
+ const templateMap = await generateAllCollections({ rootPath });
3260
+ const forestryConfig = await import_fs_extra7.default.readFile(forestryPath);
2577
3261
  const forestryYaml = import_js_yaml2.default.load(forestryConfig.toString());
2578
3262
  const forestrySchema = parseSections({ val: forestryYaml });
2579
3263
  const collections = [];
@@ -2611,10 +3295,10 @@ var generateCollections = async ({
2611
3295
  });
2612
3296
  (_a = templateObj == null ? void 0 : templateObj.pages) == null ? void 0 : _a.forEach((page) => {
2613
3297
  try {
2614
- const filePath = import_path10.default.join(rootPath2, page);
2615
- const extname = import_path10.default.extname(filePath);
2616
- const fileContent = import_fs_extra8.default.readFileSync(filePath).toString();
2617
- const content2 = (0, import_graphql10.parseFile)(
3298
+ const filePath = import_path8.default.join(rootPath, page);
3299
+ const extname = import_path8.default.extname(filePath);
3300
+ const fileContent = import_fs_extra7.default.readFileSync(filePath).toString();
3301
+ const content2 = (0, import_graphql15.parseFile)(
2618
3302
  fileContent,
2619
3303
  extname,
2620
3304
  (yup) => yup.object({})
@@ -2623,9 +3307,9 @@ var generateCollections = async ({
2623
3307
  _template: stringifyLabel(tem),
2624
3308
  ...content2
2625
3309
  };
2626
- import_fs_extra8.default.writeFileSync(
3310
+ import_fs_extra7.default.writeFileSync(
2627
3311
  filePath,
2628
- (0, import_graphql10.stringifyFile)(newContent, extname, true)
3312
+ (0, import_graphql15.stringifyFile)(newContent, extname, true)
2629
3313
  );
2630
3314
  } catch (error) {
2631
3315
  console.log("Error updating file", page);
@@ -2660,10 +3344,10 @@ var generateCollections = async ({
2660
3344
  fields.push(...additionalFields);
2661
3345
  (_a = templateObj == null ? void 0 : templateObj.pages) == null ? void 0 : _a.forEach((page) => {
2662
3346
  try {
2663
- const filePath = import_path10.default.join(rootPath2, page);
2664
- const extname = import_path10.default.extname(filePath);
2665
- const fileContent = import_fs_extra8.default.readFileSync(filePath).toString();
2666
- const content2 = (0, import_graphql10.parseFile)(
3347
+ const filePath = import_path8.default.join(rootPath, page);
3348
+ const extname = import_path8.default.extname(filePath);
3349
+ const fileContent = import_fs_extra7.default.readFileSync(filePath).toString();
3350
+ const content2 = (0, import_graphql15.parseFile)(
2667
3351
  fileContent,
2668
3352
  extname,
2669
3353
  (yup) => yup.object({})
@@ -2672,9 +3356,9 @@ var generateCollections = async ({
2672
3356
  _template: stringifyLabel(tem),
2673
3357
  ...content2
2674
3358
  };
2675
- import_fs_extra8.default.writeFileSync(
3359
+ import_fs_extra7.default.writeFileSync(
2676
3360
  filePath,
2677
- (0, import_graphql10.stringifyFile)(newContent, extname, true)
3361
+ (0, import_graphql15.stringifyFile)(newContent, extname, true)
2678
3362
  );
2679
3363
  } catch (error) {
2680
3364
  logger.log("Error updating file", page);
@@ -2715,8 +3399,11 @@ var generateCollections = async ({
2715
3399
  };
2716
3400
 
2717
3401
  // src/cmds/init/index.ts
2718
- async function initStaticTina(ctx, next, options) {
2719
- const baseDir = ctx.rootPath;
3402
+ async function initStaticTina({
3403
+ rootPath,
3404
+ noTelemetry
3405
+ }) {
3406
+ const baseDir = rootPath;
2720
3407
  logger.level = "info";
2721
3408
  const clientId = await chooseClientId();
2722
3409
  let token = null;
@@ -2727,24 +3414,24 @@ async function initStaticTina(ctx, next, options) {
2727
3414
  const framework = await chooseFramework();
2728
3415
  const usingTypescript = await chooseTypescript();
2729
3416
  const publicFolder = await choosePublicFolder({ framework });
2730
- const forestryPath = await hasForestryConfig({ rootPath: ctx.rootPath });
3417
+ const forestryPath = await hasForestryConfig({ rootPath });
2731
3418
  let collections;
2732
3419
  if (forestryPath.exists) {
2733
3420
  collections = await forestryMigrate({
2734
3421
  forestryPath: forestryPath.path,
2735
- rootPath: ctx.rootPath
3422
+ rootPath
2736
3423
  });
2737
3424
  }
2738
3425
  await reportTelemetry({
2739
3426
  usingTypescript,
2740
3427
  hasForestryConfig: forestryPath.exists,
2741
- noTelemetry: options.noTelemetry
3428
+ noTelemetry
2742
3429
  });
2743
- const hasPackageJSON = await import_fs_extra9.default.pathExistsSync("package.json");
3430
+ const hasPackageJSON = await import_fs_extra8.default.pathExistsSync("package.json");
2744
3431
  if (!hasPackageJSON) {
2745
3432
  await createPackageJSON();
2746
3433
  }
2747
- const hasGitignore = await import_fs_extra9.default.pathExistsSync(".gitignore");
3434
+ const hasGitignore = await import_fs_extra8.default.pathExistsSync(".gitignore");
2748
3435
  if (!hasGitignore) {
2749
3436
  await createGitignore({ baseDir });
2750
3437
  } else {
@@ -2863,7 +3550,7 @@ var chooseFramework = async () => {
2863
3550
  };
2864
3551
  var forestryMigrate = async ({
2865
3552
  forestryPath,
2866
- rootPath: rootPath2
3553
+ rootPath
2867
3554
  }) => {
2868
3555
  logger.info(
2869
3556
  `It looks like you have a ${focusText(
@@ -2897,7 +3584,7 @@ ${logText(
2897
3584
  });
2898
3585
  const collections = await generateCollections({
2899
3586
  forestryPath,
2900
- rootPath: rootPath2
3587
+ rootPath
2901
3588
  });
2902
3589
  ErrorSingleton.getInstance().printNameErrors();
2903
3590
  return JSON.stringify(collections, null, 2);
@@ -2910,12 +3597,12 @@ var reportTelemetry = async ({
2910
3597
  if (noTelemetry) {
2911
3598
  logger.info(logText("Telemetry disabled"));
2912
3599
  }
2913
- const telemetry = new import_metrics3.Telemetry({ disabled: noTelemetry });
2914
- const schemaFileType2 = usingTypescript ? "ts" : "js";
3600
+ const telemetry = new import_metrics2.Telemetry({ disabled: noTelemetry });
3601
+ const schemaFileType = usingTypescript ? "ts" : "js";
2915
3602
  await telemetry.submitRecord({
2916
3603
  event: {
2917
3604
  name: "tinacms:cli:init:invoke",
2918
- schemaFileType: schemaFileType2,
3605
+ schemaFileType,
2919
3606
  hasForestryConfig: hasForestryConfig2
2920
3607
  }
2921
3608
  });
@@ -2926,22 +3613,22 @@ var createPackageJSON = async () => {
2926
3613
  };
2927
3614
  var createGitignore = async ({ baseDir }) => {
2928
3615
  logger.info(logText("No .gitignore found, creating one"));
2929
- await import_fs_extra9.default.outputFileSync(import_path11.default.join(baseDir, ".gitignore"), "node_modules");
3616
+ await import_fs_extra8.default.outputFileSync(import_path9.default.join(baseDir, ".gitignore"), "node_modules");
2930
3617
  };
2931
3618
  var checkGitignoreForNodeModules = async ({
2932
3619
  baseDir
2933
3620
  }) => {
2934
- const gitignoreContent = await import_fs_extra9.default.readFileSync(import_path11.default.join(baseDir, ".gitignore")).toString();
3621
+ const gitignoreContent = await import_fs_extra8.default.readFileSync(import_path9.default.join(baseDir, ".gitignore")).toString();
2935
3622
  return gitignoreContent.split("\n").some((item) => item === "node_modules");
2936
3623
  };
2937
3624
  var addNodeModulesToGitignore = async ({ baseDir }) => {
2938
3625
  logger.info(logText("Adding node_modules to .gitignore"));
2939
- const gitignoreContent = await import_fs_extra9.default.readFileSync(import_path11.default.join(baseDir, ".gitignore")).toString();
3626
+ const gitignoreContent = await import_fs_extra8.default.readFileSync(import_path9.default.join(baseDir, ".gitignore")).toString();
2940
3627
  const newGitignoreContent = [
2941
3628
  ...gitignoreContent.split("\n"),
2942
3629
  "node_modules"
2943
3630
  ].join("\n");
2944
- await import_fs_extra9.default.writeFileSync(import_path11.default.join(baseDir, ".gitignore"), newGitignoreContent);
3631
+ await import_fs_extra8.default.writeFileSync(import_path9.default.join(baseDir, ".gitignore"), newGitignoreContent);
2945
3632
  };
2946
3633
  var addDependencies = async (packageManager) => {
2947
3634
  logger.info(logText("Adding dependencies, this might take a moment..."));
@@ -2956,12 +3643,12 @@ var addDependencies = async (packageManager) => {
2956
3643
  };
2957
3644
  var addConfigFile = async (args) => {
2958
3645
  const { baseDir, usingTypescript } = args;
2959
- const configPath = import_path11.default.join(
3646
+ const configPath = import_path9.default.join(
2960
3647
  ".tina",
2961
3648
  `config.${usingTypescript ? "ts" : "js"}`
2962
3649
  );
2963
- const fullConfigPath = import_path11.default.join(baseDir, configPath);
2964
- if (import_fs_extra9.default.pathExistsSync(fullConfigPath)) {
3650
+ const fullConfigPath = import_path9.default.join(baseDir, configPath);
3651
+ if (import_fs_extra8.default.pathExistsSync(fullConfigPath)) {
2965
3652
  const override = await (0, import_prompts2.default)({
2966
3653
  name: "selection",
2967
3654
  type: "confirm",
@@ -2969,7 +3656,7 @@ var addConfigFile = async (args) => {
2969
3656
  });
2970
3657
  if (override["selection"]) {
2971
3658
  logger.info(logText(`Overriding file at ${configPath}.`));
2972
- await import_fs_extra9.default.outputFileSync(fullConfigPath, config(args));
3659
+ await import_fs_extra8.default.outputFileSync(fullConfigPath, config2(args));
2973
3660
  } else {
2974
3661
  logger.info(logText(`Not overriding file at ${configPath}.`));
2975
3662
  }
@@ -2979,13 +3666,13 @@ var addConfigFile = async (args) => {
2979
3666
  `Adding config file at .tina/config.${usingTypescript ? "ts" : "js"}`
2980
3667
  )
2981
3668
  );
2982
- await import_fs_extra9.default.outputFileSync(fullConfigPath, config(args));
3669
+ await import_fs_extra8.default.outputFileSync(fullConfigPath, config2(args));
2983
3670
  }
2984
3671
  };
2985
3672
  var addContentFile = async ({ baseDir }) => {
2986
- const contentPath = import_path11.default.join("content", "posts", "hello-world.md");
2987
- const fullContentPath = import_path11.default.join(baseDir, contentPath);
2988
- if (import_fs_extra9.default.pathExistsSync(fullContentPath)) {
3673
+ const contentPath = import_path9.default.join("content", "posts", "hello-world.md");
3674
+ const fullContentPath = import_path9.default.join(baseDir, contentPath);
3675
+ if (import_fs_extra8.default.pathExistsSync(fullContentPath)) {
2989
3676
  const override = await (0, import_prompts2.default)({
2990
3677
  name: "selection",
2991
3678
  type: "confirm",
@@ -2993,13 +3680,13 @@ var addContentFile = async ({ baseDir }) => {
2993
3680
  });
2994
3681
  if (override["selection"]) {
2995
3682
  logger.info(logText(`Overriding file at ${contentPath}.`));
2996
- await import_fs_extra9.default.outputFileSync(fullContentPath, content);
3683
+ await import_fs_extra8.default.outputFileSync(fullContentPath, content);
2997
3684
  } else {
2998
3685
  logger.info(logText(`Not overriding file at ${contentPath}.`));
2999
3686
  }
3000
3687
  } else {
3001
3688
  logger.info(logText(`Adding content file at ${contentPath}`));
3002
- await import_fs_extra9.default.outputFileSync(fullContentPath, content);
3689
+ await import_fs_extra8.default.outputFileSync(fullContentPath, content);
3003
3690
  }
3004
3691
  };
3005
3692
  var logNextSteps = ({
@@ -3041,8 +3728,8 @@ var frameworkDevCmds = {
3041
3728
  return installText;
3042
3729
  }
3043
3730
  };
3044
- var config = (args) => {
3045
- return (0, import_prettier.format)(configExamples[args.framework.name](args));
3731
+ var config2 = (args) => {
3732
+ return (0, import_prettier.format)(configExamples[args.framework.name](args), { parser: "babel" });
3046
3733
  };
3047
3734
  var content = `---
3048
3735
  title: Hello, World!
@@ -3059,20 +3746,20 @@ var addReactiveFile = {
3059
3746
  baseDir,
3060
3747
  usingTypescript
3061
3748
  }) => {
3062
- const usingSrc = !import_fs_extra9.default.pathExistsSync(import_path11.default.join(baseDir, "pages"));
3063
- const pagesPath = import_path11.default.join(baseDir, usingSrc ? "src" : "", "pages");
3064
- const packageJSONPath = import_path11.default.join(baseDir, "package.json");
3065
- const tinaBlogPagePath = import_path11.default.join(pagesPath, "demo", "blog");
3066
- const tinaBlogPagePathFile = import_path11.default.join(
3749
+ const usingSrc = !import_fs_extra8.default.pathExistsSync(import_path9.default.join(baseDir, "pages"));
3750
+ const pagesPath = import_path9.default.join(baseDir, usingSrc ? "src" : "", "pages");
3751
+ const packageJSONPath = import_path9.default.join(baseDir, "package.json");
3752
+ const tinaBlogPagePath = import_path9.default.join(pagesPath, "demo", "blog");
3753
+ const tinaBlogPagePathFile = import_path9.default.join(
3067
3754
  tinaBlogPagePath,
3068
3755
  `[filename].${usingTypescript ? "tsx" : "js"}`
3069
3756
  );
3070
- if (!import_fs_extra9.default.pathExistsSync(tinaBlogPagePathFile)) {
3071
- import_fs_extra9.default.mkdirpSync(tinaBlogPagePath);
3072
- import_fs_extra9.default.writeFileSync(tinaBlogPagePathFile, nextPostPage({ usingSrc }));
3757
+ if (!import_fs_extra8.default.pathExistsSync(tinaBlogPagePathFile)) {
3758
+ import_fs_extra8.default.mkdirpSync(tinaBlogPagePath);
3759
+ import_fs_extra8.default.writeFileSync(tinaBlogPagePathFile, nextPostPage({ usingSrc }));
3073
3760
  }
3074
3761
  logger.info("Adding a nextjs example... \u2705");
3075
- const pack = JSON.parse(import_fs_extra9.default.readFileSync(packageJSONPath).toString());
3762
+ const pack = JSON.parse(import_fs_extra8.default.readFileSync(packageJSONPath).toString());
3076
3763
  const oldScripts = pack.scripts || {};
3077
3764
  const newPack = JSON.stringify(
3078
3765
  {
@@ -3082,7 +3769,7 @@ var addReactiveFile = {
3082
3769
  null,
3083
3770
  2
3084
3771
  );
3085
- import_fs_extra9.default.writeFileSync(packageJSONPath, newPack);
3772
+ import_fs_extra8.default.writeFileSync(packageJSONPath, newPack);
3086
3773
  }
3087
3774
  };
3088
3775
  function execShellCommand(cmd) {
@@ -3097,577 +3784,49 @@ function execShellCommand(cmd) {
3097
3784
  });
3098
3785
  }
3099
3786
 
3100
- // src/buildTina/attachDatabase.ts
3101
- var path10 = __toESM(require("path"));
3102
- var import_datalayer2 = require("@tinacms/datalayer");
3103
- var import_graphql11 = require("@tinacms/graphql");
3104
- var import_fs_extra11 = __toESM(require("fs-extra"));
3105
-
3106
- // src/buildTina/git.ts
3107
- var import_fs_extra10 = __toESM(require("fs-extra"));
3108
- var import_ini = __toESM(require("ini"));
3109
- var import_os = __toESM(require("os"));
3110
- var import_path12 = __toESM(require("path"));
3111
- var resolveGitRoot = async () => {
3112
- const pathParts = process.cwd().split(import_path12.default.sep);
3113
- while (true) {
3114
- const pathToGit = pathParts.join(import_path12.default.sep);
3115
- if (await import_fs_extra10.default.pathExists(import_path12.default.join(pathToGit, ".git"))) {
3116
- return pathToGit;
3117
- }
3118
- if (!pathParts.length) {
3119
- throw new Error(
3120
- "Unable to locate your .git folder (required for isomorphicGitBridge)"
3121
- );
3122
- }
3123
- pathParts.pop();
3124
- }
3125
- };
3126
- async function makeIsomorphicOptions(fsBridge) {
3127
- var _a, _b, _c, _d;
3128
- const gitRoot = await resolveGitRoot();
3129
- const options = {
3130
- gitRoot,
3131
- author: {
3132
- name: "",
3133
- email: ""
3134
- },
3135
- onPut: async (filepath, data) => {
3136
- await fsBridge.put(filepath, data);
3137
- },
3138
- onDelete: async (filepath) => {
3139
- await fsBridge.delete(filepath);
3140
- }
3141
- };
3142
- const userGitConfig = `${import_os.default.homedir()}${import_path12.default.sep}.gitconfig`;
3143
- if (await import_fs_extra10.default.pathExists(userGitConfig)) {
3144
- const config2 = import_ini.default.parse(await import_fs_extra10.default.readFile(userGitConfig, "utf-8"));
3145
- if ((_a = config2["user"]) == null ? void 0 : _a["name"]) {
3146
- options.author.name = config2["user"]["name"];
3147
- }
3148
- if ((_b = config2["user"]) == null ? void 0 : _b["email"]) {
3149
- options.author.email = config2["user"]["email"];
3150
- }
3151
- }
3152
- let repoGitConfig = void 0;
3153
- if (!options.author.name) {
3154
- repoGitConfig = import_ini.default.parse(
3155
- await import_fs_extra10.default.readFile(`${gitRoot}/.git/config`, "utf-8")
3156
- );
3157
- if ((_c = repoGitConfig["user"]) == null ? void 0 : _c["name"]) {
3158
- options.author.name = repoGitConfig["user"]["name"];
3159
- }
3160
- if (!options.author.name) {
3161
- throw new Error(
3162
- 'Unable to determine user.name from git config. Hint: `git config --global user.name "John Doe"`'
3163
- );
3164
- }
3165
- }
3166
- if (!options.author.email) {
3167
- repoGitConfig = repoGitConfig || import_ini.default.parse(await import_fs_extra10.default.readFile(`${gitRoot}/.git/config`, "utf-8"));
3168
- if ((_d = repoGitConfig["user"]) == null ? void 0 : _d["email"]) {
3169
- options.author.email = repoGitConfig["user"]["email"];
3170
- }
3171
- if (!options.author.email) {
3172
- throw new Error(
3173
- "Unable to determine user.email from git config. Hint: `git config --global user.email johndoe@example.com`"
3174
- );
3175
- }
3176
- }
3177
- return options;
3178
- }
3179
-
3180
- // src/buildTina/attachDatabase.ts
3181
- var import_memory_level2 = require("memory-level");
3182
- var import_many_level = require("many-level");
3183
- var import_readable_stream = require("readable-stream");
3184
- var import_net = require("net");
3185
- var attachDatabase = async (ctx, next, _options) => {
3186
- const tinaPath = path10.join(ctx.rootPath, ".tina");
3187
- const tinaGeneratedPath = path10.join(tinaPath, "__generated__");
3188
- const tinaTempPath = path10.join(tinaGeneratedPath, `temp_database`);
3189
- const define = {};
3190
- if (!process.env.NODE_ENV) {
3191
- define["process.env.NODE_ENV"] = _options.dev ? '"development"' : '"production"';
3192
- }
3193
- const inputFile = getPath({
3194
- projectDir: path10.join(ctx.rootPath, ".tina"),
3195
- filename: "database",
3196
- allowedTypes: ["js", "jsx", "tsx", "ts"]
3197
- });
3198
- const fsBridge = new import_datalayer2.FilesystemBridge(ctx.rootPath);
3199
- const levelHost = new import_many_level.ManyLevelHost(
3200
- new import_memory_level2.MemoryLevel({
3201
- valueEncoding: "json"
3202
- })
3203
- );
3204
- const server = (0, import_net.createServer)(function(socket) {
3205
- (0, import_readable_stream.pipeline)(socket, levelHost.createRpcStream(), socket, () => {
3206
- });
3207
- });
3208
- server.listen(9e3);
3209
- ctx.dbServer = server;
3210
- if (inputFile) {
3211
- try {
3212
- await transpile(
3213
- inputFile,
3214
- "database.cjs",
3215
- tinaTempPath,
3216
- _options.verbose,
3217
- define,
3218
- path10.join(ctx.rootPath, "package.json"),
3219
- "node"
3220
- );
3221
- } catch (e) {
3222
- await import_fs_extra11.default.remove(tinaTempPath);
3223
- throw new BuildSchemaError(e);
3224
- }
3225
- Object.keys(require.cache).map((key) => {
3226
- if (key.startsWith(tinaTempPath)) {
3227
- delete require.cache[require.resolve(key)];
3228
- }
3229
- });
3230
- try {
3231
- const databaseFunc = require(path10.join(tinaTempPath, `database.cjs`));
3232
- ctx.database = databaseFunc.default;
3233
- ctx.database.bridge = fsBridge;
3234
- ctx.bridge = ctx.database.bridge;
3235
- ctx.isSelfHostedDatabase = true;
3236
- await import_fs_extra11.default.remove(tinaTempPath);
3237
- } catch (e) {
3238
- await import_fs_extra11.default.remove(tinaTempPath);
3239
- throw e;
3240
- }
3241
- } else {
3242
- const bridge = _options.isomorphicGitBridge ? new import_datalayer2.IsomorphicBridge(
3243
- ctx.rootPath,
3244
- _options.isomorphicGitBridge && await makeIsomorphicOptions(fsBridge)
3245
- ) : fsBridge;
3246
- const level = new import_graphql11.TinaLevelClient();
3247
- level.openConnection();
3248
- ctx.database = await (0, import_graphql11.createDatabase)({ level, bridge });
3249
- ctx.bridge = bridge;
3250
- }
3251
- next();
3252
- };
3253
-
3254
- // src/cmds/statusChecks/checkClientInformation.ts
3255
- var import_progress2 = __toESM(require("progress"));
3256
- var import_graphql12 = require("graphql");
3257
- var import_core2 = require("@graphql-inspector/core");
3258
- var import_schema_tools2 = require("@tinacms/schema-tools");
3259
- async function request(args) {
3260
- const headers = new Headers();
3261
- if (args.token) {
3262
- headers.append("X-API-KEY", args.token);
3263
- }
3264
- headers.append("Content-Type", "application/json");
3265
- const url = args == null ? void 0 : args.url;
3266
- const res = await fetch(url, {
3267
- method: "GET",
3268
- headers,
3269
- redirect: "follow"
3270
- });
3271
- const json = await res.json();
3272
- if (!res.ok) {
3273
- let additionalInfo = "";
3274
- if (res.status === 401 || res.status === 403) {
3275
- additionalInfo = "Please check that your client ID, URL and read only token are configured properly.";
3276
- }
3277
- if (json) {
3278
- additionalInfo += `
3279
-
3280
- Message from server: ${json.message}`;
3281
- }
3282
- throw new Error(
3283
- `Server responded with status code ${res.status}, ${res.statusText}. ${additionalInfo ? additionalInfo : ""} Please see our FAQ for more information: https://tina.io/docs/errors/faq/`
3284
- );
3285
- }
3286
- if (json.errors) {
3287
- throw new Error(
3288
- `Unable to fetch, please see our FAQ for more information: https://tina.io/docs/errors/faq/
3289
-
3290
- Errors:
3291
- ${json.errors.map((error) => error.message).join("\n")}`
3292
- );
3293
- }
3294
- return {
3295
- status: json == null ? void 0 : json.status,
3296
- timestamp: json == null ? void 0 : json.timestamp
3297
- };
3298
- }
3299
- var checkClientInfo = async (ctx, next, _options) => {
3300
- var _a;
3301
- if (ctx.isSelfHostedDatabase) {
3302
- return next();
3303
- }
3304
- const config2 = (_a = ctx.schema) == null ? void 0 : _a.config;
3305
- const token = config2.token;
3306
- const { clientId, branch, host } = (0, import_schema_tools2.parseURL)(ctx.apiUrl);
3307
- const url = `https://${host}/db/${clientId}/status/${branch}`;
3308
- const bar = new import_progress2.default("Checking clientId, token and branch. :prog", 1);
3309
- try {
3310
- await request({
3311
- token,
3312
- url
3313
- });
3314
- bar.tick({
3315
- prog: "\u2705"
3787
+ // src/next/commands/init-command/index.ts
3788
+ var InitCommand = class extends import_clipanion4.Command {
3789
+ constructor() {
3790
+ super(...arguments);
3791
+ this.rootPath = import_clipanion4.Option.String("--rootPath", {
3792
+ description: "Specify the root directory to run the CLI from"
3316
3793
  });
3317
- } catch (e) {
3318
- bar.tick({
3319
- prog: "\u274C"
3794
+ this.noTelemetry = import_clipanion4.Option.Boolean("--noTelemetry", false, {
3795
+ description: "Disable anonymous telemetry that is collected"
3320
3796
  });
3321
- console.warn(
3322
- `Error when checking client information. You provided
3323
-
3324
- ${JSON.stringify(
3325
- {
3326
- branch: config2 == null ? void 0 : config2.branch,
3327
- clientId: config2 == null ? void 0 : config2.clientId,
3328
- token: config2 == null ? void 0 : config2.token
3329
- },
3330
- null,
3331
- 2
3332
- )}
3333
-
3334
- Please check you have the correct "clientId", "branch" and "token" configured. For more information see https://tina.io/docs/tina-cloud/connecting-site/`
3335
- );
3336
- throw e;
3337
3797
  }
3338
- next();
3339
- };
3340
- var fetchRemoteGraphqlSchema = async ({
3341
- url,
3342
- token
3343
- }) => {
3344
- const headers = new Headers();
3345
- if (token) {
3346
- headers.append("X-API-KEY", token);
3798
+ async catch(error) {
3799
+ logger.error("Error occured during tinacms init");
3800
+ console.error(error);
3801
+ process.exit(1);
3347
3802
  }
3348
- const body = JSON.stringify({ query: (0, import_graphql12.getIntrospectionQuery)(), variables: {} });
3349
- headers.append("Content-Type", "application/json");
3350
- const res = await fetch(url, {
3351
- method: "POST",
3352
- headers,
3353
- body
3354
- });
3355
- const data = await res.json();
3356
- return data == null ? void 0 : data.data;
3357
- };
3358
- var checkGraphqlSchema = async (ctx, next, _options) => {
3359
- var _a;
3360
- const bar = new import_progress2.default(
3361
- "Checking local GraphQL Schema matches server. :prog",
3362
- 1
3363
- );
3364
- const config2 = (_a = ctx.schema) == null ? void 0 : _a.config;
3365
- const token = config2.token;
3366
- const url = ctx.apiUrl;
3367
- const remoteSchema = await fetchRemoteGraphqlSchema({
3368
- url,
3369
- token
3370
- });
3371
- const remoteGqlSchema = (0, import_graphql12.buildClientSchema)(remoteSchema);
3372
- const localSchemaDocument = await ctx.database.getGraphQLSchemaFromBridge();
3373
- const localGraphqlSchema = (0, import_graphql12.buildSchema)((0, import_graphql12.print)(localSchemaDocument));
3374
- const diffResult = await (0, import_core2.diff)(localGraphqlSchema, remoteGqlSchema);
3375
- if (diffResult.length === 0) {
3376
- bar.tick({
3377
- prog: "\u2705"
3378
- });
3379
- } else {
3380
- bar.tick({
3381
- prog: "\u274C"
3803
+ async execute() {
3804
+ await initStaticTina({
3805
+ rootPath: this.rootPath || process.cwd(),
3806
+ noTelemetry: this.noTelemetry
3382
3807
  });
3383
- let errorMessage = `The local GraphQL schema doesn't match the remote GraphQL schema. Please push up your changes to Github to update your remote GraphQL schema.`;
3384
- if (config2 == null ? void 0 : config2.branch) {
3385
- errorMessage += `
3386
-
3387
- Additional info: Branch: ${config2.branch}, Client ID: ${config2.clientId} `;
3388
- }
3389
- throw new Error(errorMessage);
3808
+ process.exit();
3390
3809
  }
3391
- next();
3392
- };
3393
-
3394
- // src/cmds/baseCmds.ts
3395
- var CMD_START_SERVER = "server:start";
3396
- var CMD_DEV = "dev";
3397
- var INIT = "init";
3398
- var AUDIT = "audit";
3399
- var CMD_BUILD = "build";
3400
- var startServerPortOption = {
3401
- name: "--port <port>",
3402
- description: "Specify a port to run the server on. (default 4001)"
3403
3810
  };
3404
- var rootPathOption = {
3405
- name: "--rootPath <rootPath>",
3406
- description: "Specify the root directory to run the CLI from (defaults to current working directory)"
3407
- };
3408
- var experimentalDatalayer = {
3409
- name: "--experimentalData",
3410
- description: "Build the server with additional data querying capabilities"
3411
- };
3412
- var isomorphicGitBridge = {
3413
- name: "--isomorphicGitBridge",
3414
- description: "Enable Isomorphic Git Bridge Implementation"
3415
- };
3416
- var schemaFileType = {
3417
- name: "--schemaFileType [fileType]",
3418
- description: "The file type to use for the Tina schema"
3419
- };
3420
- var subCommand = {
3421
- name: "-c, --command <command>",
3422
- description: "The sub-command to run"
3423
- };
3424
- var noWatchOption = {
3425
- name: "--noWatch",
3426
- description: "Don't regenerate config on file changes"
3427
- };
3428
- var noSDKCodegenOption = {
3429
- name: "--noSDK",
3430
- description: "Don't generate the generated client SDK"
3431
- };
3432
- var cleanOption = {
3433
- name: "--clean",
3434
- description: "Updates all content files to remove any data not explicitly permitted by the current schema definition"
3435
- };
3436
- var useDefaultValuesOption = {
3437
- name: "--useDefaultValues",
3438
- 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`)"
3439
- };
3440
- var noTelemetryOption = {
3441
- name: "--noTelemetry",
3442
- description: "Disable anonymous telemetry that is collected"
3443
- };
3444
- var watchFileOption = {
3445
- name: "-w, --watchFolders [folders...]",
3446
- description: "a list of folders (relative to where this is being run) that the cli will watch for changes"
3447
- };
3448
- var verboseOption = {
3449
- name: "-v, --verbose",
3450
- description: "increase verbosity of logged output",
3451
- defaultValue: false
3452
- };
3453
- var developmentOption = {
3454
- name: "--dev",
3455
- description: "Uses NODE_ENV=development when compiling client and schema"
3456
- };
3457
- var localOption = {
3458
- name: "--local",
3459
- description: "Uses the local file system graphql server",
3460
- defaultValue: false
3461
- };
3462
- var checkOptions = async (_ctx, next, options) => {
3463
- if (options == null ? void 0 : options.experimentalData) {
3464
- logger.warn(
3465
- warnText(
3466
- "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"
3467
- )
3468
- );
3469
- }
3470
- next();
3471
- };
3472
- var baseCmds = [
3473
- {
3474
- command: CMD_START_SERVER,
3475
- description: "Start Filesystem Graphql Server",
3476
- options: [
3477
- startServerPortOption,
3478
- subCommand,
3479
- experimentalDatalayer,
3480
- isomorphicGitBridge,
3481
- noWatchOption,
3482
- noSDKCodegenOption,
3483
- noTelemetryOption,
3484
- watchFileOption,
3485
- verboseOption,
3486
- developmentOption,
3487
- localOption
3488
- ],
3489
- action: (options) => chain(
3490
- [
3491
- attachPath,
3492
- attachDatabase,
3493
- async (ctx, next, _2) => {
3494
- logger.warn(
3495
- warnText(
3496
- "server:start will be deprecated in the future, please use `tinacms dev` instead"
3497
- )
3498
- );
3499
- next();
3500
- },
3501
- checkOptions,
3502
- buildSetupCmdServerStart,
3503
- startServer,
3504
- startSubprocess
3505
- ],
3506
- options
3507
- )
3508
- },
3509
- {
3510
- command: CMD_DEV,
3511
- description: "Builds tina and starts the dev server.",
3512
- options: [
3513
- startServerPortOption,
3514
- subCommand,
3515
- isomorphicGitBridge,
3516
- noWatchOption,
3517
- noSDKCodegenOption,
3518
- noTelemetryOption,
3519
- watchFileOption,
3520
- verboseOption,
3521
- rootPathOption
3522
- ],
3523
- action: (options) => chain(
3524
- [
3525
- attachPath,
3526
- attachDatabase,
3527
- checkOptions,
3528
- buildSetupCmdServerStart,
3529
- startServer,
3530
- startSubprocess
3531
- ],
3532
- options
3533
- )
3534
- },
3535
- {
3536
- command: CMD_BUILD,
3537
- description: "Build Tina",
3538
- options: [
3539
- experimentalDatalayer,
3540
- isomorphicGitBridge,
3541
- noSDKCodegenOption,
3542
- noTelemetryOption,
3543
- verboseOption,
3544
- developmentOption,
3545
- localOption,
3546
- rootPathOption
3547
- ],
3548
- action: (options) => chain(
3549
- [
3550
- attachPath,
3551
- attachDatabase,
3552
- checkOptions,
3553
- buildSetupCmdBuild,
3554
- buildCmdBuild,
3555
- checkClientInfo,
3556
- waitForDB,
3557
- checkGraphqlSchema,
3558
- indexIntoSelfHostedDatabase
3559
- ],
3560
- options
3561
- )
3562
- },
3563
- {
3564
- command: INIT,
3565
- options: [
3566
- rootPathOption,
3567
- experimentalDatalayer,
3568
- isomorphicGitBridge,
3569
- noTelemetryOption,
3570
- schemaFileType
3571
- ],
3572
- description: "Add Tina Cloud to an existing project",
3573
- action: (options) => {
3574
- chain([attachPath, checkOptions, initStaticTina], options);
3575
- }
3576
- },
3577
- {
3578
- options: [
3579
- rootPathOption,
3580
- cleanOption,
3581
- useDefaultValuesOption,
3582
- noTelemetryOption,
3583
- verboseOption
3584
- ],
3585
- command: AUDIT,
3586
- description: "Audit your schema and the files to check for errors",
3587
- action: (options) => chain(
3588
- [
3589
- attachPath,
3590
- buildSetupCmdAudit,
3591
- auditCmdBuild,
3592
- async (_ctx, next) => {
3593
- logger.level = "info";
3594
- logger.info(
3595
- import_chalk4.default.hex("#eb6337").bgWhite("Welcome to tina audit \u{1F999}")
3596
- );
3597
- next();
3598
- },
3599
- audit,
3600
- printFinalMessage
3601
- ],
3602
- options
3603
- )
3604
- }
3605
- ];
3811
+ InitCommand.paths = [["init"]];
3812
+ InitCommand.usage = import_clipanion4.Command.Usage({
3813
+ category: `Commands`,
3814
+ description: `Add Tina to an existing project`
3815
+ });
3606
3816
 
3607
3817
  // src/index.ts
3608
- var program = new commander.Command(name);
3609
- var registerCommands = (commands, noHelp = false) => {
3610
- commands.forEach((command, i) => {
3611
- let newCmd = program.command(command.command, { noHelp }).description(command.description).action((...args) => {
3612
- command.action(...args);
3613
- });
3614
- if (command.alias) {
3615
- newCmd = newCmd.alias(command.alias);
3616
- }
3617
- newCmd.on("--help", function() {
3618
- if (command.examples) {
3619
- logger.info(`
3620
- Examples:
3621
- ${command.examples}`);
3622
- }
3623
- if (command.subCommands) {
3624
- logger.info("\nCommands:");
3625
- const optionTag = " [options]";
3626
- command.subCommands.forEach((subcommand, i2) => {
3627
- const commandStr = `${subcommand.command}${(subcommand.options || []).length ? optionTag : ""}`;
3628
- const padLength = Math.max(...command.subCommands.map((sub) => sub.command.length)) + optionTag.length;
3629
- logger.info(
3630
- `${commandStr.padEnd(padLength)} ${subcommand.description}`
3631
- );
3632
- });
3633
- }
3634
- logger.info("");
3635
- });
3636
- (command.options || []).forEach((option) => {
3637
- newCmd.option(option.name, option.description, option == null ? void 0 : option.defaultValue);
3638
- });
3639
- if (command.subCommands) {
3640
- registerCommands(command.subCommands, true);
3641
- }
3642
- });
3643
- };
3644
- async function init(args) {
3645
- program.version(version);
3646
- const commands = [...baseCmds];
3647
- registerCommands(commands);
3648
- program.usage("command [options]");
3649
- program.on("command:*", function() {
3650
- logger.error(
3651
- "Invalid command: %s\nSee --help for a list of available commands.",
3652
- args.join(" ")
3653
- );
3654
- process.exit(1);
3655
- });
3656
- program.on("--help", function() {
3657
- logger.info(
3658
- logText(`
3659
- You can get help on any command with "-h" or "--help".
3660
- e.g: "tinacms server:start --help"
3661
- `)
3662
- );
3663
- });
3664
- if (!process.argv.slice(2).length) {
3665
- program.help();
3666
- }
3667
- program.parse(args);
3668
- }
3669
- // Annotate the CommonJS export names for ESM import in node:
3670
- 0 && (module.exports = {
3671
- defineSchema,
3672
- init
3818
+ var cli = new import_clipanion5.Cli({
3819
+ binaryName: `tinacms`,
3820
+ binaryLabel: `TinaCMS`,
3821
+ binaryVersion: version
3673
3822
  });
3823
+ cli.register(DevCommand);
3824
+ cli.register(BuildCommand);
3825
+ cli.register(AuditCommand);
3826
+ cli.register(InitCommand);
3827
+ cli.register(import_clipanion5.Builtins.DefinitionsCommand);
3828
+ cli.register(import_clipanion5.Builtins.HelpCommand);
3829
+ cli.register(import_clipanion5.Builtins.VersionCommand);
3830
+ var src_default = cli;
3831
+ // Annotate the CommonJS export names for ESM import in node:
3832
+ 0 && (module.exports = {});