tinacms 1.2.2 → 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("zod"), require("@tinacms/toolkit"), require("graphql"), require("lodash.set"), require("react"), require("final-form"), require("@tinacms/schema-tools"), require("yup"), require("graphql-tag"), 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", "lodash.set", "react", "final-form", "@tinacms/schema-tools", "yup", "graphql-tag", "@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, global.NOOP, global.NOOP));
3
- })(this, function(exports2, zod, toolkit, G, set, React, finalForm, schemaTools, yup, gql$1, sharedctx, core, 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,2105 +25,34 @@
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
- var yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
32
- var gql__default = /* @__PURE__ */ _interopDefaultLegacy(gql$1);
33
- function popupWindow(url, title, window2, w, h) {
34
- const y = window2.top.outerHeight / 2 + window2.top.screenY - h / 2;
35
- const x = window2.top.outerWidth / 2 + window2.top.screenX - w / 2;
36
- return window2.open(url, title, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=" + w + ", height=" + h + ", top=" + y + ", left=" + x);
37
- }
38
- const TINA_LOGIN_EVENT = "tinaCloudLogin";
39
- const AUTH_TOKEN_KEY = "tinacms-auth";
40
- const authenticate = (clientId, frontendUrl) => {
41
- 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 } });
28
+ var gql__default = /* @__PURE__ */ _interopDefaultLegacy(gql$1);
29
+ var React__default = /* @__PURE__ */ _interopDefaultLegacy(React);
30
+ var yup__namespace = /* @__PURE__ */ _interopNamespace(yup);
31
+ function popupWindow(url, title, window2, w, h) {
32
+ const y = window2.top.outerHeight / 2 + window2.top.screenY - h / 2;
33
+ const x = window2.top.outerWidth / 2 + window2.top.screenX - w / 2;
34
+ return window2.open(url, title, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=" + w + ", height=" + h + ", top=" + y + ", left=" + x);
35
+ }
36
+ const TINA_LOGIN_EVENT = "tinaCloudLogin";
37
+ const AUTH_TOKEN_KEY = "tinacms-auth";
38
+ const authenticate = (clientId, frontendUrl) => {
39
+ return new Promise((resolve) => {
40
+ let authTab;
41
+ window.addEventListener("message", function(e) {
42
+ if (e.data.source === TINA_LOGIN_EVENT) {
43
+ if (authTab) {
44
+ authTab.close();
1835
45
  }
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
- });
46
+ resolve({
47
+ id_token: e.data.id_token,
48
+ access_token: e.data.access_token,
49
+ refresh_token: e.data.refresh_token
1856
50
  });
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);
1953
- }
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;
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) => {
@@ -2197,10 +126,10 @@ mutation addPendingDocumentMutation(
2197
126
  };
2198
127
  this.getSchema = async () => {
2199
128
  if (!this.gqlSchema) {
2200
- const data = await this.request(G.getIntrospectionQuery(), {
129
+ const data = await this.request(graphql.getIntrospectionQuery(), {
2201
130
  variables: {}
2202
131
  });
2203
- this.gqlSchema = G.buildClientSchema(data);
132
+ this.gqlSchema = graphql.buildClientSchema(data);
2204
133
  }
2205
134
  return this.gqlSchema;
2206
135
  };
@@ -2208,9 +137,9 @@ mutation addPendingDocumentMutation(
2208
137
  const data = await this.request(`query GetOptimizedQuery($queryString: String!) {
2209
138
  getOptimizedQuery(queryString: $queryString)
2210
139
  }`, {
2211
- variables: { queryString: G.print(documentNode) }
140
+ variables: { queryString: graphql.print(documentNode) }
2212
141
  });
2213
- return G.parse(data.getOptimizedQuery);
142
+ return graphql.parse(data.getOptimizedQuery);
2214
143
  };
2215
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;
2216
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;
@@ -2298,24 +227,6 @@ mutation addPendingDocumentMutation(
2298
227
  this.contentApiBase = ((_d = this.options.tinaioConfig) == null ? void 0 : _d.contentApiUrlOverride) || `https://content.tinajs.io`;
2299
228
  this.contentApiUrl = this.options.customContentApiUrl || `${this.contentApiBase}/content/${this.options.clientId}/github/${encodedBranch}`;
2300
229
  }
2301
- async requestWithForm(query, {
2302
- variables,
2303
- useUnstableFormify
2304
- }) {
2305
- const schema = await this.getSchema();
2306
- let formifiedQuery;
2307
- if (useUnstableFormify) {
2308
- const res = await formify({
2309
- schema,
2310
- query: G.print(query(gql__default["default"])),
2311
- getOptimizedQuery: this.getOptimizedQuery
2312
- });
2313
- formifiedQuery = res.formifiedQuery;
2314
- } else {
2315
- formifiedQuery = formify$1(query(gql__default["default"]), schema);
2316
- }
2317
- return this.request(G.print(formifiedQuery), { variables });
2318
- }
2319
230
  async request(query, { variables }) {
2320
231
  const res = await fetch(this.contentApiUrl, {
2321
232
  method: "POST",
@@ -2324,7 +235,7 @@ mutation addPendingDocumentMutation(
2324
235
  Authorization: "Bearer " + (await this.getToken()).id_token
2325
236
  },
2326
237
  body: JSON.stringify({
2327
- query: typeof query === "function" ? G.print(query(gql__default["default"])) : query,
238
+ query: typeof query === "function" ? graphql.print(query(gql__default["default"])) : query,
2328
239
  variables
2329
240
  })
2330
241
  });
@@ -2609,6 +520,7 @@ mutation addPendingDocumentMutation(
2609
520
  }
2610
521
  }, [action, setSubmitting]);
2611
522
  return /* @__PURE__ */ React__default["default"].createElement(toolkit.Button, {
523
+ "data-test": name.replace(/\s/g, "-").toLowerCase(),
2612
524
  variant: primary ? "primary" : "secondary",
2613
525
  onClick,
2614
526
  busy: submitting,
@@ -2630,6 +542,39 @@ mutation addPendingDocumentMutation(
2630
542
  localStorage[TINA_AUTH_CONFIG] = JSON.stringify(config);
2631
543
  }, []);
2632
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
+ }
2633
578
  class TinaAdminApi {
2634
579
  constructor(cms) {
2635
580
  this.api = cms.api.tina;
@@ -2641,7 +586,7 @@ mutation addPendingDocumentMutation(
2641
586
  async checkGraphqlSchema({ localSchema }) {
2642
587
  const schemaFromCloud = await this.api.getSchema();
2643
588
  const schema1 = schemaFromCloud;
2644
- const schema2 = G.buildSchema(G.print(localSchema));
589
+ const schema2 = graphql.buildSchema(graphql.print(localSchema));
2645
590
  const diffOutput = await core.diff(schema1, schema2);
2646
591
  if (diffOutput.length > 0) {
2647
592
  return false;
@@ -3384,6 +1329,15 @@ mutation addPendingDocumentMutation(
3384
1329
  margin-left: auto;
3385
1330
  margin-right: auto;
3386
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
+ }
3387
1341
  .tina-tailwind .-ml-px {
3388
1342
  margin-left: -1px;
3389
1343
  }
@@ -3417,18 +1371,12 @@ mutation addPendingDocumentMutation(
3417
1371
  .tina-tailwind .mr-1\\.5 {
3418
1372
  margin-right: 6px;
3419
1373
  }
3420
- .tina-tailwind .mr-1 {
3421
- margin-right: 4px;
3422
- }
3423
1374
  .tina-tailwind .block {
3424
1375
  display: block;
3425
1376
  }
3426
1377
  .tina-tailwind .inline-block {
3427
1378
  display: inline-block;
3428
1379
  }
3429
- .tina-tailwind .inline {
3430
- display: inline;
3431
- }
3432
1380
  .tina-tailwind .flex {
3433
1381
  display: flex;
3434
1382
  }
@@ -3471,6 +1419,12 @@ mutation addPendingDocumentMutation(
3471
1419
  .tina-tailwind .w-10 {
3472
1420
  width: 40px;
3473
1421
  }
1422
+ .tina-tailwind .w-12 {
1423
+ width: 48px;
1424
+ }
1425
+ .tina-tailwind .w-7 {
1426
+ width: 28px;
1427
+ }
3474
1428
  .tina-tailwind .w-auto {
3475
1429
  width: auto;
3476
1430
  }
@@ -3666,6 +1620,10 @@ mutation addPendingDocumentMutation(
3666
1620
  --tw-bg-opacity: 1;
3667
1621
  background-color: rgb(255 255 255 / var(--tw-bg-opacity));
3668
1622
  }
1623
+ .tina-tailwind .bg-gray-100 {
1624
+ --tw-bg-opacity: 1;
1625
+ background-color: rgb(237 236 243 / var(--tw-bg-opacity));
1626
+ }
3669
1627
  .tina-tailwind .bg-gray-50 {
3670
1628
  --tw-bg-opacity: 1;
3671
1629
  background-color: rgb(246 246 249 / var(--tw-bg-opacity));
@@ -3708,6 +1666,9 @@ mutation addPendingDocumentMutation(
3708
1666
  .tina-tailwind .to-black {
3709
1667
  --tw-gradient-to: #000;
3710
1668
  }
1669
+ .tina-tailwind .fill-current {
1670
+ fill: currentColor;
1671
+ }
3711
1672
  .tina-tailwind .px-4 {
3712
1673
  padding-left: 16px;
3713
1674
  padding-right: 16px;
@@ -3802,14 +1763,18 @@ mutation addPendingDocumentMutation(
3802
1763
  font-size: 16px;
3803
1764
  line-height: 1.5;
3804
1765
  }
3805
- .tina-tailwind .text-sm {
3806
- font-size: 14px;
3807
- line-height: 1.43;
1766
+ .tina-tailwind .text-4xl {
1767
+ font-size: 36px;
1768
+ line-height: 1.1;
3808
1769
  }
3809
1770
  .tina-tailwind .text-xl {
3810
1771
  font-size: 20px;
3811
1772
  line-height: 1.4;
3812
1773
  }
1774
+ .tina-tailwind .text-sm {
1775
+ font-size: 14px;
1776
+ line-height: 1.43;
1777
+ }
3813
1778
  .tina-tailwind .text-md {
3814
1779
  font-size: 16px;
3815
1780
  line-height: 1.5;
@@ -3850,6 +1815,14 @@ mutation addPendingDocumentMutation(
3850
1815
  --tw-text-opacity: 1;
3851
1816
  color: rgb(67 62 82 / var(--tw-text-opacity));
3852
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
+ }
3853
1826
  .tina-tailwind .text-blue-600 {
3854
1827
  --tw-text-opacity: 1;
3855
1828
  color: rgb(5 116 228 / var(--tw-text-opacity));
@@ -3885,13 +1858,12 @@ mutation addPendingDocumentMutation(
3885
1858
  --tw-text-opacity: 1;
3886
1859
  color: rgb(37 35 54 / var(--tw-text-opacity));
3887
1860
  }
3888
- .tina-tailwind .text-red-500 {
3889
- --tw-text-opacity: 1;
3890
- color: rgb(239 68 68 / var(--tw-text-opacity));
3891
- }
3892
1861
  .tina-tailwind .underline {
3893
1862
  text-decoration-line: underline;
3894
1863
  }
1864
+ .tina-tailwind .opacity-70 {
1865
+ opacity: .7;
1866
+ }
3895
1867
  .tina-tailwind .opacity-100 {
3896
1868
  opacity: 1;
3897
1869
  }
@@ -3910,9 +1882,6 @@ mutation addPendingDocumentMutation(
3910
1882
  .tina-tailwind .opacity-50 {
3911
1883
  opacity: .5;
3912
1884
  }
3913
- .tina-tailwind .opacity-70 {
3914
- opacity: .7;
3915
- }
3916
1885
  .tina-tailwind .shadow-lg {
3917
1886
  --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
3918
1887
  --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);
@@ -4237,42 +2206,6 @@ mutation addPendingDocumentMutation(
4237
2206
  };
4238
2207
  }, [plugin]);
4239
2208
  };
4240
- function useTina({
4241
- query,
4242
- variables,
4243
- data
4244
- }) {
4245
- React__default["default"].useEffect(() => {
4246
- console.warn(`
4247
- "useTina" from 'tinacms/dist/edit-state' is now deprecated
4248
- * Use "import { useTina } from 'tinacms/dist/react" instead.
4249
- * See https://tina.io/blog/upgrading-to-iframe/ for full migration details
4250
- `);
4251
- }, []);
4252
- const {
4253
- setRequest,
4254
- state,
4255
- isDummyContainer,
4256
- isLoading: contextLoading
4257
- } = React__default["default"].useContext(sharedctx.TinaDataContext);
4258
- const [waitForContextRerender, setWaitForContextRerender] = React.useState(!isDummyContainer);
4259
- const isLoading = contextLoading || waitForContextRerender;
4260
- React__default["default"].useEffect(() => {
4261
- setRequest({ query, variables });
4262
- }, [JSON.stringify(variables), query]);
4263
- React.useEffect(() => {
4264
- if (!isDummyContainer) {
4265
- setTimeout(() => setWaitForContextRerender(false), 0);
4266
- }
4267
- return () => {
4268
- setRequest(void 0);
4269
- };
4270
- }, [isDummyContainer]);
4271
- return {
4272
- data: isDummyContainer || isLoading ? data : state.payload,
4273
- isLoading
4274
- };
4275
- }
4276
2209
  const errorButtonStyles = {
4277
2210
  background: "#eb6337",
4278
2211
  padding: "12px 18px",
@@ -4360,12 +2293,6 @@ mutation addPendingDocumentMutation(
4360
2293
  ...props
4361
2294
  }) => {
4362
2295
  var _a, _b, _c, _d, _e;
4363
- React__default["default"].useEffect(() => {
4364
- console.warn(`
4365
- * Tina no longer requires wrapping your site in the TinaProvider
4366
- * See https://tina.io/blog/upgrading-to-iframe/ for full migration details
4367
- `);
4368
- }, []);
4369
2296
  if (props == null ? void 0 : props.apiURL) {
4370
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");
4371
2298
  }
@@ -4391,84 +2318,7 @@ mutation addPendingDocumentMutation(
4391
2318
  mediaStore: props.mediaStore,
4392
2319
  apiUrl: apiURL,
4393
2320
  schema: { ...schema, config: { ...schema.config, ...props } }
4394
- }, /* @__PURE__ */ React__default["default"].createElement("style", null, styles), /* @__PURE__ */ React__default["default"].createElement(ErrorBoundary, null, /* @__PURE__ */ React__default["default"].createElement(DocumentCreator, {
4395
- documentCreatorCallback
4396
- }), /* @__PURE__ */ React__default["default"].createElement(TinaDataProvider, {
4397
- formifyCallback
4398
- }, typeof props.children == "function" ? /* @__PURE__ */ React__default["default"].createElement(TinaQuery, {
4399
- ...props,
4400
- variables: props.variables,
4401
- data: props.data,
4402
- query,
4403
- formifyCallback,
4404
- children: props.children
4405
- }) : props.children))));
4406
- };
4407
- const DocumentCreator = ({
4408
- documentCreatorCallback
4409
- }) => {
4410
- useDocumentCreatorPlugin(documentCreatorCallback);
4411
- return null;
4412
- };
4413
- const TinaQuery = (props) => {
4414
- return /* @__PURE__ */ React__default["default"].createElement(TinaQueryInner, {
4415
- key: `rootQuery-${props.query}`,
4416
- ...props
4417
- });
4418
- };
4419
- const TinaQueryInner = ({ children, ...props }) => {
4420
- const { data: liveData, isLoading } = useTina({
4421
- query: props.query,
4422
- variables: props.variables,
4423
- data: props.data
4424
- });
4425
- return /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, children(isLoading || !props.query ? props : { ...props, data: liveData }));
4426
- };
4427
- const TinaDataProvider = ({
4428
- children,
4429
- formifyCallback
4430
- }) => {
4431
- const [request, setRequest] = React.useState();
4432
- const [state, setState] = React__default["default"].useState({
4433
- payload: void 0,
4434
- isLoading: true
4435
- });
4436
- return /* @__PURE__ */ React__default["default"].createElement(sharedctx.TinaDataContext.Provider, {
4437
- value: {
4438
- setRequest,
4439
- isLoading: state.isLoading,
4440
- state: { payload: state.payload }
4441
- }
4442
- }, /* @__PURE__ */ React__default["default"].createElement(FormRegistrar, {
4443
- key: request == null ? void 0 : request.query,
4444
- request,
4445
- formifyCallback,
4446
- onPayloadStateChange: setState
4447
- }), children);
4448
- };
4449
- const FormRegistrar = ({
4450
- request,
4451
- formifyCallback,
4452
- onPayloadStateChange
4453
- }) => {
4454
- const cms = toolkit.useCMS();
4455
- const { setFormsRegistering } = React__default["default"].useContext(sharedctx.EditContext);
4456
- const [payload, isLoading] = useGraphqlForms({
4457
- query: request == null ? void 0 : request.query,
4458
- variables: request == null ? void 0 : request.variables,
4459
- formify: (args) => {
4460
- if (formifyCallback) {
4461
- return formifyCallback(args, cms);
4462
- } else {
4463
- return args.createForm(args.formConfig);
4464
- }
4465
- }
4466
- });
4467
- React__default["default"].useEffect(() => {
4468
- onPayloadStateChange({ payload, isLoading });
4469
- setFormsRegistering && setFormsRegistering(isLoading);
4470
- }, [JSON.stringify(payload), isLoading]);
4471
- 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)));
4472
2322
  };
4473
2323
  const Loader = (props) => {
4474
2324
  return /* @__PURE__ */ React__default["default"].createElement(React__default["default"].Fragment, null, /* @__PURE__ */ React__default["default"].createElement("div", {
@@ -4662,10 +2512,10 @@ This will work when developing locally but NOT when deployed to production.
4662
2512
  return t;
4663
2513
  };
4664
2514
  function Tree2Element(tree) {
4665
- return tree && tree.map(function(node2, i) {
4666
- 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({
4667
2517
  key: i
4668
- }, node2.attr), Tree2Element(node2.child));
2518
+ }, node.attr), Tree2Element(node.child));
4669
2519
  });
4670
2520
  }
4671
2521
  function GenIcon(data) {
@@ -4715,6 +2565,9 @@ This will work when developing locally but NOT when deployed to production.
4715
2565
  function BiEdit(props) {
4716
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);
4717
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
+ }
4718
2571
  function BiLogIn(props) {
4719
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);
4720
2573
  }
@@ -4733,6 +2586,9 @@ This will work when developing locally but NOT when deployed to production.
4733
2586
  function BiSearch(props) {
4734
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);
4735
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
+ }
4736
2592
  function BiTrash(props) {
4737
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);
4738
2594
  }
@@ -5144,6 +3000,25 @@ This will work when developing locally but NOT when deployed to production.
5144
3000
  fontWeight: "normal"
5145
3001
  }
5146
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
+ };
5147
3022
  const useGetCollection = (cms, collectionName, includeDocuments = true, after = "", sortKey, filterArgs) => {
5148
3023
  const api = new TinaAdminApi(cms);
5149
3024
  const schema = cms.api.tina.schema;
@@ -5187,7 +3062,7 @@ This will work when developing locally but NOT when deployed to production.
5187
3062
  }) => {
5188
3063
  const { collection, loading, error, reFetchCollection, collectionExtra } = useGetCollection(cms, collectionName, includeDocuments, startCursor || "", sortKey, filterArgs) || {};
5189
3064
  if (error) {
5190
- return null;
3065
+ return /* @__PURE__ */ React__default["default"].createElement(FullscreenError, null);
5191
3066
  }
5192
3067
  if (loading) {
5193
3068
  return /* @__PURE__ */ React__default["default"].createElement(LoadingPage, null);
@@ -5289,7 +3164,7 @@ This will work when developing locally but NOT when deployed to production.
5289
3164
  }));
5290
3165
  }, [collectionName]);
5291
3166
  return /* @__PURE__ */ React__default["default"].createElement(GetCMS, null, (cms) => {
5292
- return /* @__PURE__ */ React__default["default"].createElement(GetCollection, {
3167
+ return /* @__PURE__ */ React__default["default"].createElement(PageWrapper, null, /* @__PURE__ */ React__default["default"].createElement(GetCollection, {
5293
3168
  cms,
5294
3169
  collectionName,
5295
3170
  includeDocuments: true,
@@ -5323,7 +3198,7 @@ This will work when developing locally but NOT when deployed to production.
5323
3198
  const collectionDefinition = cms.api.tina.schema.getCollection(collection.name);
5324
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;
5325
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;
5326
- 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, {
5327
3202
  filename: vars.relativePath,
5328
3203
  deleteFunc: async () => {
5329
3204
  try {
@@ -5432,7 +3307,7 @@ This will work when developing locally but NOT when deployed to production.
5432
3307
  value: ""
5433
3308
  },
5434
3309
  ...filterFields.map((x) => ({
5435
- label: x.label || x.name,
3310
+ label: typeof x.label === "string" && x.label || x.name,
5436
3311
  value: x.name
5437
3312
  }))
5438
3313
  ],
@@ -5687,8 +3562,8 @@ This will work when developing locally but NOT when deployed to production.
5687
3562
  setEndCursor(prev);
5688
3563
  }
5689
3564
  }
5690
- }))))));
5691
- });
3565
+ })))));
3566
+ }));
5692
3567
  });
5693
3568
  };
5694
3569
  const NoDocumentsPlaceholder = () => {
@@ -5747,6 +3622,42 @@ This will work when developing locally but NOT when deployed to production.
5747
3622
  function HiChevronRight(props) {
5748
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);
5749
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
+ };
5750
3661
  function FaLock(props) {
5751
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);
5752
3663
  }
@@ -5828,7 +3739,7 @@ This will work when developing locally but NOT when deployed to production.
5828
3739
  schema,
5829
3740
  template
5830
3741
  });
5831
- 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;
5832
3743
  if (!slugFunction) {
5833
3744
  const titleField = (_c = template == null ? void 0 : template.fields.find((x) => x.required && x.type === "string" && x.isTitle)) == null ? void 0 : _c.name;
5834
3745
  if (titleField) {
@@ -5861,11 +3772,11 @@ This will work when developing locally but NOT when deployed to production.
5861
3772
  component: slugFunction ? toolkit.wrapFieldsWithMeta(({ field, input, meta }) => {
5862
3773
  var _a3, _b3;
5863
3774
  return /* @__PURE__ */ React__default["default"].createElement(FilenameInput, {
5864
- 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,
5865
3776
  ...input
5866
3777
  });
5867
3778
  }) : "text",
5868
- 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,
5869
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")),
5870
3781
  placeholder: `My_Document`,
5871
3782
  validate: (value, allValues, meta) => {
@@ -5959,7 +3870,7 @@ This will work when developing locally but NOT when deployed to production.
5959
3870
  }) => {
5960
3871
  const { document, loading, error } = useGetDocument(cms, collectionName, relativePath);
5961
3872
  if (error) {
5962
- return null;
3873
+ return /* @__PURE__ */ React__default["default"].createElement(FullscreenError, null);
5963
3874
  }
5964
3875
  if (loading) {
5965
3876
  return /* @__PURE__ */ React__default["default"].createElement(LoadingPage, null);
@@ -5995,7 +3906,7 @@ This will work when developing locally but NOT when deployed to production.
5995
3906
  includeCollection: true,
5996
3907
  includeTemplate: !!collection.templates
5997
3908
  };
5998
- return /* @__PURE__ */ React__default["default"].createElement(GetDocument, {
3909
+ return /* @__PURE__ */ React__default["default"].createElement(PageWrapper, null, /* @__PURE__ */ React__default["default"].createElement(GetDocument, {
5999
3910
  cms,
6000
3911
  collectionName: collection.name,
6001
3912
  relativePath
@@ -6006,7 +3917,7 @@ This will work when developing locally but NOT when deployed to production.
6006
3917
  relativePath,
6007
3918
  collection,
6008
3919
  mutationInfo
6009
- }));
3920
+ })));
6010
3921
  }));
6011
3922
  };
6012
3923
  const RenderForm = ({
@@ -6052,7 +3963,7 @@ This will work when developing locally but NOT when deployed to production.
6052
3963
  const windowWidth = windowSize.useWindowWidth();
6053
3964
  const renderNavToggle = windowWidth < navBreakpoint + 1;
6054
3965
  const headerPadding = renderNavToggle ? "px-20" : "px-6";
6055
- 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", {
6056
3967
  className: `py-4 border-b border-gray-200 bg-white ${headerPadding}`
6057
3968
  }, /* @__PURE__ */ React__default["default"].createElement("div", {
6058
3969
  className: "max-w-form mx-auto"
@@ -6072,7 +3983,7 @@ This will work when developing locally but NOT when deployed to production.
6072
3983
  }))), /* @__PURE__ */ React__default["default"].createElement(toolkit.FormBuilder, {
6073
3984
  form,
6074
3985
  onPristineChange: setFormIsPristine
6075
- })));
3986
+ }));
6076
3987
  };
6077
3988
  const ScreenPage = () => {
6078
3989
  const { screenName } = reactRouterDom.useParams();
@@ -6329,7 +4240,6 @@ This will work when developing locally but NOT when deployed to production.
6329
4240
  exports2.TinaCMSProvider2 = TinaCMSProvider2;
6330
4241
  exports2.TinaCloudAuthWall = TinaCloudAuthWall;
6331
4242
  exports2.TinaCloudProvider = TinaCloudProvider;
6332
- exports2.TinaDataProvider = TinaDataProvider;
6333
4243
  exports2.assertShape = assertShape;
6334
4244
  exports2.asyncPoll = asyncPoll;
6335
4245
  exports2.createClient = createClient;
@@ -6343,7 +4253,6 @@ This will work when developing locally but NOT when deployed to production.
6343
4253
  exports2.safeAssertShape = safeAssertShape;
6344
4254
  exports2.staticRequest = staticRequest;
6345
4255
  exports2.useDocumentCreatorPlugin = useDocumentCreatorPlugin;
6346
- exports2.useGraphqlForms = useGraphqlForms;
6347
4256
  exports2.useTinaAuthRedirect = useTinaAuthRedirect;
6348
4257
  Object.keys(toolkit).forEach(function(k) {
6349
4258
  if (k !== "default" && !exports2.hasOwnProperty(k))