tinacms 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@tinacms/toolkit"), require("graphql"), require("lodash.set"), require("react"), require("final-form"), require("@tinacms/schema-tools"), require("graphql-tag"), require("yup"), require("@tinacms/sharedctx"), require("react-router-dom"), require("@headlessui/react"), require("@react-hook/window-size")) : typeof define === "function" && define.amd ? define(["exports", "@tinacms/toolkit", "graphql", "lodash.set", "react", "final-form", "@tinacms/schema-tools", "graphql-tag", "yup", "@tinacms/sharedctx", "react-router-dom", "@headlessui/react", "@react-hook/window-size"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.tinacms = {}, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP));
3
- })(this, function(exports2, toolkit, G, set, React, finalForm, schemaTools, gql$1, yup, sharedctx, reactRouterDom, react, windowSize) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("zod"), require("@tinacms/toolkit"), require("graphql"), require("graphql-tag"), require("@tinacms/schema-tools"), require("react"), require("yup"), require("@tinacms/sharedctx"), require("@graphql-inspector/core"), require("react-router-dom"), require("@headlessui/react"), require("@react-hook/window-size")) : typeof define === "function" && define.amd ? define(["exports", "zod", "@tinacms/toolkit", "graphql", "graphql-tag", "@tinacms/schema-tools", "react", "yup", "@tinacms/sharedctx", "@graphql-inspector/core", "react-router-dom", "@headlessui/react", "@react-hook/window-size"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.tinacms = {}, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP, global.NOOP));
3
+ })(this, function(exports2, zod, toolkit, graphql, gql$1, schemaTools, React, yup, sharedctx, core, reactRouterDom, react, windowSize) {
4
4
  "use strict";
5
5
  function _interopDefaultLegacy(e) {
6
6
  return e && typeof e === "object" && "default" in e ? e : { "default": e };
@@ -25,10 +25,8 @@
25
25
  n["default"] = e;
26
26
  return Object.freeze(n);
27
27
  }
28
- var G__namespace = /* @__PURE__ */ _interopNamespace(G);
29
- var set__default = /* @__PURE__ */ _interopDefaultLegacy(set);
30
- var React__default = /* @__PURE__ */ _interopDefaultLegacy(React);
31
28
  var gql__default = /* @__PURE__ */ _interopDefaultLegacy(gql$1);
29
+ var React__default = /* @__PURE__ */ _interopDefaultLegacy(React);
32
30
  var yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
33
31
  function popupWindow(url, title, window2, w, h) {
34
32
  const y = window2.top.outerHeight / 2 + window2.top.screenY - h / 2;
@@ -39,2097 +37,60 @@
39
37
  const AUTH_TOKEN_KEY = "tinacms-auth";
40
38
  const authenticate = (clientId, frontendUrl) => {
41
39
  return new Promise((resolve) => {
42
- let authTab;
43
- window.addEventListener("message", function(e) {
44
- if (e.data.source === TINA_LOGIN_EVENT) {
45
- if (authTab) {
46
- authTab.close();
47
- }
48
- resolve({
49
- id_token: e.data.id_token,
50
- access_token: e.data.access_token,
51
- refresh_token: e.data.refresh_token
52
- });
53
- }
54
- });
55
- const origin = `${window.location.protocol}//${window.location.host}`;
56
- authTab = popupWindow(`${frontendUrl}/signin?clientId=${clientId}&origin=${origin}`, "_blank", window, 1e3, 700);
57
- });
58
- };
59
- const formify$1 = (query, schema) => {
60
- const typeInfo = new G.TypeInfo(schema);
61
- const pathsToPopulate = [];
62
- const visitor = {
63
- leave(node2, key, parent, path, ancestors) {
64
- const type = typeInfo.getType();
65
- if (type) {
66
- const namedType = G.getNamedType(type);
67
- if (namedType instanceof G.GraphQLObjectType) {
68
- const hasNodeInterface = !!namedType.getInterfaces().find((i) => i.name === "Node");
69
- if (hasNodeInterface) {
70
- if (typeof path[path.length - 1] === "number") {
71
- assertIsObjectType(namedType);
72
- const valuesNode = namedType.getFields().values;
73
- const namedValuesNode = G.getNamedType(valuesNode.type);
74
- const pathForValues = [...path];
75
- pathForValues.push("selectionSet");
76
- pathForValues.push("selections");
77
- const valuesAst = buildValuesForType(namedValuesNode);
78
- pathForValues.push(100);
79
- const formNode = namedType.getFields().form;
80
- const namedFormNode = G.getNamedType(formNode.type);
81
- const pathForForm = [...path];
82
- pathForForm.push("selectionSet");
83
- pathForForm.push("selections");
84
- const formAst = buildFormForType(namedFormNode);
85
- pathForForm.push(101);
86
- const sysNode = namedType.getFields().sys;
87
- const namedSysNode = G.getNamedType(sysNode.type);
88
- const pathForSys = [...path];
89
- pathForSys.push("selectionSet");
90
- pathForSys.push("selections");
91
- const sysAst = buildSysForType(namedSysNode);
92
- pathForSys.push(102);
93
- pathsToPopulate.push({
94
- path: path.map((p) => p.toString()).join("-"),
95
- paths: [
96
- {
97
- path: pathForValues.map((p) => p.toString()),
98
- ast: valuesAst
99
- },
100
- {
101
- path: pathForForm.map((p) => p.toString()),
102
- ast: formAst
103
- },
104
- {
105
- path: pathForSys.map((p) => p.toString()),
106
- ast: sysAst
107
- }
108
- ]
109
- });
110
- }
111
- }
112
- }
113
- }
114
- }
115
- };
116
- G.visit(query, G.visitWithTypeInfo(typeInfo, visitor));
117
- const topLevelPaths = pathsToPopulate.filter((p, i) => {
118
- const otherPaths = pathsToPopulate.filter((_, index) => index !== i);
119
- const isChildOfOtherPaths = otherPaths.some((op) => {
120
- if (p.path.startsWith(op.path)) {
121
- return true;
122
- } else {
123
- return false;
124
- }
125
- });
126
- if (isChildOfOtherPaths) {
127
- return false;
128
- } else {
129
- return true;
130
- }
131
- });
132
- topLevelPaths.map((p) => {
133
- p.paths.map((pathNode) => {
134
- set__default["default"](query, pathNode.path, pathNode.ast);
135
- });
136
- });
137
- return query;
138
- };
139
- const buildSysForType = (type) => {
140
- assertIsObjectType(type);
141
- return {
142
- kind: "Field",
143
- alias: {
144
- kind: "Name",
145
- value: "_internalSys"
146
- },
147
- name: {
148
- kind: "Name",
149
- value: "sys"
150
- },
151
- selectionSet: {
152
- kind: "SelectionSet",
153
- selections: buildSelectionsFields(Object.values(type.getFields()), (fields) => {
154
- return {
155
- continue: true,
156
- filteredFields: fields.filter((field) => field.name !== "documents")
157
- };
158
- })
159
- }
160
- };
161
- };
162
- const buildValuesForType = (type) => {
163
- try {
164
- assertIsUnionType(type);
165
- return {
166
- kind: "Field",
167
- name: {
168
- kind: "Name",
169
- value: "values"
170
- },
171
- selectionSet: {
172
- kind: "SelectionSet",
173
- selections: buildSelectionInlineFragments(type.getTypes())
174
- }
175
- };
176
- } catch (e) {
177
- return {
178
- kind: "Field",
179
- name: {
180
- kind: "Name",
181
- value: "values"
182
- }
183
- };
184
- }
185
- };
186
- const buildFormForType = (type) => {
187
- try {
188
- assertIsUnionType(type);
189
- return {
190
- kind: "Field",
191
- name: {
192
- kind: "Name",
193
- value: "form"
194
- },
195
- selectionSet: {
196
- kind: "SelectionSet",
197
- selections: buildSelectionInlineFragments(type.getTypes())
198
- }
199
- };
200
- } catch (e) {
201
- return {
202
- kind: "Field",
203
- name: {
204
- kind: "Name",
205
- value: "form"
206
- }
207
- };
208
- }
209
- };
210
- const buildSelectionInlineFragments = (types, callback) => {
211
- return types.map((type) => {
212
- return {
213
- kind: "InlineFragment",
214
- typeCondition: {
215
- kind: "NamedType",
216
- name: {
217
- kind: "Name",
218
- value: type.name
219
- }
220
- },
221
- selectionSet: {
222
- kind: "SelectionSet",
223
- selections: [
224
- ...Object.values(type.getFields()).map((field) => {
225
- const namedType = G.getNamedType(field.type);
226
- if (G.isLeafType(namedType)) {
227
- return {
228
- kind: "Field",
229
- name: {
230
- kind: "Name",
231
- value: field.name
232
- }
233
- };
234
- } else if (namedType instanceof G.GraphQLUnionType) {
235
- return {
236
- kind: "Field",
237
- name: {
238
- kind: "Name",
239
- value: field.name
240
- },
241
- selectionSet: {
242
- kind: "SelectionSet",
243
- selections: [
244
- ...buildSelectionInlineFragments(namedType.getTypes(), callback)
245
- ]
246
- }
247
- };
248
- } else if (namedType instanceof G.GraphQLObjectType) {
249
- return {
250
- kind: "Field",
251
- name: {
252
- kind: "Name",
253
- value: field.name
254
- },
255
- selectionSet: {
256
- kind: "SelectionSet",
257
- selections: [
258
- ...buildSelectionsFields(Object.values(namedType.getFields()), callback)
259
- ]
260
- }
261
- };
262
- } else {
263
- throw new Error(`Unexpected GraphQL type for field ${namedType.name}`);
264
- }
265
- })
266
- ]
267
- }
268
- };
269
- });
270
- };
271
- const buildSelectionsFields = (fields, callback) => {
272
- let filteredFields = fields;
273
- if (callback) {
274
- const result = callback(fields);
275
- if (!result.continue) {
276
- if (fields.every((field) => {
277
- return !G.isScalarType(G.getNamedType(field.type));
278
- })) {
279
- return [
280
- {
281
- kind: "Field",
282
- name: {
283
- kind: "Name",
284
- value: "__typename"
285
- }
286
- }
287
- ];
288
- }
289
- return buildSelectionsFields(result.filteredFields.filter((field) => {
290
- if (G.isScalarType(G.getNamedType(field.type))) {
291
- return true;
292
- }
293
- return false;
294
- }));
295
- } else {
296
- filteredFields = result.filteredFields;
297
- }
298
- }
299
- return filteredFields.map((field) => {
300
- const namedType = G.getNamedType(field.type);
301
- if (G.isLeafType(namedType)) {
302
- return {
303
- kind: "Field",
304
- name: {
305
- kind: "Name",
306
- value: field.name
307
- }
308
- };
309
- } else if (namedType instanceof G.GraphQLUnionType) {
310
- return {
311
- kind: "Field",
312
- name: {
313
- kind: "Name",
314
- value: field.name
315
- },
316
- selectionSet: {
317
- kind: "SelectionSet",
318
- selections: [
319
- ...buildSelectionInlineFragments(namedType.getTypes(), callback)
320
- ]
321
- }
322
- };
323
- } else if (namedType instanceof G.GraphQLObjectType) {
324
- return {
325
- kind: "Field",
326
- name: {
327
- kind: "Name",
328
- value: field.name
329
- },
330
- selectionSet: {
331
- kind: "SelectionSet",
332
- selections: [
333
- ...buildSelectionsFields(Object.values(namedType.getFields()), callback)
334
- ]
335
- }
336
- };
337
- } else {
338
- return {
339
- kind: "Field",
340
- name: {
341
- kind: "Name",
342
- value: field.name
343
- },
344
- selectionSet: {
345
- kind: "SelectionSet",
346
- selections: []
347
- }
348
- };
349
- }
350
- });
351
- };
352
- function assertIsObjectType(type) {
353
- if (type instanceof G.GraphQLObjectType)
354
- ;
355
- else {
356
- throw new Error(`Expected an instance of GraphQLObjectType for type ${type.name}`);
357
- }
358
- }
359
- function assertIsUnionType(type) {
360
- if (type instanceof G.GraphQLUnionType)
361
- ;
362
- else {
363
- throw new Error(`Expected an instance of GraphQLUnionType for type ${type.name}`);
364
- }
365
- }
366
- const createClient = ({
367
- clientId,
368
- isLocalClient = true,
369
- branch,
370
- tinaioConfig,
371
- schema,
372
- apiUrl
373
- }) => {
374
- return isLocalClient ? new LocalClient({ customContentApiUrl: apiUrl, schema }) : new Client({
375
- clientId: clientId || "",
376
- branch: branch || "main",
377
- tokenStorage: "LOCAL_STORAGE",
378
- tinaioConfig,
379
- schema
380
- });
381
- };
382
- function assertShape(value, yupSchema, errorMessage) {
383
- const shape = yupSchema(yup__namespace);
384
- try {
385
- shape.validateSync(value);
386
- } catch (e) {
387
- const message = errorMessage || `Failed to assertShape - ${e.message}`;
388
- throw new Error(message);
389
- }
390
- }
391
- function safeAssertShape(value, yupSchema) {
392
- try {
393
- assertShape(value, yupSchema);
394
- return true;
395
- } catch (e) {
396
- return false;
397
- }
398
- }
399
- function useGraphqlForms({
400
- variables,
401
- onSubmit,
402
- query,
403
- formify: formify2,
404
- eventList
405
- }) {
406
- const cms = toolkit.useCMS();
407
- const state = useFormify({
408
- query,
409
- cms,
410
- variables,
411
- formify: formify2,
412
- eventList,
413
- onSubmit
414
- });
415
- if (!query) {
416
- return [state.data, false];
417
- }
418
- return [state.data, state.status !== "done"];
419
- }
420
- const transformDocumentIntoMutationRequestPayload = (document, instructions) => {
421
- const { _collection, __typename, _template, ...rest } = document;
422
- const params = transformParams(rest);
423
- const paramsWithTemplate = instructions.includeTemplate ? { [_template]: params } : params;
424
- return instructions.includeCollection ? { [_collection]: paramsWithTemplate } : paramsWithTemplate;
425
- };
426
- const transformParams = (data) => {
427
- if (["string", "number", "boolean"].includes(typeof data)) {
428
- return data;
429
- }
430
- if (Array.isArray(data)) {
431
- return data.map((item) => transformParams(item));
432
- }
433
- try {
434
- assertShape(data, (yup2) => yup2.object({ _template: yup2.string().required() }));
435
- const { _template, __typename, ...rest } = data;
436
- const nested = transformParams(rest);
437
- return { [_template]: nested };
438
- } catch (e) {
439
- if (e.message === "Failed to assertShape - _template is a required field") {
440
- if (!data) {
441
- return [];
442
- }
443
- const accum = {};
444
- Object.entries(data).map(([keyName, value]) => {
445
- accum[keyName] = transformParams(value);
446
- });
447
- return accum;
448
- } else {
449
- if (!data) {
450
- return [];
451
- }
452
- throw e;
453
- }
454
- }
455
- };
456
- const generateFormCreators = (cms, showInSidebar, global) => {
457
- const createForm = (formConfig) => {
458
- const form = new toolkit.Form(formConfig);
459
- if (showInSidebar) {
460
- if (global) {
461
- const options = typeof global === "boolean" ? [null, "fullscreen"] : [global.icon, global.layout];
462
- cms.plugins.add(new toolkit.GlobalFormPlugin(form, ...options));
463
- } else {
464
- cms.forms.add(form);
465
- }
466
- }
467
- return form;
468
- };
469
- const createGlobalForm = (formConfig, options) => {
470
- const form = new toolkit.Form(formConfig);
471
- if (showInSidebar) {
472
- cms.plugins.add(new toolkit.GlobalFormPlugin(form, options == null ? void 0 : options.icon, options == null ? void 0 : options.layout));
473
- }
474
- return form;
475
- };
476
- return { createForm, createGlobalForm };
477
- };
478
- const getValueForBlueprint = (state, path) => {
479
- const pathArray = path.split(".");
480
- let latest = state;
481
- pathArray.every((item, index) => {
482
- if (item === "[]") {
483
- const restOfItems = pathArray.slice(index + 1);
484
- if (latest) {
485
- const next = [];
486
- if (Array.isArray(latest)) {
487
- latest.forEach((latest2, index2) => {
488
- const res = getValueForBlueprint(latest2, restOfItems.join("."));
489
- next.push(res);
490
- });
491
- } else {
492
- throw new Error(`Expected value to be an array for "[]" item`);
493
- }
494
- if (next.length > 0) {
495
- latest = next;
496
- } else {
497
- latest = void 0;
498
- }
499
- }
500
- return false;
501
- } else {
502
- if (latest) {
503
- latest = latest[item];
504
- } else {
505
- latest = void 0;
506
- }
507
- }
508
- return true;
509
- });
510
- return latest;
511
- };
512
- const getFieldNameOrAlias = (fieldBlueprint) => {
513
- return fieldBlueprint.path[fieldBlueprint.path.length - 1].alias;
514
- };
515
- const spliceLocation = (string, location) => {
516
- const accum = [];
517
- let counter = 0;
518
- string.split(".").forEach((item) => {
519
- if (item === "[]") {
520
- accum.push(location[counter]);
521
- counter++;
522
- } else {
523
- accum.push(item);
524
- }
525
- });
526
- return accum.join(".");
527
- };
528
- const getPathToChange = (documentBlueprint, formNode, event) => {
529
- const fieldName = event.field.name;
530
- const location = [...formNode.location, ...stripIndices(fieldName)];
531
- const accum = [];
532
- let counter = 0;
533
- documentBlueprint.path.forEach((item) => {
534
- accum.push(item.alias);
535
- if (item.list) {
536
- if (location[counter] !== void 0) {
537
- accum.push(location[counter]);
538
- counter++;
539
- }
540
- }
541
- });
542
- return accum.join(".");
543
- };
544
- const buildForm = (doc, cms, formify2, showInSidebar = false, onSubmit) => {
545
- var _a;
546
- const id = doc._internalSys.path;
547
- const enrichedSchema = cms.api.tina.schema;
548
- const collection = enrichedSchema.getCollection(doc._internalSys.collection.name);
549
- const { createForm, createGlobalForm } = generateFormCreators(cms, showInSidebar, (_a = collection.ui) == null ? void 0 : _a.global);
550
- const SKIPPED = "SKIPPED";
551
- let form;
552
- let skipped;
553
- const skip = () => {
554
- skipped = SKIPPED;
555
- };
556
- if (skipped)
557
- return;
558
- const template = enrichedSchema.getTemplateForData({
559
- collection,
560
- data: doc._values
561
- });
562
- const formCommon = {
563
- id,
564
- label: id,
565
- initialValues: doc._values,
566
- onSubmit: async (payload) => {
567
- try {
568
- const params = transformDocumentIntoMutationRequestPayload(payload, {
569
- includeCollection: false,
570
- includeTemplate: !!collection.templates
571
- });
572
- const variables = { params };
573
- const mutationString = `#graphql
574
- mutation UpdateDocument($collection: String!, $relativePath: String!, $params: DocumentUpdateMutation!) {
575
- updateDocument(collection: $collection, relativePath: $relativePath, params: $params) {
576
- __typename
577
- }
578
- }
579
- `;
580
- if (onSubmit) {
581
- onSubmit({
582
- queryString: mutationString,
583
- mutationString,
584
- variables: {
585
- collection: doc._internalSys.collection.name,
586
- relativePath: doc._internalSys.relativePath,
587
- params: { [doc._internalSys.collection.name]: variables }
588
- }
589
- });
590
- } else {
591
- try {
592
- await cms.api.tina.request(mutationString, {
593
- variables: {
594
- collection: doc._internalSys.collection.name,
595
- relativePath: doc._internalSys.relativePath,
596
- params: {
597
- [doc._internalSys.collection.name]: variables.params
598
- }
599
- }
600
- });
601
- cms.alerts.success("Document saved!");
602
- } catch (e) {
603
- cms.alerts.error("There was a problem saving your document.");
604
- console.error(e);
605
- }
606
- }
607
- } catch (e) {
608
- console.error(e);
609
- cms.alerts.error("There was a problem saving your document.");
610
- }
611
- }
612
- };
613
- let formConfig = {};
614
- const formInfo = schemaTools.resolveForm({
615
- collection,
616
- basename: collection.name,
617
- schema: enrichedSchema,
618
- template
619
- });
620
- formConfig = {
621
- label: formInfo.label,
622
- fields: formInfo.fields,
623
- ...formCommon
624
- };
625
- if (formify2) {
626
- form = formify2({
627
- formConfig,
628
- createForm,
629
- createGlobalForm,
630
- skip
631
- }, cms);
632
- } else {
633
- form = createForm(formConfig);
634
- }
635
- if (!(form instanceof toolkit.Form)) {
636
- if (skipped === SKIPPED) {
637
- return;
638
- }
639
- throw new Error("formify must return a form or skip()");
640
- }
641
- return form;
642
- };
643
- const formNodeId = (formNode) => {
644
- return spliceLocation(formNode.documentBlueprintId, formNode.location) + formNode.documentFormId;
645
- };
646
- const formNodePath = (formNode) => {
647
- return spliceLocation(formNode.documentBlueprintId, formNode.location);
648
- };
649
- const formNodeNotIn = (formNode, formNodes) => {
650
- return !formNodes.find((fn) => formNodeId(fn) === formNodeId(formNode));
651
- };
652
- const sequential = async (items, callback) => {
653
- const accum = [];
654
- if (!items) {
655
- return [];
656
- }
657
- const reducePromises = async (previous, endpoint) => {
658
- const prev = await previous;
659
- if (prev) {
660
- accum.push(prev);
661
- }
662
- return callback(endpoint, accum.length);
663
- };
664
- const result = await items.reduce(reducePromises, Promise.resolve());
665
- if (result) {
666
- accum.push(result);
667
- }
668
- return accum;
669
- };
670
- const getFormNodesStartingWith = (string, state) => {
671
- return state.formNodes.filter((subFormNode) => {
672
- return subFormNode.documentBlueprintId.startsWith(string);
673
- });
674
- };
675
- const getFormNodesForField = (fieldBlueprint, formNode, event, state) => {
676
- const pathToChange = getPathToChange(fieldBlueprint, formNode, event);
677
- const formNodes = getFormNodesStartingWith(fieldBlueprint.id, state);
678
- const eventLocation = [
679
- ...formNode.location,
680
- ...stripIndices(event.field.name)
681
- ];
682
- const existing = finalForm.getIn(state.data, pathToChange);
683
- return { pathToChange, formNodes, eventLocation, existing };
684
- };
685
- const getBlueprintAliasPath = (blueprint) => {
686
- const namePath = [];
687
- const aliasPath = [];
688
- blueprint.path.forEach((p) => {
689
- namePath.push(p.name);
690
- aliasPath.push(p.alias);
691
- if (p.list) {
692
- namePath.push("[]");
693
- aliasPath.push("[]");
694
- }
695
- });
696
- return aliasPath.join(".");
697
- };
698
- const getBlueprintFieldsForEvent = (blueprint, event) => {
699
- return blueprint.fields.filter((fbp) => {
700
- if (getBlueprintNamePath(fbp) === getEventPath(event, blueprint)) {
701
- return true;
702
- }
703
- }).filter((fbp) => {
704
- return filterFieldBlueprintsByParentTypename(fbp, event.field.data.tinaField.parentTypename);
705
- });
706
- };
707
- const filterFieldBlueprintsByParentTypename = (fbp, typename) => {
708
- let lastDisambiguator;
709
- fbp.path.forEach((path) => {
710
- if (path.parentTypename) {
711
- lastDisambiguator = path.parentTypename;
712
- }
713
- });
714
- if (lastDisambiguator) {
715
- return typename === lastDisambiguator;
716
- } else {
717
- return true;
718
- }
719
- };
720
- const getBlueprintNamePath = (blueprint, disambiguator) => {
721
- const namePath = [];
722
- blueprint.path.forEach((p) => {
723
- if (disambiguator) {
724
- if (p.parentTypename) {
725
- namePath.push(p.parentTypename);
726
- }
727
- }
728
- namePath.push(p.name);
729
- if (p.list) {
730
- namePath.push("[]");
731
- }
732
- });
733
- return namePath.join(".");
734
- };
735
- const getEventPath = (event, blueprint) => {
736
- const stringArray = event.field.name.split(".");
737
- const eventPath = stringArray.map((item) => {
738
- if (isNaN(Number(item))) {
739
- return item;
740
- }
741
- return `[]`;
742
- }).join(".");
743
- const items = [blueprint.id, eventPath];
744
- const isList = event.field.data.tinaField.list;
745
- if (isList && !eventPath.endsWith("[]")) {
746
- items.push(`[]`);
747
- }
748
- return items.join(".");
749
- };
750
- const stripIndices = (string) => {
751
- const accum = [];
752
- const stringArray = string.split(".");
753
- stringArray.forEach((item) => {
754
- if (isNaN(item))
755
- ;
756
- else {
757
- accum.push(Number(item));
758
- }
759
- });
760
- return accum;
761
- };
762
- const replaceRealNum = (string) => {
763
- const stringArray = string.split(".");
764
- return stringArray.map((item) => {
765
- if (isNaN(item)) {
766
- return item;
767
- }
768
- return "[]";
769
- }).join(".");
770
- };
771
- const getMatchName = ({ field, prefix, blueprint }) => {
772
- const fieldName = field.list ? `${field.name}.[]` : field.name;
773
- const blueprintName = getBlueprintNamePath(blueprint);
774
- const extra = [];
775
- if (prefix) {
776
- extra.push(prefix);
777
- }
778
- const matchName = [blueprintName, ...extra, fieldName].join(".");
779
- return { matchName, fieldName };
780
- };
781
- const getFormNodesFromEvent = (state, event) => {
782
- const formNodes = state.formNodes.filter((formNode) => formNode.documentFormId === event.formId);
783
- return formNodes;
784
- };
785
- const printEvent = (event) => {
786
- var _a, _b;
787
- return {
788
- type: event.type,
789
- value: event.value,
790
- previousValue: event.previousValue,
791
- mutationType: event.mutationType,
792
- formId: event.formId,
793
- field: {
794
- data: (_a = event.field) == null ? void 0 : _a.data,
795
- name: (_b = event.field) == null ? void 0 : _b.name
796
- }
797
- };
798
- };
799
- const getFormNodeBlueprint = (formNode, state) => {
800
- return state.blueprints.find((d) => d.id === formNode.documentBlueprintId);
801
- };
802
- const getMoveMapping = (existing, from, to) => {
803
- const newOrderObject = {};
804
- if (from < to) {
805
- existing.map((_, i) => {
806
- if (i === from) {
807
- newOrderObject[i] = to;
808
- return;
809
- }
810
- if (i > from) {
811
- if (i < to) {
812
- newOrderObject[i] = i - 1;
813
- return;
814
- } else {
815
- if (i === to) {
816
- newOrderObject[i] = i - 1;
817
- return;
818
- }
819
- newOrderObject[i] = i;
820
- return;
821
- }
822
- } else {
823
- newOrderObject[i] = i;
824
- return;
825
- }
826
- });
827
- } else {
828
- existing.map((_, i) => {
829
- if (i === from) {
830
- newOrderObject[i] = to;
831
- return;
832
- }
833
- if (i > to) {
834
- if (i < from) {
835
- newOrderObject[i] = i + 1;
836
- return;
837
- } else {
838
- newOrderObject[i] = i;
839
- return;
840
- }
841
- } else {
842
- if (i === to) {
843
- newOrderObject[i] = i + 1;
844
- return;
845
- }
846
- newOrderObject[i] = i;
847
- return;
848
- }
849
- });
850
- }
851
- return newOrderObject;
852
- };
853
- const matchLocation = (eventLocation, formNode) => {
854
- return eventLocation.every((item, index) => item === formNode.location[index]);
855
- };
856
- const bumpLocation = (location) => {
857
- return location.map((item, index) => {
858
- if (index === location.length - 1) {
859
- return item + 1;
860
- }
861
- return item;
862
- });
863
- };
864
- const maybeLowerLocation = (location, at) => {
865
- return location.map((item, index) => {
866
- if (index === location.length - 1) {
867
- return item < at ? item : item - 1;
868
- }
869
- return item;
870
- });
871
- };
872
- const matchesAt = (location, at) => {
873
- let matches = false;
874
- location.map((item, index) => {
875
- if (index === location.length - 1) {
876
- if (item === at) {
877
- matches = true;
878
- }
879
- }
880
- });
881
- return matches;
882
- };
883
- const swapLocation = (location, mapping) => {
884
- return location.map((item, index) => {
885
- if (index === location.length - 1) {
886
- return mapping[item];
887
- }
888
- return item;
889
- });
890
- };
891
- const getSubFields = (changeSet) => {
892
- var _a;
893
- const fields = changeSet.fieldDefinition.fields ? changeSet.fieldDefinition.fields : changeSet.fieldDefinition.templates[changeSet.value[0]._template].fields;
894
- let __typename;
895
- if ((_a = changeSet.fieldDefinition) == null ? void 0 : _a.templates) {
896
- __typename = changeSet.fieldDefinition.typeMap[changeSet.value[0]._template];
897
- }
898
- return { fields, __typename };
899
- };
900
- const isFormifiableDocument = (t) => {
901
- const type = G__namespace.getNamedType(t);
902
- if (G__namespace.isUnionType(type)) {
903
- return type.getTypes().every((type2) => {
904
- return type2.getInterfaces().find((intfc) => intfc.name === "Node");
905
- });
906
- } else if (G__namespace.isObjectType(type)) {
907
- return !!type.getInterfaces().find((intfc) => intfc.name === "Node");
908
- } else {
909
- return false;
910
- }
911
- };
912
- const isScalarType = (t) => {
913
- const namedType = G__namespace.getNamedType(t);
914
- return G__namespace.isScalarType(namedType);
915
- };
916
- const isConnectionField = (t) => {
917
- const type = G__namespace.getNamedType(t);
918
- if (G__namespace.isObjectType(type)) {
919
- return !!type.getInterfaces().find((intfc) => intfc.name === "Connection");
920
- } else {
921
- throw new Error(`Expected GraphQLObjectType for isConnectionField check`);
922
- }
923
- };
924
- const getObjectField = (object, selectionNode) => {
925
- const namedType = G__namespace.getNamedType(object);
926
- ensureObjectOrInterfaceType(namedType);
927
- return namedType.getFields()[selectionNode.name.value];
928
- };
929
- const getSelectedUnionType = (unionType, selectionNode) => {
930
- const namedType = G__namespace.getNamedType(unionType);
931
- if (!G__namespace.isUnionType(namedType)) {
932
- return;
933
- }
934
- const types = namedType.getTypes();
935
- const typeCondition = selectionNode.typeCondition.name.value;
936
- let intfc;
937
- types.forEach((type) => {
938
- intfc = type.getInterfaces().find((intfc2) => intfc2.name === typeCondition);
939
- });
940
- if (intfc) {
941
- return intfc;
942
- }
943
- return namedType.getTypes().find((type) => type.name === typeCondition);
944
- };
945
- function isListType(type) {
946
- if (G__namespace.isListType(type)) {
947
- return true;
948
- } else if (G__namespace.isNonNullType(type)) {
949
- if (G__namespace.isListType(type.ofType)) {
950
- return true;
951
- }
952
- }
953
- return false;
954
- }
955
- function ensureObjectOrInterfaceType(type) {
956
- if (G__namespace.isInterfaceType(type) || G__namespace.isObjectType(type))
957
- ;
958
- else {
959
- console.log("Expected type to be GraphQLObjectType or GraphQLInterfaceType", type);
960
- throw new Error(`Expected type to be GraphQLObjectType or GraphQLInterfaceType`);
961
- }
962
- }
963
- function ensureOperationDefinition(type) {
964
- if (type.kind !== "OperationDefinition") {
965
- throw new Error(`Expected top-level definition to be an OperationDefinition node, ensure your query has been optimized before calling formify`);
966
- }
967
- }
968
- function buildPath({
969
- fieldNode,
970
- type,
971
- parentTypename,
972
- path
973
- }) {
974
- const p = path || [];
975
- const list = isListType(type);
976
- const isNode = isFormifiableDocument(type);
977
- return [
978
- ...p,
979
- {
980
- name: fieldNode.name.value,
981
- alias: fieldNode.alias ? fieldNode.alias.value : fieldNode.name.value,
982
- parentTypename,
983
- list: !!list,
984
- isNode: !!isNode
985
- }
986
- ];
987
- }
988
- const node = G__namespace.parse(`
989
- query Sample {
990
- ...on Document {
991
- _internalSys: _sys {
992
- path
993
- relativePath
994
- collection {
995
- name
996
- }
997
- }
998
- _values
999
- }
1000
- }`);
1001
- const metaFields = node.definitions[0].selectionSet.selections;
1002
- const getRelativeBlueprint = (path) => {
1003
- let indexOfLastNode = 0;
1004
- path.forEach((item, i) => {
1005
- if (item.isNode) {
1006
- if (i === path.length - 1)
1007
- ;
1008
- else {
1009
- indexOfLastNode = i;
1010
- }
1011
- }
1012
- });
1013
- const documentBlueprintPath = path.slice(0, indexOfLastNode + 1);
1014
- return getBlueprintNamePath({ path: documentBlueprintPath });
1015
- };
1016
- const isSysField = (fieldNode) => {
1017
- if (fieldNode.name.value === "__typename") {
1018
- return true;
1019
- }
1020
- if (fieldNode.name.value === "_sys") {
1021
- return true;
1022
- }
1023
- if (fieldNode.name.value === "_values") {
1024
- return true;
1025
- }
1026
- if (fieldNode.name.value === "id") {
1027
- return true;
1028
- }
1029
- return false;
1030
- };
1031
- const getBlueprintId = (path) => {
1032
- const namePath = [];
1033
- const aliasPath = [];
1034
- path.forEach((p) => {
1035
- namePath.push(p.name);
1036
- aliasPath.push(p.alias);
1037
- if (p.list) {
1038
- namePath.push("[]");
1039
- aliasPath.push("[]");
1040
- }
1041
- });
1042
- return namePath.join(".");
1043
- };
1044
- const NOOP = "This is either an error or is not yet supported";
1045
- const UNEXPECTED = "Formify encountered an unexpected error, please contact support";
1046
- const EDGES_NODE_NAME = "edges";
1047
- const NODE_NAME = "node";
1048
- const COLLECTION_FIELD_NAME = "collection";
1049
- const COLLECTIONS_FIELD_NAME = "collections";
1050
- const COLLECTIONS_DOCUMENTS_NAME = "documents";
1051
- const formify = async ({
1052
- schema,
1053
- query,
1054
- getOptimizedQuery
1055
- }) => {
1056
- const blueprints = [];
1057
- const documentNode = G__namespace.parse(query);
1058
- const visitor = {
1059
- OperationDefinition: (node2) => {
1060
- if (!node2.name) {
1061
- return {
1062
- ...node2,
1063
- name: {
1064
- kind: "Name",
1065
- value: `QueryOperation`
1066
- }
1067
- };
1068
- }
1069
- return node2;
1070
- }
1071
- };
1072
- const documentNodeWithName = G__namespace.visit(documentNode, visitor);
1073
- const optimizedQuery = await getOptimizedQuery(documentNodeWithName);
1074
- const typeInfo = new G__namespace.TypeInfo(schema);
1075
- const formifyConnection = ({
1076
- parentType,
1077
- selectionNode,
1078
- path
1079
- }) => {
1080
- return {
1081
- ...selectionNode,
1082
- selectionSet: {
1083
- kind: "SelectionSet",
1084
- selections: selectionNode.selectionSet.selections.map((selectionNode2) => {
1085
- switch (selectionNode2.kind) {
1086
- case "Field":
1087
- if (selectionNode2.name.value === EDGES_NODE_NAME) {
1088
- const edgeField = getObjectField(parentType, selectionNode2);
1089
- const edgesPath = buildPath({
1090
- fieldNode: selectionNode2,
1091
- type: edgeField.type,
1092
- path
1093
- });
1094
- return {
1095
- ...selectionNode2,
1096
- selectionSet: {
1097
- kind: "SelectionSet",
1098
- selections: selectionNode2.selectionSet.selections.map((subSelectionNode) => {
1099
- switch (subSelectionNode.kind) {
1100
- case "Field":
1101
- if (subSelectionNode.name.value === NODE_NAME) {
1102
- const nodeField = getObjectField(edgeField.type, subSelectionNode);
1103
- return formifyFieldNodeDocument({
1104
- fieldNode: subSelectionNode,
1105
- type: nodeField.type,
1106
- path: buildPath({
1107
- fieldNode: subSelectionNode,
1108
- type: nodeField.type,
1109
- path: edgesPath
1110
- }),
1111
- showInSidebar: false
1112
- });
1113
- } else {
1114
- return subSelectionNode;
1115
- }
1116
- default:
1117
- throw new FormifyError("NOOP");
1118
- }
1119
- })
1120
- }
1121
- };
1122
- }
1123
- return selectionNode2;
1124
- default:
1125
- throw new FormifyError("UNEXPECTED");
1126
- }
1127
- })
1128
- }
1129
- };
1130
- };
1131
- function formifyInlineFragmentDocument({
1132
- inlineFragmentNode,
1133
- type,
1134
- path,
1135
- showInSidebar = false
1136
- }) {
1137
- return formifyDocument({
1138
- selection: inlineFragmentNode,
1139
- type,
1140
- path,
1141
- showInSidebar
1142
- });
1143
- }
1144
- function formifyFieldNodeDocument({
1145
- fieldNode,
1146
- type,
1147
- path,
1148
- showInSidebar = false
1149
- }) {
1150
- return formifyDocument({ selection: fieldNode, type, path, showInSidebar });
1151
- }
1152
- function formifyDocument({
1153
- selection,
1154
- type,
1155
- path,
1156
- showInSidebar = false
1157
- }) {
1158
- let extraFields = [];
1159
- const hasDataJSONField = false;
1160
- let hasValuesField = false;
1161
- let shouldFormify = false;
1162
- selection.selectionSet.selections.forEach((selection2) => {
1163
- if (selection2.kind === "Field") {
1164
- shouldFormify = true;
1165
- if (selection2.name.value === "_values") {
1166
- hasValuesField = true;
1167
- }
1168
- }
1169
- });
1170
- if (shouldFormify) {
1171
- blueprints.push({
1172
- id: getBlueprintId(path),
1173
- path,
1174
- selection,
1175
- fields: [],
1176
- showInSidebar,
1177
- hasDataJSONField,
1178
- hasValuesField
1179
- });
1180
- extraFields = metaFields;
1181
- }
1182
- return {
1183
- ...selection,
1184
- selectionSet: {
1185
- kind: "SelectionSet",
1186
- selections: [
1187
- ...selection.selectionSet.selections.map((selectionNode) => {
1188
- switch (selectionNode.kind) {
1189
- case "InlineFragment": {
1190
- const namedType = G__namespace.getNamedType(type);
1191
- if (G__namespace.isInterfaceType(namedType)) {
1192
- const subType = schema.getImplementations(namedType).objects.find((item) => item.name === selectionNode.typeCondition.name.value);
1193
- return formifyInlineFragmentDocument({
1194
- inlineFragmentNode: selectionNode,
1195
- type: subType,
1196
- path,
1197
- showInSidebar: true
1198
- });
1199
- }
1200
- return formifyInlineFragmentNode({
1201
- inlineFragmentNode: selectionNode,
1202
- parentType: type,
1203
- path,
1204
- showInSidebar: true
1205
- });
1206
- }
1207
- case "Field": {
1208
- return formifyFieldNode({
1209
- fieldNode: selectionNode,
1210
- parentType: type,
1211
- path
1212
- });
1213
- }
1214
- default:
1215
- throw new FormifyError("UNEXPECTED");
1216
- }
1217
- }),
1218
- ...extraFields
1219
- ]
1220
- }
1221
- };
1222
- }
1223
- const formifyFieldNode = ({
1224
- fieldNode,
1225
- parentType,
1226
- path
1227
- }) => {
1228
- if (fieldNode.name.value === "__typename") {
1229
- return fieldNode;
1230
- }
1231
- const field = getObjectField(parentType, fieldNode);
1232
- if (!field) {
1233
- return fieldNode;
1234
- }
1235
- const fieldPath = buildPath({
1236
- fieldNode,
1237
- type: field.type,
1238
- parentTypename: G__namespace.getNamedType(parentType).name,
1239
- path
1240
- });
1241
- const blueprint = blueprints.find((blueprint2) => blueprint2.id === getRelativeBlueprint(fieldPath));
1242
- if (!blueprint) {
1243
- return fieldNode;
1244
- }
1245
- if (isSysField(fieldNode)) {
1246
- return fieldNode;
1247
- }
1248
- blueprint.fields.push({
1249
- id: getBlueprintId(fieldPath),
1250
- documentBlueprintId: blueprint.id,
1251
- path: fieldPath
1252
- });
1253
- if (isScalarType(field.type)) {
1254
- return fieldNode;
1255
- }
1256
- return {
1257
- ...fieldNode,
1258
- selectionSet: {
1259
- kind: "SelectionSet",
1260
- selections: [
1261
- ...fieldNode.selectionSet.selections.map((selectionNode) => {
1262
- switch (selectionNode.kind) {
1263
- case "Field": {
1264
- return formifyFieldNode({
1265
- fieldNode: selectionNode,
1266
- parentType: field.type,
1267
- path: fieldPath
1268
- });
1269
- }
1270
- case "InlineFragment": {
1271
- return formifyInlineFragmentNode({
1272
- inlineFragmentNode: selectionNode,
1273
- parentType: field.type,
1274
- path: fieldPath,
1275
- showInSidebar: false
1276
- });
1277
- }
1278
- default:
1279
- throw new FormifyError("UNEXPECTED", `selection ${selectionNode.kind}`);
1280
- }
1281
- })
1282
- ]
1283
- }
1284
- };
1285
- };
1286
- const formifyInlineFragmentNode = ({
1287
- inlineFragmentNode,
1288
- parentType,
1289
- path,
1290
- showInSidebar
1291
- }) => {
1292
- const type = getSelectedUnionType(parentType, inlineFragmentNode);
1293
- if (!type) {
1294
- return inlineFragmentNode;
1295
- }
1296
- if (isFormifiableDocument(type)) {
1297
- return formifyInlineFragmentDocument({
1298
- inlineFragmentNode,
1299
- type,
1300
- path,
1301
- showInSidebar
1302
- });
1303
- }
1304
- return {
1305
- ...inlineFragmentNode,
1306
- selectionSet: {
1307
- kind: "SelectionSet",
1308
- selections: inlineFragmentNode.selectionSet.selections.map((selectionNode) => {
1309
- switch (selectionNode.kind) {
1310
- case "Field":
1311
- return formifyFieldNode({
1312
- fieldNode: selectionNode,
1313
- parentType: type,
1314
- path
1315
- });
1316
- default:
1317
- throw new FormifyError("UNEXPECTED", `selection ${selectionNode.kind}`);
1318
- }
1319
- })
1320
- }
1321
- };
1322
- };
1323
- const formifiedQuery = {
1324
- kind: "Document",
1325
- definitions: optimizedQuery.definitions.map((definition) => {
1326
- typeInfo.enter(definition);
1327
- ensureOperationDefinition(definition);
1328
- const parentType = typeInfo.getType();
1329
- return {
1330
- ...definition,
1331
- selectionSet: {
1332
- kind: "SelectionSet",
1333
- selections: definition.selectionSet.selections.map((selectionNode) => {
1334
- switch (selectionNode.kind) {
1335
- case "Field":
1336
- const field = getObjectField(parentType, selectionNode);
1337
- const path = buildPath({
1338
- fieldNode: selectionNode,
1339
- type: field.type
1340
- });
1341
- if (isFormifiableDocument(field.type)) {
1342
- return formifyFieldNodeDocument({
1343
- fieldNode: selectionNode,
1344
- type: field.type,
1345
- path,
1346
- showInSidebar: true
1347
- });
1348
- } else if (isConnectionField(field.type)) {
1349
- return formifyConnection({
1350
- parentType: field.type,
1351
- selectionNode,
1352
- path
1353
- });
1354
- }
1355
- if (selectionNode.name.value === COLLECTION_FIELD_NAME || selectionNode.name.value === COLLECTIONS_FIELD_NAME) {
1356
- const path2 = buildPath({
1357
- fieldNode: selectionNode,
1358
- type: field.type
1359
- });
1360
- return {
1361
- ...selectionNode,
1362
- selectionSet: {
1363
- kind: "SelectionSet",
1364
- selections: selectionNode.selectionSet.selections.map((subSelectionNode) => {
1365
- switch (subSelectionNode.kind) {
1366
- case "Field":
1367
- if (subSelectionNode.name.value === COLLECTIONS_DOCUMENTS_NAME) {
1368
- const subField = getObjectField(field.type, subSelectionNode);
1369
- return formifyConnection({
1370
- parentType: subField.type,
1371
- selectionNode: subSelectionNode,
1372
- path: buildPath({
1373
- fieldNode: subSelectionNode,
1374
- type: subField.type,
1375
- path: path2
1376
- })
1377
- });
1378
- }
1379
- return subSelectionNode;
1380
- default:
1381
- throw new FormifyError("NOOP");
1382
- }
1383
- })
1384
- }
1385
- };
1386
- }
1387
- throw new FormifyError("NOOP");
1388
- default:
1389
- throw new FormifyError("UNEXPECTED");
1390
- }
1391
- })
1392
- }
1393
- };
1394
- })
1395
- };
1396
- return { formifiedQuery, blueprints };
1397
- };
1398
- class FormifyError extends Error {
1399
- constructor(code, details) {
1400
- let message;
1401
- switch (code) {
1402
- case "NOOP":
1403
- message = NOOP;
1404
- break;
1405
- case "UNEXPECTED":
1406
- message = UNEXPECTED;
1407
- break;
1408
- default:
1409
- message = "";
1410
- break;
1411
- }
1412
- super(`${message} ${details || ""}`);
1413
- this.name = "FormifyError";
1414
- }
1415
- }
1416
- const defaultState = {
1417
- status: "idle",
1418
- schema: void 0,
1419
- query: null,
1420
- queryString: null,
1421
- data: {},
1422
- changeSets: [],
1423
- count: 0,
1424
- blueprints: [],
1425
- formNodes: [],
1426
- documentForms: []
1427
- };
1428
- function reducer(state, action) {
1429
- var _a, _b, _c, _d;
1430
- switch (action.type) {
1431
- case "start":
1432
- return {
1433
- ...state,
1434
- ...defaultState,
1435
- query: action.value.query ? G__namespace.parse(action.value.query) : null,
1436
- queryString: action.value.query,
1437
- status: "initialized"
1438
- };
1439
- case "addDocumentBlueprints":
1440
- return {
1441
- ...state,
1442
- status: "formified",
1443
- blueprints: action.value.blueprints,
1444
- query: action.value.formifiedQuery
1445
- };
1446
- case "addOrReplaceDocumentFormNode": {
1447
- const existingDocumentForms = state.documentForms.filter((documentForm) => {
1448
- var _a2, _b2;
1449
- return documentForm.id !== ((_b2 = (_a2 = action.value) == null ? void 0 : _a2.documentForm) == null ? void 0 : _b2.id);
1450
- });
1451
- const existingDocumentFormNodes = state.formNodes.filter((formNode) => {
1452
- return formNodeId(formNode) !== formNodeId(action.value.formNode);
1453
- });
1454
- const newDocumentForms = [];
1455
- if ((_a = action.value) == null ? void 0 : _a.documentForm) {
1456
- newDocumentForms.push((_b = action.value) == null ? void 0 : _b.documentForm);
1457
- }
1458
- return {
1459
- ...state,
1460
- formNodes: [...existingDocumentFormNodes, action.value.formNode],
1461
- documentForms: [...existingDocumentForms, ...newDocumentForms]
1462
- };
1463
- }
1464
- case "onFieldChange": {
1465
- const event = action.value.event;
1466
- const changeSets = [];
1467
- const formNodesToReplace = [];
1468
- const formNodesToRemove = [];
1469
- const newFormNodes = [];
1470
- const form = state.documentForms.find((documentForm) => documentForm.id === event.formId);
1471
- getFormNodesFromEvent(state, event).forEach((formNode) => {
1472
- const blueprint = getFormNodeBlueprint(formNode, state);
1473
- if (blueprint.hasValuesField) {
1474
- changeSets.push({
1475
- path: [formNodePath(formNode), "values"].join("."),
1476
- ...buildChangeSet(event, formNode),
1477
- value: form.values,
1478
- mutationType: {
1479
- type: "global"
1480
- }
1481
- });
1482
- }
1483
- if (blueprint.hasDataJSONField) {
1484
- changeSets.push({
1485
- path: [formNodePath(formNode), "dataJSON"].join("."),
1486
- ...buildChangeSet(event, formNode),
1487
- value: form.values,
1488
- mutationType: {
1489
- type: "global"
1490
- }
1491
- });
1492
- }
1493
- if (event.mutationType.type === "change") {
1494
- if (!action.value.form) {
1495
- getBlueprintFieldsForEvent(blueprint, event).forEach((fieldBlueprint) => {
1496
- const { pathToChange } = getFormNodesForField(fieldBlueprint, formNode, event, state);
1497
- changeSets.push({
1498
- path: pathToChange,
1499
- ...buildChangeSet(event, formNode)
1500
- });
1501
- });
1502
- }
1503
- } else if (event.mutationType.type === "referenceChange") {
1504
- getBlueprintFieldsForEvent(blueprint, event).forEach((fieldBlueprint) => {
1505
- const {
1506
- pathToChange,
1507
- formNodes: subFormNodes,
1508
- eventLocation
1509
- } = getFormNodesForField(fieldBlueprint, formNode, event, state);
1510
- if (action.value.form && state.blueprints.find((blueprint2) => blueprint2.id === fieldBlueprint.id)) {
1511
- const newFormNode = {
1512
- documentBlueprintId: fieldBlueprint.id,
1513
- documentFormId: action.value.form.id,
1514
- location: eventLocation
1515
- };
1516
- newFormNodes.push(newFormNode);
1517
- changeSets.push({
1518
- path: pathToChange,
1519
- ...buildChangeSet(event, newFormNode)
1520
- });
1521
- }
1522
- subFormNodes.forEach((subFormNode) => {
1523
- if (matchLocation(eventLocation, subFormNode)) {
1524
- if (!action.value.form) {
1525
- changeSets.push({
1526
- path: pathToChange,
1527
- ...buildChangeSet(event, subFormNode),
1528
- value: null
1529
- });
1530
- }
1531
- formNodesToReplace.push(subFormNode);
1532
- }
1533
- });
1534
- });
1535
- } else {
1536
- getBlueprintFieldsForEvent(blueprint, event).forEach((fieldBlueprint) => {
1537
- const { pathToChange, formNodes, existing, eventLocation } = getFormNodesForField(fieldBlueprint, formNode, event, state);
1538
- if (event.mutationType.type === "insert") {
1539
- formNodes.forEach((subFormNode) => {
1540
- if (matchLocation(eventLocation, subFormNode)) {
1541
- newFormNodes.push({
1542
- ...subFormNode,
1543
- location: bumpLocation(subFormNode.location)
1544
- });
1545
- formNodesToReplace.push(subFormNode);
1546
- }
1547
- });
1548
- changeSets.push({
1549
- path: pathToChange,
1550
- ...buildChangeSet(event, formNode)
1551
- });
1552
- }
1553
- if (event.mutationType.type === "remove") {
1554
- const { at } = event.mutationType;
1555
- formNodes.forEach((subFormNode) => {
1556
- if (matchLocation(eventLocation, subFormNode)) {
1557
- if (matchesAt(subFormNode.location, at)) {
1558
- formNodesToRemove.push(subFormNode);
1559
- } else {
1560
- newFormNodes.push({
1561
- ...subFormNode,
1562
- location: maybeLowerLocation(subFormNode.location, at)
1563
- });
1564
- formNodesToReplace.push(subFormNode);
1565
- }
1566
- }
1567
- });
1568
- const next = existing.filter((_, index) => index !== at);
1569
- changeSets.push({
1570
- path: pathToChange,
1571
- ...buildChangeSet(event, formNode),
1572
- value: next
1573
- });
1574
- }
1575
- if (event.mutationType.type === "move") {
1576
- const next = [];
1577
- const { from, to } = event.mutationType;
1578
- const newOrderObject = getMoveMapping(existing, from, to);
1579
- formNodes.forEach((subFormNode) => {
1580
- if (matchLocation(eventLocation, subFormNode)) {
1581
- newFormNodes.push({
1582
- ...subFormNode,
1583
- location: swapLocation(subFormNode.location, newOrderObject)
1584
- });
1585
- formNodesToReplace.push(subFormNode);
1586
- }
1587
- });
1588
- Object.values(newOrderObject).forEach((orderIndex, index) => {
1589
- next[orderIndex] = existing[index];
1590
- });
1591
- changeSets.push({
1592
- path: pathToChange,
1593
- ...buildChangeSet(event, formNode),
1594
- value: next
1595
- });
1596
- }
1597
- });
1598
- }
1599
- });
1600
- const existingDocumentForms = state.documentForms.filter((documentForm) => {
1601
- var _a2;
1602
- return documentForm.id !== ((_a2 = action.value.form) == null ? void 0 : _a2.id);
1603
- });
1604
- const newDocumentForms = [];
1605
- if ((_c = action.value) == null ? void 0 : _c.form) {
1606
- newDocumentForms.push((_d = action.value) == null ? void 0 : _d.form);
1607
- }
1608
- return {
1609
- ...state,
1610
- changeSets,
1611
- formNodes: [
1612
- ...state.formNodes.filter((formNode) => formNodeNotIn(formNode, formNodesToReplace)).filter((formNode) => formNodeNotIn(formNode, formNodesToRemove)),
1613
- ...newFormNodes
1614
- ],
1615
- documentForms: [...existingDocumentForms, ...newDocumentForms]
1616
- };
1617
- }
1618
- case "formOnReset": {
1619
- const { event } = action.value;
1620
- const changeSets = [];
1621
- const form = state.documentForms.find((documentForm) => documentForm.id === event.formId);
1622
- state.formNodes.filter((fn) => fn.documentFormId === (form == null ? void 0 : form.id)).forEach((formNode) => {
1623
- const blueprint = getFormNodeBlueprint(formNode, state);
1624
- if (blueprint.hasValuesField) {
1625
- changeSets.push({
1626
- path: [formNodePath(formNode), "_values"].join("."),
1627
- ...buildChangeSet(event, formNode)
1628
- });
1629
- }
1630
- changeSets.push({
1631
- path: [formNodePath(formNode)].join("."),
1632
- ...buildChangeSet(event, formNode)
1633
- });
1634
- });
1635
- return { ...state, changeSets };
1636
- }
1637
- case "ready":
1638
- return { ...state, status: "ready" };
1639
- case "done":
1640
- return { ...state, status: "done" };
1641
- case "setData":
1642
- return { ...state, data: action.value };
1643
- case "setIn": {
1644
- let newData;
1645
- if (action.value.displaceIndex) {
1646
- const existing = finalForm.getIn(state.data, action.value.path) || [];
1647
- newData = finalForm.setIn(state.data, action.value.path, [
1648
- action.value.value,
1649
- ...existing
1650
- ]);
1651
- } else {
1652
- newData = finalForm.setIn(state.data, action.value.path, action.value.value);
1653
- }
1654
- const changeSets = state.changeSets.filter((cs) => cs.path !== action.value.path);
1655
- return {
1656
- ...state,
1657
- data: newData,
1658
- changeSets
1659
- };
1660
- }
1661
- default:
1662
- return state;
1663
- }
1664
- }
1665
- const buildChangeSet = (event, formNode) => {
1666
- var _a, _b, _c;
1667
- return {
1668
- fieldDefinition: (_b = (_a = event.field) == null ? void 0 : _a.data) == null ? void 0 : _b.tinaField,
1669
- name: (_c = event.field) == null ? void 0 : _c.name,
1670
- formId: event.formId,
1671
- mutationType: event.mutationType,
1672
- value: event.value,
1673
- formNode
1674
- };
1675
- };
1676
- const useFormify = ({
1677
- query,
1678
- cms,
1679
- variables,
1680
- onSubmit,
1681
- formify: formifyFunc,
1682
- eventList
1683
- }) => {
1684
- const formIds = React__default["default"].useRef([]);
1685
- const [state, dispatch] = React__default["default"].useReducer(reducer, {
1686
- status: "idle",
1687
- schema: void 0,
1688
- query: query ? G__namespace.parse(query) : null,
1689
- queryString: query,
1690
- data: {},
1691
- changeSets: [],
1692
- count: 0,
1693
- blueprints: [],
1694
- formNodes: [],
1695
- documentForms: []
1696
- });
1697
- React__default["default"].useEffect(() => {
1698
- if (query) {
1699
- dispatch({ type: "start", value: { query } });
1700
- formIds.current.forEach((formId) => {
1701
- const form = cms.forms.find(formId);
1702
- if (form) {
1703
- cms.plugins.remove(form);
1704
- }
1705
- });
1706
- }
1707
- }, [query, JSON.stringify(variables)]);
1708
- React__default["default"].useEffect(() => {
1709
- if (state.status === "initialized") {
1710
- cms.api.tina.request(query, { variables }).then((res) => {
1711
- delete res.paths;
1712
- dispatch({ type: "setData", value: res });
1713
- });
1714
- }
1715
- }, [state.status]);
1716
- React__default["default"].useEffect(() => {
1717
- const run = async () => {
1718
- const schema = await cms.api.tina.getSchema();
1719
- const result = await formify({
1720
- schema,
1721
- query,
1722
- getOptimizedQuery: cms.api.tina.getOptimizedQuery
1723
- });
1724
- dispatch({
1725
- type: "addDocumentBlueprints",
1726
- value: result
1727
- });
1728
- };
1729
- if (state.status === "initialized") {
1730
- run();
1731
- }
1732
- }, [state.status]);
1733
- React__default["default"].useEffect(() => {
1734
- const run = async () => {
1735
- const result = await cms.api.tina.request(G__namespace.print(state.query), {
1736
- variables
1737
- });
1738
- state.blueprints.map((blueprint) => {
1739
- const responseAtBlueprint = getValueForBlueprint(result, getBlueprintAliasPath(blueprint));
1740
- const location = [];
1741
- const findFormNodes = (res, location2) => {
1742
- if (Array.isArray(res)) {
1743
- res.forEach((item, index) => {
1744
- if (Array.isArray(item)) {
1745
- findFormNodes(item, [...location2, index]);
1746
- } else {
1747
- if (item) {
1748
- const form = buildForm(item, cms, formifyFunc, blueprint.showInSidebar, onSubmit);
1749
- const formNode = buildFormNode(blueprint, form, [
1750
- ...location2,
1751
- index
1752
- ]);
1753
- dispatch({
1754
- type: "addOrReplaceDocumentFormNode",
1755
- value: {
1756
- formNode,
1757
- documentForm: form
1758
- }
1759
- });
1760
- }
1761
- }
1762
- });
1763
- } else {
1764
- if (res) {
1765
- const form = buildForm(res, cms, formifyFunc, blueprint.showInSidebar, onSubmit);
1766
- const formNode = buildFormNode(blueprint, form, location2);
1767
- dispatch({
1768
- type: "addOrReplaceDocumentFormNode",
1769
- value: {
1770
- formNode,
1771
- documentForm: form
1772
- }
1773
- });
1774
- }
1775
- }
1776
- };
1777
- findFormNodes(responseAtBlueprint, location);
1778
- });
1779
- dispatch({ type: "ready" });
1780
- };
1781
- if (state.status === "formified") {
1782
- run();
1783
- }
1784
- }, [state.status]);
1785
- React__default["default"].useEffect(() => {
1786
- if (state.status === "ready") {
1787
- cms.events.subscribe(`forms:reset`, (event) => {
1788
- if (eventList) {
1789
- eventList.push(printEvent(event));
1790
- }
1791
- dispatch({ type: "formOnReset", value: { event } });
1792
- });
1793
- cms.events.subscribe(`forms:fields:onChange`, async (event) => {
1794
- if (eventList) {
1795
- eventList.push(printEvent(event));
1796
- }
1797
- if (event.field.data.tinaField.type === "reference") {
1798
- let form;
1799
- if (event.value && typeof event.value === "string") {
1800
- const existingForm = cms.forms.find(event.value);
1801
- if (existingForm) {
1802
- form = existingForm;
1803
- } else {
1804
- const formInfo = await cms.api.tina.request(`#graphql
1805
- query Node($id: String!) {
1806
- node(id: $id) {
1807
- ...on Document {
1808
- _values
1809
- _internalSys: _sys {
1810
- path
1811
- relativePath
1812
- collection {
1813
- name
1814
- }
1815
- }
1816
- }
1817
- }
1818
- }
1819
- `, { variables: { id: event.value } });
1820
- form = buildForm(formInfo.node, cms, formifyFunc, false, onSubmit);
1821
- }
1822
- }
1823
- dispatch({
1824
- type: "onFieldChange",
1825
- value: {
1826
- event: {
1827
- ...event,
1828
- mutationType: { type: "referenceChange" }
1829
- },
1830
- form
1831
- }
1832
- });
1833
- } else {
1834
- dispatch({ type: "onFieldChange", value: { event } });
1835
- }
1836
- });
1837
- dispatch({ type: "done" });
1838
- }
1839
- }, [state.status]);
1840
- React__default["default"].useEffect(() => {
1841
- state.changeSets.forEach((changeSet) => {
1842
- if (changeSet.mutationType.type === "reset") {
1843
- const form = cms.forms.find(changeSet.formId);
1844
- resolveSubFields({
1845
- formNode: changeSet.formNode,
1846
- form,
1847
- loc: []
1848
- }).then((res) => {
1849
- dispatch({
1850
- type: "setIn",
1851
- value: {
1852
- value: res,
1853
- path: changeSet.path
1854
- }
1855
- });
1856
- });
1857
- return;
1858
- } else if (changeSet.mutationType.type === "insert") {
1859
- if (changeSet.fieldDefinition.type === "object") {
1860
- const fieldName = changeSet.fieldDefinition.list ? `${changeSet.name}.[]` : changeSet.name;
1861
- const { fields, __typename } = getSubFields(changeSet);
1862
- resolveSubFields({
1863
- formNode: changeSet.formNode,
1864
- prefix: replaceRealNum(fieldName),
1865
- loc: [...stripIndices(changeSet.path), 0],
1866
- form: {
1867
- fields,
1868
- values: changeSet.value[0]
1869
- }
1870
- }).then((res) => {
1871
- const extra = {};
1872
- if (__typename) {
1873
- extra["__typename"] = __typename;
1874
- }
1875
- dispatch({
1876
- type: "setIn",
1877
- value: {
1878
- displaceIndex: true,
1879
- ...changeSet,
1880
- value: {
1881
- ...res,
1882
- ...extra
1883
- }
1884
- }
1885
- });
1886
- });
1887
- } else {
1888
- dispatch({
1889
- type: "setIn",
1890
- value: {
1891
- displaceIndex: true,
1892
- ...changeSet,
1893
- value: changeSet.value[0]
1894
- }
1895
- });
1896
- }
1897
- } else {
1898
- if (changeSet.mutationType.type === "referenceChange") {
1899
- const { formNode } = changeSet;
1900
- const blueprint = getFormNodeBlueprint(formNode, state);
1901
- if (!changeSet.value) {
1902
- dispatch({
1903
- type: "setIn",
1904
- value: {
1905
- ...changeSet,
1906
- value: null
1907
- }
1908
- });
1909
- } else {
1910
- cms.api.tina.request(`
1911
- query Node($id: String!) {
1912
- node(id: $id) {
1913
- ${G__namespace.print(blueprint.selection)}
1914
- }
1915
- }
1916
- `, { variables: { id: changeSet.value } }).then(async (res) => {
1917
- const form = state.documentForms.find((documentForm) => documentForm.id === formNode.documentFormId);
1918
- const data = await resolveSubFields({
1919
- formNode,
1920
- form,
1921
- loc: formNode.location
1922
- });
1923
- dispatch({
1924
- type: "setIn",
1925
- value: {
1926
- ...changeSet,
1927
- value: {
1928
- ...res.node,
1929
- ...data
1930
- }
1931
- }
1932
- });
1933
- }).catch((e) => {
1934
- cms.alerts.error(`Unexpected error fetching reference.`);
1935
- console.log(e);
1936
- });
1937
- }
1938
- } else {
1939
- dispatch({ type: "setIn", value: changeSet });
1940
- }
1941
- }
1942
- });
1943
- }, [JSON.stringify(state.changeSets)]);
1944
- React__default["default"].useEffect(() => {
1945
- formIds.current = state.documentForms.map((df) => df.id);
1946
- }, [state.documentForms.length]);
1947
- React__default["default"].useEffect(() => {
1948
- return () => {
1949
- formIds.current.forEach((formId) => {
1950
- const form = cms.forms.find(formId);
1951
- if (form) {
1952
- cms.plugins.remove(form);
40
+ let authTab;
41
+ window.addEventListener("message", function(e) {
42
+ if (e.data.source === TINA_LOGIN_EVENT) {
43
+ if (authTab) {
44
+ authTab.close();
1953
45
  }
1954
- });
1955
- };
1956
- }, []);
1957
- const resolveSubFields = React__default["default"].useCallback(async (args) => {
1958
- const { form, formNode, prefix, loc } = args;
1959
- const data = {};
1960
- await sequential(form.fields, async (field) => {
1961
- const value = form.values[field.name];
1962
- const blueprint = getFormNodeBlueprint(formNode, state);
1963
- const { matchName, fieldName } = getMatchName({
1964
- field,
1965
- prefix,
1966
- blueprint
1967
- });
1968
- const fieldBlueprints = blueprint.fields.filter((fieldBlueprint) => {
1969
- return matchName === getBlueprintNamePath(fieldBlueprint);
1970
- }).filter((fbp) => filterFieldBlueprintsByParentTypename(fbp, field.parentTypename));
1971
- switch (field.type) {
1972
- case "object":
1973
- if (field.templates) {
1974
- if (field.list) {
1975
- await sequential(fieldBlueprints, async (fieldBlueprint) => {
1976
- const keyName = getFieldNameOrAlias(fieldBlueprint);
1977
- if (!value) {
1978
- data[keyName] = null;
1979
- return true;
1980
- }
1981
- if (!Array.isArray(value)) {
1982
- throw new Error(`Expected value for object list field to be an array`);
1983
- }
1984
- data[keyName] = await sequential(value, async (item, index) => {
1985
- const template = field.templates[item._template];
1986
- return {
1987
- ...await resolveSubFields({
1988
- formNode,
1989
- form: { fields: template.fields, values: item },
1990
- prefix: prefix ? [prefix, fieldName].join(".") : fieldName,
1991
- loc: [...loc, index]
1992
- }),
1993
- __typename: field.typeMap[item._template]
1994
- };
1995
- });
1996
- });
1997
- } else {
1998
- throw new Error("blocks without list true is not yet supported");
1999
- }
2000
- } else {
2001
- if (field.list) {
2002
- await sequential(fieldBlueprints, async (fieldBlueprint) => {
2003
- const keyName = getFieldNameOrAlias(fieldBlueprint);
2004
- if (!value) {
2005
- data[keyName] = null;
2006
- return true;
2007
- }
2008
- if (!Array.isArray(value)) {
2009
- throw new Error(`Expected value for object list field to be an array`);
2010
- }
2011
- data[keyName] = await sequential(value, async (item, index) => {
2012
- return resolveSubFields({
2013
- formNode,
2014
- form: { fields: field.fields, values: item },
2015
- prefix: [prefix, fieldName].join("."),
2016
- loc: [...loc, index]
2017
- });
2018
- });
2019
- return true;
2020
- });
2021
- } else {
2022
- await sequential(fieldBlueprints, async (fieldBlueprint) => {
2023
- const keyName = getFieldNameOrAlias(fieldBlueprint);
2024
- if (!value) {
2025
- data[keyName] = null;
2026
- return true;
2027
- }
2028
- data[keyName] = await resolveSubFields({
2029
- formNode,
2030
- form: { fields: field.fields, values: value },
2031
- prefix: [prefix, fieldName].join("."),
2032
- loc
2033
- });
2034
- return true;
2035
- });
2036
- }
2037
- }
2038
- break;
2039
- case "reference":
2040
- let form2;
2041
- if (typeof value === "string") {
2042
- const existingForm = cms.forms.find(value);
2043
- if (existingForm) {
2044
- form2 = existingForm;
2045
- } else {
2046
- const formInfo = await cms.api.tina.request(`#graphql
2047
- query Node($id: String!) {
2048
- node(id: $id) {
2049
- ...on Document {
2050
- _values
2051
- _internalSys: _sys {
2052
- path
2053
- relativePath
2054
- collection {
2055
- name
2056
- }
2057
- }
2058
- }
2059
- }
2060
- }
2061
- `, { variables: { id: value } });
2062
- form2 = buildForm(formInfo.node, cms, formifyFunc, false, onSubmit);
2063
- }
2064
- }
2065
- await sequential(fieldBlueprints, async (fieldBlueprint) => {
2066
- const keyName = getFieldNameOrAlias(fieldBlueprint);
2067
- if (!value) {
2068
- data[keyName] = null;
2069
- return true;
2070
- }
2071
- const documentBlueprint = state.blueprints.find((dp) => getBlueprintNamePath(dp) === matchName);
2072
- const location = [...formNode.location];
2073
- if (loc) {
2074
- loc.forEach((item) => location.push(item));
2075
- }
2076
- const subDocumentFormNode = buildFormNode(documentBlueprint, form2, location);
2077
- dispatch({
2078
- type: "addOrReplaceDocumentFormNode",
2079
- value: {
2080
- formNode: subDocumentFormNode,
2081
- documentForm: form2
2082
- }
2083
- });
2084
- const res = await cms.api.tina.request(`
2085
- query Node($id: String!) {
2086
- node(id: $id) {
2087
- ${G__namespace.print(documentBlueprint.selection)}
2088
- }
2089
- }
2090
- `, { variables: { id: value } });
2091
- data[keyName] = {
2092
- ...res.node,
2093
- ...await resolveSubFields({
2094
- formNode: subDocumentFormNode,
2095
- form: form2,
2096
- loc: location
2097
- })
2098
- };
2099
- });
2100
- break;
2101
- default:
2102
- fieldBlueprints.forEach((fieldBlueprint) => {
2103
- const keyName = getFieldNameOrAlias(fieldBlueprint);
2104
- if (!value) {
2105
- data[keyName] = null;
2106
- } else {
2107
- data[keyName] = value;
2108
- }
2109
- });
2110
- break;
46
+ resolve({
47
+ id_token: e.data.id_token,
48
+ access_token: e.data.access_token,
49
+ refresh_token: e.data.refresh_token
50
+ });
2111
51
  }
2112
- return true;
2113
52
  });
2114
- return data;
2115
- }, [cms, JSON.stringify(state), dispatch]);
2116
- return {
2117
- ...state,
2118
- queryString: G__namespace.print(state.query)
2119
- };
2120
- };
2121
- const buildFormNode = (documentBlueprint, form, location) => {
2122
- return {
2123
- documentBlueprintId: documentBlueprint.id,
2124
- documentFormId: form.id,
2125
- location
2126
- };
53
+ const origin = `${window.location.protocol}//${window.location.host}`;
54
+ authTab = popupWindow(`${frontendUrl}/signin?clientId=${clientId}&origin=${origin}`, "_blank", window, 1e3, 700);
55
+ });
2127
56
  };
2128
57
  const captureBranchName = /^refs\/heads\/(.*)/;
2129
58
  const parseRefForBranchName = (ref) => {
2130
59
  const matches = ref.match(captureBranchName);
2131
60
  return matches[1];
2132
61
  };
62
+ const ListBranchResponse = zod.z.object({
63
+ name: zod.z.string(),
64
+ protected: zod.z.boolean(),
65
+ commit: zod.z.object({ sha: zod.z.string(), url: zod.z.string() })
66
+ }).array();
67
+ const IndexStatusResponse = zod.z.object({
68
+ status: zod.z.union([
69
+ zod.z.literal("complete"),
70
+ zod.z.literal("unknown"),
71
+ zod.z.literal("failed"),
72
+ zod.z.literal("inprogress")
73
+ ]).optional(),
74
+ timestamp: zod.z.number().optional()
75
+ });
76
+ async function asyncPoll(fn, pollInterval = 5 * 1e3, pollTimeout = 30 * 1e3) {
77
+ const endTime = new Date().getTime() + pollTimeout;
78
+ const checkCondition = (resolve, reject) => {
79
+ Promise.resolve(fn()).then((result) => {
80
+ const now = new Date().getTime();
81
+ if (result.done) {
82
+ resolve(result.data);
83
+ } else if (now < endTime) {
84
+ setTimeout(checkCondition, pollInterval, resolve, reject);
85
+ } else {
86
+ reject(new Error("AsyncPoller: reached timeout"));
87
+ }
88
+ }).catch((err) => {
89
+ reject(err);
90
+ });
91
+ };
92
+ return new Promise(checkCondition);
93
+ }
2133
94
  class Client {
2134
95
  constructor({ tokenStorage = "MEMORY", ...options }) {
2135
96
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P;
@@ -2165,10 +126,10 @@ mutation addPendingDocumentMutation(
2165
126
  };
2166
127
  this.getSchema = async () => {
2167
128
  if (!this.gqlSchema) {
2168
- const data = await this.request(G.getIntrospectionQuery(), {
129
+ const data = await this.request(graphql.getIntrospectionQuery(), {
2169
130
  variables: {}
2170
131
  });
2171
- this.gqlSchema = G.buildClientSchema(data);
132
+ this.gqlSchema = graphql.buildClientSchema(data);
2172
133
  }
2173
134
  return this.gqlSchema;
2174
135
  };
@@ -2176,9 +137,9 @@ mutation addPendingDocumentMutation(
2176
137
  const data = await this.request(`query GetOptimizedQuery($queryString: String!) {
2177
138
  getOptimizedQuery(queryString: $queryString)
2178
139
  }`, {
2179
- variables: { queryString: G.print(documentNode) }
140
+ variables: { queryString: graphql.print(documentNode) }
2180
141
  });
2181
- return G.parse(data.getOptimizedQuery);
142
+ return graphql.parse(data.getOptimizedQuery);
2182
143
  };
2183
144
  this.onLogin = (_d = (_c = (_b = (_a = options.schema) == null ? void 0 : _a.config) == null ? void 0 : _b.admin) == null ? void 0 : _c.auth) == null ? void 0 : _d.onLogin;
2184
145
  this.onLogout = (_h = (_g = (_f = (_e = options.schema) == null ? void 0 : _e.config) == null ? void 0 : _f.admin) == null ? void 0 : _g.auth) == null ? void 0 : _h.onLogout;
@@ -2266,24 +227,6 @@ mutation addPendingDocumentMutation(
2266
227
  this.contentApiBase = ((_d = this.options.tinaioConfig) == null ? void 0 : _d.contentApiUrlOverride) || `https://content.tinajs.io`;
2267
228
  this.contentApiUrl = this.options.customContentApiUrl || `${this.contentApiBase}/content/${this.options.clientId}/github/${encodedBranch}`;
2268
229
  }
2269
- async requestWithForm(query, {
2270
- variables,
2271
- useUnstableFormify
2272
- }) {
2273
- const schema = await this.getSchema();
2274
- let formifiedQuery;
2275
- if (useUnstableFormify) {
2276
- const res = await formify({
2277
- schema,
2278
- query: G.print(query(gql__default["default"])),
2279
- getOptimizedQuery: this.getOptimizedQuery
2280
- });
2281
- formifiedQuery = res.formifiedQuery;
2282
- } else {
2283
- formifiedQuery = formify$1(query(gql__default["default"]), schema);
2284
- }
2285
- return this.request(G.print(formifiedQuery), { variables });
2286
- }
2287
230
  async request(query, { variables }) {
2288
231
  const res = await fetch(this.contentApiUrl, {
2289
232
  method: "POST",
@@ -2292,7 +235,7 @@ mutation addPendingDocumentMutation(
2292
235
  Authorization: "Bearer " + (await this.getToken()).id_token
2293
236
  },
2294
237
  body: JSON.stringify({
2295
- query: typeof query === "function" ? G.print(query(gql__default["default"])) : query,
238
+ query: typeof query === "function" ? graphql.print(query(gql__default["default"])) : query,
2296
239
  variables
2297
240
  })
2298
241
  });
@@ -2447,12 +390,64 @@ mutation addPendingDocumentMutation(
2447
390
  return null;
2448
391
  }
2449
392
  }
393
+ async waitForIndexStatus({ ref }) {
394
+ try {
395
+ const result = await asyncPoll(async () => {
396
+ try {
397
+ const result2 = await this.getIndexStatus({ ref });
398
+ if (!(result2.status === "inprogress" || result2.status === "unknown")) {
399
+ return Promise.resolve({
400
+ done: true,
401
+ data: result2
402
+ });
403
+ } else {
404
+ return Promise.resolve({
405
+ done: false
406
+ });
407
+ }
408
+ } catch (err) {
409
+ return Promise.reject(err);
410
+ }
411
+ }, 5e3, 9e5);
412
+ return result;
413
+ } catch (error) {
414
+ if (error.message === "AsyncPoller: reached timeout") {
415
+ console.warn(error);
416
+ return {
417
+ status: "timeout"
418
+ };
419
+ }
420
+ throw error;
421
+ }
422
+ }
423
+ async getIndexStatus({ ref }) {
424
+ const url = `${this.contentApiBase}/db/${this.clientId}/status/${ref}`;
425
+ const res = await this.fetchWithToken(url);
426
+ const result = await res.json();
427
+ const parsedResult = IndexStatusResponse.parse(result);
428
+ return parsedResult;
429
+ }
2450
430
  async listBranches() {
2451
- const url = `${this.contentApiBase}/github/${this.clientId}/list_branches`;
2452
- const res = await this.fetchWithToken(url, {
2453
- method: "GET"
2454
- });
2455
- return res.json();
431
+ try {
432
+ const url = `${this.contentApiBase}/github/${this.clientId}/list_branches`;
433
+ const res = await this.fetchWithToken(url, {
434
+ method: "GET"
435
+ });
436
+ const branches = await res.json();
437
+ const parsedBranches = ListBranchResponse.parse(branches);
438
+ const indexStatusPromises = parsedBranches.map(async (branch) => {
439
+ const indexStatus2 = await this.getIndexStatus({ ref: branch.name });
440
+ return {
441
+ ...branch,
442
+ indexStatus: indexStatus2
443
+ };
444
+ });
445
+ const indexStatus = await Promise.all(indexStatusPromises);
446
+ return indexStatus;
447
+ } catch (error) {
448
+ console.error("There was an error listing branches.", error);
449
+ throw error;
450
+ }
2456
451
  }
2457
452
  async createBranch({ baseBranch, branchName }) {
2458
453
  const url = `${this.contentApiBase}/github/${this.clientId}/create_branch`;
@@ -2525,6 +520,7 @@ mutation addPendingDocumentMutation(
2525
520
  }
2526
521
  }, [action, setSubmitting]);
2527
522
  return /* @__PURE__ */ React__default["default"].createElement(toolkit.Button, {
523
+ "data-test": name.replace(/\s/g, "-").toLowerCase(),
2528
524
  variant: primary ? "primary" : "secondary",
2529
525
  onClick,
2530
526
  busy: submitting,
@@ -2546,6 +542,39 @@ mutation addPendingDocumentMutation(
2546
542
  localStorage[TINA_AUTH_CONFIG] = JSON.stringify(config);
2547
543
  }, []);
2548
544
  };
545
+ const createClient = ({
546
+ clientId,
547
+ isLocalClient = true,
548
+ branch,
549
+ tinaioConfig,
550
+ schema,
551
+ apiUrl
552
+ }) => {
553
+ return isLocalClient ? new LocalClient({ customContentApiUrl: apiUrl, schema }) : new Client({
554
+ clientId: clientId || "",
555
+ branch: branch || "main",
556
+ tokenStorage: "LOCAL_STORAGE",
557
+ tinaioConfig,
558
+ schema
559
+ });
560
+ };
561
+ function assertShape(value, yupSchema, errorMessage) {
562
+ const shape = yupSchema(yup__namespace);
563
+ try {
564
+ shape.validateSync(value);
565
+ } catch (e) {
566
+ const message = errorMessage || `Failed to assertShape - ${e.message}`;
567
+ throw new Error(message);
568
+ }
569
+ }
570
+ function safeAssertShape(value, yupSchema) {
571
+ try {
572
+ assertShape(value, yupSchema);
573
+ return true;
574
+ } catch (e) {
575
+ return false;
576
+ }
577
+ }
2549
578
  class TinaAdminApi {
2550
579
  constructor(cms) {
2551
580
  this.api = cms.api.tina;
@@ -2554,6 +583,17 @@ mutation addPendingDocumentMutation(
2554
583
  async isAuthenticated() {
2555
584
  return await this.api.isAuthenticated();
2556
585
  }
586
+ async checkGraphqlSchema({ localSchema }) {
587
+ const schemaFromCloud = await this.api.getSchema();
588
+ const schema1 = schemaFromCloud;
589
+ const schema2 = graphql.buildSchema(graphql.print(localSchema));
590
+ const diffOutput = await core.diff(schema1, schema2);
591
+ if (diffOutput.length > 0) {
592
+ return false;
593
+ } else {
594
+ return true;
595
+ }
596
+ }
2557
597
  fetchCollections() {
2558
598
  return this.schema.getCollections();
2559
599
  }
@@ -3289,6 +1329,15 @@ mutation addPendingDocumentMutation(
3289
1329
  margin-left: auto;
3290
1330
  margin-right: auto;
3291
1331
  }
1332
+ .tina-tailwind .mb-6 {
1333
+ margin-bottom: 24px;
1334
+ }
1335
+ .tina-tailwind .mr-1 {
1336
+ margin-right: 4px;
1337
+ }
1338
+ .tina-tailwind .mb-8 {
1339
+ margin-bottom: 32px;
1340
+ }
3292
1341
  .tina-tailwind .-ml-px {
3293
1342
  margin-left: -1px;
3294
1343
  }
@@ -3322,18 +1371,12 @@ mutation addPendingDocumentMutation(
3322
1371
  .tina-tailwind .mr-1\\.5 {
3323
1372
  margin-right: 6px;
3324
1373
  }
3325
- .tina-tailwind .mr-1 {
3326
- margin-right: 4px;
3327
- }
3328
1374
  .tina-tailwind .block {
3329
1375
  display: block;
3330
1376
  }
3331
1377
  .tina-tailwind .inline-block {
3332
1378
  display: inline-block;
3333
1379
  }
3334
- .tina-tailwind .inline {
3335
- display: inline;
3336
- }
3337
1380
  .tina-tailwind .flex {
3338
1381
  display: flex;
3339
1382
  }
@@ -3376,6 +1419,12 @@ mutation addPendingDocumentMutation(
3376
1419
  .tina-tailwind .w-10 {
3377
1420
  width: 40px;
3378
1421
  }
1422
+ .tina-tailwind .w-12 {
1423
+ width: 48px;
1424
+ }
1425
+ .tina-tailwind .w-7 {
1426
+ width: 28px;
1427
+ }
3379
1428
  .tina-tailwind .w-auto {
3380
1429
  width: auto;
3381
1430
  }
@@ -3571,6 +1620,10 @@ mutation addPendingDocumentMutation(
3571
1620
  --tw-bg-opacity: 1;
3572
1621
  background-color: rgb(255 255 255 / var(--tw-bg-opacity));
3573
1622
  }
1623
+ .tina-tailwind .bg-gray-100 {
1624
+ --tw-bg-opacity: 1;
1625
+ background-color: rgb(237 236 243 / var(--tw-bg-opacity));
1626
+ }
3574
1627
  .tina-tailwind .bg-gray-50 {
3575
1628
  --tw-bg-opacity: 1;
3576
1629
  background-color: rgb(246 246 249 / var(--tw-bg-opacity));
@@ -3613,6 +1666,9 @@ mutation addPendingDocumentMutation(
3613
1666
  .tina-tailwind .to-black {
3614
1667
  --tw-gradient-to: #000;
3615
1668
  }
1669
+ .tina-tailwind .fill-current {
1670
+ fill: currentColor;
1671
+ }
3616
1672
  .tina-tailwind .px-4 {
3617
1673
  padding-left: 16px;
3618
1674
  padding-right: 16px;
@@ -3707,14 +1763,18 @@ mutation addPendingDocumentMutation(
3707
1763
  font-size: 16px;
3708
1764
  line-height: 1.5;
3709
1765
  }
3710
- .tina-tailwind .text-sm {
3711
- font-size: 14px;
3712
- line-height: 1.43;
1766
+ .tina-tailwind .text-4xl {
1767
+ font-size: 36px;
1768
+ line-height: 1.1;
3713
1769
  }
3714
1770
  .tina-tailwind .text-xl {
3715
1771
  font-size: 20px;
3716
1772
  line-height: 1.4;
3717
1773
  }
1774
+ .tina-tailwind .text-sm {
1775
+ font-size: 14px;
1776
+ line-height: 1.43;
1777
+ }
3718
1778
  .tina-tailwind .text-md {
3719
1779
  font-size: 16px;
3720
1780
  line-height: 1.5;
@@ -3755,6 +1815,14 @@ mutation addPendingDocumentMutation(
3755
1815
  --tw-text-opacity: 1;
3756
1816
  color: rgb(67 62 82 / var(--tw-text-opacity));
3757
1817
  }
1818
+ .tina-tailwind .text-red-500 {
1819
+ --tw-text-opacity: 1;
1820
+ color: rgb(239 68 68 / var(--tw-text-opacity));
1821
+ }
1822
+ .tina-tailwind .text-red-400 {
1823
+ --tw-text-opacity: 1;
1824
+ color: rgb(248 113 113 / var(--tw-text-opacity));
1825
+ }
3758
1826
  .tina-tailwind .text-blue-600 {
3759
1827
  --tw-text-opacity: 1;
3760
1828
  color: rgb(5 116 228 / var(--tw-text-opacity));
@@ -3790,13 +1858,12 @@ mutation addPendingDocumentMutation(
3790
1858
  --tw-text-opacity: 1;
3791
1859
  color: rgb(37 35 54 / var(--tw-text-opacity));
3792
1860
  }
3793
- .tina-tailwind .text-red-500 {
3794
- --tw-text-opacity: 1;
3795
- color: rgb(239 68 68 / var(--tw-text-opacity));
3796
- }
3797
1861
  .tina-tailwind .underline {
3798
1862
  text-decoration-line: underline;
3799
1863
  }
1864
+ .tina-tailwind .opacity-70 {
1865
+ opacity: .7;
1866
+ }
3800
1867
  .tina-tailwind .opacity-100 {
3801
1868
  opacity: 1;
3802
1869
  }
@@ -3815,9 +1882,6 @@ mutation addPendingDocumentMutation(
3815
1882
  .tina-tailwind .opacity-50 {
3816
1883
  opacity: .5;
3817
1884
  }
3818
- .tina-tailwind .opacity-70 {
3819
- opacity: .7;
3820
- }
3821
1885
  .tina-tailwind .shadow-lg {
3822
1886
  --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
3823
1887
  --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);
@@ -4142,42 +2206,6 @@ mutation addPendingDocumentMutation(
4142
2206
  };
4143
2207
  }, [plugin]);
4144
2208
  };
4145
- function useTina({
4146
- query,
4147
- variables,
4148
- data
4149
- }) {
4150
- React__default["default"].useEffect(() => {
4151
- console.warn(`
4152
- "useTina" from 'tinacms/dist/edit-state' is now deprecated
4153
- * Use "import { useTina } from 'tinacms/dist/react" instead.
4154
- * See https://tina.io/blog/upgrading-to-iframe/ for full migration details
4155
- `);
4156
- }, []);
4157
- const {
4158
- setRequest,
4159
- state,
4160
- isDummyContainer,
4161
- isLoading: contextLoading
4162
- } = React__default["default"].useContext(sharedctx.TinaDataContext);
4163
- const [waitForContextRerender, setWaitForContextRerender] = React.useState(!isDummyContainer);
4164
- const isLoading = contextLoading || waitForContextRerender;
4165
- React__default["default"].useEffect(() => {
4166
- setRequest({ query, variables });
4167
- }, [JSON.stringify(variables), query]);
4168
- React.useEffect(() => {
4169
- if (!isDummyContainer) {
4170
- setTimeout(() => setWaitForContextRerender(false), 0);
4171
- }
4172
- return () => {
4173
- setRequest(void 0);
4174
- };
4175
- }, [isDummyContainer]);
4176
- return {
4177
- data: isDummyContainer || isLoading ? data : state.payload,
4178
- isLoading
4179
- };
4180
- }
4181
2209
  const errorButtonStyles = {
4182
2210
  background: "#eb6337",
4183
2211
  padding: "12px 18px",
@@ -4265,12 +2293,6 @@ mutation addPendingDocumentMutation(
4265
2293
  ...props
4266
2294
  }) => {
4267
2295
  var _a, _b, _c, _d, _e;
4268
- React__default["default"].useEffect(() => {
4269
- console.warn(`
4270
- * Tina no longer requires wrapping your site in the TinaProvider
4271
- * See https://tina.io/blog/upgrading-to-iframe/ for full migration details
4272
- `);
4273
- }, []);
4274
2296
  if (props == null ? void 0 : props.apiURL) {
4275
2297
  console.warn("The apiURL prop is deprecated. Please see https://tina.io/blog/tina-v-0.68.14 for information on how to upgrade to the new API");
4276
2298
  }
@@ -4296,84 +2318,7 @@ mutation addPendingDocumentMutation(
4296
2318
  mediaStore: props.mediaStore,
4297
2319
  apiUrl: apiURL,
4298
2320
  schema: { ...schema, config: { ...schema.config, ...props } }
4299
- }, /* @__PURE__ */ React__default["default"].createElement("style", null, styles), /* @__PURE__ */ React__default["default"].createElement(ErrorBoundary, null, /* @__PURE__ */ React__default["default"].createElement(DocumentCreator, {
4300
- documentCreatorCallback
4301
- }), /* @__PURE__ */ React__default["default"].createElement(TinaDataProvider, {
4302
- formifyCallback
4303
- }, typeof props.children == "function" ? /* @__PURE__ */ React__default["default"].createElement(TinaQuery, {
4304
- ...props,
4305
- variables: props.variables,
4306
- data: props.data,
4307
- query,
4308
- formifyCallback,
4309
- children: props.children
4310
- }) : props.children))));
4311
- };
4312
- const DocumentCreator = ({
4313
- documentCreatorCallback
4314
- }) => {
4315
- useDocumentCreatorPlugin(documentCreatorCallback);
4316
- return null;
4317
- };
4318
- const TinaQuery = (props) => {
4319
- return /* @__PURE__ */ React__default["default"].createElement(TinaQueryInner, {
4320
- key: `rootQuery-${props.query}`,
4321
- ...props
4322
- });
4323
- };
4324
- const TinaQueryInner = ({ children, ...props }) => {
4325
- const { data: liveData, isLoading } = useTina({
4326
- query: props.query,
4327
- variables: props.variables,
4328
- data: props.data
4329
- });
4330
- return /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, children(isLoading || !props.query ? props : { ...props, data: liveData }));
4331
- };
4332
- const TinaDataProvider = ({
4333
- children,
4334
- formifyCallback
4335
- }) => {
4336
- const [request, setRequest] = React.useState();
4337
- const [state, setState] = React__default["default"].useState({
4338
- payload: void 0,
4339
- isLoading: true
4340
- });
4341
- return /* @__PURE__ */ React__default["default"].createElement(sharedctx.TinaDataContext.Provider, {
4342
- value: {
4343
- setRequest,
4344
- isLoading: state.isLoading,
4345
- state: { payload: state.payload }
4346
- }
4347
- }, /* @__PURE__ */ React__default["default"].createElement(FormRegistrar, {
4348
- key: request == null ? void 0 : request.query,
4349
- request,
4350
- formifyCallback,
4351
- onPayloadStateChange: setState
4352
- }), children);
4353
- };
4354
- const FormRegistrar = ({
4355
- request,
4356
- formifyCallback,
4357
- onPayloadStateChange
4358
- }) => {
4359
- const cms = toolkit.useCMS();
4360
- const { setFormsRegistering } = React__default["default"].useContext(sharedctx.EditContext);
4361
- const [payload, isLoading] = useGraphqlForms({
4362
- query: request == null ? void 0 : request.query,
4363
- variables: request == null ? void 0 : request.variables,
4364
- formify: (args) => {
4365
- if (formifyCallback) {
4366
- return formifyCallback(args, cms);
4367
- } else {
4368
- return args.createForm(args.formConfig);
4369
- }
4370
- }
4371
- });
4372
- React__default["default"].useEffect(() => {
4373
- onPayloadStateChange({ payload, isLoading });
4374
- setFormsRegistering && setFormsRegistering(isLoading);
4375
- }, [JSON.stringify(payload), isLoading]);
4376
- return isLoading ? /* @__PURE__ */ React__default["default"].createElement(Loader, null, /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null)) : null;
2321
+ }, /* @__PURE__ */ React__default["default"].createElement("style", null, styles), /* @__PURE__ */ React__default["default"].createElement(ErrorBoundary, null, props.children)));
4377
2322
  };
4378
2323
  const Loader = (props) => {
4379
2324
  return /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, /* @__PURE__ */ React__default["default"].createElement("div", {
@@ -4567,10 +2512,10 @@ This will work when developing locally but NOT when deployed to production.
4567
2512
  return t;
4568
2513
  };
4569
2514
  function Tree2Element(tree) {
4570
- return tree && tree.map(function(node2, i) {
4571
- return React__default["default"].createElement(node2.tag, __assign({
2515
+ return tree && tree.map(function(node, i) {
2516
+ return React__default["default"].createElement(node.tag, __assign({
4572
2517
  key: i
4573
- }, node2.attr), Tree2Element(node2.child));
2518
+ }, node.attr), Tree2Element(node.child));
4574
2519
  });
4575
2520
  }
4576
2521
  function GenIcon(data) {
@@ -4620,6 +2565,9 @@ This will work when developing locally but NOT when deployed to production.
4620
2565
  function BiEdit(props) {
4621
2566
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "m7 17.013 4.413-.015 9.632-9.54c.378-.378.586-.88.586-1.414s-.208-1.036-.586-1.414l-1.586-1.586c-.756-.756-2.075-.752-2.825-.003L7 12.583v4.43zM18.045 4.458l1.589 1.583-1.597 1.582-1.586-1.585 1.594-1.58zM9 13.417l6.03-5.973 1.586 1.586-6.029 5.971L9 15.006v-1.589z" } }, { "tag": "path", "attr": { "d": "M5 21h14c1.103 0 2-.897 2-2v-8.668l-2 2V19H8.158c-.026 0-.053.01-.079.01-.033 0-.066-.009-.1-.01H5V5h6.847l2-2H5c-1.103 0-2 .897-2 2v14c0 1.103.897 2 2 2z" } }] })(props);
4622
2567
  }
2568
+ function BiError(props) {
2569
+ return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M11.001 10h2v5h-2zM11 16h2v2h-2z" } }, { "tag": "path", "attr": { "d": "M13.768 4.2C13.42 3.545 12.742 3.138 12 3.138s-1.42.407-1.768 1.063L2.894 18.064a1.986 1.986 0 0 0 .054 1.968A1.984 1.984 0 0 0 4.661 21h14.678c.708 0 1.349-.362 1.714-.968a1.989 1.989 0 0 0 .054-1.968L13.768 4.2zM4.661 19 12 5.137 19.344 19H4.661z" } }] })(props);
2570
+ }
4623
2571
  function BiLogIn(props) {
4624
2572
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "m13 16 5-4-5-4v3H4v2h9z" } }, { "tag": "path", "attr": { "d": "M20 3h-9c-1.103 0-2 .897-2 2v4h2V5h9v14h-9v-4H9v4c0 1.103.897 2 2 2h9c1.103 0 2-.897 2-2V5c0-1.103-.897-2-2-2z" } }] })(props);
4625
2573
  }
@@ -4638,6 +2586,9 @@ This will work when developing locally but NOT when deployed to production.
4638
2586
  function BiSearch(props) {
4639
2587
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M10 18a7.952 7.952 0 0 0 4.897-1.688l4.396 4.396 1.414-1.414-4.396-4.396A7.952 7.952 0 0 0 18 10c0-4.411-3.589-8-8-8s-8 3.589-8 8 3.589 8 8 8zm0-14c3.309 0 6 2.691 6 6s-2.691 6-6 6-6-2.691-6-6 2.691-6 6-6z" } }] })(props);
4640
2588
  }
2589
+ function BiSync(props) {
2590
+ return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "m13 7.101.01.001a4.978 4.978 0 0 1 2.526 1.362 5.005 5.005 0 0 1 1.363 2.528 5.061 5.061 0 0 1-.001 2.016 4.976 4.976 0 0 1-1.363 2.527l1.414 1.414a7.014 7.014 0 0 0 1.908-3.54 6.98 6.98 0 0 0 0-2.819 6.957 6.957 0 0 0-1.907-3.539 6.97 6.97 0 0 0-2.223-1.5 6.921 6.921 0 0 0-1.315-.408c-.137-.028-.275-.043-.412-.063V2L9 6l4 4V7.101zm-7.45 7.623c.174.412.392.812.646 1.19.249.37.537.718.854 1.034a7.036 7.036 0 0 0 2.224 1.501c.425.18.868.317 1.315.408.167.034.338.056.508.078v2.944l4-4-4-4v3.03c-.035-.006-.072-.003-.107-.011a4.978 4.978 0 0 1-2.526-1.362 4.994 4.994 0 0 1 .001-7.071L7.051 7.05a7.01 7.01 0 0 0-1.5 2.224A6.974 6.974 0 0 0 5 12a6.997 6.997 0 0 0 .55 2.724z" } }] })(props);
2591
+ }
4641
2592
  function BiTrash(props) {
4642
2593
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M5 20a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8h2V6h-4V4a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v2H3v2h2zM9 4h6v2H9zM8 8h9v12H7V8z" } }, { "tag": "path", "attr": { "d": "M9 10h2v8H9zm4 0h2v8h-2z" } }] })(props);
4643
2594
  }
@@ -5049,6 +3000,25 @@ This will work when developing locally but NOT when deployed to production.
5049
3000
  fontWeight: "normal"
5050
3001
  }
5051
3002
  }, "Please wait, Tina is loading data..."))));
3003
+ const FullscreenError = ({
3004
+ title = "Error",
3005
+ errorMessage = "It looks like something went wrong."
3006
+ }) => {
3007
+ return /* @__PURE__ */ React__default["default"].createElement("div", {
3008
+ className: "flex flex-col justify-center items-center h-screen bg-gray-100"
3009
+ }, /* @__PURE__ */ React__default["default"].createElement("div", {
3010
+ className: "text-red-500 text-4xl mb-6 flex items-center"
3011
+ }, /* @__PURE__ */ React__default["default"].createElement(BiError, {
3012
+ className: "w-12 h-auto fill-current text-red-400 opacity-70 mr-1"
3013
+ }), " ", title), /* @__PURE__ */ React__default["default"].createElement("p", {
3014
+ className: "text-gray-700 text-xl mb-8"
3015
+ }, errorMessage), /* @__PURE__ */ React__default["default"].createElement(toolkit.Button, {
3016
+ variant: "danger",
3017
+ onClick: () => window.location.reload()
3018
+ }, /* @__PURE__ */ React__default["default"].createElement(BiSync, {
3019
+ className: "w-7 h-auto fill-current opacity-70 mr-1"
3020
+ }), " Reload"));
3021
+ };
5052
3022
  const useGetCollection = (cms, collectionName, includeDocuments = true, after = "", sortKey, filterArgs) => {
5053
3023
  const api = new TinaAdminApi(cms);
5054
3024
  const schema = cms.api.tina.schema;
@@ -5092,7 +3062,7 @@ This will work when developing locally but NOT when deployed to production.
5092
3062
  }) => {
5093
3063
  const { collection, loading, error, reFetchCollection, collectionExtra } = useGetCollection(cms, collectionName, includeDocuments, startCursor || "", sortKey, filterArgs) || {};
5094
3064
  if (error) {
5095
- return null;
3065
+ return /* @__PURE__ */ React__default["default"].createElement(FullscreenError, null);
5096
3066
  }
5097
3067
  if (loading) {
5098
3068
  return /* @__PURE__ */ React__default["default"].createElement(LoadingPage, null);
@@ -5194,7 +3164,7 @@ This will work when developing locally but NOT when deployed to production.
5194
3164
  }));
5195
3165
  }, [collectionName]);
5196
3166
  return /* @__PURE__ */ React__default["default"].createElement(GetCMS, null, (cms) => {
5197
- return /* @__PURE__ */ React__default["default"].createElement(GetCollection, {
3167
+ return /* @__PURE__ */ React__default["default"].createElement(PageWrapper, null, /* @__PURE__ */ React__default["default"].createElement(GetCollection, {
5198
3168
  cms,
5199
3169
  collectionName,
5200
3170
  includeDocuments: true,
@@ -5228,7 +3198,7 @@ This will work when developing locally but NOT when deployed to production.
5228
3198
  const collectionDefinition = cms.api.tina.schema.getCollection(collection.name);
5229
3199
  const allowCreate = (_e = (_d = (_c = collectionDefinition == null ? void 0 : collectionDefinition.ui) == null ? void 0 : _c.allowedActions) == null ? void 0 : _d.create) != null ? _e : true;
5230
3200
  const allowDelete = (_h = (_g = (_f = collectionDefinition == null ? void 0 : collectionDefinition.ui) == null ? void 0 : _f.allowedActions) == null ? void 0 : _g.delete) != null ? _h : true;
5231
- return /* @__PURE__ */ React__default["default"].createElement(PageWrapper, null, /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, deleteModalOpen && /* @__PURE__ */ React__default["default"].createElement(DeleteModal, {
3201
+ return /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, deleteModalOpen && /* @__PURE__ */ React__default["default"].createElement(DeleteModal, {
5232
3202
  filename: vars.relativePath,
5233
3203
  deleteFunc: async () => {
5234
3204
  try {
@@ -5337,7 +3307,7 @@ This will work when developing locally but NOT when deployed to production.
5337
3307
  value: ""
5338
3308
  },
5339
3309
  ...filterFields.map((x) => ({
5340
- label: x.label || x.name,
3310
+ label: typeof x.label === "string" && x.label || x.name,
5341
3311
  value: x.name
5342
3312
  }))
5343
3313
  ],
@@ -5392,7 +3362,7 @@ This will work when developing locally but NOT when deployed to production.
5392
3362
  onChange: (e) => {
5393
3363
  setVars((old) => ({
5394
3364
  ...old,
5395
- after: e.format(),
3365
+ after: typeof e.format === "function" ? e.format() : "",
5396
3366
  booleanEquals: null,
5397
3367
  startsWith: ""
5398
3368
  }));
@@ -5410,7 +3380,7 @@ This will work when developing locally but NOT when deployed to production.
5410
3380
  onChange: (e) => {
5411
3381
  setVars((old) => ({
5412
3382
  ...old,
5413
- before: e.format(),
3383
+ before: typeof e.format === "function" ? e.format() : "",
5414
3384
  booleanEquals: null,
5415
3385
  startsWith: ""
5416
3386
  }));
@@ -5592,8 +3562,8 @@ This will work when developing locally but NOT when deployed to production.
5592
3562
  setEndCursor(prev);
5593
3563
  }
5594
3564
  }
5595
- }))))));
5596
- });
3565
+ })))));
3566
+ }));
5597
3567
  });
5598
3568
  };
5599
3569
  const NoDocumentsPlaceholder = () => {
@@ -5652,6 +3622,42 @@ This will work when developing locally but NOT when deployed to production.
5652
3622
  function HiChevronRight(props) {
5653
3623
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 20 20", "fill": "currentColor" }, "child": [{ "tag": "path", "attr": { "fillRule": "evenodd", "d": "M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z", "clipRule": "evenodd" } }] })(props);
5654
3624
  }
3625
+ const transformDocumentIntoMutationRequestPayload = (document, instructions) => {
3626
+ const { _collection, __typename, _template, ...rest } = document;
3627
+ const params = transformParams(rest);
3628
+ const paramsWithTemplate = instructions.includeTemplate ? { [_template]: params } : params;
3629
+ return instructions.includeCollection ? { [_collection]: paramsWithTemplate } : paramsWithTemplate;
3630
+ };
3631
+ const transformParams = (data) => {
3632
+ if (["string", "number", "boolean"].includes(typeof data)) {
3633
+ return data;
3634
+ }
3635
+ if (Array.isArray(data)) {
3636
+ return data.map((item) => transformParams(item));
3637
+ }
3638
+ try {
3639
+ assertShape(data, (yup2) => yup2.object({ _template: yup2.string().required() }));
3640
+ const { _template, __typename, ...rest } = data;
3641
+ const nested = transformParams(rest);
3642
+ return { [_template]: nested };
3643
+ } catch (e) {
3644
+ if (e.message === "Failed to assertShape - _template is a required field") {
3645
+ if (!data) {
3646
+ return [];
3647
+ }
3648
+ const accum = {};
3649
+ Object.entries(data).map(([keyName, value]) => {
3650
+ accum[keyName] = transformParams(value);
3651
+ });
3652
+ return accum;
3653
+ } else {
3654
+ if (!data) {
3655
+ return [];
3656
+ }
3657
+ throw e;
3658
+ }
3659
+ }
3660
+ };
5655
3661
  function FaLock(props) {
5656
3662
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 448 512" }, "child": [{ "tag": "path", "attr": { "d": "M400 224h-24v-72C376 68.2 307.8 0 224 0S72 68.2 72 152v72H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48zm-104 0H152v-72c0-39.7 32.3-72 72-72s72 32.3 72 72v72z" } }] })(props);
5657
3663
  }
@@ -5733,7 +3739,7 @@ This will work when developing locally but NOT when deployed to production.
5733
3739
  schema,
5734
3740
  template
5735
3741
  });
5736
- let slugFunction = (_b = (_a = template == null ? void 0 : template.ui) == null ? void 0 : _a.filename) == null ? void 0 : _b.slugify;
3742
+ let slugFunction = (_b = (_a = schemaCollection.ui) == null ? void 0 : _a.filename) == null ? void 0 : _b.slugify;
5737
3743
  if (!slugFunction) {
5738
3744
  const titleField = (_c = template == null ? void 0 : template.fields.find((x) => x.required && x.type === "string" && x.isTitle)) == null ? void 0 : _c.name;
5739
3745
  if (titleField) {
@@ -5766,11 +3772,11 @@ This will work when developing locally but NOT when deployed to production.
5766
3772
  component: slugFunction ? toolkit.wrapFieldsWithMeta(({ field, input, meta }) => {
5767
3773
  var _a3, _b3;
5768
3774
  return /* @__PURE__ */ React__default["default"].createElement(FilenameInput, {
5769
- readonly: (_b3 = (_a3 = template == null ? void 0 : template.ui) == null ? void 0 : _a3.filename) == null ? void 0 : _b3.readonly,
3775
+ readonly: (_b3 = (_a3 = schemaCollection == null ? void 0 : schemaCollection.ui) == null ? void 0 : _a3.filename) == null ? void 0 : _b3.readonly,
5770
3776
  ...input
5771
3777
  });
5772
3778
  }) : "text",
5773
- disabled: (_b2 = (_a2 = template == null ? void 0 : template.ui) == null ? void 0 : _a2.filename) == null ? void 0 : _b2.readonly,
3779
+ disabled: (_b2 = (_a2 = schemaCollection == null ? void 0 : schemaCollection.ui) == null ? void 0 : _a2.filename) == null ? void 0 : _b2.readonly,
5774
3780
  description: /* @__PURE__ */ React__default["default"].createElement("span", null, "A unique filename for the content.", /* @__PURE__ */ React__default["default"].createElement("br", null), "Examples: ", /* @__PURE__ */ React__default["default"].createElement("code", null, "My_Document"), ", ", /* @__PURE__ */ React__default["default"].createElement("code", null, "My_Document.en"), ",", " ", /* @__PURE__ */ React__default["default"].createElement("code", null, "sub-folder/My_Document")),
5775
3781
  placeholder: `My_Document`,
5776
3782
  validate: (value, allValues, meta) => {
@@ -5864,7 +3870,7 @@ This will work when developing locally but NOT when deployed to production.
5864
3870
  }) => {
5865
3871
  const { document, loading, error } = useGetDocument(cms, collectionName, relativePath);
5866
3872
  if (error) {
5867
- return null;
3873
+ return /* @__PURE__ */ React__default["default"].createElement(FullscreenError, null);
5868
3874
  }
5869
3875
  if (loading) {
5870
3876
  return /* @__PURE__ */ React__default["default"].createElement(LoadingPage, null);
@@ -5900,7 +3906,7 @@ This will work when developing locally but NOT when deployed to production.
5900
3906
  includeCollection: true,
5901
3907
  includeTemplate: !!collection.templates
5902
3908
  };
5903
- return /* @__PURE__ */ React__default["default"].createElement(GetDocument, {
3909
+ return /* @__PURE__ */ React__default["default"].createElement(PageWrapper, null, /* @__PURE__ */ React__default["default"].createElement(GetDocument, {
5904
3910
  cms,
5905
3911
  collectionName: collection.name,
5906
3912
  relativePath
@@ -5911,7 +3917,7 @@ This will work when developing locally but NOT when deployed to production.
5911
3917
  relativePath,
5912
3918
  collection,
5913
3919
  mutationInfo
5914
- }));
3920
+ })));
5915
3921
  }));
5916
3922
  };
5917
3923
  const RenderForm = ({
@@ -5957,7 +3963,7 @@ This will work when developing locally but NOT when deployed to production.
5957
3963
  const windowWidth = windowSize.useWindowWidth();
5958
3964
  const renderNavToggle = windowWidth < navBreakpoint + 1;
5959
3965
  const headerPadding = renderNavToggle ? "px-20" : "px-6";
5960
- return /* @__PURE__ */ React__default["default"].createElement(PageWrapper, null, /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, ((_b = (_a = cms == null ? void 0 : cms.api) == null ? void 0 : _a.tina) == null ? void 0 : _b.isLocalMode) ? /* @__PURE__ */ React__default["default"].createElement(toolkit.LocalWarning, null) : /* @__PURE__ */ React__default["default"].createElement(toolkit.BillingWarning, null), /* @__PURE__ */ React__default["default"].createElement("div", {
3966
+ return /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, ((_b = (_a = cms == null ? void 0 : cms.api) == null ? void 0 : _a.tina) == null ? void 0 : _b.isLocalMode) ? /* @__PURE__ */ React__default["default"].createElement(toolkit.LocalWarning, null) : /* @__PURE__ */ React__default["default"].createElement(toolkit.BillingWarning, null), /* @__PURE__ */ React__default["default"].createElement("div", {
5961
3967
  className: `py-4 border-b border-gray-200 bg-white ${headerPadding}`
5962
3968
  }, /* @__PURE__ */ React__default["default"].createElement("div", {
5963
3969
  className: "max-w-form mx-auto"
@@ -5977,7 +3983,7 @@ This will work when developing locally but NOT when deployed to production.
5977
3983
  }))), /* @__PURE__ */ React__default["default"].createElement(toolkit.FormBuilder, {
5978
3984
  form,
5979
3985
  onPristineChange: setFormIsPristine
5980
- })));
3986
+ }));
5981
3987
  };
5982
3988
  const ScreenPage = () => {
5983
3989
  const { screenName } = reactRouterDom.useParams();
@@ -6068,9 +4074,30 @@ This will work when developing locally but NOT when deployed to production.
6068
4074
  ...config
6069
4075
  });
6070
4076
  };
4077
+ const CheckSchema = ({
4078
+ schemaJson,
4079
+ children
4080
+ }) => {
4081
+ const cms = toolkit.useCMS();
4082
+ const api = new TinaAdminApi(cms);
4083
+ const url = api.api.contentApiUrl;
4084
+ React.useEffect(() => {
4085
+ if (schemaJson && cms) {
4086
+ api.checkGraphqlSchema({
4087
+ localSchema: schemaJson
4088
+ }).then((x) => {
4089
+ if (x === false) {
4090
+ cms.alerts.error("GraphQL Schema Mismatch. Editing may not work. If you just switched branches, try going back to the previous branch");
4091
+ }
4092
+ });
4093
+ }
4094
+ }, [cms, JSON.stringify(schemaJson || {}), url]);
4095
+ return children;
4096
+ };
6071
4097
  const TinaAdmin = ({
6072
4098
  preview,
6073
- config
4099
+ config,
4100
+ schemaJson
6074
4101
  }) => {
6075
4102
  const isSSR2 = typeof window === "undefined";
6076
4103
  const { edit } = sharedctx.useEditState();
@@ -6081,9 +4108,18 @@ This will work when developing locally but NOT when deployed to production.
6081
4108
  return /* @__PURE__ */ React__default["default"].createElement(Layout, null, /* @__PURE__ */ React__default["default"].createElement(LoginPage, null));
6082
4109
  }
6083
4110
  return /* @__PURE__ */ React__default["default"].createElement(GetCMS, null, (cms) => {
4111
+ var _a, _b, _c;
6084
4112
  const isTinaAdminEnabled = cms.flags.get("tina-admin") === false ? false : true;
6085
4113
  if (isTinaAdminEnabled) {
6086
- return /* @__PURE__ */ React__default["default"].createElement(reactRouterDom.HashRouter, null, /* @__PURE__ */ React__default["default"].createElement(SetPreviewFlag, {
4114
+ const tinaClient = (_a = cms.api) == null ? void 0 : _a.tina;
4115
+ const collectionWithRouter = (_c = (_b = tinaClient == null ? void 0 : tinaClient.schema) == null ? void 0 : _b.config) == null ? void 0 : _c.collections.find((x) => {
4116
+ var _a2;
4117
+ return typeof ((_a2 = x == null ? void 0 : x.ui) == null ? void 0 : _a2.router) === "function";
4118
+ });
4119
+ const hasRouter = Boolean(collectionWithRouter);
4120
+ return /* @__PURE__ */ React__default["default"].createElement(CheckSchema, {
4121
+ schemaJson
4122
+ }, /* @__PURE__ */ React__default["default"].createElement(reactRouterDom.HashRouter, null, /* @__PURE__ */ React__default["default"].createElement(SetPreviewFlag, {
6087
4123
  preview,
6088
4124
  cms
6089
4125
  }), /* @__PURE__ */ React__default["default"].createElement(reactRouterDom.Routes, null, preview && /* @__PURE__ */ React__default["default"].createElement(reactRouterDom.Route, {
@@ -6125,11 +4161,11 @@ This will work when developing locally but NOT when deployed to production.
6125
4161
  }), /* @__PURE__ */ React__default["default"].createElement(reactRouterDom.Route, {
6126
4162
  path: "/",
6127
4163
  element: /* @__PURE__ */ React__default["default"].createElement(MaybeRedirectToPreview, {
6128
- redirect: !!preview
4164
+ redirect: !!preview && hasRouter
6129
4165
  }, /* @__PURE__ */ React__default["default"].createElement(DefaultWrapper, {
6130
4166
  cms
6131
4167
  }, /* @__PURE__ */ React__default["default"].createElement(DashboardPage, null)))
6132
- })));
4168
+ }))));
6133
4169
  } else {
6134
4170
  return /* @__PURE__ */ React__default["default"].createElement(Layout, null, /* @__PURE__ */ React__default["default"].createElement(reactRouterDom.HashRouter, null, /* @__PURE__ */ React__default["default"].createElement(reactRouterDom.Routes, null, /* @__PURE__ */ React__default["default"].createElement(reactRouterDom.Route, {
6135
4171
  path: "logout",
@@ -6204,8 +4240,8 @@ This will work when developing locally but NOT when deployed to production.
6204
4240
  exports2.TinaCMSProvider2 = TinaCMSProvider2;
6205
4241
  exports2.TinaCloudAuthWall = TinaCloudAuthWall;
6206
4242
  exports2.TinaCloudProvider = TinaCloudProvider;
6207
- exports2.TinaDataProvider = TinaDataProvider;
6208
4243
  exports2.assertShape = assertShape;
4244
+ exports2.asyncPoll = asyncPoll;
6209
4245
  exports2.createClient = createClient;
6210
4246
  exports2["default"] = TinaCMSProvider2;
6211
4247
  exports2.defineConfig = defineConfig;
@@ -6217,7 +4253,6 @@ This will work when developing locally but NOT when deployed to production.
6217
4253
  exports2.safeAssertShape = safeAssertShape;
6218
4254
  exports2.staticRequest = staticRequest;
6219
4255
  exports2.useDocumentCreatorPlugin = useDocumentCreatorPlugin;
6220
- exports2.useGraphqlForms = useGraphqlForms;
6221
4256
  exports2.useTinaAuthRedirect = useTinaAuthRedirect;
6222
4257
  Object.keys(toolkit).forEach(function(k) {
6223
4258
  if (k !== "default" && !exports2.hasOwnProperty(k))