@rebasepro/common 0.10.1-canary.8d27c46 → 0.10.1-canary.af2af91

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
@@ -463,6 +463,19 @@ function sanitizeRelation(relation, sourceCollection, resolveCollection) {
463
463
  if (newRelation.cardinality === "many" && newRelation.direction === "inverse" && !newRelation.foreignKeyOnTarget && !newRelation.joinPath && !newRelation.inverseRelationName) throw new Error(`Configuration Error in relation from '${sourceCollection.name}': An 'inverse' one-to-many relation requires a 'foreignKeyOnTarget'. Check the relation config for '${newRelation.relationName}'`);
464
464
  return newRelation;
465
465
  }
466
+ /**
467
+ * Whether the target rows of this relation are reached through a junction — a
468
+ * many-to-many, or a multi-hop `joinPath`.
469
+ *
470
+ * The distinction decides what a write "through" the relation may touch: a
471
+ * junction-backed target is shared with other parents, so the parent owns the
472
+ * *link* and not the row. The backend enforces that (an unlink rather than a
473
+ * delete) and the admin renders it (remove-from-parent rather than delete), so
474
+ * the predicate lives here rather than once per side.
475
+ */
476
+ function isJunctionBackedRelation(relation) {
477
+ return Boolean(relation.through) || Boolean(relation.joinPath && relation.joinPath.length > 1);
478
+ }
466
479
  /** WeakMap cache — same collection instance always yields the same relation map. */
467
480
  var _resolvedRelationsCache = /* @__PURE__ */ new WeakMap();
468
481
  function resolveCollectionRelations(collection) {
@@ -721,34 +734,115 @@ function resolveEnumValues(input) {
721
734
  else if (Array.isArray(input)) return input;
722
735
  else return;
723
736
  }
724
- function getSubcollections(collection) {
725
- if (collection.childCollections) return collection.childCollections() ?? [];
726
- const declaredSubcollections = getDeclaredSubcollections(collection);
727
- if (getDataSourceCapabilities(collection.engine).supportsSubcollections && declaredSubcollections) return declaredSubcollections() ?? [];
728
- if (getDataSourceCapabilities(collection.engine).supportsRelations) {
729
- const resolvedRelations = resolveCollectionRelations(collection);
730
- return Object.values(resolvedRelations).filter((r) => r.cardinality === "many").map((r) => {
731
- const target = r.target();
732
- if (!target) return void 0;
733
- const relationKey = r.relationName || target.slug;
734
- let customName;
735
- if (collection.properties) {
736
- const prop = Object.entries(collection.properties).find(([_, p]) => p.type === "relation" && p.relationName === relationKey);
737
- if (prop && prop[1].name) customName = prop[1].name;
737
+ /**
738
+ * Relation identities that only ever appear *below* the top level of
739
+ * `properties` — inside a `map`, an `array`, or a `oneOf` branch.
740
+ *
741
+ * A relation declared at the top level is a list hanging off the record and
742
+ * earns a tab. One declared inside a map is a field of that map. Both end up in
743
+ * the collection's flat `relations` array after normalization, so the shape of
744
+ * `properties` is the only remaining evidence of which is which.
745
+ *
746
+ * An identity declared in both places is *not* nested-only, and keeps its tab.
747
+ */
748
+ function getNestedRelationIdentities(properties) {
749
+ const topLevel = /* @__PURE__ */ new Set();
750
+ const nested = /* @__PURE__ */ new Set();
751
+ const walk = (props, depth) => {
752
+ if (!props) return;
753
+ for (const [key, property] of Object.entries(props)) {
754
+ if (!property) continue;
755
+ if (property.type === "relation") {
756
+ const relProp = property;
757
+ (depth === 0 ? topLevel : nested).add(relProp.relationName ?? key);
758
+ } else if (property.type === "map") walk(property.properties, depth + 1);
759
+ else if (property.type === "array") {
760
+ const arrayProp = property;
761
+ if (Array.isArray(arrayProp.of)) arrayProp.of.forEach((p) => walk({ entry: p }, depth + 1));
762
+ else if (arrayProp.of) walk({ entry: arrayProp.of }, depth + 1);
763
+ if (arrayProp.oneOf?.properties) walk(arrayProp.oneOf.properties, depth + 1);
738
764
  }
739
- const baseOverrides = { slug: relationKey };
740
- if (customName) {
741
- baseOverrides.name = customName;
742
- baseOverrides.singularName = customName;
765
+ }
766
+ };
767
+ walk(properties, 0);
768
+ for (const identity of topLevel) nested.delete(identity);
769
+ return nested;
770
+ }
771
+ /**
772
+ * The lists rendered inside an entity view of `collection` — its tabs.
773
+ *
774
+ * The single derivation. There used to be two that disagreed: this one, and a
775
+ * copy in `CollectionRegistry.normalizeCollection` that stamped each child with
776
+ * the *target collection's* slug instead of the relation key. Since the
777
+ * registry ran first and cached its answer onto `childCollections`, its version
778
+ * was the one that won, and the frontend addressed child listings by a segment
779
+ * the backend could not resolve.
780
+ *
781
+ * Order of precedence:
782
+ * 1. `childCollections` — the explicit escape hatch for custom drivers.
783
+ * 2. `subcollections` on an engine that has real containment (Firestore).
784
+ * 3. many-relations on an engine that has relations (SQL).
785
+ */
786
+ function getEntityChildViews(collection) {
787
+ const asSubcollections = (collections) => collections.filter(Boolean).map((child) => ({
788
+ key: child.slug,
789
+ collection: child,
790
+ source: { kind: "subcollection" }
791
+ }));
792
+ if (collection.childCollections) return asSubcollections(collection.childCollections() ?? []);
793
+ const capabilities = getDataSourceCapabilities(collection.engine);
794
+ const declaredSubcollections = getDeclaredSubcollections(collection);
795
+ if (capabilities.supportsSubcollections && declaredSubcollections) return asSubcollections(declaredSubcollections() ?? []);
796
+ if (!capabilities.supportsRelations) return [];
797
+ const resolvedRelations = resolveCollectionRelations(collection);
798
+ const nestedOnly = getNestedRelationIdentities(collection.properties);
799
+ const views = [];
800
+ const seen = /* @__PURE__ */ new Set();
801
+ for (const [relationKey, relation] of Object.entries(resolvedRelations)) {
802
+ if (relation.cardinality !== "many") continue;
803
+ const identity = relation.relationName ?? relationKey;
804
+ if (seen.has(identity)) continue;
805
+ if (nestedOnly.has(identity)) continue;
806
+ let target;
807
+ try {
808
+ target = relation.target();
809
+ } catch {
810
+ continue;
811
+ }
812
+ if (!target) continue;
813
+ seen.add(identity);
814
+ const customName = Object.entries(collection.properties ?? {}).find(([propKey, p]) => p.type === "relation" && (p.relationName ?? propKey) === identity)?.[1]?.name;
815
+ const base = {
816
+ ...target,
817
+ slug: relationKey,
818
+ ...customName ? {
819
+ name: customName,
820
+ singularName: customName
821
+ } : {}
822
+ };
823
+ views.push({
824
+ key: relationKey,
825
+ collection: relation.overrides ? mergeDeep(base, relation.overrides) : base,
826
+ source: {
827
+ kind: "relation",
828
+ relationKey,
829
+ mode: isJunctionBackedRelation(relation) ? "linked" : "owned",
830
+ targetSlug: target.slug
743
831
  }
744
- const targetWithOverrides = {
745
- ...target,
746
- ...baseOverrides
747
- };
748
- return r.overrides ? mergeDeep(targetWithOverrides, r.overrides) : targetWithOverrides;
749
- }).filter((c) => Boolean(c));
832
+ });
750
833
  }
751
- return [];
834
+ return views;
835
+ }
836
+ /**
837
+ * The child views of `collection` as bare collections.
838
+ *
839
+ * The flattened view of {@link getEntityChildViews}, for navigation code that
840
+ * only needs to match a path segment against a slug. Anything that cares *what
841
+ * kind* of list it is showing — chiefly the admin, which must not offer a
842
+ * global delete on a shared row — should read the views instead.
843
+ */
844
+ function getSubcollections(collection) {
845
+ return getEntityChildViews(collection).map((view) => view.collection);
752
846
  }
753
847
  //#endregion
754
848
  //#region src/util/policy/sqlToPolicy.ts
@@ -2098,18 +2192,6 @@ var CollectionRegistry = class {
2098
2192
  relResult.relations = mergedRelations;
2099
2193
  }
2100
2194
  result.properties = this.normalizeProperties(result.properties, mergedRelations);
2101
- if (!result.childCollections) {
2102
- const capabilities = getDataSourceCapabilities(result.engine);
2103
- const declaredSubcollections = getDeclaredSubcollections(result);
2104
- if (capabilities.supportsSubcollections && declaredSubcollections) result.childCollections = declaredSubcollections;
2105
- else if (capabilities.supportsRelations && relResult.relations) {
2106
- const manyRelations = relResult.relations.filter((r) => r.cardinality === "many");
2107
- if (manyRelations.length > 0) result.childCollections = () => manyRelations.map((r) => {
2108
- const target = r.target();
2109
- return r.overrides ? mergeDeep(target, r.overrides) : target;
2110
- });
2111
- }
2112
- }
2113
2195
  return result;
2114
2196
  }
2115
2197
  /**
@@ -2208,9 +2290,7 @@ var CollectionRegistry = class {
2208
2290
  const relation = findRelation(resolveCollectionRelations(currentCollection), relationKey);
2209
2291
  if (!relation) throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);
2210
2292
  const target = relation.target();
2211
- const targetRelationKey = relation.relationName || target.slug;
2212
- const targetSlug = relation.overrides?.slug ?? targetRelationKey;
2213
- currentCollection = this.get(targetSlug) || this.normalizeCollection(target);
2293
+ currentCollection = this.collectionsByTableName.get(getTableName(target)) ?? this.normalizeCollection(target);
2214
2294
  if (i + 1 < pathSegments.length) {}
2215
2295
  }
2216
2296
  return currentCollection;
@@ -2245,7 +2325,7 @@ var CollectionRegistry = class {
2245
2325
  if (!subcollections || subcollections.length === 0) throw new Error(`No subcollections found for ${currentCollection.slug} in path: ${path}`);
2246
2326
  const subcollection = subcollections.find((c) => c.slug === subcollectionSlug);
2247
2327
  if (!subcollection) throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug}`);
2248
- currentCollection = this.get(subcollection.slug) || this.normalizeCollection(subcollection);
2328
+ currentCollection = this.normalizeCollection(subcollection);
2249
2329
  collections.push(currentCollection);
2250
2330
  }
2251
2331
  }
@@ -3356,6 +3436,6 @@ async function detectJunctionTables(executeSql) {
3356
3436
  return junctionTables;
3357
3437
  }
3358
3438
  //#endregion
3359
- export { COLLECTION_PATH_SEPARATOR, COMPOSITE_ID_SEPARATOR, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, JUNCTION_TABLES_SQL, QueryBuilder, REBASE_INTERNAL_PREFIXES, REBASE_INTERNAL_SCHEMAS, and, buildCollection, buildCompositeId, buildConditionContext, buildProperty, buildPropertyCallbacks, buildRebaseData, buildRoutedRebaseData, buildSdkData, canCreateEntity, canDeleteEntity, canEditEntity, canReadCollection, checkOperation, classifyTable, cond, createDataSourceRegistry, createRelationRef, createRelationRefWithData, defaultUsersCollection, defineCollection, deserializeFilter, deserializeLogicalCondition, deserializeOrderBy, detectJunctionTables, embedParentExpression, enumToObjectEntries, evaluateCondition, evaluatePolicy, findAnonymousGrants, findRelation, fullPathToCollectionSegments, getArrayResolvedProperties, getColumnName, getDeclaredPrimaryKeys, getDefaultValueFor, getDefaultValueFortype, getDefaultValuesFor, getEffectiveSecurityRules, getEnumVarName, getInjectedSecurityRules, getJunctionCollectionConfig, getJunctionSecurityRules, getLabelOrConfigFrom, getPrimaryKeys, getReferenceFrom, getRelationFrom, getSubcollections, getTableName, getTableVarName, isPropertyBuilder, isRebaseInternalTable, normalizeToEntityRelation, or, parseIdValues, policyToPostgres, registerConditionOperations, resolveArrayProperties, resolveCollectionRelations, resolveDataSource, resolveEnumValues, resolveJunctionSpecs, resolvePrimaryKeys, resolveProperties, resolveProperty, resolvePropertyEnum, resolvePropertyRelation, resolveRelationProperty, resolveStorageFilenameString, resolveStoragePathString, resolveStorageSource, sanitizeData, sanitizeRelation, securityRuleToConditions, segmentsToStrippedPath, serializeFilter, serializeLogicalCondition, serializeOrderBy, sortProperties, sqlToPolicy, stripCollectionPath, traverseValueProperty, traverseValuesProperties, updateDateAutoValues, wrapAsEntityData, wrapAsSdkData };
3439
+ export { COLLECTION_PATH_SEPARATOR, COMPOSITE_ID_SEPARATOR, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, JUNCTION_TABLES_SQL, QueryBuilder, REBASE_INTERNAL_PREFIXES, REBASE_INTERNAL_SCHEMAS, and, buildCollection, buildCompositeId, buildConditionContext, buildProperty, buildPropertyCallbacks, buildRebaseData, buildRoutedRebaseData, buildSdkData, canCreateEntity, canDeleteEntity, canEditEntity, canReadCollection, checkOperation, classifyTable, cond, createDataSourceRegistry, createRelationRef, createRelationRefWithData, defaultUsersCollection, defineCollection, deserializeFilter, deserializeLogicalCondition, deserializeOrderBy, detectJunctionTables, embedParentExpression, enumToObjectEntries, evaluateCondition, evaluatePolicy, findAnonymousGrants, findRelation, fullPathToCollectionSegments, getArrayResolvedProperties, getColumnName, getDeclaredPrimaryKeys, getDefaultValueFor, getDefaultValueFortype, getDefaultValuesFor, getEffectiveSecurityRules, getEntityChildViews, getEnumVarName, getInjectedSecurityRules, getJunctionCollectionConfig, getJunctionSecurityRules, getLabelOrConfigFrom, getPrimaryKeys, getReferenceFrom, getRelationFrom, getSubcollections, getTableName, getTableVarName, isJunctionBackedRelation, isPropertyBuilder, isRebaseInternalTable, normalizeToEntityRelation, or, parseIdValues, policyToPostgres, registerConditionOperations, resolveArrayProperties, resolveCollectionRelations, resolveDataSource, resolveEnumValues, resolveJunctionSpecs, resolvePrimaryKeys, resolveProperties, resolveProperty, resolvePropertyEnum, resolvePropertyRelation, resolveRelationProperty, resolveStorageFilenameString, resolveStoragePathString, resolveStorageSource, sanitizeData, sanitizeRelation, securityRuleToConditions, segmentsToStrippedPath, serializeFilter, serializeLogicalCondition, serializeOrderBy, sortProperties, sqlToPolicy, stripCollectionPath, traverseValueProperty, traverseValuesProperties, updateDateAutoValues, wrapAsEntityData, wrapAsSdkData };
3360
3440
 
3361
3441
  //# sourceMappingURL=index.es.js.map