@tinacms/graphql 1.3.2 → 1.3.4

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.es.js CHANGED
@@ -124,11 +124,11 @@ var SysFieldDefinition = {
124
124
  };
125
125
  var astBuilder = {
126
126
  FormFieldBuilder: ({
127
- name: name2,
127
+ name,
128
128
  additionalFields
129
129
  }) => {
130
130
  return astBuilder.ObjectTypeDefinition({
131
- name: name2,
131
+ name,
132
132
  interfaces: [astBuilder.NamedType({ name: "FormField" })],
133
133
  fields: [
134
134
  astBuilder.FieldDefinition({
@@ -151,14 +151,14 @@ var astBuilder = {
151
151
  });
152
152
  },
153
153
  ScalarTypeDefinition: ({
154
- name: name2,
154
+ name,
155
155
  description
156
156
  }) => {
157
157
  return {
158
158
  kind: "ScalarTypeDefinition",
159
159
  name: {
160
160
  kind: "Name",
161
- value: name2
161
+ value: name
162
162
  },
163
163
  description: {
164
164
  kind: "StringValue",
@@ -168,7 +168,7 @@ var astBuilder = {
168
168
  };
169
169
  },
170
170
  InputValueDefinition: ({
171
- name: name2,
171
+ name,
172
172
  type,
173
173
  list,
174
174
  required
@@ -185,7 +185,7 @@ var astBuilder = {
185
185
  kind: "InputValueDefinition",
186
186
  name: {
187
187
  kind: "Name",
188
- value: name2
188
+ value: name
189
189
  }
190
190
  };
191
191
  if (list) {
@@ -246,17 +246,17 @@ var astBuilder = {
246
246
  };
247
247
  },
248
248
  FieldNodeDefinition: ({
249
- name: name2,
249
+ name,
250
250
  type,
251
251
  args = [],
252
252
  list,
253
253
  required
254
254
  }) => ({
255
- name: { kind: "Name", value: name2 },
255
+ name: { kind: "Name", value: name },
256
256
  kind: "Field"
257
257
  }),
258
258
  FieldDefinition: ({
259
- name: name2,
259
+ name,
260
260
  type,
261
261
  args = [],
262
262
  list,
@@ -274,7 +274,7 @@ var astBuilder = {
274
274
  kind: "FieldDefinition",
275
275
  name: {
276
276
  kind: "Name",
277
- value: name2
277
+ value: name
278
278
  },
279
279
  arguments: args
280
280
  };
@@ -321,7 +321,7 @@ var astBuilder = {
321
321
  return res;
322
322
  },
323
323
  InterfaceTypeDefinition: ({
324
- name: name2,
324
+ name,
325
325
  fields,
326
326
  description = ""
327
327
  }) => {
@@ -330,7 +330,7 @@ var astBuilder = {
330
330
  description: { kind: "StringValue", value: description },
331
331
  name: {
332
332
  kind: "Name",
333
- value: name2
333
+ value: name
334
334
  },
335
335
  interfaces: [],
336
336
  directives: [],
@@ -338,45 +338,45 @@ var astBuilder = {
338
338
  };
339
339
  },
340
340
  InputObjectTypeDefinition: ({
341
- name: name2,
341
+ name,
342
342
  fields
343
343
  }) => ({
344
344
  kind: "InputObjectTypeDefinition",
345
345
  name: {
346
346
  kind: "Name",
347
- value: name2
347
+ value: name
348
348
  },
349
349
  fields
350
350
  }),
351
351
  UnionTypeDefinition: ({
352
- name: name2,
352
+ name,
353
353
  types
354
354
  }) => ({
355
355
  kind: "UnionTypeDefinition",
356
356
  name: {
357
357
  kind: "Name",
358
- value: name2
358
+ value: name
359
359
  },
360
360
  directives: [],
361
- types: types.map((name3) => ({
361
+ types: types.map((name2) => ({
362
362
  kind: "NamedType",
363
363
  name: {
364
364
  kind: "Name",
365
- value: name3
365
+ value: name2
366
366
  }
367
367
  }))
368
368
  }),
369
- NamedType: ({ name: name2 }) => {
369
+ NamedType: ({ name }) => {
370
370
  return {
371
371
  kind: "NamedType",
372
372
  name: {
373
373
  kind: "Name",
374
- value: name2
374
+ value: name
375
375
  }
376
376
  };
377
377
  },
378
378
  ObjectTypeDefinition: ({
379
- name: name2,
379
+ name,
380
380
  fields,
381
381
  interfaces = [],
382
382
  directives = [],
@@ -387,16 +387,16 @@ var astBuilder = {
387
387
  directives,
388
388
  name: {
389
389
  kind: "Name",
390
- value: name2
390
+ value: name
391
391
  },
392
392
  fields
393
393
  }),
394
394
  FieldWithSelectionSetDefinition: ({
395
- name: name2,
395
+ name,
396
396
  selections
397
397
  }) => {
398
398
  return {
399
- name: { kind: "Name", value: name2 },
399
+ name: { kind: "Name", value: name },
400
400
  kind: "Field",
401
401
  selectionSet: {
402
402
  kind: "SelectionSet",
@@ -405,7 +405,7 @@ var astBuilder = {
405
405
  };
406
406
  },
407
407
  InlineFragmentDefinition: ({
408
- name: name2,
408
+ name,
409
409
  selections
410
410
  }) => {
411
411
  return {
@@ -418,13 +418,13 @@ var astBuilder = {
418
418
  kind: "NamedType",
419
419
  name: {
420
420
  kind: "Name",
421
- value: name2
421
+ value: name
422
422
  }
423
423
  }
424
424
  };
425
425
  },
426
426
  FragmentDefinition: ({
427
- name: name2,
427
+ name,
428
428
  fragmentName,
429
429
  selections
430
430
  }) => {
@@ -438,7 +438,7 @@ var astBuilder = {
438
438
  kind: "NamedType",
439
439
  name: {
440
440
  kind: "Name",
441
- value: name2
441
+ value: name
442
442
  }
443
443
  },
444
444
  directives: [],
@@ -937,11 +937,14 @@ var astBuilder = {
937
937
  };
938
938
  },
939
939
  toGraphQLAst: (ast) => {
940
- const definitions = _.uniqBy([
941
- ...extractInlineTypes(ast.query),
942
- ...extractInlineTypes(ast.globalTemplates),
943
- ...ast.definitions
944
- ], (field) => field.name.value);
940
+ const definitions = _.uniqBy(
941
+ [
942
+ ...extractInlineTypes(ast.query),
943
+ ...extractInlineTypes(ast.globalTemplates),
944
+ ...ast.definitions
945
+ ],
946
+ (field) => field.name.value
947
+ );
945
948
  return {
946
949
  kind: "Document",
947
950
  definitions
@@ -975,7 +978,7 @@ var extractInlineTypes = (item) => {
975
978
  return accumulator;
976
979
  }
977
980
  };
978
- function* walk(maybeNode, visited = new WeakSet()) {
981
+ function* walk(maybeNode, visited = /* @__PURE__ */ new WeakSet()) {
979
982
  if (typeof maybeNode === "string") {
980
983
  return;
981
984
  }
@@ -1266,7 +1269,7 @@ var Builder = class {
1266
1269
  constructor(config) {
1267
1270
  this.config = config;
1268
1271
  this.buildCollectionDefinition = async (collections) => {
1269
- const name2 = "collection";
1272
+ const name = "collection";
1270
1273
  const typeName = "Collection";
1271
1274
  const args = [
1272
1275
  astBuilder.InputValueDefinition({
@@ -1329,23 +1332,23 @@ var Builder = class {
1329
1332
  });
1330
1333
  return astBuilder.FieldDefinition({
1331
1334
  type,
1332
- name: name2,
1335
+ name,
1333
1336
  args,
1334
1337
  required: true
1335
1338
  });
1336
1339
  };
1337
1340
  this.buildMultiCollectionDefinition = async (collections) => {
1338
- const name2 = "collections";
1341
+ const name = "collections";
1339
1342
  const typeName = "Collection";
1340
1343
  return astBuilder.FieldDefinition({
1341
1344
  type: typeName,
1342
- name: name2,
1345
+ name,
1343
1346
  list: true,
1344
1347
  required: true
1345
1348
  });
1346
1349
  };
1347
1350
  this.multiNodeDocument = async () => {
1348
- const name2 = "node";
1351
+ const name = "node";
1349
1352
  const args = [
1350
1353
  astBuilder.InputValueDefinition({
1351
1354
  name: "id",
@@ -1357,7 +1360,7 @@ var Builder = class {
1357
1360
  resolveType: "nodeDocument"
1358
1361
  });
1359
1362
  return astBuilder.FieldDefinition({
1360
- name: name2,
1363
+ name,
1361
1364
  args,
1362
1365
  list: false,
1363
1366
  type: astBuilder.TYPES.Node,
@@ -1365,7 +1368,7 @@ var Builder = class {
1365
1368
  });
1366
1369
  };
1367
1370
  this.multiCollectionDocument = async (collections) => {
1368
- const name2 = "document";
1371
+ const name = "document";
1369
1372
  const args = [
1370
1373
  astBuilder.InputValueDefinition({
1371
1374
  name: "collection",
@@ -1381,7 +1384,7 @@ var Builder = class {
1381
1384
  collections
1382
1385
  });
1383
1386
  return astBuilder.FieldDefinition({
1384
- name: name2,
1387
+ name,
1385
1388
  args,
1386
1389
  list: false,
1387
1390
  type,
@@ -1486,7 +1489,7 @@ var Builder = class {
1486
1489
  });
1487
1490
  };
1488
1491
  this.collectionDocument = async (collection) => {
1489
- const name2 = NAMER.queryName([collection.name]);
1492
+ const name = NAMER.queryName([collection.name]);
1490
1493
  const type = await this._buildCollectionDocumentType(collection);
1491
1494
  const args = [
1492
1495
  astBuilder.InputValueDefinition({
@@ -1501,21 +1504,24 @@ var Builder = class {
1501
1504
  [NAMER.createName([collection.name])]: "create",
1502
1505
  [NAMER.updateName([collection.name])]: "update"
1503
1506
  });
1504
- return astBuilder.FieldDefinition({ type, name: name2, args, required: true });
1507
+ return astBuilder.FieldDefinition({ type, name, args, required: true });
1505
1508
  };
1506
1509
  this.collectionFragment = async (collection) => {
1507
- const name2 = NAMER.dataTypeName(collection.namespace);
1510
+ const name = NAMER.dataTypeName(collection.namespace);
1508
1511
  const fragmentName = NAMER.fragmentName(collection.namespace);
1509
- const selections = await this._getCollectionFragmentSelections(collection, 0);
1512
+ const selections = await this._getCollectionFragmentSelections(
1513
+ collection,
1514
+ 0
1515
+ );
1510
1516
  return astBuilder.FragmentDefinition({
1511
- name: name2,
1517
+ name,
1512
1518
  fragmentName,
1513
1519
  selections: filterSelections(selections)
1514
1520
  });
1515
1521
  };
1516
1522
  this._getCollectionFragmentSelections = async (collection, depth) => {
1517
1523
  const selections = [];
1518
- if (typeof collection.fields === "object") {
1524
+ if (collection.fields?.length > 0) {
1519
1525
  await sequential(collection.fields, async (x) => {
1520
1526
  const field = await this._buildFieldNodeForFragments(x, depth);
1521
1527
  selections.push(field);
@@ -1539,7 +1545,7 @@ var Builder = class {
1539
1545
  case "rich-text":
1540
1546
  return astBuilder.FieldNodeDefinition(field);
1541
1547
  case "object":
1542
- if (typeof field.fields === "object") {
1548
+ if (field.fields?.length > 0) {
1543
1549
  const selections2 = [];
1544
1550
  await sequential(field.fields, async (item) => {
1545
1551
  const field2 = await this._buildFieldNodeForFragments(item, depth);
@@ -1552,7 +1558,7 @@ var Builder = class {
1552
1558
  ...filterSelections(selections2)
1553
1559
  ]
1554
1560
  });
1555
- } else if (typeof field.templates === "object") {
1561
+ } else if (field.templates?.length > 0) {
1556
1562
  const selections2 = [];
1557
1563
  await sequential(field.templates, async (tem) => {
1558
1564
  if (typeof tem === "object") {
@@ -1588,7 +1594,12 @@ var Builder = class {
1588
1594
  directives: [],
1589
1595
  selectionSet: {
1590
1596
  kind: "SelectionSet",
1591
- selections: filterSelections(await this._getCollectionFragmentSelections(collection, depth + 1))
1597
+ selections: filterSelections(
1598
+ await this._getCollectionFragmentSelections(
1599
+ collection,
1600
+ depth + 1
1601
+ )
1602
+ )
1592
1603
  }
1593
1604
  });
1594
1605
  });
@@ -1683,30 +1694,35 @@ var Builder = class {
1683
1694
  const documentTypeName = NAMER.documentTypeName(collection.namespace);
1684
1695
  const templateInfo = this.tinaSchema.getTemplatesForCollectable(collection);
1685
1696
  if (templateInfo.type === "union") {
1686
- return this._buildObjectOrUnionData({
1687
- ...templateInfo
1688
- }, [
1689
- astBuilder.FieldDefinition({
1690
- name: "id",
1691
- required: true,
1692
- type: astBuilder.TYPES.ID
1693
- }),
1694
- astBuilder.FieldDefinition({
1695
- name: "_sys",
1696
- required: true,
1697
- type: astBuilder.TYPES.SystemInfo
1698
- }),
1699
- ...extraFields,
1700
- astBuilder.FieldDefinition({
1701
- name: "_values",
1702
- required: true,
1703
- type: "JSON"
1704
- })
1705
- ], [
1706
- astBuilder.NamedType({ name: astBuilder.TYPES.Node }),
1707
- astBuilder.NamedType({ name: astBuilder.TYPES.Document }),
1708
- ...extraInterfaces
1709
- ], collection);
1697
+ return this._buildObjectOrUnionData(
1698
+ {
1699
+ ...templateInfo
1700
+ },
1701
+ [
1702
+ astBuilder.FieldDefinition({
1703
+ name: "id",
1704
+ required: true,
1705
+ type: astBuilder.TYPES.ID
1706
+ }),
1707
+ astBuilder.FieldDefinition({
1708
+ name: "_sys",
1709
+ required: true,
1710
+ type: astBuilder.TYPES.SystemInfo
1711
+ }),
1712
+ ...extraFields,
1713
+ astBuilder.FieldDefinition({
1714
+ name: "_values",
1715
+ required: true,
1716
+ type: "JSON"
1717
+ })
1718
+ ],
1719
+ [
1720
+ astBuilder.NamedType({ name: astBuilder.TYPES.Node }),
1721
+ astBuilder.NamedType({ name: astBuilder.TYPES.Document }),
1722
+ ...extraInterfaces
1723
+ ],
1724
+ collection
1725
+ );
1710
1726
  }
1711
1727
  const fields = templateInfo.template.fields;
1712
1728
  const templateFields = await sequential(fields, async (field) => {
@@ -1995,7 +2011,9 @@ var Builder = class {
1995
2011
  const filter = await this._connectionFilterBuilder({
1996
2012
  fieldName: field.name,
1997
2013
  namespace: field.namespace,
1998
- collections: await this.tinaSchema.getCollectionsByName(field.collections)
2014
+ collections: await this.tinaSchema.getCollectionsByName(
2015
+ field.collections
2016
+ )
1999
2017
  });
2000
2018
  return astBuilder.InputValueDefinition({
2001
2019
  name: field.name,
@@ -2051,25 +2069,33 @@ var Builder = class {
2051
2069
  this._buildReferenceMutation = async (field) => {
2052
2070
  return astBuilder.InputObjectTypeDefinition({
2053
2071
  name: NAMER.dataMutationTypeName(field.namespace),
2054
- fields: await sequential(this.tinaSchema.getCollectionsByName(field.collections), async (collection) => {
2072
+ fields: await sequential(
2073
+ this.tinaSchema.getCollectionsByName(field.collections),
2074
+ async (collection) => {
2075
+ return astBuilder.InputValueDefinition({
2076
+ name: collection.name,
2077
+ type: NAMER.dataMutationTypeName([collection.name])
2078
+ });
2079
+ }
2080
+ )
2081
+ });
2082
+ };
2083
+ this._buildUpdateDocumentMutationParams = async (field) => {
2084
+ const fields = await sequential(
2085
+ this.tinaSchema.getCollectionsByName(field.collections),
2086
+ async (collection) => {
2055
2087
  return astBuilder.InputValueDefinition({
2056
2088
  name: collection.name,
2057
2089
  type: NAMER.dataMutationTypeName([collection.name])
2058
2090
  });
2091
+ }
2092
+ );
2093
+ fields.push(
2094
+ astBuilder.InputValueDefinition({
2095
+ name: "relativePath",
2096
+ type: astBuilder.TYPES.String
2059
2097
  })
2060
- });
2061
- };
2062
- this._buildUpdateDocumentMutationParams = async (field) => {
2063
- const fields = await sequential(this.tinaSchema.getCollectionsByName(field.collections), async (collection) => {
2064
- return astBuilder.InputValueDefinition({
2065
- name: collection.name,
2066
- type: NAMER.dataMutationTypeName([collection.name])
2067
- });
2068
- });
2069
- fields.push(astBuilder.InputValueDefinition({
2070
- name: "relativePath",
2071
- type: astBuilder.TYPES.String
2072
- }));
2098
+ );
2073
2099
  return astBuilder.InputObjectTypeDefinition({
2074
2100
  name: NAMER.dataMutationUpdateTypeName(field.namespace),
2075
2101
  fields
@@ -2077,20 +2103,27 @@ var Builder = class {
2077
2103
  };
2078
2104
  this._buildObjectOrUnionData = async (collectableTemplate, extraFields = [], extraInterfaces = [], collection) => {
2079
2105
  if (collectableTemplate.type === "union") {
2080
- const name2 = NAMER.dataTypeName(collectableTemplate.namespace);
2106
+ const name = NAMER.dataTypeName(collectableTemplate.namespace);
2081
2107
  const typeMap = {};
2082
- const types = await sequential(collectableTemplate.templates, async (template) => {
2083
- const type = await this._buildTemplateData(template, extraFields, extraInterfaces);
2084
- typeMap[template.namespace[template.namespace.length - 1]] = type.name.value;
2085
- return type;
2086
- });
2108
+ const types = await sequential(
2109
+ collectableTemplate.templates,
2110
+ async (template) => {
2111
+ const type = await this._buildTemplateData(
2112
+ template,
2113
+ extraFields,
2114
+ extraInterfaces
2115
+ );
2116
+ typeMap[template.namespace[template.namespace.length - 1]] = type.name.value;
2117
+ return type;
2118
+ }
2119
+ );
2087
2120
  await this.database.addToLookupMap({
2088
- type: name2,
2121
+ type: name,
2089
2122
  resolveType: "unionData",
2090
2123
  collection: collection?.name,
2091
2124
  typeMap
2092
2125
  });
2093
- return astBuilder.UnionTypeDefinition({ name: name2, types });
2126
+ return astBuilder.UnionTypeDefinition({ name, types });
2094
2127
  }
2095
2128
  return this._buildTemplateData(collectableTemplate.template);
2096
2129
  };
@@ -2120,7 +2153,9 @@ var Builder = class {
2120
2153
  type: await this._filterCollectionDocumentType(collection)
2121
2154
  });
2122
2155
  } else {
2123
- throw new Error(`Must provide either collection or collections to filter field builder`);
2156
+ throw new Error(
2157
+ `Must provide either collection or collections to filter field builder`
2158
+ );
2124
2159
  }
2125
2160
  return filter;
2126
2161
  };
@@ -2205,7 +2240,9 @@ Visit https://tina.io/docs/errors/ui-not-supported/ for more information
2205
2240
  name: field.name,
2206
2241
  list: field.list,
2207
2242
  required: field.required,
2208
- type: await this._buildObjectOrUnionData(this.tinaSchema.getTemplatesForCollectable(field))
2243
+ type: await this._buildObjectOrUnionData(
2244
+ this.tinaSchema.getTemplatesForCollectable(field)
2245
+ )
2209
2246
  });
2210
2247
  case "rich-text":
2211
2248
  return astBuilder.FieldDefinition({
@@ -2215,23 +2252,29 @@ Visit https://tina.io/docs/errors/ui-not-supported/ for more information
2215
2252
  type: astBuilder.TYPES.JSON
2216
2253
  });
2217
2254
  case "reference":
2218
- const name2 = NAMER.documentTypeName(field.namespace);
2255
+ const name = NAMER.documentTypeName(field.namespace);
2219
2256
  if (field.list) {
2220
2257
  console.warn(listWarningMsg);
2221
2258
  return this._buildMultiCollectionDocumentListDefinition({
2222
2259
  fieldName: field.name,
2223
2260
  namespace: field.namespace,
2224
2261
  nodeType: astBuilder.UnionTypeDefinition({
2225
- name: name2,
2226
- types: field.collections.map((collectionName) => NAMER.documentTypeName([collectionName]))
2262
+ name,
2263
+ types: field.collections.map(
2264
+ (collectionName) => NAMER.documentTypeName([collectionName])
2265
+ )
2227
2266
  }),
2228
- collections: this.tinaSchema.getCollectionsByName(field.collections),
2267
+ collections: this.tinaSchema.getCollectionsByName(
2268
+ field.collections
2269
+ ),
2229
2270
  connectionNamespace: field.namespace
2230
2271
  });
2231
2272
  } else {
2232
2273
  const type = await this._buildMultiCollectionDocumentDefinition({
2233
- fieldName: name2,
2234
- collections: this.tinaSchema.getCollectionsByName(field.collections)
2274
+ fieldName: name,
2275
+ collections: this.tinaSchema.getCollectionsByName(
2276
+ field.collections
2277
+ )
2235
2278
  });
2236
2279
  return astBuilder.FieldDefinition({
2237
2280
  name: field.name,
@@ -2304,10 +2347,7 @@ import { TinaSchema } from "@tinacms/schema-tools";
2304
2347
 
2305
2348
  // src/schema/validate.ts
2306
2349
  import _2 from "lodash";
2307
- import {
2308
- object,
2309
- string
2310
- } from "yup";
2350
+ import * as yup2 from "yup";
2311
2351
  import {
2312
2352
  validateTinaCloudSchemaConfig
2313
2353
  } from "@tinacms/schema-tools";
@@ -2322,8 +2362,13 @@ var FIELD_TYPES = [
2322
2362
  "rich-text"
2323
2363
  ];
2324
2364
  var validateSchema = async (schema) => {
2325
- const schema2 = addNamespaceToSchema(_2.cloneDeep(schema));
2326
- const collections = await sequential(schema2.collections, async (collection) => validateCollection(collection));
2365
+ const schema2 = addNamespaceToSchema(
2366
+ _2.cloneDeep(schema)
2367
+ );
2368
+ const collections = await sequential(
2369
+ schema2.collections,
2370
+ async (collection) => validateCollection(collection)
2371
+ );
2327
2372
  validationCollectionsPathAndMatch(collections);
2328
2373
  if (schema2.config) {
2329
2374
  const config = validateTinaCloudSchemaConfig(schema2.config);
@@ -2357,7 +2402,7 @@ var validationCollectionsPathAndMatch = (collections) => {
2357
2402
  r[a.path] = r[a.path] || [];
2358
2403
  r[a.path].push(a);
2359
2404
  return r;
2360
- }, Object.create(null));
2405
+ }, /* @__PURE__ */ Object.create(null));
2361
2406
  Object.keys(groupbyPath).forEach((key) => {
2362
2407
  const collectionsArr = groupbyPath[key];
2363
2408
  if (collectionsArr.length === 1) {
@@ -2375,29 +2420,31 @@ var validateCollection = async (collection) => {
2375
2420
  let templates = [];
2376
2421
  let fields = [];
2377
2422
  const messageName = collection.namespace.join(".");
2378
- const collectionSchema = object({
2379
- name: string().matches(/^[a-zA-Z0-9_]*$/, {
2423
+ const collectionSchema = yup2.object({
2424
+ name: yup2.string().matches(/^[a-zA-Z0-9_]*$/, {
2380
2425
  message: (obj) => `Collection's "name" must match ${obj.regex} at ${messageName}`
2381
2426
  }).required(),
2382
- path: string().required().transform((value) => {
2427
+ path: yup2.string().required().transform((value) => {
2383
2428
  return value.replace(/^\/|\/$/g, "");
2384
2429
  })
2385
2430
  });
2386
2431
  await collectionSchema.validate(collection);
2387
- const validCollection = await collectionSchema.cast(collection);
2432
+ const validCollection = await collectionSchema.cast(
2433
+ collection
2434
+ );
2388
2435
  if (validCollection.templates) {
2389
- templates = await sequential(validCollection.templates, async (template) => {
2390
- if (typeof template === "string") {
2391
- throw new Error(`Global templates are not yet supported`);
2436
+ templates = await sequential(
2437
+ validCollection.templates,
2438
+ async (template) => {
2439
+ const fields2 = await sequential(template.fields, async (field) => {
2440
+ return validateField(field);
2441
+ });
2442
+ return {
2443
+ ...validCollection,
2444
+ ...fields2
2445
+ };
2392
2446
  }
2393
- const fields2 = await sequential(template.fields, async (field) => {
2394
- return validateField(field);
2395
- });
2396
- return {
2397
- ...validCollection,
2398
- ...fields2
2399
- };
2400
- });
2447
+ );
2401
2448
  }
2402
2449
  if (validCollection.fields) {
2403
2450
  if (typeof validCollection.fields === "string") {
@@ -2415,148 +2462,138 @@ var validateCollection = async (collection) => {
2415
2462
  };
2416
2463
  var validateField = async (field) => {
2417
2464
  const messageName = field.namespace.join(".");
2418
- const schema = object({
2419
- name: string().matches(/^[a-zA-Z0-9_]*$/, {
2465
+ const schema = yup2.object({
2466
+ name: yup2.string().matches(/^[a-zA-Z0-9_]*$/, {
2420
2467
  message: (obj) => `Field's 'name' must match ${obj.regex} at ${messageName}`
2421
2468
  }).required(),
2422
- type: string().oneOf(FIELD_TYPES, (obj) => `'type' must be one of: ${obj.values}, but got '${obj.value}' at ${messageName}`)
2469
+ type: yup2.string().oneOf(
2470
+ FIELD_TYPES,
2471
+ (obj) => `'type' must be one of: ${obj.values}, but got '${obj.value}' at ${messageName}`
2472
+ )
2423
2473
  });
2424
2474
  await schema.validate(field);
2425
- return field;
2475
+ const validField = await schema.cast(field);
2476
+ return validField;
2426
2477
  };
2427
2478
 
2428
2479
  // package.json
2429
- var name = "@tinacms/graphql";
2430
- var version = "1.3.2";
2431
- var main = "dist/index.js";
2432
- var module = "dist/index.es.js";
2433
- var typings = "dist/index.d.ts";
2434
- var files = [
2435
- "package.json",
2436
- "dist"
2437
- ];
2438
- var exports = {
2439
- import: "./dist/index.es.js",
2440
- require: "./dist/index.js"
2441
- };
2442
- var license = "SEE LICENSE IN LICENSE";
2443
- var buildConfig = {
2444
- entryPoints: [
2445
- {
2446
- name: "src/index.ts",
2447
- target: "node",
2448
- bundle: []
2449
- }
2450
- ]
2451
- };
2452
- var scripts = {
2453
- types: "pnpm tsc",
2454
- build: "tinacms-scripts build",
2455
- docs: "yarn typedoc",
2456
- serve: "yarn nodemon dist/server.js",
2457
- test: "jest",
2458
- "test-watch": "jest --watch"
2459
- };
2460
- var dependencies = {
2461
- "@graphql-tools/relay-operation-optimizer": "^6.4.1",
2462
- "@iarna/toml": "^2.2.5",
2463
- "@tinacms/mdx": "workspace:*",
2464
- "@tinacms/schema-tools": "workspace:*",
2465
- "abstract-level": "^1.0.3",
2466
- "body-parser": "^1.19.0",
2467
- cors: "^2.8.5",
2468
- dataloader: "^2.0.0",
2469
- "date-fns": "^2.21.1",
2470
- "encoding-down": "^7.1.0",
2471
- esbuild: "^0.12.25",
2472
- "esbuild-jest": "^0.5.0",
2473
- "estree-walker": "^3.0.0",
2474
- "fast-glob": "^3.2.5",
2475
- flat: "^5.0.2",
2476
- "fs-extra": "^9.0.1",
2477
- "glob-parent": "^6.0.2",
2478
- graphql: "15.8.0",
2479
- "graphql-type-json": "^0.3.2",
2480
- "gray-matter": "^4.0.2",
2481
- "isomorphic-git": "^1.21.0",
2482
- "js-yaml": "^3.14.1",
2483
- "jsonpath-plus": "^6.0.1",
2484
- leveldown: "^6.1.0",
2485
- lodash: "^4.17.20",
2486
- "many-level": "^2.0.0",
2487
- mdast: "^3.0.0",
2488
- "mdast-util-from-markdown": "^1.0.0",
2489
- "mdast-util-mdx": "^1.1.0",
2490
- "mdast-util-mdx-expression": "^1.1.0",
2491
- "mdast-util-to-markdown": "^1.2.1",
2492
- "micromark-extension-mdxjs": "^1.0.0",
2493
- "normalize-path": "^3.0.0",
2494
- prettier: "^2.2.1",
2495
- "readable-stream": "^4.3.0",
2496
- "rehype-format": "^3.1.0",
2497
- "rehype-stringify": "^8.0.0",
2498
- remark: "^13.0.0",
2499
- "remark-frontmatter": "^3.0.0",
2500
- "remark-mdx": "next",
2501
- "remark-parse": "^10.0.0",
2502
- "remark-rehype": "^8.0.0",
2503
- "remark-slate": "^1.8.0",
2504
- "remark-stringify": "^8.1.1",
2505
- unified: "^10.1.0",
2506
- "unist-util-remove-position": "^3.0.0",
2507
- "unist-util-visit": "^4.0.0",
2508
- vfile: "^4.2.0",
2509
- ws: "^7.3.1",
2510
- yup: "^0.32.9"
2511
- };
2512
- var publishConfig = {
2513
- registry: "https://registry.npmjs.org"
2514
- };
2515
- var repository = {
2516
- url: "https://github.com/tinacms/tinacms.git",
2517
- directory: "packages/tina-graphql"
2518
- };
2519
- var devDependencies = {
2520
- "@tinacms/schema-tools": "workspace:*",
2521
- "@tinacms/scripts": "workspace:*",
2522
- "@types/cors": "^2.8.7",
2523
- "@types/estree": "^0.0.50",
2524
- "@types/express": "^4.17.8",
2525
- "@types/fs-extra": "^9.0.2",
2526
- "@types/jest": "^26.0.4",
2527
- "@types/js-yaml": "^3.12.5",
2528
- "@types/lodash": "^4.14.161",
2529
- "@types/lodash.camelcase": "^4.3.6",
2530
- "@types/lodash.upperfirst": "^4.3.6",
2531
- "@types/lru-cache": "^5.1.0",
2532
- "@types/mdast": "^3.0.10",
2533
- "@types/node": "^14.17.34",
2534
- "@types/normalize-path": "^3.0.0",
2535
- "@types/ws": "^7.2.6",
2536
- "@types/yup": "^0.29.7",
2537
- jest: "27.0.6",
2538
- "jest-diff": "27.0.6",
2539
- "jest-file-snapshot": "^0.5.0",
2540
- "jest-matcher-utils": "27.0.6",
2541
- "memory-level": "^1.0.0",
2542
- nodemon: "2.0.19",
2543
- typescript: "4.3.5"
2544
- };
2545
2480
  var package_default = {
2546
- name,
2547
- version,
2548
- main,
2549
- module,
2550
- typings,
2551
- files,
2552
- exports,
2553
- license,
2554
- buildConfig,
2555
- scripts,
2556
- dependencies,
2557
- publishConfig,
2558
- repository,
2559
- devDependencies
2481
+ name: "@tinacms/graphql",
2482
+ version: "1.3.4",
2483
+ main: "dist/index.js",
2484
+ module: "dist/index.es.js",
2485
+ typings: "dist/index.d.ts",
2486
+ files: [
2487
+ "package.json",
2488
+ "dist"
2489
+ ],
2490
+ exports: {
2491
+ import: "./dist/index.es.js",
2492
+ require: "./dist/index.js"
2493
+ },
2494
+ license: "SEE LICENSE IN LICENSE",
2495
+ buildConfig: {
2496
+ entryPoints: [
2497
+ {
2498
+ name: "src/index.ts",
2499
+ target: "node",
2500
+ bundle: []
2501
+ }
2502
+ ]
2503
+ },
2504
+ scripts: {
2505
+ types: "pnpm tsc",
2506
+ build: "tinacms-scripts build",
2507
+ docs: "yarn typedoc",
2508
+ serve: "yarn nodemon dist/server.js",
2509
+ test: "jest",
2510
+ "test-watch": "jest --watch"
2511
+ },
2512
+ dependencies: {
2513
+ "@graphql-tools/relay-operation-optimizer": "^6.4.1",
2514
+ "@iarna/toml": "^2.2.5",
2515
+ "@tinacms/mdx": "workspace:*",
2516
+ "@tinacms/schema-tools": "workspace:*",
2517
+ "abstract-level": "^1.0.3",
2518
+ "body-parser": "^1.19.0",
2519
+ cors: "^2.8.5",
2520
+ dataloader: "^2.0.0",
2521
+ "date-fns": "^2.21.1",
2522
+ "encoding-down": "^7.1.0",
2523
+ esbuild: "^0.15.5",
2524
+ "esbuild-jest": "^0.5.0",
2525
+ "estree-walker": "^3.0.0",
2526
+ "fast-glob": "^3.2.5",
2527
+ flat: "^5.0.2",
2528
+ "fs-extra": "^9.0.1",
2529
+ "glob-parent": "^6.0.2",
2530
+ graphql: "15.8.0",
2531
+ "graphql-type-json": "^0.3.2",
2532
+ "gray-matter": "^4.0.2",
2533
+ "isomorphic-git": "^1.21.0",
2534
+ "js-yaml": "^3.14.1",
2535
+ "jsonpath-plus": "^6.0.1",
2536
+ leveldown: "^6.1.0",
2537
+ lodash: "^4.17.20",
2538
+ "many-level": "^2.0.0",
2539
+ mdast: "^3.0.0",
2540
+ "mdast-util-from-markdown": "^1.0.0",
2541
+ "mdast-util-mdx": "^1.1.0",
2542
+ "mdast-util-mdx-expression": "^1.1.0",
2543
+ "mdast-util-to-markdown": "^1.2.1",
2544
+ "micromark-extension-mdxjs": "^1.0.0",
2545
+ "normalize-path": "^3.0.0",
2546
+ prettier: "^2.2.1",
2547
+ "readable-stream": "^4.3.0",
2548
+ "rehype-format": "^3.1.0",
2549
+ "rehype-stringify": "^8.0.0",
2550
+ remark: "^13.0.0",
2551
+ "remark-frontmatter": "^3.0.0",
2552
+ "remark-mdx": "next",
2553
+ "remark-parse": "^10.0.0",
2554
+ "remark-rehype": "^8.0.0",
2555
+ "remark-slate": "^1.8.0",
2556
+ "remark-stringify": "^8.1.1",
2557
+ unified: "^10.1.0",
2558
+ "unist-util-remove-position": "^3.0.0",
2559
+ "unist-util-visit": "^4.0.0",
2560
+ vfile: "^4.2.0",
2561
+ ws: "^7.3.1",
2562
+ yup: "^0.32.9"
2563
+ },
2564
+ publishConfig: {
2565
+ registry: "https://registry.npmjs.org"
2566
+ },
2567
+ repository: {
2568
+ url: "https://github.com/tinacms/tinacms.git",
2569
+ directory: "packages/tina-graphql"
2570
+ },
2571
+ devDependencies: {
2572
+ "@tinacms/schema-tools": "workspace:*",
2573
+ "@tinacms/scripts": "workspace:*",
2574
+ "@types/cors": "^2.8.7",
2575
+ "@types/estree": "^0.0.50",
2576
+ "@types/express": "^4.17.8",
2577
+ "@types/fs-extra": "^9.0.2",
2578
+ "@types/jest": "^26.0.4",
2579
+ "@types/js-yaml": "^3.12.5",
2580
+ "@types/lodash": "^4.14.161",
2581
+ "@types/lodash.camelcase": "^4.3.6",
2582
+ "@types/lodash.upperfirst": "^4.3.6",
2583
+ "@types/lru-cache": "^5.1.0",
2584
+ "@types/mdast": "^3.0.10",
2585
+ "@types/node": "^14.17.34",
2586
+ "@types/normalize-path": "^3.0.0",
2587
+ "@types/ws": "^7.2.6",
2588
+ "@types/yup": "^0.29.7",
2589
+ jest: "27.0.6",
2590
+ "jest-diff": "27.0.6",
2591
+ "jest-file-snapshot": "^0.5.0",
2592
+ "jest-matcher-utils": "27.0.6",
2593
+ "memory-level": "^1.0.0",
2594
+ nodemon: "2.0.19",
2595
+ typescript: "4.3.5"
2596
+ }
2560
2597
  };
2561
2598
 
2562
2599
  // src/schema/createSchema.ts
@@ -2603,7 +2640,9 @@ var buildDotTinaFiles = async ({
2603
2640
  graphQLSchema = await _buildSchema(builder, tinaSchema);
2604
2641
  await database.putConfigFiles({ graphQLSchema, tinaSchema });
2605
2642
  } else {
2606
- graphQLSchema = JSON.parse(await database.bridge.get(".tina/__generated__/_graphql.json"));
2643
+ graphQLSchema = JSON.parse(
2644
+ await database.bridge.get(".tina/__generated__/_graphql.json")
2645
+ );
2607
2646
  }
2608
2647
  if (buildSDK) {
2609
2648
  await _buildFragments(builder, tinaSchema, database.bridge.rootPath);
@@ -2615,25 +2654,34 @@ var _buildFragments = async (builder, tinaSchema, rootPath) => {
2615
2654
  const fragmentDefinitionsFields = [];
2616
2655
  const collections = tinaSchema.getCollections();
2617
2656
  await sequential(collections, async (collection) => {
2618
- const frag = await builder.collectionFragment(collection);
2657
+ const frag = await builder.collectionFragment(
2658
+ collection
2659
+ );
2619
2660
  fragmentDefinitionsFields.push(frag);
2620
2661
  });
2621
2662
  const fragDoc = {
2622
2663
  kind: "Document",
2623
- definitions: _3.uniqBy(extractInlineTypes(fragmentDefinitionsFields), (node) => node.name.value)
2664
+ definitions: _3.uniqBy(
2665
+ extractInlineTypes(fragmentDefinitionsFields),
2666
+ (node) => node.name.value
2667
+ )
2624
2668
  };
2625
2669
  const fragPath = path.join(rootPath, ".tina", "__generated__");
2626
2670
  await fs.outputFile(path.join(fragPath, "frags.gql"), print(fragDoc));
2627
2671
  if (await (await fs.stat(path.join(fragPath, "frags.gql"))).size > 100 * 1024) {
2628
- console.warn("Warning: frags.gql is very large (>100kb). Consider setting the reference depth to 1 or 0. See code snippet below.");
2629
- console.log(`const schema = defineSchema({
2672
+ console.warn(
2673
+ "Warning: frags.gql is very large (>100kb). Consider setting the reference depth to 1 or 0. See code snippet below."
2674
+ );
2675
+ console.log(
2676
+ `const schema = defineSchema({
2630
2677
  config: {
2631
2678
  client: {
2632
2679
  referenceDepth: 1,
2633
2680
  },
2634
2681
  }
2635
2682
  // ...
2636
- })`);
2683
+ })`
2684
+ );
2637
2685
  }
2638
2686
  };
2639
2687
  var _buildQueries = async (builder, tinaSchema, rootPath) => {
@@ -2644,17 +2692,26 @@ var _buildQueries = async (builder, tinaSchema, rootPath) => {
2644
2692
  const queryListName = NAMER.generateQueryListName(collection.namespace);
2645
2693
  const queryFilterTypeName = NAMER.dataFilterTypeName(collection.namespace);
2646
2694
  const fragName = NAMER.fragmentName(collection.namespace);
2647
- operationsDefinitions.push(astBuilder.QueryOperationDefinition({ fragName, queryName }));
2648
- operationsDefinitions.push(astBuilder.ListQueryOperationDefinition({
2649
- fragName,
2650
- queryName: queryListName,
2651
- filterType: queryFilterTypeName,
2652
- dataLayer: Boolean(tinaSchema.config?.meta?.flags?.find((x) => x === "experimentalData"))
2653
- }));
2695
+ operationsDefinitions.push(
2696
+ astBuilder.QueryOperationDefinition({ fragName, queryName })
2697
+ );
2698
+ operationsDefinitions.push(
2699
+ astBuilder.ListQueryOperationDefinition({
2700
+ fragName,
2701
+ queryName: queryListName,
2702
+ filterType: queryFilterTypeName,
2703
+ dataLayer: Boolean(
2704
+ tinaSchema.config?.meta?.flags?.find((x) => x === "experimentalData")
2705
+ )
2706
+ })
2707
+ );
2654
2708
  });
2655
2709
  const queryDoc = {
2656
2710
  kind: "Document",
2657
- definitions: _3.uniqBy(extractInlineTypes(operationsDefinitions), (node) => node.name.value)
2711
+ definitions: _3.uniqBy(
2712
+ extractInlineTypes(operationsDefinitions),
2713
+ (node) => node.name.value
2714
+ )
2658
2715
  };
2659
2716
  const fragPath = path.join(rootPath, ".tina", "__generated__");
2660
2717
  await fs.outputFile(path.join(fragPath, "queries.gql"), print(queryDoc));
@@ -2665,42 +2722,71 @@ var _buildSchema = async (builder, tinaSchema) => {
2665
2722
  const queryTypeDefinitionFields = [];
2666
2723
  const mutationTypeDefinitionFields = [];
2667
2724
  const collections = tinaSchema.getCollections();
2668
- queryTypeDefinitionFields.push(astBuilder.FieldDefinition({
2669
- name: "getOptimizedQuery",
2670
- args: [
2671
- astBuilder.InputValueDefinition({
2672
- name: "queryString",
2673
- type: astBuilder.TYPES.String,
2674
- required: true
2675
- })
2676
- ],
2677
- type: astBuilder.TYPES.String
2678
- }));
2679
- queryTypeDefinitionFields.push(await builder.buildCollectionDefinition(collections));
2680
- queryTypeDefinitionFields.push(await builder.buildMultiCollectionDefinition(collections));
2725
+ queryTypeDefinitionFields.push(
2726
+ astBuilder.FieldDefinition({
2727
+ name: "getOptimizedQuery",
2728
+ args: [
2729
+ astBuilder.InputValueDefinition({
2730
+ name: "queryString",
2731
+ type: astBuilder.TYPES.String,
2732
+ required: true
2733
+ })
2734
+ ],
2735
+ type: astBuilder.TYPES.String
2736
+ })
2737
+ );
2738
+ queryTypeDefinitionFields.push(
2739
+ await builder.buildCollectionDefinition(collections)
2740
+ );
2741
+ queryTypeDefinitionFields.push(
2742
+ await builder.buildMultiCollectionDefinition(collections)
2743
+ );
2681
2744
  queryTypeDefinitionFields.push(await builder.multiNodeDocument());
2682
- queryTypeDefinitionFields.push(await builder.multiCollectionDocument(collections));
2683
- mutationTypeDefinitionFields.push(await builder.addMultiCollectionDocumentMutation());
2684
- mutationTypeDefinitionFields.push(await builder.buildUpdateCollectionDocumentMutation(collections));
2685
- mutationTypeDefinitionFields.push(await builder.buildDeleteCollectionDocumentMutation(collections));
2686
- mutationTypeDefinitionFields.push(await builder.buildCreateCollectionDocumentMutation(collections));
2745
+ queryTypeDefinitionFields.push(
2746
+ await builder.multiCollectionDocument(collections)
2747
+ );
2748
+ mutationTypeDefinitionFields.push(
2749
+ await builder.addMultiCollectionDocumentMutation()
2750
+ );
2751
+ mutationTypeDefinitionFields.push(
2752
+ await builder.buildUpdateCollectionDocumentMutation(collections)
2753
+ );
2754
+ mutationTypeDefinitionFields.push(
2755
+ await builder.buildDeleteCollectionDocumentMutation(collections)
2756
+ );
2757
+ mutationTypeDefinitionFields.push(
2758
+ await builder.buildCreateCollectionDocumentMutation(collections)
2759
+ );
2687
2760
  await sequential(collections, async (collection) => {
2688
2761
  queryTypeDefinitionFields.push(await builder.collectionDocument(collection));
2689
- mutationTypeDefinitionFields.push(await builder.updateCollectionDocumentMutation(collection));
2690
- mutationTypeDefinitionFields.push(await builder.createCollectionDocumentMutation(collection));
2691
- queryTypeDefinitionFields.push(await builder.collectionDocumentList(collection));
2762
+ mutationTypeDefinitionFields.push(
2763
+ await builder.updateCollectionDocumentMutation(collection)
2764
+ );
2765
+ mutationTypeDefinitionFields.push(
2766
+ await builder.createCollectionDocumentMutation(collection)
2767
+ );
2768
+ queryTypeDefinitionFields.push(
2769
+ await builder.collectionDocumentList(collection)
2770
+ );
2692
2771
  });
2693
- definitions.push(astBuilder.ObjectTypeDefinition({
2694
- name: "Query",
2695
- fields: queryTypeDefinitionFields
2696
- }));
2697
- definitions.push(astBuilder.ObjectTypeDefinition({
2698
- name: "Mutation",
2699
- fields: mutationTypeDefinitionFields
2700
- }));
2772
+ definitions.push(
2773
+ astBuilder.ObjectTypeDefinition({
2774
+ name: "Query",
2775
+ fields: queryTypeDefinitionFields
2776
+ })
2777
+ );
2778
+ definitions.push(
2779
+ astBuilder.ObjectTypeDefinition({
2780
+ name: "Mutation",
2781
+ fields: mutationTypeDefinitionFields
2782
+ })
2783
+ );
2701
2784
  const doc = {
2702
2785
  kind: "Document",
2703
- definitions: _3.uniqBy(extractInlineTypes(definitions), (node) => node.name.value)
2786
+ definitions: _3.uniqBy(
2787
+ extractInlineTypes(definitions),
2788
+ (node) => node.name.value
2789
+ )
2704
2790
  };
2705
2791
  return doc;
2706
2792
  };
@@ -2744,12 +2830,18 @@ var TinaFetchError = class extends Error {
2744
2830
  };
2745
2831
  var TinaQueryError = class extends TinaFetchError {
2746
2832
  constructor(args) {
2747
- super(`Error querying file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`, args);
2833
+ super(
2834
+ `Error querying file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
2835
+ args
2836
+ );
2748
2837
  }
2749
2838
  };
2750
2839
  var TinaParseDocumentError = class extends TinaFetchError {
2751
2840
  constructor(args) {
2752
- super(`Error parsing file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`, args);
2841
+ super(
2842
+ `Error parsing file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
2843
+ args
2844
+ );
2753
2845
  }
2754
2846
  toString() {
2755
2847
  return super.toString() + "\n OriginalError: \n" + this.originalError.toString();
@@ -2774,7 +2866,9 @@ var handleFetchErrorError = (e, verbose) => {
2774
2866
  // src/resolver/filter-utils.ts
2775
2867
  var resolveReferences = async (filter, fields, resolver) => {
2776
2868
  for (const fieldKey of Object.keys(filter)) {
2777
- const fieldDefinition = fields.find((f) => f.name === fieldKey);
2869
+ const fieldDefinition = fields.find(
2870
+ (f) => f.name === fieldKey
2871
+ );
2778
2872
  if (fieldDefinition) {
2779
2873
  if (fieldDefinition.type === "reference") {
2780
2874
  const { edges, values } = await resolver(filter, fieldDefinition);
@@ -2793,25 +2887,26 @@ var resolveReferences = async (filter, fields, resolver) => {
2793
2887
  }
2794
2888
  } else if (fieldDefinition.type === "object") {
2795
2889
  if (fieldDefinition.templates) {
2796
- const globalTemplates = {};
2797
- for (const template of fieldDefinition.templates) {
2798
- if (typeof template === "string") {
2799
- globalTemplates[template] = 1;
2800
- }
2801
- }
2802
2890
  for (const templateName of Object.keys(filter[fieldKey])) {
2803
- if (templateName in globalTemplates) {
2804
- throw new Error("Global templates not yet supported for queries");
2805
- }
2806
- const template = fieldDefinition.templates.find((template2) => !(typeof template2 === "string") && template2.name === templateName);
2891
+ const template = fieldDefinition.templates.find(
2892
+ (template2) => !(typeof template2 === "string") && template2.name === templateName
2893
+ );
2807
2894
  if (template) {
2808
- await resolveReferences(filter[fieldKey][templateName], template.fields, resolver);
2895
+ await resolveReferences(
2896
+ filter[fieldKey][templateName],
2897
+ template.fields,
2898
+ resolver
2899
+ );
2809
2900
  } else {
2810
2901
  throw new Error(`Template ${templateName} not found`);
2811
2902
  }
2812
2903
  }
2813
2904
  } else {
2814
- await resolveReferences(filter[fieldKey], fieldDefinition.fields, resolver);
2905
+ await resolveReferences(
2906
+ filter[fieldKey],
2907
+ fieldDefinition.fields,
2908
+ resolver
2909
+ );
2815
2910
  }
2816
2911
  }
2817
2912
  } else {
@@ -2825,35 +2920,50 @@ var collectConditionsForChildFields = (filterNode, fields, pathExpression, colle
2825
2920
  if (!childField) {
2826
2921
  throw new Error(`Unable to find type for field ${childFieldName}`);
2827
2922
  }
2828
- collectConditionsForField(childFieldName, childField, filterNode[childFieldName], pathExpression, collectCondition);
2923
+ collectConditionsForField(
2924
+ childFieldName,
2925
+ childField,
2926
+ filterNode[childFieldName],
2927
+ pathExpression,
2928
+ collectCondition
2929
+ );
2829
2930
  }
2830
2931
  };
2831
2932
  var collectConditionsForObjectField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
2832
2933
  if (field.list && field.templates) {
2833
- const globalTemplates = {};
2834
- for (const template of field.templates) {
2835
- if (typeof template === "string") {
2836
- globalTemplates[template] = 1;
2837
- }
2838
- }
2839
2934
  for (const [filterKey, childFilterNode] of Object.entries(filterNode)) {
2840
- if (filterKey in globalTemplates) {
2841
- throw new Error("Global templates not yet supported for queries");
2842
- }
2843
- const template = field.templates.find((template2) => !(typeof template2 === "string") && template2.name === filterKey);
2935
+ const template = field.templates.find(
2936
+ (template2) => !(typeof template2 === "string") && template2.name === filterKey
2937
+ );
2844
2938
  const jsonPath = `${fieldName}[?(@._template=="${filterKey}")]`;
2845
2939
  const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : jsonPath;
2846
- collectConditionsForChildFields(childFilterNode, template.fields, filterPath, collectCondition);
2940
+ collectConditionsForChildFields(
2941
+ childFilterNode,
2942
+ template.fields,
2943
+ filterPath,
2944
+ collectCondition
2945
+ );
2847
2946
  }
2848
2947
  } else {
2849
2948
  const jsonPath = `${fieldName}${field.list ? "[*]" : ""}`;
2850
2949
  const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : `${jsonPath}`;
2851
- collectConditionsForChildFields(filterNode, field.fields, filterPath, collectCondition);
2950
+ collectConditionsForChildFields(
2951
+ filterNode,
2952
+ field.fields,
2953
+ filterPath,
2954
+ collectCondition
2955
+ );
2852
2956
  }
2853
2957
  };
2854
2958
  var collectConditionsForField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
2855
2959
  if (field.type === "object") {
2856
- collectConditionsForObjectField(fieldName, field, filterNode, pathExpression, collectCondition);
2960
+ collectConditionsForObjectField(
2961
+ fieldName,
2962
+ field,
2963
+ filterNode,
2964
+ pathExpression,
2965
+ collectCondition
2966
+ );
2857
2967
  } else {
2858
2968
  collectCondition({
2859
2969
  filterPath: pathExpression ? `${pathExpression}.${fieldName}` : fieldName,
@@ -2874,7 +2984,9 @@ var resolveMediaCloudToRelative = (value, config = { useRelativeMedia: true }, s
2874
2984
  if (hasTinaMediaConfig(schema) === true) {
2875
2985
  const assetsURL = `https://${config.assetsHost}/${config.clientId}`;
2876
2986
  if (typeof value === "string" && value.includes(assetsURL)) {
2877
- const cleanMediaRoot = cleanUpSlashes(schema.config.media.tina.mediaRoot);
2987
+ const cleanMediaRoot = cleanUpSlashes(
2988
+ schema.config.media.tina.mediaRoot
2989
+ );
2878
2990
  const strippedURL = value.replace(assetsURL, "");
2879
2991
  return `${cleanMediaRoot}${strippedURL}`;
2880
2992
  }
@@ -2948,7 +3060,10 @@ var LevelProxyHandler = {
2948
3060
  };
2949
3061
  } else if (property === "sublevel") {
2950
3062
  return (...args) => {
2951
- return new Proxy(target[property].apply(target, args), LevelProxyHandler);
3063
+ return new Proxy(
3064
+ target[property].apply(target, args),
3065
+ LevelProxyHandler
3066
+ );
2952
3067
  };
2953
3068
  } else {
2954
3069
  return (...args) => target[property].apply(target, args);
@@ -2962,22 +3077,14 @@ var LevelProxy = class {
2962
3077
  };
2963
3078
 
2964
3079
  // src/database/datalayer.ts
2965
- var OP;
2966
- (function(OP2) {
2967
- OP2["EQ"] = "eq";
2968
- OP2["GT"] = "gt";
2969
- OP2["LT"] = "lt";
2970
- OP2["GTE"] = "gte";
2971
- OP2["LTE"] = "lte";
2972
- OP2["STARTS_WITH"] = "startsWith";
2973
- OP2["IN"] = "in";
2974
- })(OP || (OP = {}));
2975
3080
  var DEFAULT_COLLECTION_SORT_KEY = "__filepath__";
2976
3081
  var DEFAULT_NUMERIC_LPAD = 4;
2977
3082
  var applyPadding = (input, pad) => {
2978
3083
  if (pad) {
2979
3084
  if (Array.isArray(input)) {
2980
- return input.map((val) => String(val).padStart(pad.maxLength, pad.fillString));
3085
+ return input.map(
3086
+ (val) => String(val).padStart(pad.maxLength, pad.fillString)
3087
+ );
2981
3088
  } else {
2982
3089
  return String(input).padStart(pad.maxLength, pad.fillString);
2983
3090
  }
@@ -2990,23 +3097,23 @@ var getFilterOperator = (expression, operand) => {
2990
3097
  var inferOperatorFromFilter = (filterOperator) => {
2991
3098
  switch (filterOperator) {
2992
3099
  case "after":
2993
- return OP.GT;
3100
+ return "gt" /* GT */;
2994
3101
  case "before":
2995
- return OP.LT;
3102
+ return "lt" /* LT */;
2996
3103
  case "eq":
2997
- return OP.EQ;
3104
+ return "eq" /* EQ */;
2998
3105
  case "startsWith":
2999
- return OP.STARTS_WITH;
3106
+ return "startsWith" /* STARTS_WITH */;
3000
3107
  case "lt":
3001
- return OP.LT;
3108
+ return "lt" /* LT */;
3002
3109
  case "lte":
3003
- return OP.LTE;
3110
+ return "lte" /* LTE */;
3004
3111
  case "gt":
3005
- return OP.GT;
3112
+ return "gt" /* GT */;
3006
3113
  case "gte":
3007
- return OP.GTE;
3114
+ return "gte" /* GTE */;
3008
3115
  case "in":
3009
- return OP.IN;
3116
+ return "in" /* IN */;
3010
3117
  default:
3011
3118
  throw new Error(`unsupported filter condition: '${filterOperator}'`);
3012
3119
  }
@@ -3016,7 +3123,9 @@ var makeKeyForField = (definition, data, stringEscaper2, maxStringLength = 100)
3016
3123
  for (const field of definition.fields) {
3017
3124
  if (field.name in data && data[field.name] !== void 0 && data[field.name] !== null) {
3018
3125
  const rawValue = data[field.name];
3019
- const resolvedValue = String(field.type === "datetime" ? new Date(rawValue).getTime() : field.type === "string" ? stringEscaper2(rawValue) : rawValue).substring(0, maxStringLength);
3126
+ const resolvedValue = String(
3127
+ field.type === "datetime" ? new Date(rawValue).getTime() : field.type === "string" ? stringEscaper2(rawValue) : rawValue
3128
+ ).substring(0, maxStringLength);
3020
3129
  valueParts.push(applyPadding(resolvedValue, field.pad));
3021
3130
  } else {
3022
3131
  return null;
@@ -3034,13 +3143,17 @@ var coerceFilterChainOperands = (filterChain, escapeString = stringEscaper) => {
3034
3143
  result.push({
3035
3144
  ...filter,
3036
3145
  rightOperand: new Date(filter.rightOperand).getTime(),
3037
- leftOperand: new Date(filter.leftOperand).getTime()
3146
+ leftOperand: new Date(
3147
+ filter.leftOperand
3148
+ ).getTime()
3038
3149
  });
3039
3150
  } else {
3040
3151
  if (Array.isArray(filter.rightOperand)) {
3041
3152
  result.push({
3042
3153
  ...filter,
3043
- rightOperand: filter.rightOperand.map((operand) => new Date(operand).getTime())
3154
+ rightOperand: filter.rightOperand.map(
3155
+ (operand) => new Date(operand).getTime()
3156
+ )
3044
3157
  });
3045
3158
  } else {
3046
3159
  result.push({
@@ -3053,13 +3166,24 @@ var coerceFilterChainOperands = (filterChain, escapeString = stringEscaper) => {
3053
3166
  if (filter.leftOperand !== void 0) {
3054
3167
  result.push({
3055
3168
  ...filter,
3056
- rightOperand: applyPadding(escapeString(filter.rightOperand), filter.pad),
3057
- leftOperand: applyPadding(escapeString(filter.leftOperand), filter.pad)
3169
+ rightOperand: applyPadding(
3170
+ escapeString(filter.rightOperand),
3171
+ filter.pad
3172
+ ),
3173
+ leftOperand: applyPadding(
3174
+ escapeString(
3175
+ filter.leftOperand
3176
+ ),
3177
+ filter.pad
3178
+ )
3058
3179
  });
3059
3180
  } else {
3060
3181
  result.push({
3061
3182
  ...filter,
3062
- rightOperand: applyPadding(escapeString(filter.rightOperand), filter.pad)
3183
+ rightOperand: applyPadding(
3184
+ escapeString(filter.rightOperand),
3185
+ filter.pad
3186
+ )
3063
3187
  });
3064
3188
  }
3065
3189
  } else {
@@ -3093,7 +3217,9 @@ var makeFilter = ({
3093
3217
  return isNaN(coerced) ? Number(resolvedValue) : coerced;
3094
3218
  });
3095
3219
  } else if (dataType === "boolean") {
3096
- operands = resolvedValues.map((resolvedValue) => typeof resolvedValue === "boolean" && resolvedValue || resolvedValue === "true" || resolvedValue === "1");
3220
+ operands = resolvedValues.map(
3221
+ (resolvedValue) => typeof resolvedValue === "boolean" && resolvedValue || resolvedValue === "true" || resolvedValue === "1"
3222
+ );
3097
3223
  } else {
3098
3224
  throw new Error(`Unexpected datatype ${dataType}`);
3099
3225
  }
@@ -3101,12 +3227,14 @@ var makeFilter = ({
3101
3227
  let matches = false;
3102
3228
  if (operator) {
3103
3229
  switch (operator) {
3104
- case OP.EQ:
3105
- if (operands.findIndex((operand) => operand === filter.rightOperand) >= 0) {
3230
+ case "eq" /* EQ */:
3231
+ if (operands.findIndex(
3232
+ (operand) => operand === filter.rightOperand
3233
+ ) >= 0) {
3106
3234
  matches = true;
3107
3235
  }
3108
3236
  break;
3109
- case OP.GT:
3237
+ case "gt" /* GT */:
3110
3238
  for (const operand of operands) {
3111
3239
  if (operand > filter.rightOperand) {
3112
3240
  matches = true;
@@ -3114,7 +3242,7 @@ var makeFilter = ({
3114
3242
  }
3115
3243
  }
3116
3244
  break;
3117
- case OP.LT:
3245
+ case "lt" /* LT */:
3118
3246
  for (const operand of operands) {
3119
3247
  if (operand < filter.rightOperand) {
3120
3248
  matches = true;
@@ -3122,7 +3250,7 @@ var makeFilter = ({
3122
3250
  }
3123
3251
  }
3124
3252
  break;
3125
- case OP.GTE:
3253
+ case "gte" /* GTE */:
3126
3254
  for (const operand of operands) {
3127
3255
  if (operand >= filter.rightOperand) {
3128
3256
  matches = true;
@@ -3130,7 +3258,7 @@ var makeFilter = ({
3130
3258
  }
3131
3259
  }
3132
3260
  break;
3133
- case OP.LTE:
3261
+ case "lte" /* LTE */:
3134
3262
  for (const operand of operands) {
3135
3263
  if (operand <= filter.rightOperand) {
3136
3264
  matches = true;
@@ -3138,7 +3266,7 @@ var makeFilter = ({
3138
3266
  }
3139
3267
  }
3140
3268
  break;
3141
- case OP.IN:
3269
+ case "in" /* IN */:
3142
3270
  for (const operand of operands) {
3143
3271
  if (filter.rightOperand.indexOf(operand) >= 0) {
3144
3272
  matches = true;
@@ -3146,7 +3274,7 @@ var makeFilter = ({
3146
3274
  }
3147
3275
  }
3148
3276
  break;
3149
- case OP.STARTS_WITH:
3277
+ case "startsWith" /* STARTS_WITH */:
3150
3278
  for (const operand of operands) {
3151
3279
  if (operand.startsWith(filter.rightOperand)) {
3152
3280
  matches = true;
@@ -3162,14 +3290,14 @@ var makeFilter = ({
3162
3290
  for (const operand of operands) {
3163
3291
  let rightMatches = false;
3164
3292
  let leftMatches = false;
3165
- if (rightOperator === OP.LTE && operand <= rightOperand) {
3293
+ if (rightOperator === "lte" /* LTE */ && operand <= rightOperand) {
3166
3294
  rightMatches = true;
3167
- } else if (rightOperator === OP.LT && operand < rightOperand) {
3295
+ } else if (rightOperator === "lt" /* LT */ && operand < rightOperand) {
3168
3296
  rightMatches = true;
3169
3297
  }
3170
- if (leftOperator === OP.GTE && operand >= leftOperand) {
3298
+ if (leftOperator === "gte" /* GTE */ && operand >= leftOperand) {
3171
3299
  leftMatches = true;
3172
- } else if (leftOperator === OP.GT && operand > leftOperand) {
3300
+ } else if (leftOperator === "gt" /* GT */ && operand > leftOperand) {
3173
3301
  leftMatches = true;
3174
3302
  }
3175
3303
  if (rightMatches && leftMatches) {
@@ -3197,7 +3325,9 @@ var makeFilterChain = ({
3197
3325
  const { _type, ...keys } = filterExpression;
3198
3326
  const [key1, key2, ...extraKeys] = Object.keys(keys);
3199
3327
  if (extraKeys.length) {
3200
- throw new Error(`Unexpected keys: [${extraKeys.join(",")}] in filter expression`);
3328
+ throw new Error(
3329
+ `Unexpected keys: [${extraKeys.join(",")}] in filter expression`
3330
+ );
3201
3331
  }
3202
3332
  if (key1 && !key2) {
3203
3333
  filterChain.push({
@@ -3230,7 +3360,9 @@ var makeFilterChain = ({
3230
3360
  pad: _type === "number" ? { fillString: "0", maxLength: DEFAULT_NUMERIC_LPAD } : void 0
3231
3361
  });
3232
3362
  } else {
3233
- throw new Error(`Filter on field '${filterPath}' has invalid combination of conditions: '${key1}, ${key2}'`);
3363
+ throw new Error(
3364
+ `Filter on field '${filterPath}' has invalid combination of conditions: '${key1}, ${key2}'`
3365
+ );
3234
3366
  }
3235
3367
  }
3236
3368
  }
@@ -3245,7 +3377,7 @@ var makeFilterSuffixes = (filterChain, index) => {
3245
3377
  if (idx === -1) {
3246
3378
  return;
3247
3379
  }
3248
- if (filter.operator && filter.operator === OP.IN) {
3380
+ if (filter.operator && filter.operator === "in" /* IN */) {
3249
3381
  return;
3250
3382
  }
3251
3383
  orderedFilterChain[idx] = filter;
@@ -3267,20 +3399,34 @@ var makeFilterSuffixes = (filterChain, index) => {
3267
3399
  return;
3268
3400
  }
3269
3401
  const binaryFilter = filter;
3270
- if (binaryFilter.operator !== OP.EQ) {
3402
+ if (binaryFilter.operator !== "eq" /* EQ */) {
3271
3403
  return;
3272
3404
  }
3273
- baseFragments.push(applyPadding(orderedFilterChain[i].rightOperand, orderedFilterChain[i].pad));
3405
+ baseFragments.push(
3406
+ applyPadding(
3407
+ orderedFilterChain[i].rightOperand,
3408
+ orderedFilterChain[i].pad
3409
+ )
3410
+ );
3274
3411
  } else {
3275
3412
  if (ternaryFilter) {
3276
- leftSuffix = applyPadding(orderedFilterChain[i].leftOperand, orderedFilterChain[i].pad);
3277
- rightSuffix = applyPadding(orderedFilterChain[i].rightOperand, orderedFilterChain[i].pad);
3413
+ leftSuffix = applyPadding(
3414
+ orderedFilterChain[i].leftOperand,
3415
+ orderedFilterChain[i].pad
3416
+ );
3417
+ rightSuffix = applyPadding(
3418
+ orderedFilterChain[i].rightOperand,
3419
+ orderedFilterChain[i].pad
3420
+ );
3278
3421
  } else {
3279
3422
  const op = orderedFilterChain[i].operator;
3280
- const operand = applyPadding(orderedFilterChain[i].rightOperand, orderedFilterChain[i].pad);
3281
- if (op === OP.LT || op === OP.LTE) {
3423
+ const operand = applyPadding(
3424
+ orderedFilterChain[i].rightOperand,
3425
+ orderedFilterChain[i].pad
3426
+ );
3427
+ if (op === "lt" /* LT */ || op === "lte" /* LTE */) {
3282
3428
  rightSuffix = operand;
3283
- } else if (op === OP.GT || op === OP.GTE) {
3429
+ } else if (op === "gt" /* GT */ || op === "gte" /* GTE */) {
3284
3430
  leftSuffix = operand;
3285
3431
  } else {
3286
3432
  rightSuffix = operand;
@@ -3328,13 +3474,18 @@ var makeIndexOpsForDocument = (filepath, collection, indexDefinitions, data, opT
3328
3474
  var makeStringEscaper = (regex, replacement) => {
3329
3475
  return (input) => {
3330
3476
  if (Array.isArray(input)) {
3331
- return input.map((val) => val.replace(regex, replacement));
3477
+ return input.map(
3478
+ (val) => val.replace(regex, replacement)
3479
+ );
3332
3480
  } else {
3333
3481
  return input.replace(regex, replacement);
3334
3482
  }
3335
3483
  };
3336
3484
  };
3337
- var stringEscaper = makeStringEscaper(new RegExp(INDEX_KEY_FIELD_SEPARATOR, "gm"), encodeURIComponent(INDEX_KEY_FIELD_SEPARATOR));
3485
+ var stringEscaper = makeStringEscaper(
3486
+ new RegExp(INDEX_KEY_FIELD_SEPARATOR, "gm"),
3487
+ encodeURIComponent(INDEX_KEY_FIELD_SEPARATOR)
3488
+ );
3338
3489
 
3339
3490
  // src/resolver/index.ts
3340
3491
  var createResolver = (args) => {
@@ -3430,27 +3581,33 @@ var Resolver = class {
3430
3581
  };
3431
3582
  this.buildObjectMutations = (fieldValue, field) => {
3432
3583
  if (field.fields) {
3433
- const objectTemplate = typeof field.fields === "string" ? this.tinaSchema.getGlobalTemplate(field.fields) : field;
3584
+ const objectTemplate = field;
3434
3585
  if (Array.isArray(fieldValue)) {
3435
- return fieldValue.map((item) => this.buildFieldMutations(item, objectTemplate));
3586
+ return fieldValue.map(
3587
+ (item) => this.buildFieldMutations(item, objectTemplate)
3588
+ );
3436
3589
  } else {
3437
- return this.buildFieldMutations(fieldValue, objectTemplate);
3590
+ return this.buildFieldMutations(
3591
+ fieldValue,
3592
+ objectTemplate
3593
+ );
3438
3594
  }
3439
3595
  }
3440
3596
  if (field.templates) {
3441
3597
  if (Array.isArray(fieldValue)) {
3442
3598
  return fieldValue.map((item) => {
3443
3599
  if (typeof item === "string") {
3444
- throw new Error(`Expected object for template value for field ${field.name}`);
3600
+ throw new Error(
3601
+ `Expected object for template value for field ${field.name}`
3602
+ );
3445
3603
  }
3446
3604
  const templates = field.templates.map((templateOrTemplateName) => {
3447
- if (typeof templateOrTemplateName === "string") {
3448
- return this.tinaSchema.getGlobalTemplate(templateOrTemplateName);
3449
- }
3450
3605
  return templateOrTemplateName;
3451
3606
  });
3452
3607
  const [templateName] = Object.entries(item)[0];
3453
- const template = templates.find((template2) => template2.name === templateName);
3608
+ const template = templates.find(
3609
+ (template2) => template2.name === templateName
3610
+ );
3454
3611
  if (!template) {
3455
3612
  throw new Error(`Expected to find template ${templateName}`);
3456
3613
  }
@@ -3461,16 +3618,17 @@ var Resolver = class {
3461
3618
  });
3462
3619
  } else {
3463
3620
  if (typeof fieldValue === "string") {
3464
- throw new Error(`Expected object for template value for field ${field.name}`);
3621
+ throw new Error(
3622
+ `Expected object for template value for field ${field.name}`
3623
+ );
3465
3624
  }
3466
3625
  const templates = field.templates.map((templateOrTemplateName) => {
3467
- if (typeof templateOrTemplateName === "string") {
3468
- return this.tinaSchema.getGlobalTemplate(templateOrTemplateName);
3469
- }
3470
3626
  return templateOrTemplateName;
3471
3627
  });
3472
3628
  const [templateName] = Object.entries(fieldValue)[0];
3473
- const template = templates.find((template2) => template2.name === templateName);
3629
+ const template = templates.find(
3630
+ (template2) => template2.name === templateName
3631
+ );
3474
3632
  if (!template) {
3475
3633
  throw new Error(`Expected to find template ${templateName}`);
3476
3634
  }
@@ -3495,12 +3653,18 @@ var Resolver = class {
3495
3653
  break;
3496
3654
  case "union":
3497
3655
  const templateString = args.template;
3498
- const template = templateInfo.templates.find((template2) => lastItem(template2.namespace) === templateString);
3656
+ const template = templateInfo.templates.find(
3657
+ (template2) => lastItem(template2.namespace) === templateString
3658
+ );
3499
3659
  if (!args.template) {
3500
- throw new Error(`Must specify a template when creating content for a collection with multiple templates. Possible templates are: ${templateInfo.templates.map((t) => lastItem(t.namespace)).join(" ")}`);
3660
+ throw new Error(
3661
+ `Must specify a template when creating content for a collection with multiple templates. Possible templates are: ${templateInfo.templates.map((t) => lastItem(t.namespace)).join(" ")}`
3662
+ );
3501
3663
  }
3502
3664
  if (!template) {
3503
- throw new Error(`Expected to find template named ${templateString} in collection "${collection.name}" but none was found. Possible templates are: ${templateInfo.templates.map((t) => lastItem(t.namespace)).join(" ")}`);
3665
+ throw new Error(
3666
+ `Expected to find template named ${templateString} in collection "${collection.name}" but none was found. Possible templates are: ${templateInfo.templates.map((t) => lastItem(t.namespace)).join(" ")}`
3667
+ );
3504
3668
  }
3505
3669
  await this.database.addPendingDocument(realPath, {
3506
3670
  _template: lastItem(template.namespace)
@@ -3508,7 +3672,10 @@ var Resolver = class {
3508
3672
  }
3509
3673
  return this.getDocument(realPath);
3510
3674
  }
3511
- const params = this.buildObjectMutations(args.params[collection.name], collection);
3675
+ const params = this.buildObjectMutations(
3676
+ args.params[collection.name],
3677
+ collection
3678
+ );
3512
3679
  await this.database.put(realPath, params, collection.name);
3513
3680
  return this.getDocument(realPath);
3514
3681
  };
@@ -3527,8 +3694,15 @@ var Resolver = class {
3527
3694
  switch (templateInfo.type) {
3528
3695
  case "object":
3529
3696
  if (params2) {
3530
- const values = this.buildFieldMutations(params2, templateInfo.template);
3531
- await this.database.put(realPath, { ...oldDoc, ...values }, collection.name);
3697
+ const values = this.buildFieldMutations(
3698
+ params2,
3699
+ templateInfo.template
3700
+ );
3701
+ await this.database.put(
3702
+ realPath,
3703
+ { ...oldDoc, ...values },
3704
+ collection.name
3705
+ );
3532
3706
  }
3533
3707
  break;
3534
3708
  case "union":
@@ -3536,7 +3710,9 @@ var Resolver = class {
3536
3710
  const templateParams = params2[lastItem(template.namespace)];
3537
3711
  if (templateParams) {
3538
3712
  if (typeof templateParams === "string") {
3539
- throw new Error(`Expected to find an object for template params, but got string`);
3713
+ throw new Error(
3714
+ `Expected to find an object for template params, but got string`
3715
+ );
3540
3716
  }
3541
3717
  const values = {
3542
3718
  ...oldDoc,
@@ -3549,7 +3725,10 @@ var Resolver = class {
3549
3725
  }
3550
3726
  return this.getDocument(realPath);
3551
3727
  }
3552
- const params = this.buildObjectMutations(isCollectionSpecific ? args.params : args.params[collection.name], collection);
3728
+ const params = this.buildObjectMutations(
3729
+ isCollectionSpecific ? args.params : args.params[collection.name],
3730
+ collection
3731
+ );
3553
3732
  await this.database.put(realPath, { ...oldDoc, ...params }, collection.name);
3554
3733
  return this.getDocument(realPath);
3555
3734
  };
@@ -3568,10 +3747,19 @@ var Resolver = class {
3568
3747
  collectionLookup = Object.keys(args.params)[0];
3569
3748
  }
3570
3749
  const collectionNames = this.tinaSchema.getCollections().map((item) => item.name);
3571
- assertShape(collectionLookup, (yup3) => {
3572
- return yup3.mixed().oneOf(collectionNames);
3573
- }, `"collection" must be one of: [${collectionNames.join(", ")}] but got ${collectionLookup}`);
3574
- assertShape(args, (yup3) => yup3.object({ relativePath: yup3.string().required() }));
3750
+ assertShape(
3751
+ collectionLookup,
3752
+ (yup3) => {
3753
+ return yup3.mixed().oneOf(collectionNames);
3754
+ },
3755
+ `"collection" must be one of: [${collectionNames.join(
3756
+ ", "
3757
+ )}] but got ${collectionLookup}`
3758
+ );
3759
+ assertShape(
3760
+ args,
3761
+ (yup3) => yup3.object({ relativePath: yup3.string().required() })
3762
+ );
3575
3763
  const collection = await this.tinaSchema.getCollection(collectionLookup);
3576
3764
  const realPath = path2.join(collection?.path, args.relativePath);
3577
3765
  const alreadyExists = await this.database.documentExists(realPath);
@@ -3589,10 +3777,14 @@ var Resolver = class {
3589
3777
  }
3590
3778
  if (!alreadyExists) {
3591
3779
  if (isDeletion) {
3592
- throw new Error(`Unable to delete document, ${realPath} does not exist`);
3780
+ throw new Error(
3781
+ `Unable to delete document, ${realPath} does not exist`
3782
+ );
3593
3783
  }
3594
3784
  if (isUpdateName) {
3595
- throw new Error(`Unable to update document, ${realPath} does not exist`);
3785
+ throw new Error(
3786
+ `Unable to update document, ${realPath} does not exist`
3787
+ );
3596
3788
  }
3597
3789
  }
3598
3790
  if (isDeletion) {
@@ -3601,10 +3793,19 @@ var Resolver = class {
3601
3793
  return doc;
3602
3794
  }
3603
3795
  if (isUpdateName) {
3604
- assertShape(args, (yup3) => yup3.object({ params: yup3.object().required() }));
3605
- assertShape(args?.params, (yup3) => yup3.object({ relativePath: yup3.string().required() }));
3796
+ assertShape(
3797
+ args,
3798
+ (yup3) => yup3.object({ params: yup3.object().required() })
3799
+ );
3800
+ assertShape(
3801
+ args?.params,
3802
+ (yup3) => yup3.object({ relativePath: yup3.string().required() })
3803
+ );
3606
3804
  const doc = await this.getDocument(realPath);
3607
- const newRealPath = path2.join(collection?.path, args.params.relativePath);
3805
+ const newRealPath = path2.join(
3806
+ collection?.path,
3807
+ args.params.relativePath
3808
+ );
3608
3809
  await this.database.put(newRealPath, doc._rawData, collection.name);
3609
3810
  await this.deleteDocument(realPath);
3610
3811
  return this.getDocument(newRealPath);
@@ -3635,22 +3836,30 @@ var Resolver = class {
3635
3836
  };
3636
3837
  };
3637
3838
  this.referenceResolver = async (filter, fieldDefinition) => {
3638
- const referencedCollection = this.tinaSchema.getCollection(fieldDefinition.collections[0]);
3839
+ const referencedCollection = this.tinaSchema.getCollection(
3840
+ fieldDefinition.collections[0]
3841
+ );
3639
3842
  if (!referencedCollection) {
3640
- throw new Error(`Unable to find collection for ${fieldDefinition.collections[0]} querying ${fieldDefinition.name}`);
3843
+ throw new Error(
3844
+ `Unable to find collection for ${fieldDefinition.collections[0]} querying ${fieldDefinition.name}`
3845
+ );
3641
3846
  }
3642
- const sortKeys = Object.keys(filter[fieldDefinition.name][referencedCollection.name]);
3643
- const resolvedCollectionConnection = await this.resolveCollectionConnection({
3644
- args: {
3645
- sort: sortKeys.length === 1 ? sortKeys[0] : void 0,
3646
- filter: {
3647
- ...filter[fieldDefinition.name][referencedCollection.name]
3847
+ const sortKeys = Object.keys(
3848
+ filter[fieldDefinition.name][referencedCollection.name]
3849
+ );
3850
+ const resolvedCollectionConnection = await this.resolveCollectionConnection(
3851
+ {
3852
+ args: {
3853
+ sort: sortKeys.length === 1 ? sortKeys[0] : void 0,
3854
+ filter: {
3855
+ ...filter[fieldDefinition.name][referencedCollection.name]
3856
+ },
3857
+ first: -1
3648
3858
  },
3649
- first: -1
3650
- },
3651
- collection: referencedCollection,
3652
- hydrator: (path6) => path6
3653
- });
3859
+ collection: referencedCollection,
3860
+ hydrator: (path6) => path6
3861
+ }
3862
+ );
3654
3863
  const { edges } = resolvedCollectionConnection;
3655
3864
  const values = edges.map((edge) => edge.node);
3656
3865
  return { edges, values };
@@ -3663,14 +3872,26 @@ var Resolver = class {
3663
3872
  let conditions;
3664
3873
  if (args.filter) {
3665
3874
  if (collection.fields) {
3666
- conditions = await this.resolveFilterConditions(args.filter, collection.fields, collection.name);
3875
+ conditions = await this.resolveFilterConditions(
3876
+ args.filter,
3877
+ collection.fields,
3878
+ collection.name
3879
+ );
3667
3880
  } else if (collection.templates) {
3668
3881
  for (const templateName of Object.keys(args.filter)) {
3669
- const template = collection.templates.find((template2) => template2.name === templateName);
3882
+ const template = collection.templates.find(
3883
+ (template2) => template2.name === templateName
3884
+ );
3670
3885
  if (template) {
3671
- conditions = await this.resolveFilterConditions(args.filter[templateName], template.fields, `${collection.name}.${templateName}`);
3886
+ conditions = await this.resolveFilterConditions(
3887
+ args.filter[templateName],
3888
+ template.fields,
3889
+ `${collection.name}.${templateName}`
3890
+ );
3672
3891
  } else {
3673
- throw new Error(`Error template not found: ${templateName} in collection ${collection.name}`);
3892
+ throw new Error(
3893
+ `Error template not found: ${templateName} in collection ${collection.name}`
3894
+ );
3674
3895
  }
3675
3896
  }
3676
3897
  }
@@ -3686,7 +3907,10 @@ var Resolver = class {
3686
3907
  before: args.before,
3687
3908
  after: args.after
3688
3909
  };
3689
- const result = await this.database.query(queryOptions, hydrator ? hydrator : this.getDocument);
3910
+ const result = await this.database.query(
3911
+ queryOptions,
3912
+ hydrator ? hydrator : this.getDocument
3913
+ );
3690
3914
  const edges = result.edges;
3691
3915
  const pageInfo = result.pageInfo;
3692
3916
  return {
@@ -3723,13 +3947,25 @@ var Resolver = class {
3723
3947
  accum[fieldName] = fieldValue;
3724
3948
  break;
3725
3949
  case "image":
3726
- accum[fieldName] = resolveMediaCloudToRelative(fieldValue, this.config, this.tinaSchema.schema);
3950
+ accum[fieldName] = resolveMediaCloudToRelative(
3951
+ fieldValue,
3952
+ this.config,
3953
+ this.tinaSchema.schema
3954
+ );
3727
3955
  break;
3728
3956
  case "object":
3729
3957
  accum[fieldName] = this.buildObjectMutations(fieldValue, field);
3730
3958
  break;
3731
3959
  case "rich-text":
3732
- accum[fieldName] = stringifyMDX(fieldValue, field, (fieldValue2) => resolveMediaCloudToRelative(fieldValue2, this.config, this.tinaSchema.schema));
3960
+ accum[fieldName] = stringifyMDX(
3961
+ fieldValue,
3962
+ field,
3963
+ (fieldValue2) => resolveMediaCloudToRelative(
3964
+ fieldValue2,
3965
+ this.config,
3966
+ this.tinaSchema.schema
3967
+ )
3968
+ );
3733
3969
  break;
3734
3970
  case "reference":
3735
3971
  accum[fieldName] = fieldValue;
@@ -3761,14 +3997,28 @@ var Resolver = class {
3761
3997
  accumulator[field.name] = value;
3762
3998
  break;
3763
3999
  case "image":
3764
- accumulator[field.name] = resolveMediaRelativeToCloud(value, this.config, this.tinaSchema.schema);
4000
+ accumulator[field.name] = resolveMediaRelativeToCloud(
4001
+ value,
4002
+ this.config,
4003
+ this.tinaSchema.schema
4004
+ );
3765
4005
  break;
3766
4006
  case "rich-text":
3767
- const tree = parseMDX(value, field, (value2) => resolveMediaRelativeToCloud(value2, this.config, this.tinaSchema.schema));
4007
+ const tree = parseMDX(
4008
+ value,
4009
+ field,
4010
+ (value2) => resolveMediaRelativeToCloud(
4011
+ value2,
4012
+ this.config,
4013
+ this.tinaSchema.schema
4014
+ )
4015
+ );
3768
4016
  if (tree?.children[0]?.type === "invalid_markdown") {
3769
4017
  if (this.isAudit) {
3770
4018
  const invalidNode = tree?.children[0];
3771
- throw new GraphQLError2(`${invalidNode?.message}${invalidNode.position ? ` at line ${invalidNode.position.start.line}, column ${invalidNode.position.start.column}` : ""}`);
4019
+ throw new GraphQLError2(
4020
+ `${invalidNode?.message}${invalidNode.position ? ` at line ${invalidNode.position.start.line}, column ${invalidNode.position.start.column}` : ""}`
4021
+ );
3772
4022
  }
3773
4023
  }
3774
4024
  accumulator[field.name] = tree;
@@ -3778,7 +4028,10 @@ var Resolver = class {
3778
4028
  if (!value) {
3779
4029
  return;
3780
4030
  }
3781
- assertShape(value, (yup3) => yup3.array().of(yup3.object().required()));
4031
+ assertShape(
4032
+ value,
4033
+ (yup3) => yup3.array().of(yup3.object().required())
4034
+ );
3782
4035
  accumulator[field.name] = await sequential(value, async (item) => {
3783
4036
  const template = await this.tinaSchema.getTemplateForData({
3784
4037
  data: item,
@@ -3826,16 +4079,22 @@ var Resolver = class {
3826
4079
  };
3827
4080
  this.buildParams = (args) => {
3828
4081
  try {
3829
- assertShape(args, (yup3) => yup3.object({
3830
- collection: yup3.string().required(),
3831
- params: yup3.object().required()
3832
- }));
4082
+ assertShape(
4083
+ args,
4084
+ (yup3) => yup3.object({
4085
+ collection: yup3.string().required(),
4086
+ params: yup3.object().required()
4087
+ })
4088
+ );
3833
4089
  return args.params[args.collection];
3834
4090
  } catch (e) {
3835
4091
  }
3836
- assertShape(args, (yup3) => yup3.object({
3837
- params: yup3.object().required()
3838
- }));
4092
+ assertShape(
4093
+ args,
4094
+ (yup3) => yup3.object({
4095
+ params: yup3.object().required()
4096
+ })
4097
+ );
3839
4098
  return args.params;
3840
4099
  };
3841
4100
  this.config = init.config;
@@ -3850,17 +4109,29 @@ var Resolver = class {
3850
4109
  throw new Error("Error parsing filter - unable to generate filterPath");
3851
4110
  }
3852
4111
  if (!condition.filterExpression) {
3853
- throw new Error(`Error parsing filter - missing expression for ${condition.filterPath}`);
4112
+ throw new Error(
4113
+ `Error parsing filter - missing expression for ${condition.filterPath}`
4114
+ );
3854
4115
  }
3855
4116
  conditions.push(condition);
3856
4117
  };
3857
4118
  await resolveReferences(filter, fields, this.referenceResolver);
3858
4119
  for (const fieldName of Object.keys(filter)) {
3859
- const field = fields.find((field2) => field2.name === fieldName);
4120
+ const field = fields.find(
4121
+ (field2) => field2.name === fieldName
4122
+ );
3860
4123
  if (!field) {
3861
- throw new Error(`${fieldName} not found in collection ${collectionName}`);
4124
+ throw new Error(
4125
+ `${fieldName} not found in collection ${collectionName}`
4126
+ );
3862
4127
  }
3863
- collectConditionsForField(fieldName, field, filter[fieldName], "", conditionCollector);
4128
+ collectConditionsForField(
4129
+ fieldName,
4130
+ field,
4131
+ filter[fieldName],
4132
+ "",
4133
+ conditionCollector
4134
+ );
3864
4135
  }
3865
4136
  return conditions;
3866
4137
  }
@@ -3929,30 +4200,52 @@ var resolve = async ({
3929
4200
  return value;
3930
4201
  }
3931
4202
  if (info.fieldName === "collections") {
3932
- const collectionNode2 = info.fieldNodes.find((x) => x.name.value === "collections");
3933
- const hasDocuments2 = collectionNode2.selectionSet.selections.find((x) => {
3934
- return x?.name?.value === "documents";
3935
- });
4203
+ const collectionNode2 = info.fieldNodes.find(
4204
+ (x) => x.name.value === "collections"
4205
+ );
4206
+ const hasDocuments2 = collectionNode2.selectionSet.selections.find(
4207
+ (x) => {
4208
+ return x?.name?.value === "documents";
4209
+ }
4210
+ );
3936
4211
  return tinaSchema.getCollections().map((collection) => {
3937
- return resolver.resolveCollection(args, collection.name, Boolean(hasDocuments2));
4212
+ return resolver.resolveCollection(
4213
+ args,
4214
+ collection.name,
4215
+ Boolean(hasDocuments2)
4216
+ );
3938
4217
  });
3939
4218
  }
3940
- const collectionNode = info.fieldNodes.find((x) => x.name.value === "collection");
3941
- const hasDocuments = collectionNode.selectionSet.selections.find((x) => {
3942
- return x?.name?.value === "documents";
3943
- });
3944
- return resolver.resolveCollection(args, args.collection, Boolean(hasDocuments));
4219
+ const collectionNode = info.fieldNodes.find(
4220
+ (x) => x.name.value === "collection"
4221
+ );
4222
+ const hasDocuments = collectionNode.selectionSet.selections.find(
4223
+ (x) => {
4224
+ return x?.name?.value === "documents";
4225
+ }
4226
+ );
4227
+ return resolver.resolveCollection(
4228
+ args,
4229
+ args.collection,
4230
+ Boolean(hasDocuments)
4231
+ );
3945
4232
  }
3946
4233
  if (info.fieldName === "getOptimizedQuery") {
3947
4234
  try {
3948
- const [optimizedQuery] = optimizeDocuments(info.schema, [parse(args.queryString)], {
3949
- assumeValid: true,
3950
- includeFragments: false,
3951
- noLocation: true
3952
- });
4235
+ const [optimizedQuery] = optimizeDocuments(
4236
+ info.schema,
4237
+ [parse(args.queryString)],
4238
+ {
4239
+ assumeValid: true,
4240
+ includeFragments: false,
4241
+ noLocation: true
4242
+ }
4243
+ );
3953
4244
  return print2(optimizedQuery);
3954
4245
  } catch (e) {
3955
- throw new Error(`Invalid query provided, Error message: ${e.message}`);
4246
+ throw new Error(
4247
+ `Invalid query provided, Error message: ${e.message}`
4248
+ );
3956
4249
  }
3957
4250
  }
3958
4251
  if (!lookup) {
@@ -3961,7 +4254,10 @@ var resolve = async ({
3961
4254
  const isCreation = lookup[info.fieldName] === "create";
3962
4255
  switch (lookup.resolveType) {
3963
4256
  case "nodeDocument":
3964
- assertShape(args, (yup3) => yup3.object({ id: yup3.string().required() }));
4257
+ assertShape(
4258
+ args,
4259
+ (yup3) => yup3.object({ id: yup3.string().required() })
4260
+ );
3965
4261
  return resolver.getDocument(args.id);
3966
4262
  case "multiCollectionDocument":
3967
4263
  if (typeof value === "string") {
@@ -4016,7 +4312,9 @@ var resolve = async ({
4016
4312
  collection: value.collection
4017
4313
  });
4018
4314
  } else {
4019
- throw new Error(`Expected an array for result of ${info.fieldName} at ${info.path}`);
4315
+ throw new Error(
4316
+ `Expected an array for result of ${info.fieldName} at ${info.path}`
4317
+ );
4020
4318
  }
4021
4319
  case "collectionDocument":
4022
4320
  if (value) {
@@ -4120,12 +4418,16 @@ var stringifyFile = (content, format, keepTemplateKey, markdownParseConfig) => {
4120
4418
  case ".markdown":
4121
4419
  case ".mdx":
4122
4420
  case ".md":
4123
- const ok = matter.stringify(typeof $_body === "undefined" ? "" : `
4124
- ${$_body}`, strippedContent, {
4125
- language: markdownParseConfig?.frontmatterFormat || "yaml",
4126
- engines: matterEngines,
4127
- delimiters: markdownParseConfig?.frontmatterDelimiters || "---"
4128
- });
4421
+ const ok = matter.stringify(
4422
+ typeof $_body === "undefined" ? "" : `
4423
+ ${$_body}`,
4424
+ strippedContent,
4425
+ {
4426
+ language: markdownParseConfig?.frontmatterFormat || "yaml",
4427
+ engines: matterEngines,
4428
+ delimiters: markdownParseConfig?.frontmatterDelimiters || "---"
4429
+ }
4430
+ );
4129
4431
  return ok;
4130
4432
  case ".json":
4131
4433
  return JSON.stringify(strippedContent, null, 2);
@@ -4176,6 +4478,74 @@ var parseFile = (content, format, yupSchema, markdownParseConfig) => {
4176
4478
  };
4177
4479
  var normalizePath = (filepath) => filepath.replace(/\\/g, "/");
4178
4480
 
4481
+ // src/database/alias-utils.ts
4482
+ var replaceNameOverrides = (template, obj) => {
4483
+ if (template.list) {
4484
+ return obj.map((item) => {
4485
+ return _replaceNameOverrides(
4486
+ getTemplateForData(template, item).fields,
4487
+ item
4488
+ );
4489
+ });
4490
+ } else {
4491
+ return _replaceNameOverrides(getTemplateForData(template, obj).fields, obj);
4492
+ }
4493
+ };
4494
+ var _replaceNameOverrides = (fields, obj) => {
4495
+ const output = {};
4496
+ Object.keys(obj).forEach((key) => {
4497
+ const field = fields.find(
4498
+ (fieldWithMatchingAlias) => (fieldWithMatchingAlias?.nameOverride || fieldWithMatchingAlias?.name) === key
4499
+ );
4500
+ output[field?.name || key] = field?.type == "object" ? replaceNameOverrides(field, obj[key]) : obj[key];
4501
+ });
4502
+ return output;
4503
+ };
4504
+ var getTemplateKey = (field) => {
4505
+ const DEFAULT_TEMPLATE_KEY = "_template";
4506
+ if (field.templates?.length) {
4507
+ const templateField = field.templates[0]?.fields?.find(
4508
+ (field2) => field2.name === DEFAULT_TEMPLATE_KEY
4509
+ );
4510
+ return templateField?.alias || DEFAULT_TEMPLATE_KEY;
4511
+ }
4512
+ return DEFAULT_TEMPLATE_KEY;
4513
+ };
4514
+ var getTemplateForData = (field, data) => {
4515
+ if (field.templates?.length) {
4516
+ const templateKey = getTemplateKey(field);
4517
+ if (data[templateKey]) {
4518
+ return field.templates.find(
4519
+ (template) => template.name === data[templateKey]
4520
+ );
4521
+ }
4522
+ } else {
4523
+ return field;
4524
+ }
4525
+ throw new Error("No template found for field " + field.name);
4526
+ };
4527
+ var applyNameOverrides = (template, obj) => {
4528
+ if (template.list) {
4529
+ return obj.map((item) => {
4530
+ return _applyNameOverrides(
4531
+ getTemplateForData(template, item).fields,
4532
+ item
4533
+ );
4534
+ });
4535
+ } else {
4536
+ return _applyNameOverrides(getTemplateForData(template, obj).fields, obj);
4537
+ }
4538
+ };
4539
+ var _applyNameOverrides = (fields, obj) => {
4540
+ const output = {};
4541
+ Object.keys(obj).forEach((key) => {
4542
+ const field = fields.find((field2) => field2.name === key);
4543
+ const outputKey = field?.nameOverride || key;
4544
+ output[outputKey] = field?.type === "object" ? applyNameOverrides(field, obj[key]) : obj[key];
4545
+ });
4546
+ return output;
4547
+ };
4548
+
4179
4549
  // src/database/index.ts
4180
4550
  var createDatabase = (config) => {
4181
4551
  return new Database({
@@ -4203,7 +4573,10 @@ var Database = class {
4203
4573
  } else {
4204
4574
  const tinaSchema = await this.getSchema(this.level);
4205
4575
  const extension = path3.extname(filepath);
4206
- const contentObject = await this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS).get(normalizePath(filepath));
4576
+ const contentObject = await this.level.sublevel(
4577
+ CONTENT_ROOT_PREFIX,
4578
+ SUBLEVEL_OPTIONS
4579
+ ).get(normalizePath(filepath));
4207
4580
  if (!contentObject) {
4208
4581
  throw new GraphQLError4(`Unable to find record ${filepath}`);
4209
4582
  }
@@ -4237,8 +4610,13 @@ var Database = class {
4237
4610
  };
4238
4611
  this.addPendingDocument = async (filepath, data) => {
4239
4612
  await this.initLevel();
4240
- const { stringifiedFile, payload } = await this.stringifyFile(filepath, data);
4613
+ const dataFields = await this.formatBodyOnPayload(filepath, data);
4241
4614
  const collection = await this.collectionForPath(filepath);
4615
+ const stringifiedFile = await this.stringifyFile(
4616
+ filepath,
4617
+ dataFields,
4618
+ collection
4619
+ );
4242
4620
  let collectionIndexDefinitions;
4243
4621
  if (collection) {
4244
4622
  const indexDefinitions = await this.getIndexDefinitions(this.level);
@@ -4249,49 +4627,95 @@ var Database = class {
4249
4627
  await this.bridge.put(normalizedPath, stringifiedFile);
4250
4628
  }
4251
4629
  await this.onPut(normalizedPath, stringifiedFile);
4252
- const putOps = makeIndexOpsForDocument(normalizedPath, collection?.name, collectionIndexDefinitions, payload, "put", this.level);
4253
- const existingItem = await this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS).get(normalizedPath);
4254
- const delOps = existingItem ? makeIndexOpsForDocument(normalizedPath, collection?.name, collectionIndexDefinitions, existingItem, "del", this.level) : [];
4630
+ const putOps = makeIndexOpsForDocument(
4631
+ normalizedPath,
4632
+ collection?.name,
4633
+ collectionIndexDefinitions,
4634
+ dataFields,
4635
+ "put",
4636
+ this.level
4637
+ );
4638
+ const existingItem = await this.level.sublevel(
4639
+ CONTENT_ROOT_PREFIX,
4640
+ SUBLEVEL_OPTIONS
4641
+ ).get(normalizedPath);
4642
+ const delOps = existingItem ? makeIndexOpsForDocument(
4643
+ normalizedPath,
4644
+ collection?.name,
4645
+ collectionIndexDefinitions,
4646
+ existingItem,
4647
+ "del",
4648
+ this.level
4649
+ ) : [];
4255
4650
  const ops = [
4256
4651
  ...delOps,
4257
4652
  ...putOps,
4258
4653
  {
4259
4654
  type: "put",
4260
4655
  key: normalizedPath,
4261
- value: payload,
4262
- sublevel: this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS)
4656
+ value: dataFields,
4657
+ sublevel: this.level.sublevel(
4658
+ CONTENT_ROOT_PREFIX,
4659
+ SUBLEVEL_OPTIONS
4660
+ )
4263
4661
  }
4264
4662
  ];
4265
4663
  await this.level.batch(ops);
4266
4664
  };
4267
- this.put = async (filepath, data, collection) => {
4665
+ this.put = async (filepath, data, collectionName) => {
4268
4666
  await this.initLevel();
4269
4667
  try {
4270
4668
  if (SYSTEM_FILES.includes(filepath)) {
4271
4669
  throw new Error(`Unexpected put for config file ${filepath}`);
4272
4670
  } else {
4273
4671
  let collectionIndexDefinitions;
4274
- if (collection) {
4672
+ if (collectionName) {
4275
4673
  const indexDefinitions = await this.getIndexDefinitions(this.level);
4276
- collectionIndexDefinitions = indexDefinitions?.[collection];
4674
+ collectionIndexDefinitions = indexDefinitions?.[collectionName];
4277
4675
  }
4278
4676
  const normalizedPath = normalizePath(filepath);
4279
- const { stringifiedFile, payload } = await this.stringifyFile(filepath, data);
4677
+ const dataFields = await this.formatBodyOnPayload(filepath, data);
4678
+ const collection = await this.collectionForPath(filepath);
4679
+ const stringifiedFile = await this.stringifyFile(
4680
+ filepath,
4681
+ dataFields,
4682
+ collection
4683
+ );
4280
4684
  if (this.bridge) {
4281
4685
  await this.bridge.put(normalizedPath, stringifiedFile);
4282
4686
  }
4283
4687
  await this.onPut(normalizedPath, stringifiedFile);
4284
- const putOps = makeIndexOpsForDocument(normalizedPath, collection, collectionIndexDefinitions, payload, "put", this.level);
4285
- const existingItem = await this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS).get(normalizedPath);
4286
- const delOps = existingItem ? makeIndexOpsForDocument(normalizedPath, collection, collectionIndexDefinitions, existingItem, "del", this.level) : [];
4688
+ const putOps = makeIndexOpsForDocument(
4689
+ normalizedPath,
4690
+ collectionName,
4691
+ collectionIndexDefinitions,
4692
+ dataFields,
4693
+ "put",
4694
+ this.level
4695
+ );
4696
+ const existingItem = await this.level.sublevel(
4697
+ CONTENT_ROOT_PREFIX,
4698
+ SUBLEVEL_OPTIONS
4699
+ ).get(normalizedPath);
4700
+ const delOps = existingItem ? makeIndexOpsForDocument(
4701
+ normalizedPath,
4702
+ collectionName,
4703
+ collectionIndexDefinitions,
4704
+ existingItem,
4705
+ "del",
4706
+ this.level
4707
+ ) : [];
4287
4708
  const ops = [
4288
4709
  ...delOps,
4289
4710
  ...putOps,
4290
4711
  {
4291
4712
  type: "put",
4292
4713
  key: normalizedPath,
4293
- value: payload,
4294
- sublevel: this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS)
4714
+ value: dataFields,
4715
+ sublevel: this.level.sublevel(
4716
+ CONTENT_ROOT_PREFIX,
4717
+ SUBLEVEL_OPTIONS
4718
+ )
4295
4719
  }
4296
4720
  ];
4297
4721
  await this.level.batch(ops);
@@ -4301,94 +4725,109 @@ var Database = class {
4301
4725
  throw new TinaFetchError(`Error in PUT for ${filepath}`, {
4302
4726
  originalError: error,
4303
4727
  file: filepath,
4304
- collection,
4728
+ collection: collectionName,
4305
4729
  stack: error.stack
4306
4730
  });
4307
4731
  }
4308
4732
  };
4309
- this.stringifyFile = async (filepath, data) => {
4310
- if (SYSTEM_FILES.includes(filepath)) {
4311
- throw new Error(`Unexpected put for config file ${filepath}`);
4312
- } else {
4313
- const tinaSchema = await this.getSchema(this.level);
4314
- const collection = tinaSchema.getCollectionByFullPath(filepath);
4315
- const templateInfo = await tinaSchema.getTemplatesForCollectable(collection);
4316
- let template;
4317
- if (templateInfo.type === "object") {
4318
- template = templateInfo.template;
4319
- }
4320
- if (templateInfo.type === "union") {
4321
- if (hasOwnProperty(data, "_template")) {
4322
- template = templateInfo.templates.find((t) => lastItem(t.namespace) === data._template);
4323
- } else {
4324
- throw new Error(`Expected _template to be provided for document in an ambiguous collection`);
4733
+ this.formatBodyOnPayload = async (filepath, data) => {
4734
+ const tinaSchema = await this.getSchema(this.level);
4735
+ const collection = tinaSchema.getCollectionByFullPath(filepath);
4736
+ const { template } = await this.getTemplateDetailsForFile(collection, data);
4737
+ const bodyField = template.fields.find((field) => {
4738
+ if (field.type === "string" || field.type === "rich-text") {
4739
+ if (field.isBody) {
4740
+ return true;
4325
4741
  }
4326
4742
  }
4327
- if (!template) {
4328
- throw new Error(`Unable to determine template`);
4329
- }
4330
- const field = template.fields.find((field2) => {
4331
- if (field2.type === "string" || field2.type === "rich-text") {
4332
- if (field2.isBody) {
4333
- return true;
4334
- }
4743
+ return false;
4744
+ });
4745
+ let payload = {};
4746
+ if (["md", "mdx"].includes(collection.format) && bodyField) {
4747
+ Object.entries(data).forEach(([key, value]) => {
4748
+ if (key !== bodyField.name) {
4749
+ payload[key] = value;
4335
4750
  }
4336
- return false;
4337
4751
  });
4338
- let payload = {};
4339
- if (["md", "mdx"].includes(collection.format) && field) {
4340
- Object.entries(data).forEach(([key, value]) => {
4341
- if (key !== field.name) {
4342
- payload[key] = value;
4343
- }
4344
- });
4345
- payload["$_body"] = data[field.name];
4346
- } else {
4347
- payload = data;
4348
- }
4349
- const extension = path3.extname(filepath);
4350
- const stringifiedFile = stringifyFile(payload, extension, templateInfo.type === "union", {
4752
+ payload["$_body"] = data[bodyField.name];
4753
+ } else {
4754
+ payload = data;
4755
+ }
4756
+ return payload;
4757
+ };
4758
+ this.stringifyFile = async (filepath, payload, collection) => {
4759
+ const templateDetails = await this.getTemplateDetailsForFile(
4760
+ collection,
4761
+ payload
4762
+ );
4763
+ const writeTemplateKey = templateDetails.info.type === "union";
4764
+ const aliasedData = applyNameOverrides(templateDetails.template, payload);
4765
+ const extension = path3.extname(filepath);
4766
+ const stringifiedFile = stringifyFile(
4767
+ aliasedData,
4768
+ extension,
4769
+ writeTemplateKey,
4770
+ {
4351
4771
  frontmatterFormat: collection?.frontmatterFormat,
4352
4772
  frontmatterDelimiters: collection?.frontmatterDelimiters
4353
- });
4354
- return {
4355
- stringifiedFile,
4356
- payload,
4357
- keepTemplateKey: templateInfo.type === "union"
4358
- };
4359
- }
4773
+ }
4774
+ );
4775
+ return stringifiedFile;
4360
4776
  };
4361
4777
  this.flush = async (filepath) => {
4362
4778
  const data = await this.get(filepath);
4363
- const { stringifiedFile } = await this.stringifyFile(filepath, data);
4779
+ const dataFields = await this.formatBodyOnPayload(filepath, data);
4780
+ const collection = await this.collectionForPath(filepath);
4781
+ const stringifiedFile = await this.stringifyFile(
4782
+ filepath,
4783
+ dataFields,
4784
+ collection
4785
+ );
4364
4786
  return stringifiedFile;
4365
4787
  };
4366
4788
  this.getLookup = async (returnType) => {
4367
4789
  await this.initLevel();
4368
- const lookupPath = normalizePath(path3.join(this.getGeneratedFolder(), `_lookup.json`));
4790
+ const lookupPath = normalizePath(
4791
+ path3.join(this.getGeneratedFolder(), `_lookup.json`)
4792
+ );
4369
4793
  if (!this._lookup) {
4370
- const _lookup = await this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS).get(lookupPath);
4794
+ const _lookup = await this.level.sublevel(
4795
+ CONTENT_ROOT_PREFIX,
4796
+ SUBLEVEL_OPTIONS
4797
+ ).get(lookupPath);
4371
4798
  this._lookup = _lookup;
4372
4799
  }
4373
4800
  return this._lookup[returnType];
4374
4801
  };
4375
4802
  this.getGraphQLSchema = async () => {
4376
4803
  await this.initLevel();
4377
- const graphqlPath = normalizePath(path3.join(this.getGeneratedFolder(), `_graphql.json`));
4378
- return await this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS).get(graphqlPath);
4804
+ const graphqlPath = normalizePath(
4805
+ path3.join(this.getGeneratedFolder(), `_graphql.json`)
4806
+ );
4807
+ return await this.level.sublevel(
4808
+ CONTENT_ROOT_PREFIX,
4809
+ SUBLEVEL_OPTIONS
4810
+ ).get(graphqlPath);
4379
4811
  };
4380
4812
  this.getGraphQLSchemaFromBridge = async () => {
4381
4813
  if (!this.bridge) {
4382
4814
  throw new Error(`No bridge configured`);
4383
4815
  }
4384
- const graphqlPath = normalizePath(path3.join(this.getGeneratedFolder(), `_graphql.json`));
4816
+ const graphqlPath = normalizePath(
4817
+ path3.join(this.getGeneratedFolder(), `_graphql.json`)
4818
+ );
4385
4819
  const _graphql = await this.bridge.get(graphqlPath);
4386
4820
  return JSON.parse(_graphql);
4387
4821
  };
4388
4822
  this.getTinaSchema = async (level) => {
4389
4823
  await this.initLevel();
4390
- const schemaPath = normalizePath(path3.join(this.getGeneratedFolder(), `_schema.json`));
4391
- return await (level || this.level).sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS).get(schemaPath);
4824
+ const schemaPath = normalizePath(
4825
+ path3.join(this.getGeneratedFolder(), `_schema.json`)
4826
+ );
4827
+ return await (level || this.level).sublevel(
4828
+ CONTENT_ROOT_PREFIX,
4829
+ SUBLEVEL_OPTIONS
4830
+ ).get(schemaPath);
4392
4831
  };
4393
4832
  this.getSchema = async (level) => {
4394
4833
  if (this.tinaSchema) {
@@ -4431,7 +4870,9 @@ var Database = class {
4431
4870
  indexDefinitions[index.name] = {
4432
4871
  fields: index.fields.map((indexField) => ({
4433
4872
  name: indexField.name,
4434
- type: collection.fields.find((field) => indexField.name === field.name)?.type
4873
+ type: collection.fields.find(
4874
+ (field) => indexField.name === field.name
4875
+ )?.type
4435
4876
  }))
4436
4877
  };
4437
4878
  }
@@ -4481,12 +4922,17 @@ var Database = class {
4481
4922
  const allIndexDefinitions = await this.getIndexDefinitions(this.level);
4482
4923
  const indexDefinitions = allIndexDefinitions?.[queryOptions.collection];
4483
4924
  if (!indexDefinitions) {
4484
- throw new Error(`No indexDefinitions for collection ${queryOptions.collection}`);
4925
+ throw new Error(
4926
+ `No indexDefinitions for collection ${queryOptions.collection}`
4927
+ );
4485
4928
  }
4486
4929
  const filterChain = coerceFilterChainOperands(rawFilterChain);
4487
4930
  const indexDefinition = sort && indexDefinitions?.[sort];
4488
4931
  const filterSuffixes = indexDefinition && makeFilterSuffixes(filterChain, indexDefinition);
4489
- const rootLevel = this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS);
4932
+ const rootLevel = this.level.sublevel(
4933
+ CONTENT_ROOT_PREFIX,
4934
+ SUBLEVEL_OPTIONS
4935
+ );
4490
4936
  const sublevel = indexDefinition ? this.level.sublevel(collection, SUBLEVEL_OPTIONS).sublevel(sort, SUBLEVEL_OPTIONS) : rootLevel;
4491
4937
  if (!query.gt && !query.gte) {
4492
4938
  query.gte = filterSuffixes?.left ? filterSuffixes.left : "";
@@ -4509,7 +4955,9 @@ var Database = class {
4509
4955
  continue;
4510
4956
  }
4511
4957
  const filepath = matcher.groups["_filepath_"];
4512
- if (!itemFilter(filterSuffixes ? matcher.groups : indexDefinition ? await rootLevel.get(filepath) : value)) {
4958
+ if (!itemFilter(
4959
+ filterSuffixes ? matcher.groups : indexDefinition ? await rootLevel.get(filepath) : value
4960
+ )) {
4513
4961
  continue;
4514
4962
  }
4515
4963
  if (limit !== -1 && edges.length >= limit) {
@@ -4558,8 +5006,14 @@ var Database = class {
4558
5006
  tinaSchema
4559
5007
  }) => {
4560
5008
  if (this.bridge && this.bridge.supportsBuilding()) {
4561
- await this.bridge.putConfig(normalizePath(path3.join(this.getGeneratedFolder(), `_graphql.json`)), JSON.stringify(graphQLSchema));
4562
- await this.bridge.putConfig(normalizePath(path3.join(this.getGeneratedFolder(), `_schema.json`)), JSON.stringify(tinaSchema.schema));
5009
+ await this.bridge.putConfig(
5010
+ normalizePath(path3.join(this.getGeneratedFolder(), `_graphql.json`)),
5011
+ JSON.stringify(graphQLSchema)
5012
+ );
5013
+ await this.bridge.putConfig(
5014
+ normalizePath(path3.join(this.getGeneratedFolder(), `_schema.json`)),
5015
+ JSON.stringify(tinaSchema.schema)
5016
+ );
4563
5017
  }
4564
5018
  };
4565
5019
  this.indexContent = async ({
@@ -4572,21 +5026,37 @@ var Database = class {
4572
5026
  }
4573
5027
  await this.initLevel();
4574
5028
  await this.indexStatusCallbackWrapper(async () => {
4575
- const lookup = lookupFromLockFile || JSON.parse(await this.bridge.get(normalizePath(path3.join(this.getGeneratedFolder(), "_lookup.json"))));
5029
+ const lookup = lookupFromLockFile || JSON.parse(
5030
+ await this.bridge.get(
5031
+ normalizePath(path3.join(this.getGeneratedFolder(), "_lookup.json"))
5032
+ )
5033
+ );
4576
5034
  let nextLevel;
4577
5035
  let nextVersion;
4578
5036
  if (!this.config.version) {
4579
5037
  await this.level.clear();
4580
5038
  nextLevel = this.level;
4581
5039
  } else {
4582
- const version2 = await this.getDatabaseVersion();
4583
- nextVersion = version2 ? `${parseInt(version2) + 1}` : "0";
5040
+ const version = await this.getDatabaseVersion();
5041
+ nextVersion = version ? `${parseInt(version) + 1}` : "0";
4584
5042
  nextLevel = this.rootLevel.sublevel(nextVersion, SUBLEVEL_OPTIONS);
4585
5043
  }
4586
- const contentRootLevel = nextLevel.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS);
4587
- await contentRootLevel.put(normalizePath(path3.join(this.getGeneratedFolder(), "_graphql.json")), graphQLSchema);
4588
- await contentRootLevel.put(normalizePath(path3.join(this.getGeneratedFolder(), "_schema.json")), tinaSchema.schema);
4589
- await contentRootLevel.put(normalizePath(path3.join(this.getGeneratedFolder(), "_lookup.json")), lookup);
5044
+ const contentRootLevel = nextLevel.sublevel(
5045
+ CONTENT_ROOT_PREFIX,
5046
+ SUBLEVEL_OPTIONS
5047
+ );
5048
+ await contentRootLevel.put(
5049
+ normalizePath(path3.join(this.getGeneratedFolder(), "_graphql.json")),
5050
+ graphQLSchema
5051
+ );
5052
+ await contentRootLevel.put(
5053
+ normalizePath(path3.join(this.getGeneratedFolder(), "_schema.json")),
5054
+ tinaSchema.schema
5055
+ );
5056
+ await contentRootLevel.put(
5057
+ normalizePath(path3.join(this.getGeneratedFolder(), "_lookup.json")),
5058
+ lookup
5059
+ );
4590
5060
  await this._indexAllContent(nextLevel);
4591
5061
  if (this.config.version) {
4592
5062
  await this.updateDatabaseVersion(nextVersion);
@@ -4609,7 +5079,12 @@ var Database = class {
4609
5079
  await this.indexStatusCallbackWrapper(async () => {
4610
5080
  const { pathsByCollection, nonCollectionPaths, collections } = await this.partitionPathsByCollection(documentPaths);
4611
5081
  for (const collection of Object.keys(pathsByCollection)) {
4612
- await _deleteIndexContent(this, pathsByCollection[collection], enqueueOps, collections[collection]);
5082
+ await _deleteIndexContent(
5083
+ this,
5084
+ pathsByCollection[collection],
5085
+ enqueueOps,
5086
+ collections[collection]
5087
+ );
4613
5088
  }
4614
5089
  await _deleteIndexContent(this, nonCollectionPaths, enqueueOps, null);
4615
5090
  });
@@ -4629,7 +5104,13 @@ var Database = class {
4629
5104
  await this.indexStatusCallbackWrapper(async () => {
4630
5105
  const { pathsByCollection, nonCollectionPaths, collections } = await this.partitionPathsByCollection(documentPaths);
4631
5106
  for (const collection of Object.keys(pathsByCollection)) {
4632
- await _indexContent(this, this.level, pathsByCollection[collection], enqueueOps, collections[collection]);
5107
+ await _indexContent(
5108
+ this,
5109
+ this.level,
5110
+ pathsByCollection[collection],
5111
+ enqueueOps,
5112
+ collections[collection]
5113
+ );
4633
5114
  }
4634
5115
  await _indexContent(this, this.level, nonCollectionPaths, enqueueOps);
4635
5116
  });
@@ -4645,13 +5126,26 @@ var Database = class {
4645
5126
  const indexDefinitions = await this.getIndexDefinitions(this.level);
4646
5127
  collectionIndexDefinitions = indexDefinitions?.[collection.name];
4647
5128
  }
4648
- this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS);
5129
+ this.level.sublevel(
5130
+ CONTENT_ROOT_PREFIX,
5131
+ SUBLEVEL_OPTIONS
5132
+ );
4649
5133
  const itemKey = normalizePath(filepath);
4650
- const rootSublevel = this.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS);
5134
+ const rootSublevel = this.level.sublevel(
5135
+ CONTENT_ROOT_PREFIX,
5136
+ SUBLEVEL_OPTIONS
5137
+ );
4651
5138
  const item = await rootSublevel.get(itemKey);
4652
5139
  if (item) {
4653
5140
  await this.level.batch([
4654
- ...makeIndexOpsForDocument(filepath, collection.name, collectionIndexDefinitions, item, "del", this.level),
5141
+ ...makeIndexOpsForDocument(
5142
+ filepath,
5143
+ collection.name,
5144
+ collectionIndexDefinitions,
5145
+ item,
5146
+ "del",
5147
+ this.level
5148
+ ),
4655
5149
  {
4656
5150
  type: "del",
4657
5151
  key: itemKey,
@@ -4675,7 +5169,10 @@ var Database = class {
4675
5169
  }
4676
5170
  };
4677
5171
  await sequential(tinaSchema.getCollections(), async (collection) => {
4678
- const documentPaths = await this.bridge.glob(normalizePath(collection.path), collection.format || "md");
5172
+ const documentPaths = await this.bridge.glob(
5173
+ normalizePath(collection.path),
5174
+ collection.format || "md"
5175
+ );
4679
5176
  await _indexContent(this, level, documentPaths, enqueueOps, collection);
4680
5177
  });
4681
5178
  while (operations.length) {
@@ -4697,7 +5194,10 @@ var Database = class {
4697
5194
  ...lookupMap,
4698
5195
  [lookup.type]: lookup
4699
5196
  };
4700
- await this.bridge.putConfig(normalizePath(lookupPath), JSON.stringify(updatedLookup));
5197
+ await this.bridge.putConfig(
5198
+ normalizePath(lookupPath),
5199
+ JSON.stringify(updatedLookup)
5200
+ );
4701
5201
  };
4702
5202
  this.tinaDirectory = config.tinaDirectory || ".tina";
4703
5203
  this.bridge = config.bridge;
@@ -4724,9 +5224,9 @@ var Database = class {
4724
5224
  }
4725
5225
  return { pathsByCollection, nonCollectionPaths, collections };
4726
5226
  }
4727
- async updateDatabaseVersion(version2) {
5227
+ async updateDatabaseVersion(version) {
4728
5228
  const metadataLevel = this.rootLevel.sublevel("_metadata", SUBLEVEL_OPTIONS);
4729
- await metadataLevel.put("metadata", { version: version2 });
5229
+ await metadataLevel.put("metadata", { version });
4730
5230
  }
4731
5231
  async getDatabaseVersion() {
4732
5232
  const metadataLevel = this.rootLevel.sublevel("_metadata", SUBLEVEL_OPTIONS);
@@ -4740,17 +5240,43 @@ var Database = class {
4740
5240
  if (!this.config.version) {
4741
5241
  this.level = this.rootLevel;
4742
5242
  } else {
4743
- let version2 = await this.getDatabaseVersion();
4744
- if (!version2) {
4745
- version2 = "";
4746
- await this.updateDatabaseVersion(version2);
5243
+ let version = await this.getDatabaseVersion();
5244
+ if (!version) {
5245
+ version = "";
5246
+ await this.updateDatabaseVersion(version);
4747
5247
  }
4748
- this.level = this.rootLevel.sublevel(version2, SUBLEVEL_OPTIONS);
5248
+ this.level = this.rootLevel.sublevel(version, SUBLEVEL_OPTIONS);
4749
5249
  }
4750
5250
  if (!this.level) {
4751
5251
  throw new GraphQLError4("Error initializing LevelDB instance");
4752
5252
  }
4753
5253
  }
5254
+ async getTemplateDetailsForFile(collection, data) {
5255
+ const tinaSchema = await this.getSchema();
5256
+ const templateInfo = await tinaSchema.getTemplatesForCollectable(collection);
5257
+ let template;
5258
+ if (templateInfo.type === "object") {
5259
+ template = templateInfo.template;
5260
+ }
5261
+ if (templateInfo.type === "union") {
5262
+ if (hasOwnProperty(data, "_template")) {
5263
+ template = templateInfo.templates.find(
5264
+ (t) => lastItem(t.namespace) === data._template
5265
+ );
5266
+ } else {
5267
+ throw new Error(
5268
+ `Expected _template to be provided for document in an ambiguous collection`
5269
+ );
5270
+ }
5271
+ }
5272
+ if (!template) {
5273
+ throw new Error(`Unable to determine template`);
5274
+ }
5275
+ return {
5276
+ template,
5277
+ info: templateInfo
5278
+ };
5279
+ }
4754
5280
  clearCache() {
4755
5281
  this.tinaSchema = null;
4756
5282
  this._lookup = null;
@@ -4778,21 +5304,45 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
4778
5304
  throw new Error(`No indexDefinitions for collection ${collection.name}`);
4779
5305
  }
4780
5306
  }
5307
+ const tinaSchema = await database.getSchema();
5308
+ let templateInfo = null;
5309
+ if (collection) {
5310
+ templateInfo = await tinaSchema.getTemplatesForCollectable(collection);
5311
+ }
4781
5312
  await sequential(documentPaths, async (filepath) => {
4782
5313
  try {
4783
5314
  const dataString = await database.bridge.get(normalizePath(filepath));
4784
- const data = parseFile(dataString, path3.extname(filepath), (yup3) => yup3.object({}), {
4785
- frontmatterDelimiters: collection?.frontmatterDelimiters,
4786
- frontmatterFormat: collection?.frontmatterFormat
4787
- });
5315
+ const data = parseFile(
5316
+ dataString,
5317
+ path3.extname(filepath),
5318
+ (yup3) => yup3.object({}),
5319
+ {
5320
+ frontmatterDelimiters: collection?.frontmatterDelimiters,
5321
+ frontmatterFormat: collection?.frontmatterFormat
5322
+ }
5323
+ );
4788
5324
  const normalizedPath = normalizePath(filepath);
5325
+ const aliasedData = templateInfo ? replaceNameOverrides(
5326
+ getTemplateForFile(templateInfo, data),
5327
+ data
5328
+ ) : data;
4789
5329
  await enqueueOps([
4790
- ...makeIndexOpsForDocument(normalizedPath, collection?.name, collectionIndexDefinitions, data, "put", level),
5330
+ ...makeIndexOpsForDocument(
5331
+ normalizedPath,
5332
+ collection?.name,
5333
+ collectionIndexDefinitions,
5334
+ aliasedData,
5335
+ "put",
5336
+ level
5337
+ ),
4791
5338
  {
4792
5339
  type: "put",
4793
5340
  key: normalizedPath,
4794
- value: data,
4795
- sublevel: level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS)
5341
+ value: aliasedData,
5342
+ sublevel: level.sublevel(
5343
+ CONTENT_ROOT_PREFIX,
5344
+ SUBLEVEL_OPTIONS
5345
+ )
4796
5346
  }
4797
5347
  ]);
4798
5348
  } catch (error) {
@@ -4814,18 +5364,45 @@ var _deleteIndexContent = async (database, documentPaths, enequeueOps, collectio
4814
5364
  throw new Error(`No indexDefinitions for collection ${collection.name}`);
4815
5365
  }
4816
5366
  }
4817
- const rootLevel = database.level.sublevel(CONTENT_ROOT_PREFIX, SUBLEVEL_OPTIONS);
5367
+ const rootLevel = database.level.sublevel(
5368
+ CONTENT_ROOT_PREFIX,
5369
+ SUBLEVEL_OPTIONS
5370
+ );
4818
5371
  await sequential(documentPaths, async (filepath) => {
4819
5372
  const itemKey = normalizePath(filepath);
4820
5373
  const item = await rootLevel.get(itemKey);
4821
5374
  if (item) {
4822
5375
  await enequeueOps([
4823
- ...makeIndexOpsForDocument(itemKey, collection.name, collectionIndexDefinitions, item, "del", database.level),
5376
+ ...makeIndexOpsForDocument(
5377
+ itemKey,
5378
+ collection.name,
5379
+ collectionIndexDefinitions,
5380
+ item,
5381
+ "del",
5382
+ database.level
5383
+ ),
4824
5384
  { type: "del", key: itemKey, sublevel: rootLevel }
4825
5385
  ]);
4826
5386
  }
4827
5387
  });
4828
5388
  };
5389
+ var getTemplateForFile = (templateInfo, data) => {
5390
+ if (templateInfo.type === "object") {
5391
+ return templateInfo.template;
5392
+ }
5393
+ if (templateInfo.type === "union") {
5394
+ if (hasOwnProperty(data, "_template")) {
5395
+ return templateInfo.templates.find(
5396
+ (t) => lastItem(t.namespace) === data._template
5397
+ );
5398
+ } else {
5399
+ throw new Error(
5400
+ `Expected _template to be provided for document in an ambiguous collection`
5401
+ );
5402
+ }
5403
+ }
5404
+ throw new Error(`Unable to determine template`);
5405
+ };
4829
5406
 
4830
5407
  // src/level/tinaLevel.ts
4831
5408
  import { ManyLevelGuest } from "many-level";
@@ -4862,9 +5439,12 @@ var FilesystemBridge = class {
4862
5439
  }
4863
5440
  async glob(pattern, extension) {
4864
5441
  const basePath = path4.join(this.outputPath, ...pattern.split("/"));
4865
- const items = await fg(path4.join(basePath, "**", `/*${extension}`).replace(/\\/g, "/"), {
4866
- dot: true
4867
- });
5442
+ const items = await fg(
5443
+ path4.join(basePath, "**", `/*${extension}`).replace(/\\/g, "/"),
5444
+ {
5445
+ dot: true
5446
+ }
5447
+ );
4868
5448
  const posixRootPath = normalize(this.outputPath);
4869
5449
  return items.map((item) => {
4870
5450
  return item.replace(posixRootPath, "").replace(/^\/|\/$/g, "");
@@ -5074,7 +5654,14 @@ var IsomorphicBridge = class {
5074
5654
  if (lastIdx === 0) {
5075
5655
  return updatedParentOid;
5076
5656
  } else {
5077
- return await this.updateTreeHierarchy(parentOid, updatedParentOid, parentPath, "tree", pathEntries.slice(0, lastIdx), pathParts.slice(0, lastIdx));
5657
+ return await this.updateTreeHierarchy(
5658
+ parentOid,
5659
+ updatedParentOid,
5660
+ parentPath,
5661
+ "tree",
5662
+ pathEntries.slice(0, lastIdx),
5663
+ pathParts.slice(0, lastIdx)
5664
+ );
5078
5665
  }
5079
5666
  }
5080
5667
  async commitTree(treeSha, ref) {
@@ -5109,7 +5696,15 @@ var IsomorphicBridge = class {
5109
5696
  fullname: true
5110
5697
  });
5111
5698
  if (!ref) {
5112
- throw new GraphQLError5(`Unable to determine current branch from HEAD`, null, null, null, null, null, {});
5699
+ throw new GraphQLError5(
5700
+ `Unable to determine current branch from HEAD`,
5701
+ null,
5702
+ null,
5703
+ null,
5704
+ null,
5705
+ null,
5706
+ {}
5707
+ );
5113
5708
  }
5114
5709
  this.ref = ref;
5115
5710
  return ref;
@@ -5117,7 +5712,10 @@ var IsomorphicBridge = class {
5117
5712
  async glob(pattern, extension) {
5118
5713
  const ref = await this.getRef();
5119
5714
  const parent = globParent(this.qualifyPath(pattern));
5120
- const { pathParts, pathEntries } = await this.resolvePathEntries(parent, ref);
5715
+ const { pathParts, pathEntries } = await this.resolvePathEntries(
5716
+ parent,
5717
+ ref
5718
+ );
5121
5719
  const leafEntry = pathEntries[pathEntries.length - 1];
5122
5720
  const entryPath = pathParts[pathParts.length - 1];
5123
5721
  const parentEntry = pathEntries[pathEntries.length - 2];
@@ -5152,7 +5750,10 @@ var IsomorphicBridge = class {
5152
5750
  }
5153
5751
  async delete(filepath) {
5154
5752
  const ref = await this.getRef();
5155
- const { pathParts, pathEntries } = await this.resolvePathEntries(this.qualifyPath(filepath), ref);
5753
+ const { pathParts, pathEntries } = await this.resolvePathEntries(
5754
+ this.qualifyPath(filepath),
5755
+ ref
5756
+ );
5156
5757
  let oidToRemove;
5157
5758
  let ptr = pathEntries.length - 1;
5158
5759
  while (ptr >= 1) {
@@ -5167,7 +5768,9 @@ var IsomorphicBridge = class {
5167
5768
  oid: existingOid,
5168
5769
  cache: this.cache
5169
5770
  });
5170
- const updatedTree = treeResult.tree.filter((value) => value.path !== nodePath);
5771
+ const updatedTree = treeResult.tree.filter(
5772
+ (value) => value.path !== nodePath
5773
+ );
5171
5774
  if (updatedTree.length === 0) {
5172
5775
  ptr -= 1;
5173
5776
  continue;
@@ -5176,11 +5779,26 @@ var IsomorphicBridge = class {
5176
5779
  ...this.isomorphicConfig,
5177
5780
  tree: updatedTree
5178
5781
  });
5179
- const updatedRootTreeOid = await this.updateTreeHierarchy(existingOid, updatedTreeOid, pathParts[ptr - 1], "tree", pathEntries.slice(0, ptr - 1), pathParts.slice(0, ptr - 1));
5782
+ const updatedRootTreeOid = await this.updateTreeHierarchy(
5783
+ existingOid,
5784
+ updatedTreeOid,
5785
+ pathParts[ptr - 1],
5786
+ "tree",
5787
+ pathEntries.slice(0, ptr - 1),
5788
+ pathParts.slice(0, ptr - 1)
5789
+ );
5180
5790
  await this.commitTree(updatedRootTreeOid, ref);
5181
5791
  break;
5182
5792
  } else {
5183
- throw new GraphQLError5(`Unable to resolve path: ${filepath}`, null, null, null, null, null, { status: 404 });
5793
+ throw new GraphQLError5(
5794
+ `Unable to resolve path: ${filepath}`,
5795
+ null,
5796
+ null,
5797
+ null,
5798
+ null,
5799
+ null,
5800
+ { status: 404 }
5801
+ );
5184
5802
  }
5185
5803
  }
5186
5804
  if (oidToRemove) {
@@ -5220,7 +5838,10 @@ var IsomorphicBridge = class {
5220
5838
  }
5221
5839
  async put(filepath, data) {
5222
5840
  const ref = await this.getRef();
5223
- const { pathParts, pathEntries } = await this.resolvePathEntries(this.qualifyPath(filepath), ref);
5841
+ const { pathParts, pathEntries } = await this.resolvePathEntries(
5842
+ this.qualifyPath(filepath),
5843
+ ref
5844
+ );
5224
5845
  const blobUpdate = toUint8Array(Buffer.from(data));
5225
5846
  let existingOid;
5226
5847
  const leafEntry = pathEntries[pathEntries.length - 1];
@@ -5237,7 +5858,14 @@ var IsomorphicBridge = class {
5237
5858
  ...this.isomorphicConfig,
5238
5859
  blob: blobUpdate
5239
5860
  });
5240
- const updatedRootSha = await this.updateTreeHierarchy(existingOid, updatedOid, nodePath, "blob", pathEntries.slice(0, pathEntries.length - 1), pathParts.slice(0, pathParts.length - 1));
5861
+ const updatedRootSha = await this.updateTreeHierarchy(
5862
+ existingOid,
5863
+ updatedOid,
5864
+ nodePath,
5865
+ "blob",
5866
+ pathEntries.slice(0, pathEntries.length - 1),
5867
+ pathParts.slice(0, pathParts.length - 1)
5868
+ );
5241
5869
  await this.commitTree(updatedRootSha, ref);
5242
5870
  await git.updateIndex({
5243
5871
  ...this.isomorphicConfig,