@tinacms/graphql 0.0.0-c965b5f-20250426163441 → 0.0.0-ccab7a5-20251124054446

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -66,7 +66,7 @@ module.exports = __toCommonJS(index_exports);
66
66
 
67
67
  // src/build.ts
68
68
  var import_graphql2 = require("graphql");
69
- var import_lodash3 = __toESM(require("lodash.uniqby"));
69
+ var import_es_toolkit3 = require("es-toolkit");
70
70
 
71
71
  // src/util.ts
72
72
  var yup = __toESM(require("yup"));
@@ -122,7 +122,7 @@ var flattenDeep = (arr) => arr.flatMap(
122
122
  );
123
123
 
124
124
  // src/ast-builder/index.ts
125
- var import_lodash = __toESM(require("lodash.uniqby"));
125
+ var import_es_toolkit = require("es-toolkit");
126
126
  var SysFieldDefinition = {
127
127
  kind: "Field",
128
128
  name: {
@@ -1037,12 +1037,13 @@ var astBuilder = {
1037
1037
  };
1038
1038
  },
1039
1039
  toGraphQLAst: (ast) => {
1040
- const definitions = (0, import_lodash.default)(
1040
+ const definitions = (0, import_es_toolkit.uniqBy)(
1041
1041
  [
1042
1042
  ...extractInlineTypes(ast.query),
1043
1043
  ...extractInlineTypes(ast.globalTemplates),
1044
1044
  ...ast.definitions
1045
1045
  ],
1046
+ // @ts-ignore - all nodes have a name property in practice
1046
1047
  (field) => field.name.value
1047
1048
  );
1048
1049
  return {
@@ -1065,7 +1066,7 @@ var extractInlineTypes = (item) => {
1065
1066
  const accumulator = [item];
1066
1067
  for (const node of walk(item)) {
1067
1068
  if (node.kind === "UnionTypeDefinition") {
1068
- node.types = (0, import_lodash.default)(node.types, (type) => type.name.value);
1069
+ node.types = (0, import_es_toolkit.uniqBy)(node.types, (type) => type.name.value);
1069
1070
  }
1070
1071
  if (node.kind === "NamedType") {
1071
1072
  if (typeof node.name.value !== "string") {
@@ -1435,13 +1436,12 @@ var checkPasswordHash = async ({
1435
1436
  return true;
1436
1437
  };
1437
1438
  var mapUserFields = (collectable, prefix = []) => {
1438
- var _a, _b, _c, _d, _e;
1439
1439
  const results = [];
1440
- const passwordFields = ((_a = collectable.fields) == null ? void 0 : _a.filter((field) => field.type === "password")) || [];
1440
+ const passwordFields = collectable.fields?.filter((field) => field.type === "password") || [];
1441
1441
  if (passwordFields.length > 1) {
1442
1442
  throw new Error("Only one password field is allowed");
1443
1443
  }
1444
- const idFields = ((_b = collectable.fields) == null ? void 0 : _b.filter((field) => field.uid)) || [];
1444
+ const idFields = collectable.fields?.filter((field) => field.uid) || [];
1445
1445
  if (idFields.length > 1) {
1446
1446
  throw new Error("Only one uid field is allowed");
1447
1447
  }
@@ -1449,11 +1449,11 @@ var mapUserFields = (collectable, prefix = []) => {
1449
1449
  results.push({
1450
1450
  path: prefix,
1451
1451
  collectable,
1452
- idFieldName: (_c = idFields[0]) == null ? void 0 : _c.name,
1453
- passwordFieldName: (_d = passwordFields[0]) == null ? void 0 : _d.name
1452
+ idFieldName: idFields[0]?.name,
1453
+ passwordFieldName: passwordFields[0]?.name
1454
1454
  });
1455
1455
  }
1456
- (_e = collectable.fields) == null ? void 0 : _e.forEach((field) => {
1456
+ collectable.fields?.forEach((field) => {
1457
1457
  if (field.type === "object" && field.fields) {
1458
1458
  results.push(...mapUserFields(field, [...prefix, field.name]));
1459
1459
  }
@@ -1944,13 +1944,12 @@ var Builder = class {
1944
1944
  *
1945
1945
  * */
1946
1946
  this._getCollectionFragmentSelections = async (collection, depth) => {
1947
- var _a;
1948
1947
  const selections = [];
1949
1948
  selections.push({
1950
1949
  name: { kind: "Name", value: "__typename" },
1951
1950
  kind: "Field"
1952
1951
  });
1953
- if (((_a = collection.fields) == null ? void 0 : _a.length) > 0) {
1952
+ if (collection.fields?.length > 0) {
1954
1953
  await sequential(collection.fields, async (x) => {
1955
1954
  const field = await this._buildFieldNodeForFragments(x, depth);
1956
1955
  selections.push(field);
@@ -1965,7 +1964,6 @@ var Builder = class {
1965
1964
  return selections;
1966
1965
  };
1967
1966
  this._buildFieldNodeForFragments = async (field, depth) => {
1968
- var _a, _b;
1969
1967
  switch (field.type) {
1970
1968
  case "string":
1971
1969
  case "image":
@@ -1998,7 +1996,7 @@ var Builder = class {
1998
1996
  selections: filterSelections([passwordValue, passwordChangeRequired])
1999
1997
  });
2000
1998
  case "object":
2001
- if (((_a = field.fields) == null ? void 0 : _a.length) > 0) {
1999
+ if (field.fields?.length > 0) {
2002
2000
  const selections2 = [];
2003
2001
  await sequential(field.fields, async (item) => {
2004
2002
  const field2 = await this._buildFieldNodeForFragments(item, depth);
@@ -2011,7 +2009,7 @@ var Builder = class {
2011
2009
  ...filterSelections(selections2)
2012
2010
  ]
2013
2011
  });
2014
- } else if (((_b = field.templates) == null ? void 0 : _b.length) > 0) {
2012
+ } else if (field.templates?.length > 0) {
2015
2013
  const selections2 = [];
2016
2014
  await sequential(field.templates, async (tem) => {
2017
2015
  if (typeof tem === "object") {
@@ -2673,7 +2671,7 @@ var Builder = class {
2673
2671
  this.addToLookupMap({
2674
2672
  type: name,
2675
2673
  resolveType: "unionData",
2676
- collection: collection == null ? void 0 : collection.name,
2674
+ collection: collection?.name,
2677
2675
  typeMap
2678
2676
  });
2679
2677
  return astBuilder.UnionTypeDefinition({ name, types });
@@ -2780,7 +2778,7 @@ var Builder = class {
2780
2778
  this._buildDataField = async (field) => {
2781
2779
  const listWarningMsg = `
2782
2780
  WARNING: The user interface for ${field.type} does not support \`list: true\`
2783
- Visit https://tina.io/docs/errors/ui-not-supported/ for more information
2781
+ Visit https://tina.io/docs/r/content-fields/#list-fields/ for more information
2784
2782
 
2785
2783
  `;
2786
2784
  switch (field.type) {
@@ -2883,9 +2881,8 @@ Visit https://tina.io/docs/errors/ui-not-supported/ for more information
2883
2881
  ]
2884
2882
  });
2885
2883
  };
2886
- var _a, _b, _c, _d;
2887
2884
  this.maxDepth = // @ts-ignore
2888
- (_d = (_c = (_b = (_a = config == null ? void 0 : config.tinaSchema.schema) == null ? void 0 : _a.config) == null ? void 0 : _b.client) == null ? void 0 : _c.referenceDepth) != null ? _d : 2;
2885
+ config?.tinaSchema.schema?.config?.client?.referenceDepth ?? 2;
2889
2886
  this.tinaSchema = config.tinaSchema;
2890
2887
  this.lookupMap = {};
2891
2888
  }
@@ -2934,8 +2931,8 @@ var import_schema_tools3 = require("@tinacms/schema-tools");
2934
2931
 
2935
2932
  // src/schema/validate.ts
2936
2933
  var import_schema_tools = require("@tinacms/schema-tools");
2937
- var import_lodash2 = __toESM(require("lodash.clonedeep"));
2938
2934
  var yup2 = __toESM(require("yup"));
2935
+ var import_es_toolkit2 = require("es-toolkit");
2939
2936
  var import_schema_tools2 = require("@tinacms/schema-tools");
2940
2937
  var FIELD_TYPES = [
2941
2938
  "string",
@@ -2950,7 +2947,7 @@ var FIELD_TYPES = [
2950
2947
  ];
2951
2948
  var validateSchema = async (schema) => {
2952
2949
  const schema2 = (0, import_schema_tools.addNamespaceToSchema)(
2953
- (0, import_lodash2.default)(schema)
2950
+ (0, import_es_toolkit2.cloneDeep)(schema)
2954
2951
  );
2955
2952
  const collections = await sequential(
2956
2953
  schema2.collections,
@@ -2974,7 +2971,7 @@ var validationCollectionsPathAndMatch = (collections) => {
2974
2971
  return;
2975
2972
  }
2976
2973
  const noMatchCollections = collections.filter((x) => {
2977
- return typeof (x == null ? void 0 : x.match) === "undefined";
2974
+ return typeof x?.match === "undefined";
2978
2975
  }).map((x) => `${x.path}${x.format || "md"}`);
2979
2976
  if (noMatchCollections.length !== new Set(noMatchCollections).size) {
2980
2977
  throw new Error(
@@ -2985,10 +2982,7 @@ var validationCollectionsPathAndMatch = (collections) => {
2985
2982
  const hasMatchAndPath = collections.filter((x) => {
2986
2983
  return typeof x.path !== "undefined" && typeof x.match !== "undefined";
2987
2984
  }).map(
2988
- (x) => {
2989
- var _a, _b;
2990
- return `${x.path}|${((_a = x == null ? void 0 : x.match) == null ? void 0 : _a.exclude) || ""}|${((_b = x == null ? void 0 : x.match) == null ? void 0 : _b.include) || ""}|${x.format || "md"}`;
2991
- }
2985
+ (x) => `${x.path}|${x?.match?.exclude || ""}|${x?.match?.include || ""}|${x.format || "md"}`
2992
2986
  );
2993
2987
  if (hasMatchAndPath.length !== new Set(hasMatchAndPath).size) {
2994
2988
  throw new Error(
@@ -3012,7 +3006,7 @@ var validationCollectionsPathAndMatch = (collections) => {
3012
3006
  );
3013
3007
  }
3014
3008
  const matches = collectionsArr.map(
3015
- (x) => typeof (x == null ? void 0 : x.match) === "object" ? JSON.stringify(x.match) : ""
3009
+ (x) => typeof x?.match === "object" ? JSON.stringify(x.match) : ""
3016
3010
  );
3017
3011
  if (matches.length === new Set(matches).size) {
3018
3012
  return;
@@ -3090,7 +3084,7 @@ var validateField = async (field) => {
3090
3084
  // package.json
3091
3085
  var package_default = {
3092
3086
  name: "@tinacms/graphql",
3093
- version: "1.5.16",
3087
+ version: "1.6.1",
3094
3088
  main: "dist/index.js",
3095
3089
  module: "dist/index.mjs",
3096
3090
  typings: "dist/index.d.ts",
@@ -3116,33 +3110,30 @@ var package_default = {
3116
3110
  types: "pnpm tsc",
3117
3111
  build: "tinacms-scripts build",
3118
3112
  docs: "pnpm typedoc",
3119
- serve: "pnpm nodemon dist/server.js",
3120
3113
  test: "vitest run",
3121
3114
  "test-watch": "vitest"
3122
3115
  },
3123
3116
  dependencies: {
3124
- "@iarna/toml": "^2.2.5",
3117
+ "@iarna/toml": "catalog:",
3125
3118
  "@tinacms/mdx": "workspace:*",
3126
3119
  "@tinacms/schema-tools": "workspace:*",
3127
- "abstract-level": "^1.0.4",
3120
+ "abstract-level": "catalog:",
3128
3121
  "date-fns": "^2.30.0",
3129
- "fast-glob": "^3.3.3",
3130
- "fs-extra": "^11.3.0",
3131
- "glob-parent": "^6.0.2",
3122
+ "es-toolkit": "^1.42.0",
3123
+ "fast-glob": "catalog:",
3124
+ "fs-extra": "catalog:",
3125
+ "glob-parent": "catalog:",
3132
3126
  graphql: "15.8.0",
3133
- "gray-matter": "^4.0.3",
3134
- "isomorphic-git": "^1.29.0",
3135
- "js-sha1": "^0.6.0",
3127
+ "gray-matter": "catalog:",
3128
+ "isomorphic-git": "catalog:",
3129
+ "js-sha1": "catalog:",
3136
3130
  "js-yaml": "^3.14.1",
3137
- "jsonpath-plus": "10.1.0",
3138
- "lodash.clonedeep": "^4.5.0",
3139
- "lodash.set": "^4.3.2",
3140
- "lodash.uniqby": "^4.7.0",
3141
- "many-level": "^2.0.0",
3142
- micromatch: "4.0.8",
3143
- "normalize-path": "^3.0.0",
3144
- "readable-stream": "^4.7.0",
3145
- scmp: "^2.1.0",
3131
+ "jsonpath-plus": "catalog:",
3132
+ "many-level": "catalog:",
3133
+ micromatch: "catalog:",
3134
+ "normalize-path": "catalog:",
3135
+ "readable-stream": "catalog:",
3136
+ scmp: "catalog:",
3146
3137
  yup: "^0.32.11"
3147
3138
  },
3148
3139
  publishConfig: {
@@ -3157,25 +3148,22 @@ var package_default = {
3157
3148
  "@tinacms/scripts": "workspace:*",
3158
3149
  "@types/cors": "^2.8.17",
3159
3150
  "@types/estree": "^0.0.50",
3160
- "@types/express": "^4.17.21",
3151
+ "@types/express": "catalog:",
3161
3152
  "@types/fs-extra": "^9.0.13",
3162
3153
  "@types/js-yaml": "^3.12.10",
3163
- "@types/lodash.camelcase": "^4.3.9",
3164
- "@types/lodash.upperfirst": "^4.3.9",
3165
- "@types/lru-cache": "^5.1.1",
3166
- "@types/mdast": "^3.0.15",
3167
- "@types/micromatch": "^4.0.9",
3154
+ "@types/lru-cache": "catalog:",
3155
+ "@types/mdast": "catalog:",
3156
+ "@types/micromatch": "catalog:",
3168
3157
  "@types/node": "^22.13.1",
3169
- "@types/normalize-path": "^3.0.2",
3170
- "@types/ws": "^7.4.7",
3158
+ "@types/normalize-path": "catalog:",
3159
+ "@types/ws": "catalog:",
3171
3160
  "@types/yup": "^0.29.14",
3172
3161
  "jest-file-snapshot": "^0.5.0",
3173
- "memory-level": "^1.0.0",
3174
- nodemon: "3.1.4",
3162
+ "memory-level": "catalog:",
3175
3163
  typescript: "^5.7.3",
3176
3164
  vite: "^4.5.9",
3177
3165
  vitest: "^0.32.4",
3178
- zod: "^3.24.2"
3166
+ zod: "catalog:"
3179
3167
  }
3180
3168
  };
3181
3169
 
@@ -3245,9 +3233,9 @@ var _buildFragments = async (builder, tinaSchema) => {
3245
3233
  });
3246
3234
  const fragDoc = {
3247
3235
  kind: "Document",
3248
- definitions: (0, import_lodash3.default)(
3249
- // @ts-ignore
3236
+ definitions: (0, import_es_toolkit3.uniqBy)(
3250
3237
  extractInlineTypes(fragmentDefinitionsFields),
3238
+ // @ts-ignore - all nodes returned by extractInlineTypes have a name property
3251
3239
  (node) => node.name.value
3252
3240
  )
3253
3241
  };
@@ -3257,7 +3245,6 @@ var _buildQueries = async (builder, tinaSchema) => {
3257
3245
  const operationsDefinitions = [];
3258
3246
  const collections = tinaSchema.getCollections();
3259
3247
  await sequential(collections, async (collection) => {
3260
- var _a, _b, _c;
3261
3248
  const queryName = NAMER.queryName(collection.namespace);
3262
3249
  const queryListName = NAMER.generateQueryListName(collection.namespace);
3263
3250
  const queryFilterTypeName = NAMER.dataFilterTypeName(collection.namespace);
@@ -3272,16 +3259,16 @@ var _buildQueries = async (builder, tinaSchema) => {
3272
3259
  filterType: queryFilterTypeName,
3273
3260
  // look for flag to see if the data layer is enabled
3274
3261
  dataLayer: Boolean(
3275
- (_c = (_b = (_a = tinaSchema.config) == null ? void 0 : _a.meta) == null ? void 0 : _b.flags) == null ? void 0 : _c.find((x) => x === "experimentalData")
3262
+ tinaSchema.config?.meta?.flags?.find((x) => x === "experimentalData")
3276
3263
  )
3277
3264
  })
3278
3265
  );
3279
3266
  });
3280
3267
  const queryDoc = {
3281
3268
  kind: "Document",
3282
- definitions: (0, import_lodash3.default)(
3283
- // @ts-ignore
3269
+ definitions: (0, import_es_toolkit3.uniqBy)(
3284
3270
  extractInlineTypes(operationsDefinitions),
3271
+ // @ts-ignore - all nodes returned by extractInlineTypes have a name property
3285
3272
  (node) => node.name.value
3286
3273
  )
3287
3274
  };
@@ -3368,14 +3355,15 @@ var _buildSchema = async (builder, tinaSchema) => {
3368
3355
  fields: mutationTypeDefinitionFields
3369
3356
  })
3370
3357
  );
3371
- return {
3358
+ const schema = {
3372
3359
  kind: "Document",
3373
- definitions: (0, import_lodash3.default)(
3374
- // @ts-ignore
3360
+ definitions: (0, import_es_toolkit3.uniqBy)(
3375
3361
  extractInlineTypes(definitions),
3362
+ // @ts-ignore - all nodes returned by extractInlineTypes have a name property
3376
3363
  (node) => node.name.value
3377
3364
  )
3378
3365
  };
3366
+ return schema;
3379
3367
  };
3380
3368
 
3381
3369
  // src/resolve.ts
@@ -3384,251 +3372,11 @@ var import_graphql5 = require("graphql");
3384
3372
  // src/resolver/index.ts
3385
3373
  var import_path3 = __toESM(require("path"));
3386
3374
  var import_isValid = __toESM(require("date-fns/isValid/index.js"));
3375
+ var import_jsonpath_plus2 = require("jsonpath-plus");
3387
3376
 
3388
3377
  // src/mdx/index.ts
3389
3378
  var import_mdx = require("@tinacms/mdx");
3390
3379
 
3391
- // src/resolver/index.ts
3392
- var import_jsonpath_plus2 = require("jsonpath-plus");
3393
-
3394
- // src/resolver/error.ts
3395
- var TinaGraphQLError = class extends Error {
3396
- constructor(message, extensions) {
3397
- super(message);
3398
- if (!this.name) {
3399
- Object.defineProperty(this, "name", { value: "TinaGraphQLError" });
3400
- }
3401
- this.extensions = { ...extensions };
3402
- }
3403
- };
3404
- var TinaFetchError = class extends Error {
3405
- constructor(message, args) {
3406
- super(message);
3407
- this.name = "TinaFetchError";
3408
- this.collection = args.collection;
3409
- this.stack = args.stack;
3410
- this.file = args.file;
3411
- this.originalError = args.originalError;
3412
- }
3413
- };
3414
- var TinaQueryError = class extends TinaFetchError {
3415
- constructor(args) {
3416
- super(
3417
- `Error querying file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
3418
- args
3419
- );
3420
- }
3421
- };
3422
- var TinaParseDocumentError = class extends TinaFetchError {
3423
- constructor(args) {
3424
- super(
3425
- `Error parsing file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
3426
- args
3427
- );
3428
- }
3429
- toString() {
3430
- return super.toString() + "\n OriginalError: \n" + this.originalError.toString();
3431
- }
3432
- };
3433
- var auditMessage = (includeAuditMessage = true) => includeAuditMessage ? `Please run "tinacms audit" or add the --verbose option for more info` : "";
3434
- var handleFetchErrorError = (e, verbose) => {
3435
- if (e instanceof Error) {
3436
- if (e instanceof TinaFetchError) {
3437
- if (verbose) {
3438
- console.log(e.toString());
3439
- console.log(e);
3440
- console.log(e.stack);
3441
- }
3442
- }
3443
- } else {
3444
- console.error(e);
3445
- }
3446
- throw e;
3447
- };
3448
-
3449
- // src/resolver/filter-utils.ts
3450
- var resolveReferences = async (filter, fields, resolver) => {
3451
- for (const fieldKey of Object.keys(filter)) {
3452
- const fieldDefinition = fields.find(
3453
- (f) => f.name === fieldKey
3454
- );
3455
- if (fieldDefinition) {
3456
- if (fieldDefinition.type === "reference") {
3457
- const { edges, values } = await resolver(filter, fieldDefinition);
3458
- if (edges.length === 1) {
3459
- filter[fieldKey] = {
3460
- eq: values[0]
3461
- };
3462
- } else if (edges.length > 1) {
3463
- filter[fieldKey] = {
3464
- in: values
3465
- };
3466
- } else {
3467
- filter[fieldKey] = {
3468
- eq: "___null___"
3469
- };
3470
- }
3471
- } else if (fieldDefinition.type === "object") {
3472
- if (fieldDefinition.templates) {
3473
- for (const templateName of Object.keys(filter[fieldKey])) {
3474
- const template = fieldDefinition.templates.find(
3475
- (template2) => !(typeof template2 === "string") && template2.name === templateName
3476
- );
3477
- if (template) {
3478
- await resolveReferences(
3479
- filter[fieldKey][templateName],
3480
- template.fields,
3481
- resolver
3482
- );
3483
- } else {
3484
- throw new Error(`Template ${templateName} not found`);
3485
- }
3486
- }
3487
- } else {
3488
- await resolveReferences(
3489
- filter[fieldKey],
3490
- fieldDefinition.fields,
3491
- resolver
3492
- );
3493
- }
3494
- }
3495
- } else {
3496
- throw new Error(`Unable to find field ${fieldKey}`);
3497
- }
3498
- }
3499
- };
3500
- var collectConditionsForChildFields = (filterNode, fields, pathExpression, collectCondition) => {
3501
- for (const childFieldName of Object.keys(filterNode)) {
3502
- const childField = fields.find((field) => field.name === childFieldName);
3503
- if (!childField) {
3504
- throw new Error(`Unable to find type for field ${childFieldName}`);
3505
- }
3506
- collectConditionsForField(
3507
- childFieldName,
3508
- childField,
3509
- filterNode[childFieldName],
3510
- pathExpression,
3511
- collectCondition
3512
- );
3513
- }
3514
- };
3515
- var collectConditionsForObjectField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
3516
- if (field.list && field.templates) {
3517
- for (const [filterKey, childFilterNode] of Object.entries(filterNode)) {
3518
- const template = field.templates.find(
3519
- (template2) => !(typeof template2 === "string") && template2.name === filterKey
3520
- );
3521
- const jsonPath = `${fieldName}[?(@._template=="${filterKey}")]`;
3522
- const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : jsonPath;
3523
- collectConditionsForChildFields(
3524
- childFilterNode,
3525
- template.fields,
3526
- filterPath,
3527
- collectCondition
3528
- );
3529
- }
3530
- } else {
3531
- const jsonPath = `${fieldName}${field.list ? "[*]" : ""}`;
3532
- const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : `${jsonPath}`;
3533
- collectConditionsForChildFields(
3534
- filterNode,
3535
- field.fields,
3536
- filterPath,
3537
- collectCondition
3538
- );
3539
- }
3540
- };
3541
- var collectConditionsForField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
3542
- if (field.type === "object") {
3543
- collectConditionsForObjectField(
3544
- fieldName,
3545
- field,
3546
- filterNode,
3547
- pathExpression,
3548
- collectCondition
3549
- );
3550
- } else {
3551
- collectCondition({
3552
- filterPath: pathExpression ? `${pathExpression}.${fieldName}` : fieldName,
3553
- filterExpression: {
3554
- _type: field.type,
3555
- _list: !!field.list,
3556
- ...filterNode
3557
- }
3558
- });
3559
- }
3560
- };
3561
-
3562
- // src/resolver/media-utils.ts
3563
- var resolveMediaCloudToRelative = (value, config = { useRelativeMedia: true }, schema) => {
3564
- if (config && value) {
3565
- if (config.useRelativeMedia === true) {
3566
- return value;
3567
- }
3568
- if (hasTinaMediaConfig(schema) === true) {
3569
- const assetsURL = `https://${config.assetsHost}/${config.clientId}`;
3570
- if (typeof value === "string" && value.includes(assetsURL)) {
3571
- const cleanMediaRoot = cleanUpSlashes(
3572
- schema.config.media.tina.mediaRoot
3573
- );
3574
- const strippedURL = value.replace(assetsURL, "");
3575
- return `${cleanMediaRoot}${strippedURL}`;
3576
- }
3577
- if (Array.isArray(value)) {
3578
- return value.map((v) => {
3579
- if (!v || typeof v !== "string") return v;
3580
- const cleanMediaRoot = cleanUpSlashes(
3581
- schema.config.media.tina.mediaRoot
3582
- );
3583
- const strippedURL = v.replace(assetsURL, "");
3584
- return `${cleanMediaRoot}${strippedURL}`;
3585
- });
3586
- }
3587
- return value;
3588
- }
3589
- return value;
3590
- } else {
3591
- return value;
3592
- }
3593
- };
3594
- var resolveMediaRelativeToCloud = (value, config = { useRelativeMedia: true }, schema) => {
3595
- if (config && value) {
3596
- if (config.useRelativeMedia === true) {
3597
- return value;
3598
- }
3599
- if (hasTinaMediaConfig(schema) === true) {
3600
- const cleanMediaRoot = cleanUpSlashes(schema.config.media.tina.mediaRoot);
3601
- if (typeof value === "string") {
3602
- const strippedValue = value.replace(cleanMediaRoot, "");
3603
- return `https://${config.assetsHost}/${config.clientId}${strippedValue}`;
3604
- }
3605
- if (Array.isArray(value)) {
3606
- return value.map((v) => {
3607
- if (!v || typeof v !== "string") return v;
3608
- const strippedValue = v.replace(cleanMediaRoot, "");
3609
- return `https://${config.assetsHost}/${config.clientId}${strippedValue}`;
3610
- });
3611
- }
3612
- }
3613
- return value;
3614
- } else {
3615
- return value;
3616
- }
3617
- };
3618
- var cleanUpSlashes = (path7) => {
3619
- if (path7) {
3620
- return `/${path7.replace(/^\/+|\/+$/gm, "")}`;
3621
- }
3622
- return "";
3623
- };
3624
- var hasTinaMediaConfig = (schema) => {
3625
- var _a, _b, _c, _d, _e, _f, _g, _h;
3626
- if (!((_b = (_a = schema.config) == null ? void 0 : _a.media) == null ? void 0 : _b.tina)) return false;
3627
- if (typeof ((_e = (_d = (_c = schema.config) == null ? void 0 : _c.media) == null ? void 0 : _d.tina) == null ? void 0 : _e.publicFolder) !== "string" && typeof ((_h = (_g = (_f = schema.config) == null ? void 0 : _f.media) == null ? void 0 : _g.tina) == null ? void 0 : _h.mediaRoot) !== "string")
3628
- return false;
3629
- return true;
3630
- };
3631
-
3632
3380
  // src/resolver/index.ts
3633
3381
  var import_graphql3 = require("graphql");
3634
3382
 
@@ -3690,11 +3438,11 @@ var import_path2 = __toESM(require("path"));
3690
3438
 
3691
3439
  // src/database/util.ts
3692
3440
  var import_toml = __toESM(require("@iarna/toml"));
3693
- var import_js_yaml = __toESM(require("js-yaml"));
3694
- var import_gray_matter = __toESM(require("gray-matter"));
3695
3441
  var import_schema_tools4 = require("@tinacms/schema-tools");
3696
- var import_micromatch = __toESM(require("micromatch"));
3442
+ var import_gray_matter = __toESM(require("gray-matter"));
3443
+ var import_js_yaml = __toESM(require("js-yaml"));
3697
3444
  var import_path = __toESM(require("path"));
3445
+ var import_micromatch = __toESM(require("micromatch"));
3698
3446
 
3699
3447
  // src/database/alias-utils.ts
3700
3448
  var replaceBlockAliases = (template, item) => {
@@ -3731,22 +3479,20 @@ var replaceNameOverrides = (template, obj) => {
3731
3479
  }
3732
3480
  };
3733
3481
  function isBlockField(field) {
3734
- var _a;
3735
- return field && field.type === "object" && ((_a = field.templates) == null ? void 0 : _a.length) > 0;
3482
+ return field && field.type === "object" && field.templates?.length > 0;
3736
3483
  }
3737
3484
  var _replaceNameOverrides = (fields, obj) => {
3738
3485
  const output = {};
3739
3486
  Object.keys(obj).forEach((key) => {
3740
3487
  const field = fields.find(
3741
- (fieldWithMatchingAlias) => ((fieldWithMatchingAlias == null ? void 0 : fieldWithMatchingAlias.nameOverride) || (fieldWithMatchingAlias == null ? void 0 : fieldWithMatchingAlias.name)) === key
3488
+ (fieldWithMatchingAlias) => (fieldWithMatchingAlias?.nameOverride || fieldWithMatchingAlias?.name) === key
3742
3489
  );
3743
- output[(field == null ? void 0 : field.name) || key] = (field == null ? void 0 : field.type) == "object" ? replaceNameOverrides(field, obj[key]) : obj[key];
3490
+ output[field?.name || key] = field?.type == "object" ? replaceNameOverrides(field, obj[key]) : obj[key];
3744
3491
  });
3745
3492
  return output;
3746
3493
  };
3747
3494
  var getTemplateForData = (field, data) => {
3748
- var _a;
3749
- if ((_a = field.templates) == null ? void 0 : _a.length) {
3495
+ if (field.templates?.length) {
3750
3496
  const templateKey = "_template";
3751
3497
  if (data[templateKey]) {
3752
3498
  const result = field.templates.find(
@@ -3804,8 +3550,8 @@ var _applyNameOverrides = (fields, obj) => {
3804
3550
  const output = {};
3805
3551
  Object.keys(obj).forEach((key) => {
3806
3552
  const field = fields.find((field2) => field2.name === key);
3807
- const outputKey = (field == null ? void 0 : field.nameOverride) || key;
3808
- output[outputKey] = (field == null ? void 0 : field.type) === "object" ? applyNameOverrides(field, obj[key]) : obj[key];
3553
+ const outputKey = field?.nameOverride || key;
3554
+ output[outputKey] = field?.type === "object" ? applyNameOverrides(field, obj[key]) : obj[key];
3809
3555
  });
3810
3556
  return output;
3811
3557
  };
@@ -3818,7 +3564,6 @@ var matterEngines = {
3818
3564
  }
3819
3565
  };
3820
3566
  var stringifyFile = (content, format, keepTemplateKey, markdownParseConfig) => {
3821
- var _a, _b;
3822
3567
  const {
3823
3568
  _relativePath,
3824
3569
  _keepTemplateKey,
@@ -3842,9 +3587,9 @@ var stringifyFile = (content, format, keepTemplateKey, markdownParseConfig) => {
3842
3587
  ${$_body}`,
3843
3588
  strippedContent,
3844
3589
  {
3845
- language: (_a = markdownParseConfig == null ? void 0 : markdownParseConfig.frontmatterFormat) != null ? _a : "yaml",
3590
+ language: markdownParseConfig?.frontmatterFormat ?? "yaml",
3846
3591
  engines: matterEngines,
3847
- delimiters: (_b = markdownParseConfig == null ? void 0 : markdownParseConfig.frontmatterDelimiters) != null ? _b : "---"
3592
+ delimiters: markdownParseConfig?.frontmatterDelimiters ?? "---"
3848
3593
  }
3849
3594
  );
3850
3595
  return ok;
@@ -3860,15 +3605,14 @@ ${$_body}`,
3860
3605
  }
3861
3606
  };
3862
3607
  var parseFile = (content, format, yupSchema, markdownParseConfig) => {
3863
- var _a, _b;
3864
3608
  try {
3865
3609
  switch (format) {
3866
3610
  case ".markdown":
3867
3611
  case ".mdx":
3868
3612
  case ".md":
3869
3613
  const contentJSON = (0, import_gray_matter.default)(content || "", {
3870
- language: (_a = markdownParseConfig == null ? void 0 : markdownParseConfig.frontmatterFormat) != null ? _a : "yaml",
3871
- delimiters: (_b = markdownParseConfig == null ? void 0 : markdownParseConfig.frontmatterDelimiters) != null ? _b : "---",
3614
+ language: markdownParseConfig?.frontmatterFormat ?? "yaml",
3615
+ delimiters: markdownParseConfig?.frontmatterDelimiters ?? "---",
3872
3616
  engines: matterEngines
3873
3617
  });
3874
3618
  const markdownData = {
@@ -3967,7 +3711,7 @@ var transformDocument = (filepath, contentObject, tinaSchema) => {
3967
3711
  ),
3968
3712
  template: void 0
3969
3713
  } : tinaSchema.getCollectionAndTemplateByFullPath(filepath, templateName);
3970
- const field = template == null ? void 0 : template.fields.find((field2) => {
3714
+ const field = template?.fields.find((field2) => {
3971
3715
  if (field2.type === "string" || field2.type === "rich-text") {
3972
3716
  if (field2.isBody) {
3973
3717
  return true;
@@ -3987,7 +3731,7 @@ var transformDocument = (filepath, contentObject, tinaSchema) => {
3987
3731
  ...data,
3988
3732
  _collection: collection.name,
3989
3733
  _keepTemplateKey: !!collection.templates,
3990
- _template: (template == null ? void 0 : template.namespace) ? lastItem(template == null ? void 0 : template.namespace) : void 0,
3734
+ _template: template?.namespace ? lastItem(template?.namespace) : void 0,
3991
3735
  _relativePath: filepath.replace(collection.path, "").replace(/^\/|\/$/g, ""),
3992
3736
  _id: filepath
3993
3737
  };
@@ -3996,10 +3740,10 @@ function hasOwnProperty(obj, prop) {
3996
3740
  return obj.hasOwnProperty(prop);
3997
3741
  }
3998
3742
  var getTemplateForFile = (templateInfo, data) => {
3999
- if ((templateInfo == null ? void 0 : templateInfo.type) === "object") {
3743
+ if (templateInfo?.type === "object") {
4000
3744
  return templateInfo.template;
4001
3745
  }
4002
- if ((templateInfo == null ? void 0 : templateInfo.type) === "union") {
3746
+ if (templateInfo?.type === "union") {
4003
3747
  if (hasOwnProperty(data, "_template")) {
4004
3748
  const template = templateInfo.templates.find(
4005
3749
  (t) => lastItem(t.namespace) === data._template
@@ -4023,8 +3767,8 @@ var loadAndParseWithAliases = async (bridge, filepath, collection, templateInfo)
4023
3767
  import_path.default.extname(filepath),
4024
3768
  (yup3) => yup3.object({}),
4025
3769
  {
4026
- frontmatterDelimiters: collection == null ? void 0 : collection.frontmatterDelimiters,
4027
- frontmatterFormat: collection == null ? void 0 : collection.frontmatterFormat
3770
+ frontmatterDelimiters: collection?.frontmatterDelimiters,
3771
+ frontmatterFormat: collection?.frontmatterFormat
4028
3772
  }
4029
3773
  );
4030
3774
  const template = getTemplateForFile(templateInfo, data);
@@ -4611,87 +4355,322 @@ var makeIndexOpsForDocument = (filepath, collection, indexDefinitions, data, opT
4611
4355
  });
4612
4356
  }
4613
4357
  }
4614
- }
4358
+ }
4359
+ }
4360
+ return result;
4361
+ };
4362
+ var makeRefOpsForDocument = (filepath, collection, references, data, opType, level) => {
4363
+ const result = [];
4364
+ if (collection) {
4365
+ for (const [c, referencePaths] of Object.entries(references || {})) {
4366
+ if (!referencePaths.length) {
4367
+ continue;
4368
+ }
4369
+ const collectionSublevel = level.sublevel(c, SUBLEVEL_OPTIONS);
4370
+ const refSublevel = collectionSublevel.sublevel(
4371
+ REFS_COLLECTIONS_SORT_KEY,
4372
+ SUBLEVEL_OPTIONS
4373
+ );
4374
+ const references2 = {};
4375
+ for (const path7 of referencePaths) {
4376
+ const ref = (0, import_jsonpath_plus.JSONPath)({ path: path7, json: data });
4377
+ if (!ref) {
4378
+ continue;
4379
+ }
4380
+ if (Array.isArray(ref)) {
4381
+ for (const r of ref) {
4382
+ if (!r) {
4383
+ continue;
4384
+ }
4385
+ if (references2[r]) {
4386
+ references2[r].push(path7);
4387
+ } else {
4388
+ references2[r] = [path7];
4389
+ }
4390
+ }
4391
+ } else {
4392
+ if (references2[ref]) {
4393
+ references2[ref].push(path7);
4394
+ } else {
4395
+ references2[ref] = [path7];
4396
+ }
4397
+ }
4398
+ }
4399
+ for (const ref of Object.keys(references2)) {
4400
+ for (const path7 of references2[ref]) {
4401
+ result.push({
4402
+ type: opType,
4403
+ key: `${ref}${INDEX_KEY_FIELD_SEPARATOR}${path7}${INDEX_KEY_FIELD_SEPARATOR}${filepath}`,
4404
+ sublevel: refSublevel,
4405
+ value: opType === "put" ? {} : void 0
4406
+ });
4407
+ }
4408
+ }
4409
+ }
4410
+ }
4411
+ return result;
4412
+ };
4413
+ var makeStringEscaper = (regex, replacement) => {
4414
+ return (input) => {
4415
+ if (Array.isArray(input)) {
4416
+ return input.map(
4417
+ (val) => val.replace(regex, replacement)
4418
+ );
4419
+ } else {
4420
+ if (typeof input === "string") {
4421
+ return input.replace(regex, replacement);
4422
+ } else {
4423
+ return input;
4424
+ }
4425
+ }
4426
+ };
4427
+ };
4428
+ var stringEscaper = makeStringEscaper(
4429
+ new RegExp(INDEX_KEY_FIELD_SEPARATOR, "gm"),
4430
+ encodeURIComponent(INDEX_KEY_FIELD_SEPARATOR)
4431
+ );
4432
+
4433
+ // src/resolver/error.ts
4434
+ var TinaGraphQLError = class extends Error {
4435
+ constructor(message, extensions) {
4436
+ super(message);
4437
+ if (!this.name) {
4438
+ Object.defineProperty(this, "name", { value: "TinaGraphQLError" });
4439
+ }
4440
+ this.extensions = { ...extensions };
4441
+ }
4442
+ };
4443
+ var TinaFetchError = class extends Error {
4444
+ constructor(message, args) {
4445
+ super(message);
4446
+ this.name = "TinaFetchError";
4447
+ this.collection = args.collection;
4448
+ this.file = args.file;
4449
+ this.originalError = args.originalError;
4450
+ }
4451
+ };
4452
+ var TinaQueryError = class extends TinaFetchError {
4453
+ constructor(args) {
4454
+ super(
4455
+ `Error querying file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
4456
+ args
4457
+ );
4458
+ }
4459
+ };
4460
+ var TinaParseDocumentError = class extends TinaFetchError {
4461
+ constructor(args) {
4462
+ super(
4463
+ `Error parsing file ${args.file} from collection ${args.collection}. ${auditMessage(args.includeAuditMessage)}`,
4464
+ args
4465
+ );
4466
+ }
4467
+ toString() {
4468
+ return super.toString() + "\n OriginalError: \n" + this.originalError.toString();
4469
+ }
4470
+ };
4471
+ var auditMessage = (includeAuditMessage = true) => includeAuditMessage ? `Please run "tinacms audit" or add the --verbose option for more info` : "";
4472
+ var handleFetchErrorError = (e, verbose) => {
4473
+ if (e instanceof Error) {
4474
+ if (e instanceof TinaFetchError) {
4475
+ if (verbose) {
4476
+ console.log(e.toString());
4477
+ console.log(e);
4478
+ console.log(e.stack);
4479
+ }
4480
+ }
4481
+ } else {
4482
+ console.error(e);
4483
+ }
4484
+ throw e;
4485
+ };
4486
+
4487
+ // src/resolver/filter-utils.ts
4488
+ var resolveReferences = async (filter, fields, resolver) => {
4489
+ for (const fieldKey of Object.keys(filter)) {
4490
+ const fieldDefinition = fields.find(
4491
+ (f) => f.name === fieldKey
4492
+ );
4493
+ if (fieldDefinition) {
4494
+ if (fieldDefinition.type === "reference") {
4495
+ const { edges, values } = await resolver(filter, fieldDefinition);
4496
+ if (edges.length === 1) {
4497
+ filter[fieldKey] = {
4498
+ eq: values[0]
4499
+ };
4500
+ } else if (edges.length > 1) {
4501
+ filter[fieldKey] = {
4502
+ in: values
4503
+ };
4504
+ } else {
4505
+ filter[fieldKey] = {
4506
+ eq: "___null___"
4507
+ };
4508
+ }
4509
+ } else if (fieldDefinition.type === "object") {
4510
+ if (fieldDefinition.templates) {
4511
+ for (const templateName of Object.keys(filter[fieldKey])) {
4512
+ const template = fieldDefinition.templates.find(
4513
+ (template2) => !(typeof template2 === "string") && template2.name === templateName
4514
+ );
4515
+ if (template) {
4516
+ await resolveReferences(
4517
+ filter[fieldKey][templateName],
4518
+ template.fields,
4519
+ resolver
4520
+ );
4521
+ } else {
4522
+ throw new Error(`Template ${templateName} not found`);
4523
+ }
4524
+ }
4525
+ } else {
4526
+ await resolveReferences(
4527
+ filter[fieldKey],
4528
+ fieldDefinition.fields,
4529
+ resolver
4530
+ );
4531
+ }
4532
+ }
4533
+ } else {
4534
+ throw new Error(`Unable to find field ${fieldKey}`);
4535
+ }
4536
+ }
4537
+ };
4538
+ var collectConditionsForChildFields = (filterNode, fields, pathExpression, collectCondition) => {
4539
+ for (const childFieldName of Object.keys(filterNode)) {
4540
+ const childField = fields.find((field) => field.name === childFieldName);
4541
+ if (!childField) {
4542
+ throw new Error(`Unable to find type for field ${childFieldName}`);
4543
+ }
4544
+ collectConditionsForField(
4545
+ childFieldName,
4546
+ childField,
4547
+ filterNode[childFieldName],
4548
+ pathExpression,
4549
+ collectCondition
4550
+ );
4551
+ }
4552
+ };
4553
+ var collectConditionsForObjectField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
4554
+ if (field.list && field.templates) {
4555
+ for (const [filterKey, childFilterNode] of Object.entries(filterNode)) {
4556
+ const template = field.templates.find(
4557
+ (template2) => !(typeof template2 === "string") && template2.name === filterKey
4558
+ );
4559
+ const jsonPath = `${fieldName}[?(@._template=="${filterKey}")]`;
4560
+ const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : jsonPath;
4561
+ collectConditionsForChildFields(
4562
+ childFilterNode,
4563
+ template.fields,
4564
+ filterPath,
4565
+ collectCondition
4566
+ );
4567
+ }
4568
+ } else {
4569
+ const jsonPath = `${fieldName}${field.list ? "[*]" : ""}`;
4570
+ const filterPath = pathExpression ? `${pathExpression}.${jsonPath}` : `${jsonPath}`;
4571
+ collectConditionsForChildFields(
4572
+ filterNode,
4573
+ field.fields,
4574
+ filterPath,
4575
+ collectCondition
4576
+ );
4577
+ }
4578
+ };
4579
+ var collectConditionsForField = (fieldName, field, filterNode, pathExpression, collectCondition) => {
4580
+ if (field.type === "object") {
4581
+ collectConditionsForObjectField(
4582
+ fieldName,
4583
+ field,
4584
+ filterNode,
4585
+ pathExpression,
4586
+ collectCondition
4587
+ );
4588
+ } else {
4589
+ collectCondition({
4590
+ filterPath: pathExpression ? `${pathExpression}.${fieldName}` : fieldName,
4591
+ filterExpression: {
4592
+ _type: field.type,
4593
+ _list: !!field.list,
4594
+ ...filterNode
4595
+ }
4596
+ });
4615
4597
  }
4616
- return result;
4617
4598
  };
4618
- var makeRefOpsForDocument = (filepath, collection, references, data, opType, level) => {
4619
- const result = [];
4620
- if (collection) {
4621
- for (const [c, referencePaths] of Object.entries(references || {})) {
4622
- if (!referencePaths.length) {
4623
- continue;
4624
- }
4625
- const collectionSublevel = level.sublevel(c, SUBLEVEL_OPTIONS);
4626
- const refSublevel = collectionSublevel.sublevel(
4627
- REFS_COLLECTIONS_SORT_KEY,
4628
- SUBLEVEL_OPTIONS
4629
- );
4630
- const references2 = {};
4631
- for (const path7 of referencePaths) {
4632
- const ref = (0, import_jsonpath_plus.JSONPath)({ path: path7, json: data });
4633
- if (!ref) {
4634
- continue;
4635
- }
4636
- if (Array.isArray(ref)) {
4637
- for (const r of ref) {
4638
- if (!r) {
4639
- continue;
4640
- }
4641
- if (references2[r]) {
4642
- references2[r].push(path7);
4643
- } else {
4644
- references2[r] = [path7];
4645
- }
4646
- }
4647
- } else {
4648
- if (references2[ref]) {
4649
- references2[ref].push(path7);
4650
- } else {
4651
- references2[ref] = [path7];
4652
- }
4653
- }
4599
+
4600
+ // src/resolver/media-utils.ts
4601
+ var resolveMediaCloudToRelative = (value, config = { useRelativeMedia: true }, schema) => {
4602
+ if (config && value) {
4603
+ if (config.useRelativeMedia === true) {
4604
+ return value;
4605
+ }
4606
+ if (hasTinaMediaConfig(schema) === true) {
4607
+ const assetsURL = `https://${config.assetsHost}/${config.clientId}`;
4608
+ if (typeof value === "string" && value.includes(assetsURL)) {
4609
+ const cleanMediaRoot = cleanUpSlashes(
4610
+ schema.config.media.tina.mediaRoot
4611
+ );
4612
+ const strippedURL = value.replace(assetsURL, "");
4613
+ return `${cleanMediaRoot}${strippedURL}`;
4654
4614
  }
4655
- for (const ref of Object.keys(references2)) {
4656
- for (const path7 of references2[ref]) {
4657
- result.push({
4658
- type: opType,
4659
- key: `${ref}${INDEX_KEY_FIELD_SEPARATOR}${path7}${INDEX_KEY_FIELD_SEPARATOR}${filepath}`,
4660
- sublevel: refSublevel,
4661
- value: opType === "put" ? {} : void 0
4662
- });
4663
- }
4615
+ if (Array.isArray(value)) {
4616
+ return value.map((v) => {
4617
+ if (!v || typeof v !== "string") return v;
4618
+ const cleanMediaRoot = cleanUpSlashes(
4619
+ schema.config.media.tina.mediaRoot
4620
+ );
4621
+ const strippedURL = v.replace(assetsURL, "");
4622
+ return `${cleanMediaRoot}${strippedURL}`;
4623
+ });
4664
4624
  }
4625
+ return value;
4665
4626
  }
4627
+ return value;
4628
+ } else {
4629
+ return value;
4666
4630
  }
4667
- return result;
4668
4631
  };
4669
- var makeStringEscaper = (regex, replacement) => {
4670
- return (input) => {
4671
- if (Array.isArray(input)) {
4672
- return input.map(
4673
- (val) => val.replace(regex, replacement)
4674
- );
4675
- } else {
4676
- if (typeof input === "string") {
4677
- return input.replace(regex, replacement);
4678
- } else {
4679
- return input;
4632
+ var resolveMediaRelativeToCloud = (value, config = { useRelativeMedia: true }, schema) => {
4633
+ if (config && value) {
4634
+ if (config.useRelativeMedia === true) {
4635
+ return value;
4636
+ }
4637
+ if (hasTinaMediaConfig(schema) === true) {
4638
+ const cleanMediaRoot = cleanUpSlashes(schema.config.media.tina.mediaRoot);
4639
+ if (typeof value === "string") {
4640
+ const strippedValue = value.replace(cleanMediaRoot, "");
4641
+ return `https://${config.assetsHost}/${config.clientId}${strippedValue}`;
4642
+ }
4643
+ if (Array.isArray(value)) {
4644
+ return value.map((v) => {
4645
+ if (!v || typeof v !== "string") return v;
4646
+ const strippedValue = v.replace(cleanMediaRoot, "");
4647
+ return `https://${config.assetsHost}/${config.clientId}${strippedValue}`;
4648
+ });
4680
4649
  }
4681
4650
  }
4682
- };
4651
+ return value;
4652
+ } else {
4653
+ return value;
4654
+ }
4655
+ };
4656
+ var cleanUpSlashes = (path7) => {
4657
+ if (path7) {
4658
+ return `/${path7.replace(/^\/+|\/+$/gm, "")}`;
4659
+ }
4660
+ return "";
4661
+ };
4662
+ var hasTinaMediaConfig = (schema) => {
4663
+ if (!schema.config?.media?.tina) return false;
4664
+ if (typeof schema.config?.media?.tina?.publicFolder !== "string" && typeof schema.config?.media?.tina?.mediaRoot !== "string")
4665
+ return false;
4666
+ return true;
4683
4667
  };
4684
- var stringEscaper = makeStringEscaper(
4685
- new RegExp(INDEX_KEY_FIELD_SEPARATOR, "gm"),
4686
- encodeURIComponent(INDEX_KEY_FIELD_SEPARATOR)
4687
- );
4688
4668
 
4689
4669
  // src/resolver/index.ts
4690
4670
  var createResolver = (args) => {
4691
4671
  return new Resolver(args);
4692
4672
  };
4693
4673
  var resolveFieldData = async ({ namespace, ...field }, rawData, accumulator, tinaSchema, config, isAudit) => {
4694
- var _a, _b;
4695
4674
  if (!rawData) {
4696
4675
  return void 0;
4697
4676
  }
@@ -4719,7 +4698,7 @@ var resolveFieldData = async ({ namespace, ...field }, rawData, accumulator, tin
4719
4698
  accumulator[field.name] = {
4720
4699
  value: void 0,
4721
4700
  // never resolve the password hash
4722
- passwordChangeRequired: (_a = value["passwordChangeRequired"]) != null ? _a : false
4701
+ passwordChangeRequired: value["passwordChangeRequired"] ?? false
4723
4702
  };
4724
4703
  break;
4725
4704
  case "image":
@@ -4735,11 +4714,11 @@ var resolveFieldData = async ({ namespace, ...field }, rawData, accumulator, tin
4735
4714
  field,
4736
4715
  (value2) => resolveMediaRelativeToCloud(value2, config, tinaSchema.schema)
4737
4716
  );
4738
- if (((_b = tree == null ? void 0 : tree.children[0]) == null ? void 0 : _b.type) === "invalid_markdown") {
4717
+ if (tree?.children[0]?.type === "invalid_markdown") {
4739
4718
  if (isAudit) {
4740
- const invalidNode = tree == null ? void 0 : tree.children[0];
4719
+ const invalidNode = tree?.children[0];
4741
4720
  throw new import_graphql3.GraphQLError(
4742
- `${invalidNode == null ? void 0 : invalidNode.message}${invalidNode.position ? ` at line ${invalidNode.position.start.line}, column ${invalidNode.position.start.column}` : ""}`
4721
+ `${invalidNode?.message}${invalidNode.position ? ` at line ${invalidNode.position.start.line}, column ${invalidNode.position.start.column}` : ""}`
4743
4722
  );
4744
4723
  }
4745
4724
  }
@@ -4847,16 +4826,15 @@ var transformDocumentIntoPayload = async (fullPath, rawData, tinaSchema, config,
4847
4826
  originalError: e,
4848
4827
  collection: collection.name,
4849
4828
  includeAuditMessage: !isAudit,
4850
- file: relativePath,
4851
- stack: e.stack
4829
+ file: relativePath
4852
4830
  });
4853
4831
  }
4854
4832
  const titleField = template.fields.find((x) => {
4855
- if (x.type === "string" && (x == null ? void 0 : x.isTitle)) {
4833
+ if (x.type === "string" && x?.isTitle) {
4856
4834
  return true;
4857
4835
  }
4858
4836
  });
4859
- const titleFieldName = titleField == null ? void 0 : titleField.name;
4837
+ const titleFieldName = titleField?.name;
4860
4838
  const title = data[titleFieldName || " "] || null;
4861
4839
  return {
4862
4840
  __typename: collection.fields ? NAMER.documentTypeName(collection.namespace) : NAMER.documentTypeName(template.namespace),
@@ -4966,7 +4944,7 @@ var Resolver = class {
4966
4944
  );
4967
4945
  }
4968
4946
  const rawData = await this.getRaw(fullPath);
4969
- const hasReferences = (opts == null ? void 0 : opts.checkReferences) ? await this.hasReferences(fullPath, opts.collection) : void 0;
4947
+ const hasReferences = opts?.checkReferences ? await this.hasReferences(fullPath, opts.collection) : void 0;
4970
4948
  return transformDocumentIntoPayload(
4971
4949
  fullPath,
4972
4950
  rawData,
@@ -5006,9 +4984,9 @@ var Resolver = class {
5006
4984
  return this.buildFieldMutations(
5007
4985
  item,
5008
4986
  objectTemplate,
5009
- idField && existingData && (existingData == null ? void 0 : existingData.find(
4987
+ idField && existingData && existingData?.find(
5010
4988
  (d) => d[idField.name] === item[idField.name]
5011
- ))
4989
+ )
5012
4990
  );
5013
4991
  }
5014
4992
  )
@@ -5134,7 +5112,7 @@ var Resolver = class {
5134
5112
  isCollectionSpecific
5135
5113
  }) => {
5136
5114
  const doc = await this.getDocument(realPath);
5137
- const oldDoc = this.resolveLegacyValues((doc == null ? void 0 : doc._rawData) || {}, collection);
5115
+ const oldDoc = this.resolveLegacyValues(doc?._rawData || {}, collection);
5138
5116
  if (isAddPendingDocument === true) {
5139
5117
  const templateInfo = this.tinaSchema.getTemplatesForCollectable(collection);
5140
5118
  const params2 = this.buildParams(args);
@@ -5144,7 +5122,7 @@ var Resolver = class {
5144
5122
  const values = await this.buildFieldMutations(
5145
5123
  params2,
5146
5124
  templateInfo.template,
5147
- doc == null ? void 0 : doc._rawData
5125
+ doc?._rawData
5148
5126
  );
5149
5127
  await this.database.put(
5150
5128
  realPath,
@@ -5168,7 +5146,7 @@ var Resolver = class {
5168
5146
  // @ts-ignore FIXME: failing on unknown, which we don't need to know because it's recursive
5169
5147
  templateParams,
5170
5148
  template,
5171
- doc == null ? void 0 : doc._rawData
5149
+ doc?._rawData
5172
5150
  ),
5173
5151
  _template: lastItem(template.namespace)
5174
5152
  };
@@ -5182,7 +5160,7 @@ var Resolver = class {
5182
5160
  //@ts-ignore
5183
5161
  isCollectionSpecific ? args.params : args.params[collection.name],
5184
5162
  collection,
5185
- doc == null ? void 0 : doc._rawData
5163
+ doc?._rawData
5186
5164
  );
5187
5165
  await this.database.put(
5188
5166
  realPath,
@@ -5198,7 +5176,6 @@ var Resolver = class {
5198
5176
  this.resolveLegacyValues = (oldDoc, collection) => {
5199
5177
  const legacyValues = {};
5200
5178
  Object.entries(oldDoc).forEach(([key, value]) => {
5201
- var _a;
5202
5179
  const reservedKeys = [
5203
5180
  "$_body",
5204
5181
  "_collection",
@@ -5211,7 +5188,7 @@ var Resolver = class {
5211
5188
  return;
5212
5189
  }
5213
5190
  if (oldDoc._template && collection.templates) {
5214
- const template = (_a = collection.templates) == null ? void 0 : _a.find(
5191
+ const template = collection.templates?.find(
5215
5192
  ({ name }) => name === oldDoc._template
5216
5193
  );
5217
5194
  if (template) {
@@ -5258,7 +5235,7 @@ var Resolver = class {
5258
5235
  (yup3) => yup3.object({ relativePath: yup3.string().required() })
5259
5236
  );
5260
5237
  const collection = await this.tinaSchema.getCollection(collectionLookup);
5261
- let realPath = import_path3.default.join(collection == null ? void 0 : collection.path, args.relativePath);
5238
+ let realPath = import_path3.default.join(collection?.path, args.relativePath);
5262
5239
  if (isFolderCreation) {
5263
5240
  realPath = `${realPath}/.gitkeep.${collection.format || "md"}`;
5264
5241
  }
@@ -5342,12 +5319,12 @@ var Resolver = class {
5342
5319
  (yup3) => yup3.object({ params: yup3.object().required() })
5343
5320
  );
5344
5321
  assertShape(
5345
- args == null ? void 0 : args.params,
5322
+ args?.params,
5346
5323
  (yup3) => yup3.object({ relativePath: yup3.string().required() })
5347
5324
  );
5348
5325
  const doc = await this.getDocument(realPath);
5349
5326
  const newRealPath = import_path3.default.join(
5350
- collection == null ? void 0 : collection.path,
5327
+ collection?.path,
5351
5328
  args.params.relativePath
5352
5329
  );
5353
5330
  if (newRealPath === realPath) {
@@ -5577,7 +5554,7 @@ var Resolver = class {
5577
5554
  if (!references[c.name][refId]) {
5578
5555
  references[c.name][refId] = [];
5579
5556
  }
5580
- const referencePath = rawItem == null ? void 0 : rawItem[REFS_PATH_FIELD];
5557
+ const referencePath = rawItem?.[REFS_PATH_FIELD];
5581
5558
  if (referencePath) {
5582
5559
  references[c.name][refId].push(referencePath);
5583
5560
  }
@@ -5587,7 +5564,6 @@ var Resolver = class {
5587
5564
  return references;
5588
5565
  };
5589
5566
  this.buildFieldMutations = async (fieldParams, template, existingData) => {
5590
- var _a;
5591
5567
  const accum = {};
5592
5568
  for (const passwordField of template.fields.filter(
5593
5569
  (f) => f.type === "password"
@@ -5630,7 +5606,7 @@ var Resolver = class {
5630
5606
  accum[fieldName] = await this.buildObjectMutations(
5631
5607
  fieldValue,
5632
5608
  field,
5633
- existingData == null ? void 0 : existingData[fieldName]
5609
+ existingData?.[fieldName]
5634
5610
  );
5635
5611
  break;
5636
5612
  case "password":
@@ -5649,12 +5625,12 @@ var Resolver = class {
5649
5625
  } else {
5650
5626
  accum[fieldName] = {
5651
5627
  ...fieldValue,
5652
- value: (_a = existingData == null ? void 0 : existingData[fieldName]) == null ? void 0 : _a["value"]
5628
+ value: existingData?.[fieldName]?.["value"]
5653
5629
  };
5654
5630
  }
5655
5631
  break;
5656
5632
  case "rich-text":
5657
- accum[fieldName] = (0, import_mdx.stringifyMDX)(
5633
+ accum[fieldName] = (0, import_mdx.serializeMDX)(
5658
5634
  fieldValue,
5659
5635
  field,
5660
5636
  (fieldValue2) => resolveMediaCloudToRelative(
@@ -5761,8 +5737,129 @@ var resolveDateInput = (value) => {
5761
5737
  return date;
5762
5738
  };
5763
5739
 
5764
- // src/resolve.ts
5765
- var import_lodash4 = __toESM(require("lodash.set"));
5740
+ // src/resolver/auth-fields.ts
5741
+ var import_compat = require("es-toolkit/compat");
5742
+ async function getUserDocumentContext(tinaSchema, resolver) {
5743
+ const collection = tinaSchema.getCollections().find((c) => c.isAuthCollection);
5744
+ if (!collection) {
5745
+ throw new Error("Auth collection not found");
5746
+ }
5747
+ const userFields = mapUserFields(collection, ["_rawData"]);
5748
+ if (!userFields.length) {
5749
+ throw new Error(`No user field found in collection ${collection.name}`);
5750
+ }
5751
+ if (userFields.length > 1) {
5752
+ throw new Error(
5753
+ `Multiple user fields found in collection ${collection.name}`
5754
+ );
5755
+ }
5756
+ const userField = userFields[0];
5757
+ const realPath = `${collection.path}/index.json`;
5758
+ const userDoc = await resolver.getDocument(realPath);
5759
+ const users = get(userDoc, userField.path);
5760
+ if (!users) {
5761
+ throw new Error("No users found");
5762
+ }
5763
+ return { collection, userField, users, userDoc, realPath };
5764
+ }
5765
+ function findUserInCollection(users, userField, userSub) {
5766
+ const { idFieldName } = userField;
5767
+ if (!idFieldName) {
5768
+ throw new Error("No uid field found on user field");
5769
+ }
5770
+ return users.find((u) => u[idFieldName] === userSub) || null;
5771
+ }
5772
+ async function handleAuthenticate({
5773
+ tinaSchema,
5774
+ resolver,
5775
+ sub,
5776
+ password,
5777
+ ctxUser
5778
+ }) {
5779
+ const userSub = sub || ctxUser?.sub;
5780
+ const { userField, users } = await getUserDocumentContext(
5781
+ tinaSchema,
5782
+ resolver
5783
+ );
5784
+ const user = findUserInCollection(users, userField, userSub);
5785
+ if (!user) {
5786
+ return null;
5787
+ }
5788
+ const { passwordFieldName } = userField;
5789
+ const saltedHash = get(user, [passwordFieldName || "", "value"]);
5790
+ if (!saltedHash) {
5791
+ throw new Error("No password field found on user field");
5792
+ }
5793
+ const matches = await checkPasswordHash({
5794
+ saltedHash,
5795
+ password
5796
+ });
5797
+ return matches ? user : null;
5798
+ }
5799
+ async function handleAuthorize({
5800
+ tinaSchema,
5801
+ resolver,
5802
+ sub,
5803
+ ctxUser
5804
+ }) {
5805
+ const userSub = sub || ctxUser?.sub;
5806
+ const { userField, users } = await getUserDocumentContext(
5807
+ tinaSchema,
5808
+ resolver
5809
+ );
5810
+ const user = findUserInCollection(users, userField, userSub);
5811
+ return user ? user : null;
5812
+ }
5813
+ async function handleUpdatePassword({
5814
+ tinaSchema,
5815
+ resolver,
5816
+ password,
5817
+ ctxUser
5818
+ }) {
5819
+ if (!ctxUser?.sub) {
5820
+ throw new Error("Not authorized");
5821
+ }
5822
+ if (!password) {
5823
+ throw new Error("No password provided");
5824
+ }
5825
+ const { collection, userField, users, realPath } = await getUserDocumentContext(tinaSchema, resolver);
5826
+ const { idFieldName, passwordFieldName } = userField;
5827
+ const user = users.find((u) => u[idFieldName] === ctxUser.sub);
5828
+ if (!user) {
5829
+ throw new Error("Not authorized");
5830
+ }
5831
+ user[passwordFieldName] = {
5832
+ value: password,
5833
+ passwordChangeRequired: false
5834
+ };
5835
+ const params = {};
5836
+ (0, import_compat.set)(
5837
+ params,
5838
+ userField.path.slice(1),
5839
+ // remove _rawData from users path
5840
+ users.map((u) => {
5841
+ if (user[idFieldName] === u[idFieldName]) {
5842
+ return user;
5843
+ }
5844
+ return {
5845
+ // don't overwrite other users' passwords
5846
+ ...u,
5847
+ [passwordFieldName]: {
5848
+ ...u[passwordFieldName],
5849
+ value: ""
5850
+ }
5851
+ };
5852
+ })
5853
+ );
5854
+ await resolver.updateResolveDocument({
5855
+ collection,
5856
+ args: { params },
5857
+ realPath,
5858
+ isCollectionSpecific: true,
5859
+ isAddPendingDocument: false
5860
+ });
5861
+ return true;
5862
+ }
5766
5863
 
5767
5864
  // src/error.ts
5768
5865
  var import_graphql4 = require("graphql");
@@ -5784,9 +5881,8 @@ var resolve = async ({
5784
5881
  isAudit,
5785
5882
  ctxUser
5786
5883
  }) => {
5787
- var _a;
5788
5884
  try {
5789
- const verboseValue = verbose != null ? verbose : true;
5885
+ const verboseValue = verbose ?? true;
5790
5886
  const graphQLSchemaAst = await database.getGraphQLSchema();
5791
5887
  if (!graphQLSchemaAst) {
5792
5888
  throw new import_graphql5.GraphQLError("GraphQL schema not found");
@@ -5798,7 +5894,7 @@ var resolve = async ({
5798
5894
  // @ts-ignore
5799
5895
  schema: tinaConfig,
5800
5896
  // @ts-ignore
5801
- flags: (_a = tinaConfig == null ? void 0 : tinaConfig.meta) == null ? void 0 : _a.flags
5897
+ flags: tinaConfig?.meta?.flags
5802
5898
  });
5803
5899
  const resolver = createResolver({
5804
5900
  config,
@@ -5823,7 +5919,6 @@ var resolve = async ({
5823
5919
  throw new Error(`Unable to find lookup key for ${namedType}`);
5824
5920
  },
5825
5921
  fieldResolver: async (source = {}, _args = {}, _context, info) => {
5826
- var _a2, _b, _c, _d;
5827
5922
  try {
5828
5923
  const args = JSON.parse(JSON.stringify(_args));
5829
5924
  const returnType = (0, import_graphql5.getNamedType)(info.returnType).toString();
@@ -5840,8 +5935,7 @@ var resolve = async ({
5840
5935
  );
5841
5936
  const hasDocuments2 = collectionNode2.selectionSet.selections.find(
5842
5937
  (x) => {
5843
- var _a3;
5844
- return ((_a3 = x == null ? void 0 : x.name) == null ? void 0 : _a3.value) === "documents";
5938
+ return x?.name?.value === "documents";
5845
5939
  }
5846
5940
  );
5847
5941
  return tinaSchema.getCollections().map((collection) => {
@@ -5857,8 +5951,7 @@ var resolve = async ({
5857
5951
  );
5858
5952
  const hasDocuments = collectionNode.selectionSet.selections.find(
5859
5953
  (x) => {
5860
- var _a3;
5861
- return ((_a3 = x == null ? void 0 : x.name) == null ? void 0 : _a3.value) === "documents";
5954
+ return x?.name?.value === "documents";
5862
5955
  }
5863
5956
  );
5864
5957
  return resolver.resolveCollection(
@@ -5876,119 +5969,33 @@ var resolve = async ({
5876
5969
  );
5877
5970
  }
5878
5971
  }
5879
- if (info.fieldName === "authenticate" || info.fieldName === "authorize") {
5880
- const sub = args.sub || (ctxUser == null ? void 0 : ctxUser.sub);
5881
- const collection = tinaSchema.getCollections().find((c) => c.isAuthCollection);
5882
- if (!collection) {
5883
- throw new Error("Auth collection not found");
5884
- }
5885
- const userFields = mapUserFields(collection, ["_rawData"]);
5886
- if (!userFields.length) {
5887
- throw new Error(
5888
- `No user field found in collection ${collection.name}`
5889
- );
5890
- }
5891
- if (userFields.length > 1) {
5892
- throw new Error(
5893
- `Multiple user fields found in collection ${collection.name}`
5894
- );
5895
- }
5896
- const userField = userFields[0];
5897
- const realPath = `${collection.path}/index.json`;
5898
- const userDoc = await resolver.getDocument(realPath);
5899
- const users = get(userDoc, userField.path);
5900
- if (!users) {
5901
- throw new Error("No users found");
5902
- }
5903
- const { idFieldName, passwordFieldName } = userField;
5904
- if (!idFieldName) {
5905
- throw new Error("No uid field found on user field");
5906
- }
5907
- const user = users.find((u) => u[idFieldName] === sub);
5908
- if (!user) {
5909
- return null;
5910
- }
5911
- if (info.fieldName === "authenticate") {
5912
- const saltedHash = get(user, [passwordFieldName || "", "value"]);
5913
- if (!saltedHash) {
5914
- throw new Error("No password field found on user field");
5915
- }
5916
- const matches = await checkPasswordHash({
5917
- saltedHash,
5918
- password: args.password
5919
- });
5920
- if (matches) {
5921
- return user;
5922
- }
5923
- return null;
5924
- }
5925
- return user;
5972
+ if (info.fieldName === "authenticate") {
5973
+ return handleAuthenticate({
5974
+ tinaSchema,
5975
+ resolver,
5976
+ sub: args.sub,
5977
+ password: args.password,
5978
+ info,
5979
+ ctxUser
5980
+ });
5981
+ }
5982
+ if (info.fieldName === "authorize") {
5983
+ return handleAuthorize({
5984
+ tinaSchema,
5985
+ resolver,
5986
+ sub: args.sub,
5987
+ info,
5988
+ ctxUser
5989
+ });
5926
5990
  }
5927
5991
  if (info.fieldName === "updatePassword") {
5928
- if (!(ctxUser == null ? void 0 : ctxUser.sub)) {
5929
- throw new Error("Not authorized");
5930
- }
5931
- if (!args.password) {
5932
- throw new Error("No password provided");
5933
- }
5934
- const collection = tinaSchema.getCollections().find((c) => c.isAuthCollection);
5935
- if (!collection) {
5936
- throw new Error("Auth collection not found");
5937
- }
5938
- const userFields = mapUserFields(collection, ["_rawData"]);
5939
- if (!userFields.length) {
5940
- throw new Error(
5941
- `No user field found in collection ${collection.name}`
5942
- );
5943
- }
5944
- if (userFields.length > 1) {
5945
- throw new Error(
5946
- `Multiple user fields found in collection ${collection.name}`
5947
- );
5948
- }
5949
- const userField = userFields[0];
5950
- const realPath = `${collection.path}/index.json`;
5951
- const userDoc = await resolver.getDocument(realPath);
5952
- const users = get(userDoc, userField.path);
5953
- if (!users) {
5954
- throw new Error("No users found");
5955
- }
5956
- const { idFieldName, passwordFieldName } = userField;
5957
- const user = users.find((u) => u[idFieldName] === ctxUser.sub);
5958
- if (!user) {
5959
- throw new Error("Not authorized");
5960
- }
5961
- user[passwordFieldName] = {
5962
- value: args.password,
5963
- passwordChangeRequired: false
5964
- };
5965
- const params = {};
5966
- (0, import_lodash4.default)(
5967
- params,
5968
- userField.path.slice(1),
5969
- // remove _rawData from users path
5970
- users.map((u) => {
5971
- if (user[idFieldName] === u[idFieldName]) {
5972
- return user;
5973
- }
5974
- return {
5975
- // don't overwrite other users' passwords
5976
- ...u,
5977
- [passwordFieldName]: {
5978
- ...u[passwordFieldName],
5979
- value: ""
5980
- }
5981
- };
5982
- })
5983
- );
5984
- await resolver.updateResolveDocument({
5985
- collection,
5986
- args: { params },
5987
- realPath,
5988
- isCollectionSpecific: true,
5989
- isAddPendingDocument: false
5992
+ return handleUpdatePassword({
5993
+ tinaSchema,
5994
+ resolver,
5995
+ password: args.password,
5996
+ info,
5997
+ ctxUser
5990
5998
  });
5991
- return true;
5992
5999
  }
5993
6000
  if (!lookup) {
5994
6001
  return value;
@@ -6008,7 +6015,7 @@ var resolve = async ({
6008
6015
  if (typeof value === "string" && value !== "") {
6009
6016
  return resolver.getDocument(value);
6010
6017
  }
6011
- if ((args == null ? void 0 : args.collection) && info.fieldName === "addPendingDocument") {
6018
+ if (args?.collection && info.fieldName === "addPendingDocument") {
6012
6019
  return resolver.resolveDocument({
6013
6020
  args: { ...args, params: {} },
6014
6021
  collection: args.collection,
@@ -6032,7 +6039,7 @@ var resolve = async ({
6032
6039
  // Right now this is the only case for deletion
6033
6040
  isDeletion: info.fieldName === "deleteDocument",
6034
6041
  isFolderCreation: info.fieldName === "createFolder",
6035
- isUpdateName: Boolean((_a2 = args == null ? void 0 : args.params) == null ? void 0 : _a2.relativePath),
6042
+ isUpdateName: Boolean(args?.params?.relativePath),
6036
6043
  isAddPendingDocument: false,
6037
6044
  isCollectionSpecific: false
6038
6045
  });
@@ -6051,16 +6058,16 @@ var resolve = async ({
6051
6058
  })
6052
6059
  };
6053
6060
  }
6054
- if (info.fieldName === "documents" && (value == null ? void 0 : value.collection) && (value == null ? void 0 : value.hasDocuments)) {
6061
+ if (info.fieldName === "documents" && value?.collection && value?.hasDocuments) {
6055
6062
  let filter = args.filter;
6056
6063
  if (
6057
6064
  // 1. Make sure that the filter exists
6058
- typeof (args == null ? void 0 : args.filter) !== "undefined" && (args == null ? void 0 : args.filter) !== null && // 2. Make sure that the collection name exists
6065
+ typeof args?.filter !== "undefined" && args?.filter !== null && // 2. Make sure that the collection name exists
6059
6066
  // @ts-ignore
6060
- typeof ((_b = value == null ? void 0 : value.collection) == null ? void 0 : _b.name) === "string" && // 3. Make sure that the collection name is in the filter and is not undefined
6067
+ typeof value?.collection?.name === "string" && // 3. Make sure that the collection name is in the filter and is not undefined
6061
6068
  // @ts-ignore
6062
- Object.keys(args.filter).includes((_c = value == null ? void 0 : value.collection) == null ? void 0 : _c.name) && // @ts-ignore
6063
- typeof args.filter[(_d = value == null ? void 0 : value.collection) == null ? void 0 : _d.name] !== "undefined"
6069
+ Object.keys(args.filter).includes(value?.collection?.name) && // @ts-ignore
6070
+ typeof args.filter[value?.collection?.name] !== "undefined"
6064
6071
  ) {
6065
6072
  filter = args.filter[value.collection.name];
6066
6073
  }
@@ -6197,15 +6204,15 @@ var TinaLevelClient = class extends import_many_level.ManyLevelGuest {
6197
6204
  };
6198
6205
 
6199
6206
  // src/database/index.ts
6200
- var import_node_path = __toESM(require("path"));
6207
+ var import_node_path = __toESM(require("node:path"));
6201
6208
  var import_graphql6 = require("graphql");
6202
6209
  var import_micromatch2 = __toESM(require("micromatch"));
6203
6210
  var import_js_sha12 = __toESM(require("js-sha1"));
6204
- var import_lodash5 = __toESM(require("lodash.set"));
6211
+ var import_compat2 = require("es-toolkit/compat");
6205
6212
  var createLocalDatabase = (config) => {
6206
- const level = new TinaLevelClient(config == null ? void 0 : config.port);
6213
+ const level = new TinaLevelClient(config?.port);
6207
6214
  level.openConnection();
6208
- const fsBridge = new FilesystemBridge((config == null ? void 0 : config.rootPath) || process.cwd());
6215
+ const fsBridge = new FilesystemBridge(config?.rootPath || process.cwd());
6209
6216
  return new Database({
6210
6217
  bridge: fsBridge,
6211
6218
  ...config || {},
@@ -6278,7 +6285,7 @@ var Database = class {
6278
6285
  );
6279
6286
  }
6280
6287
  const metadata = await metadataLevel.get(`metadata_${key}`);
6281
- return metadata == null ? void 0 : metadata.value;
6288
+ return metadata?.value;
6282
6289
  };
6283
6290
  this.setMetadata = async (key, value) => {
6284
6291
  await this.initLevel();
@@ -6300,7 +6307,7 @@ var Database = class {
6300
6307
  let level = this.contentLevel;
6301
6308
  if (this.appLevel) {
6302
6309
  collection = await this.collectionForPath(filepath);
6303
- if (collection == null ? void 0 : collection.isDetached) {
6310
+ if (collection?.isDetached) {
6304
6311
  level = this.appLevel.sublevel(collection.name, SUBLEVEL_OPTIONS);
6305
6312
  }
6306
6313
  }
@@ -6319,7 +6326,6 @@ var Database = class {
6319
6326
  }
6320
6327
  };
6321
6328
  this.addPendingDocument = async (filepath, data) => {
6322
- var _a;
6323
6329
  await this.initLevel();
6324
6330
  const dataFields = await this.formatBodyOnPayload(filepath, data);
6325
6331
  const collection = await this.collectionForPath(filepath);
@@ -6332,10 +6338,10 @@ var Database = class {
6332
6338
  collection
6333
6339
  );
6334
6340
  const indexDefinitions = await this.getIndexDefinitions(this.contentLevel);
6335
- const collectionIndexDefinitions = indexDefinitions == null ? void 0 : indexDefinitions[collection.name];
6336
- const collectionReferences = (_a = await this.getCollectionReferences()) == null ? void 0 : _a[collection.name];
6341
+ const collectionIndexDefinitions = indexDefinitions?.[collection.name];
6342
+ const collectionReferences = (await this.getCollectionReferences())?.[collection.name];
6337
6343
  const normalizedPath = (0, import_schema_tools4.normalizePath)(filepath);
6338
- if (!(collection == null ? void 0 : collection.isDetached)) {
6344
+ if (!collection?.isDetached) {
6339
6345
  if (this.bridge) {
6340
6346
  await this.bridge.put(normalizedPath, stringifiedFile);
6341
6347
  }
@@ -6353,7 +6359,7 @@ var Database = class {
6353
6359
  }
6354
6360
  }
6355
6361
  let level = this.contentLevel;
6356
- if (collection == null ? void 0 : collection.isDetached) {
6362
+ if (collection?.isDetached) {
6357
6363
  level = this.appLevel.sublevel(collection.name, SUBLEVEL_OPTIONS);
6358
6364
  }
6359
6365
  const folderTreeBuilder = new FolderTreeBuilder();
@@ -6364,7 +6370,7 @@ var Database = class {
6364
6370
  putOps = [
6365
6371
  ...makeRefOpsForDocument(
6366
6372
  normalizedPath,
6367
- collection == null ? void 0 : collection.name,
6373
+ collection?.name,
6368
6374
  collectionReferences,
6369
6375
  dataFields,
6370
6376
  "put",
@@ -6372,7 +6378,7 @@ var Database = class {
6372
6378
  ),
6373
6379
  ...makeIndexOpsForDocument(
6374
6380
  normalizedPath,
6375
- collection == null ? void 0 : collection.name,
6381
+ collection?.name,
6376
6382
  collectionIndexDefinitions,
6377
6383
  dataFields,
6378
6384
  "put",
@@ -6381,7 +6387,7 @@ var Database = class {
6381
6387
  // folder indices
6382
6388
  ...makeIndexOpsForDocument(
6383
6389
  normalizedPath,
6384
- `${collection == null ? void 0 : collection.name}_${folderKey}`,
6390
+ `${collection?.name}_${folderKey}`,
6385
6391
  collectionIndexDefinitions,
6386
6392
  dataFields,
6387
6393
  "put",
@@ -6395,7 +6401,7 @@ var Database = class {
6395
6401
  delOps = existingItem ? [
6396
6402
  ...makeRefOpsForDocument(
6397
6403
  normalizedPath,
6398
- collection == null ? void 0 : collection.name,
6404
+ collection?.name,
6399
6405
  collectionReferences,
6400
6406
  existingItem,
6401
6407
  "del",
@@ -6403,7 +6409,7 @@ var Database = class {
6403
6409
  ),
6404
6410
  ...makeIndexOpsForDocument(
6405
6411
  normalizedPath,
6406
- collection == null ? void 0 : collection.name,
6412
+ collection?.name,
6407
6413
  collectionIndexDefinitions,
6408
6414
  existingItem,
6409
6415
  "del",
@@ -6412,7 +6418,7 @@ var Database = class {
6412
6418
  // folder indices
6413
6419
  ...makeIndexOpsForDocument(
6414
6420
  normalizedPath,
6415
- `${collection == null ? void 0 : collection.name}_${folderKey}`,
6421
+ `${collection?.name}_${folderKey}`,
6416
6422
  collectionIndexDefinitions,
6417
6423
  existingItem,
6418
6424
  "del",
@@ -6436,7 +6442,6 @@ var Database = class {
6436
6442
  await level.batch(ops);
6437
6443
  };
6438
6444
  this.put = async (filepath, data, collectionName) => {
6439
- var _a, _b, _c;
6440
6445
  await this.initLevel();
6441
6446
  try {
6442
6447
  if (SYSTEM_FILES.includes(filepath)) {
@@ -6447,16 +6452,16 @@ var Database = class {
6447
6452
  const indexDefinitions = await this.getIndexDefinitions(
6448
6453
  this.contentLevel
6449
6454
  );
6450
- collectionIndexDefinitions = indexDefinitions == null ? void 0 : indexDefinitions[collectionName];
6455
+ collectionIndexDefinitions = indexDefinitions?.[collectionName];
6451
6456
  }
6452
- const collectionReferences = (_a = await this.getCollectionReferences()) == null ? void 0 : _a[collectionName];
6457
+ const collectionReferences = (await this.getCollectionReferences())?.[collectionName];
6453
6458
  const normalizedPath = (0, import_schema_tools4.normalizePath)(filepath);
6454
6459
  const dataFields = await this.formatBodyOnPayload(filepath, data);
6455
6460
  const collection = await this.collectionForPath(filepath);
6456
6461
  if (!collection) {
6457
6462
  throw new import_graphql6.GraphQLError(`Unable to find collection for ${filepath}.`);
6458
6463
  }
6459
- if (((_b = collection.match) == null ? void 0 : _b.exclude) || ((_c = collection.match) == null ? void 0 : _c.include)) {
6464
+ if (collection.match?.exclude || collection.match?.include) {
6460
6465
  const matches = this.tinaSchema.getMatches({ collection });
6461
6466
  const match = import_micromatch2.default.isMatch(filepath, matches);
6462
6467
  if (!match) {
@@ -6470,7 +6475,7 @@ var Database = class {
6470
6475
  const stringifiedFile = filepath.endsWith(
6471
6476
  `.gitkeep.${collection.format || "md"}`
6472
6477
  ) ? "" : await this.stringifyFile(filepath, dataFields, collection);
6473
- if (!(collection == null ? void 0 : collection.isDetached)) {
6478
+ if (!collection?.isDetached) {
6474
6479
  if (this.bridge) {
6475
6480
  await this.bridge.put(normalizedPath, stringifiedFile);
6476
6481
  }
@@ -6492,7 +6497,7 @@ var Database = class {
6492
6497
  filepath,
6493
6498
  collection.path || ""
6494
6499
  );
6495
- const level = (collection == null ? void 0 : collection.isDetached) ? this.appLevel.sublevel(collection == null ? void 0 : collection.name, SUBLEVEL_OPTIONS) : this.contentLevel;
6500
+ const level = collection?.isDetached ? this.appLevel.sublevel(collection?.name, SUBLEVEL_OPTIONS) : this.contentLevel;
6496
6501
  let putOps = [];
6497
6502
  let delOps = [];
6498
6503
  if (!isGitKeep(normalizedPath, collection)) {
@@ -6516,7 +6521,7 @@ var Database = class {
6516
6521
  // folder indices
6517
6522
  ...makeIndexOpsForDocument(
6518
6523
  normalizedPath,
6519
- `${collection == null ? void 0 : collection.name}_${folderKey}`,
6524
+ `${collection?.name}_${folderKey}`,
6520
6525
  collectionIndexDefinitions,
6521
6526
  dataFields,
6522
6527
  "put",
@@ -6547,7 +6552,7 @@ var Database = class {
6547
6552
  // folder indices
6548
6553
  ...makeIndexOpsForDocument(
6549
6554
  normalizedPath,
6550
- `${collection == null ? void 0 : collection.name}_${folderKey}`,
6555
+ `${collection?.name}_${folderKey}`,
6551
6556
  collectionIndexDefinitions,
6552
6557
  existingItem,
6553
6558
  "del",
@@ -6578,8 +6583,7 @@ var Database = class {
6578
6583
  throw new TinaFetchError(`Error in PUT for ${filepath}`, {
6579
6584
  originalError: error,
6580
6585
  file: filepath,
6581
- collection: collectionName,
6582
- stack: error.stack
6586
+ collection: collectionName
6583
6587
  });
6584
6588
  }
6585
6589
  };
@@ -6624,8 +6628,8 @@ var Database = class {
6624
6628
  writeTemplateKey,
6625
6629
  //templateInfo.type === 'union',
6626
6630
  {
6627
- frontmatterFormat: collection == null ? void 0 : collection.frontmatterFormat,
6628
- frontmatterDelimiters: collection == null ? void 0 : collection.frontmatterDelimiters
6631
+ frontmatterFormat: collection?.frontmatterFormat,
6632
+ frontmatterDelimiters: collection?.frontmatterDelimiters
6629
6633
  }
6630
6634
  );
6631
6635
  };
@@ -6794,8 +6798,8 @@ var Database = class {
6794
6798
  );
6795
6799
  return {
6796
6800
  name: indexField.name,
6797
- type: field == null ? void 0 : field.type,
6798
- list: !!(field == null ? void 0 : field.list)
6801
+ type: field?.type,
6802
+ list: !!field?.list
6799
6803
  };
6800
6804
  })
6801
6805
  };
@@ -6821,7 +6825,6 @@ var Database = class {
6821
6825
  return true;
6822
6826
  };
6823
6827
  this.query = async (queryOptions, hydrator) => {
6824
- var _a;
6825
6828
  await this.initLevel();
6826
6829
  const {
6827
6830
  first,
@@ -6849,14 +6852,14 @@ var Database = class {
6849
6852
  const allIndexDefinitions = await this.getIndexDefinitions(
6850
6853
  this.contentLevel
6851
6854
  );
6852
- const indexDefinitions = allIndexDefinitions == null ? void 0 : allIndexDefinitions[collection.name];
6855
+ const indexDefinitions = allIndexDefinitions?.[collection.name];
6853
6856
  if (!indexDefinitions) {
6854
6857
  throw new Error(`No indexDefinitions for collection ${collection.name}`);
6855
6858
  }
6856
6859
  const filterChain = coerceFilterChainOperands(rawFilterChain);
6857
- const indexDefinition = sort && (indexDefinitions == null ? void 0 : indexDefinitions[sort]);
6860
+ const indexDefinition = sort && indexDefinitions?.[sort];
6858
6861
  const filterSuffixes = indexDefinition && makeFilterSuffixes(filterChain, indexDefinition);
6859
- const level = (collection == null ? void 0 : collection.isDetached) ? this.appLevel.sublevel(collection == null ? void 0 : collection.name, SUBLEVEL_OPTIONS) : this.contentLevel;
6862
+ const level = collection?.isDetached ? this.appLevel.sublevel(collection?.name, SUBLEVEL_OPTIONS) : this.contentLevel;
6860
6863
  const rootLevel = level.sublevel(
6861
6864
  CONTENT_ROOT_PREFIX,
6862
6865
  SUBLEVEL_OPTIONS
@@ -6866,17 +6869,17 @@ var Database = class {
6866
6869
  SUBLEVEL_OPTIONS
6867
6870
  ).sublevel(sort, SUBLEVEL_OPTIONS) : rootLevel;
6868
6871
  if (!query.gt && !query.gte) {
6869
- query.gte = (filterSuffixes == null ? void 0 : filterSuffixes.left) ? filterSuffixes.left : "";
6872
+ query.gte = filterSuffixes?.left ? filterSuffixes.left : "";
6870
6873
  }
6871
6874
  if (!query.lt && !query.lte) {
6872
- query.lte = (filterSuffixes == null ? void 0 : filterSuffixes.right) ? `${filterSuffixes.right}\uFFFF` : "\uFFFF";
6875
+ query.lte = filterSuffixes?.right ? `${filterSuffixes.right}\uFFFF` : "\uFFFF";
6873
6876
  }
6874
6877
  let edges = [];
6875
6878
  let startKey = "";
6876
6879
  let endKey = "";
6877
6880
  let hasPreviousPage = false;
6878
6881
  let hasNextPage = false;
6879
- const fieldsPattern = ((_a = indexDefinition == null ? void 0 : indexDefinition.fields) == null ? void 0 : _a.length) ? `${indexDefinition.fields.map((p) => `(?<${p.name}>.+)${INDEX_KEY_FIELD_SEPARATOR}`).join("")}` : "";
6882
+ const fieldsPattern = indexDefinition?.fields?.length ? `${indexDefinition.fields.map((p) => `(?<${p.name}>.+)${INDEX_KEY_FIELD_SEPARATOR}`).join("")}` : "";
6880
6883
  const valuesRegex = indexDefinition ? new RegExp(`^${fieldsPattern}(?<_filepath_>.+)`) : new RegExp(`^(?<_filepath_>.+)`);
6881
6884
  const itemFilter = makeFilter({ filterChain });
6882
6885
  const iterator = sublevel.iterator(query);
@@ -6940,8 +6943,7 @@ var Database = class {
6940
6943
  throw new TinaQueryError({
6941
6944
  originalError: error,
6942
6945
  file: path7,
6943
- collection: collection.name,
6944
- stack: error.stack
6946
+ collection: collection.name
6945
6947
  });
6946
6948
  }
6947
6949
  throw error;
@@ -7071,13 +7073,14 @@ var Database = class {
7071
7073
  documentPaths,
7072
7074
  async (collection, documentPaths2) => {
7073
7075
  if (collection && !collection.isDetached) {
7074
- await _indexContent(
7075
- this,
7076
- this.contentLevel,
7077
- documentPaths2,
7076
+ await _indexContent({
7077
+ database: this,
7078
+ level: this.contentLevel,
7079
+ documentPaths: documentPaths2,
7078
7080
  enqueueOps,
7079
- collection
7080
- );
7081
+ collection,
7082
+ isPartialReindex: true
7083
+ });
7081
7084
  }
7082
7085
  }
7083
7086
  );
@@ -7087,18 +7090,17 @@ var Database = class {
7087
7090
  }
7088
7091
  };
7089
7092
  this.delete = async (filepath) => {
7090
- var _a;
7091
7093
  await this.initLevel();
7092
7094
  const collection = await this.collectionForPath(filepath);
7093
7095
  if (!collection) {
7094
7096
  throw new Error(`No collection found for path: ${filepath}`);
7095
7097
  }
7096
7098
  const indexDefinitions = await this.getIndexDefinitions(this.contentLevel);
7097
- const collectionReferences = (_a = await this.getCollectionReferences()) == null ? void 0 : _a[collection.name];
7098
- const collectionIndexDefinitions = indexDefinitions == null ? void 0 : indexDefinitions[collection.name];
7099
+ const collectionReferences = (await this.getCollectionReferences())?.[collection.name];
7100
+ const collectionIndexDefinitions = indexDefinitions?.[collection.name];
7099
7101
  let level = this.contentLevel;
7100
- if (collection == null ? void 0 : collection.isDetached) {
7101
- level = this.appLevel.sublevel(collection == null ? void 0 : collection.name, SUBLEVEL_OPTIONS);
7102
+ if (collection?.isDetached) {
7103
+ level = this.appLevel.sublevel(collection?.name, SUBLEVEL_OPTIONS);
7102
7104
  }
7103
7105
  const normalizedPath = (0, import_schema_tools4.normalizePath)(filepath);
7104
7106
  const rootSublevel = level.sublevel(
@@ -7145,7 +7147,7 @@ var Database = class {
7145
7147
  }
7146
7148
  ]);
7147
7149
  }
7148
- if (!(collection == null ? void 0 : collection.isDetached)) {
7150
+ if (!collection?.isDetached) {
7149
7151
  if (this.bridge) {
7150
7152
  await this.bridge.delete(normalizedPath);
7151
7153
  }
@@ -7185,26 +7187,26 @@ var Database = class {
7185
7187
  );
7186
7188
  const doc = await level2.keys({ limit: 1 }).next();
7187
7189
  if (!doc) {
7188
- await _indexContent(
7189
- this,
7190
- level2,
7191
- contentPaths,
7190
+ await _indexContent({
7191
+ database: this,
7192
+ level: level2,
7193
+ documentPaths: contentPaths,
7192
7194
  enqueueOps,
7193
7195
  collection,
7194
- userFields.map((field) => [
7196
+ passwordFields: userFields.map((field) => [
7195
7197
  ...field.path,
7196
7198
  field.passwordFieldName
7197
7199
  ])
7198
- );
7200
+ });
7199
7201
  }
7200
7202
  } else {
7201
- await _indexContent(
7202
- this,
7203
+ await _indexContent({
7204
+ database: this,
7203
7205
  level,
7204
- contentPaths,
7206
+ documentPaths: contentPaths,
7205
7207
  enqueueOps,
7206
7208
  collection
7207
- );
7209
+ });
7208
7210
  }
7209
7211
  }
7210
7212
  );
@@ -7240,7 +7242,7 @@ var Database = class {
7240
7242
  );
7241
7243
  }
7242
7244
  const metadata = await metadataLevel.get("metadata");
7243
- return metadata == null ? void 0 : metadata.version;
7245
+ return metadata?.version;
7244
7246
  }
7245
7247
  async initLevel() {
7246
7248
  if (this.contentLevel) {
@@ -7317,7 +7319,7 @@ var hashPasswordVisitor = async (node, path7) => {
7317
7319
  const passwordValuePath = [...path7, "value"];
7318
7320
  const plaintextPassword = get(node, passwordValuePath);
7319
7321
  if (plaintextPassword) {
7320
- (0, import_lodash5.default)(
7322
+ (0, import_compat2.set)(
7321
7323
  node,
7322
7324
  passwordValuePath,
7323
7325
  await generatePasswordHash({ password: plaintextPassword })
@@ -7326,7 +7328,7 @@ var hashPasswordVisitor = async (node, path7) => {
7326
7328
  };
7327
7329
  var visitNodes = async (node, path7, callback) => {
7328
7330
  const [currentLevel, ...remainingLevels] = path7;
7329
- if (!(remainingLevels == null ? void 0 : remainingLevels.length)) {
7331
+ if (!remainingLevels?.length) {
7330
7332
  return callback(node, path7);
7331
7333
  }
7332
7334
  if (Array.isArray(node[currentLevel])) {
@@ -7342,20 +7344,27 @@ var hashPasswordValues = async (data, passwordFields) => Promise.all(
7342
7344
  async (passwordField) => visitNodes(data, passwordField, hashPasswordVisitor)
7343
7345
  )
7344
7346
  );
7345
- var isGitKeep = (filepath, collection) => filepath.endsWith(`.gitkeep.${(collection == null ? void 0 : collection.format) || "md"}`);
7346
- var _indexContent = async (database, level, documentPaths, enqueueOps, collection, passwordFields) => {
7347
- var _a;
7347
+ var isGitKeep = (filepath, collection) => filepath.endsWith(`.gitkeep.${collection?.format || "md"}`);
7348
+ var _indexContent = async ({
7349
+ database,
7350
+ level,
7351
+ documentPaths,
7352
+ enqueueOps,
7353
+ collection,
7354
+ passwordFields,
7355
+ isPartialReindex
7356
+ }) => {
7348
7357
  let collectionIndexDefinitions;
7349
7358
  let collectionPath;
7350
7359
  if (collection) {
7351
7360
  const indexDefinitions = await database.getIndexDefinitions(level);
7352
- collectionIndexDefinitions = indexDefinitions == null ? void 0 : indexDefinitions[collection.name];
7361
+ collectionIndexDefinitions = indexDefinitions?.[collection.name];
7353
7362
  if (!collectionIndexDefinitions) {
7354
7363
  throw new Error(`No indexDefinitions for collection ${collection.name}`);
7355
7364
  }
7356
7365
  collectionPath = collection.path;
7357
7366
  }
7358
- const collectionReferences = (_a = await database.getCollectionReferences()) == null ? void 0 : _a[collection == null ? void 0 : collection.name];
7367
+ const collectionReferences = (await database.getCollectionReferences())?.[collection?.name];
7359
7368
  const tinaSchema = await database.getSchema();
7360
7369
  let templateInfo = null;
7361
7370
  if (collection) {
@@ -7373,7 +7382,7 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7373
7382
  if (!aliasedData) {
7374
7383
  return;
7375
7384
  }
7376
- if (passwordFields == null ? void 0 : passwordFields.length) {
7385
+ if (passwordFields?.length) {
7377
7386
  await hashPasswordValues(aliasedData, passwordFields);
7378
7387
  }
7379
7388
  const normalizedPath = (0, import_schema_tools4.normalizePath)(filepath);
@@ -7385,46 +7394,48 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7385
7394
  normalizedPath,
7386
7395
  collectionPath || ""
7387
7396
  );
7388
- const item = await rootSublevel.get(normalizedPath);
7389
- if (item) {
7390
- await database.contentLevel.batch([
7391
- ...makeRefOpsForDocument(
7392
- normalizedPath,
7393
- collection == null ? void 0 : collection.name,
7394
- collectionReferences,
7395
- item,
7396
- "del",
7397
- level
7398
- ),
7399
- ...makeIndexOpsForDocument(
7400
- normalizedPath,
7401
- collection.name,
7402
- collectionIndexDefinitions,
7403
- item,
7404
- "del",
7405
- level
7406
- ),
7407
- // folder indices
7408
- ...makeIndexOpsForDocument(
7409
- normalizedPath,
7410
- `${collection.name}_${folderKey}`,
7411
- collectionIndexDefinitions,
7412
- item,
7413
- "del",
7414
- level
7415
- ),
7416
- {
7417
- type: "del",
7418
- key: normalizedPath,
7419
- sublevel: rootSublevel
7420
- }
7421
- ]);
7397
+ if (isPartialReindex) {
7398
+ const item = await rootSublevel.get(normalizedPath);
7399
+ if (item) {
7400
+ await database.contentLevel.batch([
7401
+ ...makeRefOpsForDocument(
7402
+ normalizedPath,
7403
+ collection?.name,
7404
+ collectionReferences,
7405
+ item,
7406
+ "del",
7407
+ level
7408
+ ),
7409
+ ...makeIndexOpsForDocument(
7410
+ normalizedPath,
7411
+ collection.name,
7412
+ collectionIndexDefinitions,
7413
+ item,
7414
+ "del",
7415
+ level
7416
+ ),
7417
+ // folder indices
7418
+ ...makeIndexOpsForDocument(
7419
+ normalizedPath,
7420
+ `${collection.name}_${folderKey}`,
7421
+ collectionIndexDefinitions,
7422
+ item,
7423
+ "del",
7424
+ level
7425
+ ),
7426
+ {
7427
+ type: "del",
7428
+ key: normalizedPath,
7429
+ sublevel: rootSublevel
7430
+ }
7431
+ ]);
7432
+ }
7422
7433
  }
7423
7434
  if (!isGitKeep(filepath, collection)) {
7424
7435
  await enqueueOps([
7425
7436
  ...makeRefOpsForDocument(
7426
7437
  normalizedPath,
7427
- collection == null ? void 0 : collection.name,
7438
+ collection?.name,
7428
7439
  collectionReferences,
7429
7440
  aliasedData,
7430
7441
  "put",
@@ -7432,7 +7443,7 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7432
7443
  ),
7433
7444
  ...makeIndexOpsForDocument(
7434
7445
  normalizedPath,
7435
- collection == null ? void 0 : collection.name,
7446
+ collection?.name,
7436
7447
  collectionIndexDefinitions,
7437
7448
  aliasedData,
7438
7449
  "put",
@@ -7441,7 +7452,7 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7441
7452
  // folder indexes
7442
7453
  ...makeIndexOpsForDocument(
7443
7454
  normalizedPath,
7444
- `${collection == null ? void 0 : collection.name}_${folderKey}`,
7455
+ `${collection?.name}_${folderKey}`,
7445
7456
  collectionIndexDefinitions,
7446
7457
  aliasedData,
7447
7458
  "put",
@@ -7462,8 +7473,7 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7462
7473
  throw new TinaFetchError(`Unable to seed ${filepath}`, {
7463
7474
  originalError: error,
7464
7475
  file: filepath,
7465
- collection: collection == null ? void 0 : collection.name,
7466
- stack: error.stack
7476
+ collection: collection?.name
7467
7477
  });
7468
7478
  }
7469
7479
  });
@@ -7480,7 +7490,6 @@ var _indexContent = async (database, level, documentPaths, enqueueOps, collectio
7480
7490
  }
7481
7491
  };
7482
7492
  var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection) => {
7483
- var _a;
7484
7493
  if (!documentPaths.length) {
7485
7494
  return;
7486
7495
  }
@@ -7489,12 +7498,12 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7489
7498
  const indexDefinitions = await database.getIndexDefinitions(
7490
7499
  database.contentLevel
7491
7500
  );
7492
- collectionIndexDefinitions = indexDefinitions == null ? void 0 : indexDefinitions[collection.name];
7501
+ collectionIndexDefinitions = indexDefinitions?.[collection.name];
7493
7502
  if (!collectionIndexDefinitions) {
7494
7503
  throw new Error(`No indexDefinitions for collection ${collection.name}`);
7495
7504
  }
7496
7505
  }
7497
- const collectionReferences = (_a = await database.getCollectionReferences()) == null ? void 0 : _a[collection == null ? void 0 : collection.name];
7506
+ const collectionReferences = (await database.getCollectionReferences())?.[collection?.name];
7498
7507
  const tinaSchema = await database.getSchema();
7499
7508
  let templateInfo = null;
7500
7509
  if (collection) {
@@ -7511,7 +7520,7 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7511
7520
  if (item) {
7512
7521
  const folderKey = folderTreeBuilder.update(
7513
7522
  itemKey,
7514
- (collection == null ? void 0 : collection.path) || ""
7523
+ collection?.path || ""
7515
7524
  );
7516
7525
  const aliasedData = templateInfo ? replaceNameOverrides(
7517
7526
  getTemplateForFile(templateInfo, item),
@@ -7520,7 +7529,7 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7520
7529
  await enqueueOps([
7521
7530
  ...makeRefOpsForDocument(
7522
7531
  itemKey,
7523
- collection == null ? void 0 : collection.name,
7532
+ collection?.name,
7524
7533
  collectionReferences,
7525
7534
  aliasedData,
7526
7535
  "del",
@@ -7537,7 +7546,7 @@ var _deleteIndexContent = async (database, documentPaths, enqueueOps, collection
7537
7546
  // folder indexes
7538
7547
  ...makeIndexOpsForDocument(
7539
7548
  itemKey,
7540
- `${collection == null ? void 0 : collection.name}_${folderKey}`,
7549
+ `${collection?.name}_${folderKey}`,
7541
7550
  collectionIndexDefinitions,
7542
7551
  aliasedData,
7543
7552
  "del",
@@ -7622,12 +7631,12 @@ var getChangedFiles = async ({
7622
7631
  }
7623
7632
  }
7624
7633
  }
7625
- if (await (B == null ? void 0 : B.type()) === "tree") {
7634
+ if (await B?.type() === "tree") {
7626
7635
  return;
7627
7636
  }
7628
7637
  if (matches) {
7629
- const oidA = await (A == null ? void 0 : A.oid());
7630
- const oidB = await (B == null ? void 0 : B.oid());
7638
+ const oidA = await A?.oid();
7639
+ const oidB = await B?.oid();
7631
7640
  if (oidA !== oidB) {
7632
7641
  if (oidA === void 0) {
7633
7642
  results.added.push(relativePath);
@@ -7655,8 +7664,8 @@ var import_path5 = __toESM(require("path"));
7655
7664
  var import_normalize_path = __toESM(require("normalize-path"));
7656
7665
  var FilesystemBridge = class {
7657
7666
  constructor(rootPath, outputPath) {
7658
- this.rootPath = rootPath || "";
7659
- this.outputPath = outputPath || rootPath;
7667
+ this.rootPath = import_path5.default.resolve(rootPath);
7668
+ this.outputPath = outputPath ? import_path5.default.resolve(outputPath) : this.rootPath;
7660
7669
  }
7661
7670
  async glob(pattern, extension) {
7662
7671
  const basePath = import_path5.default.join(this.outputPath, ...pattern.split("/"));
@@ -7668,19 +7677,19 @@ var FilesystemBridge = class {
7668
7677
  }
7669
7678
  );
7670
7679
  const posixRootPath = (0, import_normalize_path.default)(this.outputPath);
7671
- return items.map((item) => {
7672
- return item.replace(posixRootPath, "").replace(/^\/|\/$/g, "");
7673
- });
7680
+ return items.map(
7681
+ (item) => item.substring(posixRootPath.length).replace(/^\/|\/$/g, "")
7682
+ );
7674
7683
  }
7675
7684
  async delete(filepath) {
7676
7685
  await import_fs_extra2.default.remove(import_path5.default.join(this.outputPath, filepath));
7677
7686
  }
7678
7687
  async get(filepath) {
7679
- return import_fs_extra2.default.readFileSync(import_path5.default.join(this.outputPath, filepath)).toString();
7688
+ return (await import_fs_extra2.default.readFile(import_path5.default.join(this.outputPath, filepath))).toString();
7680
7689
  }
7681
7690
  async put(filepath, data, basePathOverride) {
7682
7691
  const basePath = basePathOverride || this.outputPath;
7683
- await import_fs_extra2.default.outputFileSync(import_path5.default.join(basePath, filepath), data);
7692
+ await import_fs_extra2.default.outputFile(import_path5.default.join(basePath, filepath), data);
7684
7693
  }
7685
7694
  };
7686
7695
  var AuditFileSystemBridge = class extends FilesystemBridge {