@rebasepro/common 0.23.0 → 0.24.1-canary.g56af4a4
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/collections/CollectionRegistry.d.ts +72 -3
- package/dist/collections/CollectionRegistry.es.js +404 -0
- package/dist/collections/CollectionRegistry.es.js.map +1 -0
- package/dist/collections/auth-secrets.es.js +47 -0
- package/dist/collections/auth-secrets.es.js.map +1 -0
- package/dist/collections/default-collections.es.js +120 -0
- package/dist/collections/default-collections.es.js.map +1 -0
- package/dist/collections/engine-support.es.js +35 -0
- package/dist/collections/engine-support.es.js.map +1 -0
- package/dist/collections/field-access.d.ts +13 -0
- package/dist/collections/field-access.es.js +142 -0
- package/dist/collections/field-access.es.js.map +1 -0
- package/dist/collections/index.d.ts +1 -0
- package/dist/collections/soft-delete.es.js +34 -0
- package/dist/collections/soft-delete.es.js.map +1 -0
- package/dist/collections/unknown-field.d.ts +65 -0
- package/dist/collections/unknown-field.es.js +135 -0
- package/dist/collections/unknown-field.es.js.map +1 -0
- package/dist/data/buildRebaseData.d.ts +27 -2
- package/dist/data/buildRebaseData.es.js +1026 -0
- package/dist/data/buildRebaseData.es.js.map +1 -0
- package/dist/data/buildRoutedRebaseData.d.ts +6 -1
- package/dist/data/buildRoutedRebaseData.es.js +47 -0
- package/dist/data/buildRoutedRebaseData.es.js.map +1 -0
- package/dist/data/collection-accessor.d.ts +54 -0
- package/dist/data/collection-accessor.es.js +101 -0
- package/dist/data/collection-accessor.es.js.map +1 -0
- package/dist/data/cursor.d.ts +1 -1
- package/dist/data/cursor.es.js +166 -0
- package/dist/data/cursor.es.js.map +1 -0
- package/dist/data/filter-conditions.es.js +24 -0
- package/dist/data/filter-conditions.es.js.map +1 -0
- package/dist/data/filter-dialect.d.ts +3 -3
- package/dist/data/filter-dialect.es.js +786 -0
- package/dist/data/filter-dialect.es.js.map +1 -0
- package/dist/data/include-spec.d.ts +2 -0
- package/dist/data/include-spec.es.js +273 -0
- package/dist/data/include-spec.es.js.map +1 -0
- package/dist/data/paginate.d.ts +8 -1
- package/dist/data/paginate.es.js +181 -0
- package/dist/data/paginate.es.js.map +1 -0
- package/dist/data/query_builder.d.ts +52 -4
- package/dist/data/query_builder.es.js +151 -0
- package/dist/data/query_builder.es.js.map +1 -0
- package/dist/data/resolveDataSource.es.js +87 -0
- package/dist/data/resolveDataSource.es.js.map +1 -0
- package/dist/data/row-etag.d.ts +46 -0
- package/dist/data/row-etag.es.js +64 -0
- package/dist/data/row-etag.es.js.map +1 -0
- package/dist/data/sort-dialect.es.js +236 -0
- package/dist/data/sort-dialect.es.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.es.js +56 -7235
- package/dist/table-classification.es.js +107 -0
- package/dist/table-classification.es.js.map +1 -0
- package/dist/util/auth-default-policies.es.js +184 -0
- package/dist/util/auth-default-policies.es.js.map +1 -0
- package/dist/util/builders.es.js +15 -0
- package/dist/util/builders.es.js.map +1 -0
- package/dist/util/callback-errors.es.js +164 -0
- package/dist/util/callback-errors.es.js.map +1 -0
- package/dist/util/callbacks.es.js +72 -0
- package/dist/util/callbacks.es.js.map +1 -0
- package/dist/util/collections.es.js +79 -0
- package/dist/util/collections.es.js.map +1 -0
- package/dist/util/common.es.js +7 -0
- package/dist/util/common.es.js.map +1 -0
- package/dist/util/conditions.es.js +100 -0
- package/dist/util/conditions.es.js.map +1 -0
- package/dist/util/copy.d.ts +33 -0
- package/dist/util/copy.es.js +74 -0
- package/dist/util/copy.es.js.map +1 -0
- package/dist/util/download-url-cache.d.ts +122 -0
- package/dist/util/download-url-cache.es.js +187 -0
- package/dist/util/download-url-cache.es.js.map +1 -0
- package/dist/util/email.es.js +36 -0
- package/dist/util/email.es.js.map +1 -0
- package/dist/util/entities.d.ts +27 -2
- package/dist/util/entities.es.js +328 -0
- package/dist/util/entities.es.js.map +1 -0
- package/dist/util/enums.d.ts +10 -1
- package/dist/util/enums.es.js +37 -0
- package/dist/util/enums.es.js.map +1 -0
- package/dist/util/identity.es.js +138 -0
- package/dist/util/identity.es.js.map +1 -0
- package/dist/util/index.d.ts +6 -0
- package/dist/util/internal-tables.d.ts +10 -0
- package/dist/util/internal-tables.es.js +202 -0
- package/dist/util/internal-tables.es.js.map +1 -0
- package/dist/util/junction-policies.es.js +273 -0
- package/dist/util/junction-policies.es.js.map +1 -0
- package/dist/util/paths.es.js +26 -0
- package/dist/util/paths.es.js.map +1 -0
- package/dist/util/permissions.es.js +108 -0
- package/dist/util/permissions.es.js.map +1 -0
- package/dist/util/pg-column-to-property.es.js +303 -0
- package/dist/util/pg-column-to-property.es.js.map +1 -0
- package/dist/util/policy/compileRulePolicies.d.ts +32 -0
- package/dist/util/policy/compileRulePolicies.es.js +43 -0
- package/dist/util/policy/compileRulePolicies.es.js.map +1 -0
- package/dist/util/policy/evaluatePolicy.es.js +104 -0
- package/dist/util/policy/evaluatePolicy.es.js.map +1 -0
- package/dist/util/policy/index.d.ts +1 -0
- package/dist/util/policy/policyToPostgres.d.ts +24 -0
- package/dist/util/policy/policyToPostgres.es.js +593 -0
- package/dist/util/policy/policyToPostgres.es.js.map +1 -0
- package/dist/util/policy/policyToSecurityRule.es.js +79 -0
- package/dist/util/policy/policyToSecurityRule.es.js.map +1 -0
- package/dist/util/policy/securityRuleToConditions.es.js +48 -0
- package/dist/util/policy/securityRuleToConditions.es.js.map +1 -0
- package/dist/util/policy/sqlToPolicy.es.js +326 -0
- package/dist/util/policy/sqlToPolicy.es.js.map +1 -0
- package/dist/util/relations.es.js +243 -0
- package/dist/util/relations.es.js.map +1 -0
- package/dist/util/resolutions.es.js +318 -0
- package/dist/util/resolutions.es.js.map +1 -0
- package/dist/util/resolve-relation.es.js +163 -0
- package/dist/util/resolve-relation.es.js.map +1 -0
- package/dist/util/resumable-upload-threshold.d.ts +15 -0
- package/dist/util/resumable-upload-threshold.es.js +20 -0
- package/dist/util/resumable-upload-threshold.es.js.map +1 -0
- package/dist/util/resumable-upload.d.ts +51 -0
- package/dist/util/resumable-upload.es.js +121 -0
- package/dist/util/resumable-upload.es.js.map +1 -0
- package/dist/util/sql-redaction.d.ts +21 -0
- package/dist/util/sql-redaction.es.js +107 -0
- package/dist/util/sql-redaction.es.js.map +1 -0
- package/dist/util/sql-rows.es.js +41 -0
- package/dist/util/sql-rows.es.js.map +1 -0
- package/dist/util/storage.d.ts +26 -4
- package/dist/util/storage.es.js +117 -0
- package/dist/util/storage.es.js.map +1 -0
- package/dist/util/string-column-length.es.js +31 -0
- package/dist/util/string-column-length.es.js.map +1 -0
- package/dist/util/tenant.es.js +201 -0
- package/dist/util/tenant.es.js.map +1 -0
- package/dist/util/untrusted-envelope.d.ts +25 -0
- package/dist/util/untrusted-envelope.es.js +40 -0
- package/dist/util/untrusted-envelope.es.js.map +1 -0
- package/package.json +5 -3
- package/dist/index.es.js.map +0 -1
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { DEFAULT_ONE_OF_TYPE } from "./common.es.js";
|
|
2
|
+
import { isPropertyBuilder } from "./entities.es.js";
|
|
3
|
+
import { enumToObjectEntries } from "./enums.es.js";
|
|
4
|
+
import { resolveRelation } from "./resolve-relation.es.js";
|
|
5
|
+
import { isJunctionBackedRelation, resolveCollectionRelations } from "./relations.es.js";
|
|
6
|
+
import { getDataSourceCapabilities, getDeclaredSubcollections } from "@rebasepro/types";
|
|
7
|
+
import { getIn, isDefaultFieldConfigId, mergeDeep } from "@rebasepro/utils";
|
|
8
|
+
//#region src/util/resolutions.ts
|
|
9
|
+
function resolveProperty(props) {
|
|
10
|
+
const { property, ignoreMissingFields = false, ...rest } = props;
|
|
11
|
+
let resultProperty;
|
|
12
|
+
if (isPropertyBuilder(property)) {
|
|
13
|
+
const path = rest.path;
|
|
14
|
+
if (!path) resultProperty = property;
|
|
15
|
+
else {
|
|
16
|
+
const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : void 0;
|
|
17
|
+
const dynamicProps = property.dynamicProps?.({
|
|
18
|
+
...rest,
|
|
19
|
+
path,
|
|
20
|
+
propertyValue: usedPropertyValue,
|
|
21
|
+
values: rest.values ?? {},
|
|
22
|
+
previousValues: rest.previousValues ?? rest.values ?? {}
|
|
23
|
+
});
|
|
24
|
+
resultProperty = mergeDeep(property, dynamicProps ?? {});
|
|
25
|
+
}
|
|
26
|
+
} else resultProperty = property;
|
|
27
|
+
if (resultProperty?.dynamicProps && rest.path) {
|
|
28
|
+
const path = rest.path;
|
|
29
|
+
const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : void 0;
|
|
30
|
+
const dynamicPropsResult = resultProperty.dynamicProps({
|
|
31
|
+
...rest,
|
|
32
|
+
path,
|
|
33
|
+
propertyValue: usedPropertyValue,
|
|
34
|
+
values: rest.values ?? {},
|
|
35
|
+
previousValues: rest.previousValues ?? rest.values ?? {}
|
|
36
|
+
});
|
|
37
|
+
if (dynamicPropsResult) resultProperty = mergeDeep(resultProperty, dynamicPropsResult);
|
|
38
|
+
}
|
|
39
|
+
let resolvedProperty;
|
|
40
|
+
if (resultProperty?.type === "map" && resultProperty.properties) {
|
|
41
|
+
const properties = resolveProperties({
|
|
42
|
+
ignoreMissingFields,
|
|
43
|
+
...rest,
|
|
44
|
+
properties: resultProperty.properties
|
|
45
|
+
});
|
|
46
|
+
resolvedProperty = {
|
|
47
|
+
...resultProperty,
|
|
48
|
+
properties
|
|
49
|
+
};
|
|
50
|
+
} else if (resultProperty?.type === "array") resolvedProperty = resultProperty;
|
|
51
|
+
else if ((resultProperty?.type === "string" || resultProperty?.type === "number") && resultProperty.enum) resolvedProperty = resolvePropertyEnum(resultProperty);
|
|
52
|
+
else resolvedProperty = resultProperty;
|
|
53
|
+
if (resolvedProperty?.propertyConfig && !isDefaultFieldConfigId(resolvedProperty.propertyConfig)) {
|
|
54
|
+
const cmsFields = rest.propertyConfigs;
|
|
55
|
+
if (!cmsFields && !ignoreMissingFields) throw Error(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property configs were provided. Use the property 'propertyConfigs' in your app config to provide them`);
|
|
56
|
+
const customField = cmsFields?.[resolvedProperty.propertyConfig];
|
|
57
|
+
if (!customField) {
|
|
58
|
+
console.warn(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property config with that key was found. Check the 'propertyConfigs' in your app config`);
|
|
59
|
+
return resolvedProperty;
|
|
60
|
+
}
|
|
61
|
+
if (customField.property) {
|
|
62
|
+
const restConfigProperty = { ...customField.property };
|
|
63
|
+
delete restConfigProperty.propertyConfig;
|
|
64
|
+
const customFieldProperty = resolveProperty({
|
|
65
|
+
property: {
|
|
66
|
+
name: "",
|
|
67
|
+
...restConfigProperty
|
|
68
|
+
},
|
|
69
|
+
ignoreMissingFields,
|
|
70
|
+
...rest
|
|
71
|
+
});
|
|
72
|
+
if (customFieldProperty) resolvedProperty = mergeDeep(customFieldProperty, resolvedProperty);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return resolvedProperty;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The resolved relation a relation property refers to.
|
|
79
|
+
*
|
|
80
|
+
* Normalization stamps `resolvedRelation` onto the property, so this is usually
|
|
81
|
+
* a field read. It falls back to resolving from the collection for properties
|
|
82
|
+
* that never went through the registry — a preview, or a form rendered straight
|
|
83
|
+
* from an authored config.
|
|
84
|
+
*/
|
|
85
|
+
function resolveRelationProperty(property, collection, propertyKey) {
|
|
86
|
+
if (property.resolvedRelation) return property.resolvedRelation;
|
|
87
|
+
if (property.relation) return resolveRelation(property.relation, collection, propertyKey);
|
|
88
|
+
const name = propertyKey ?? "";
|
|
89
|
+
const declared = resolveCollectionRelations(collection)[name];
|
|
90
|
+
if (!declared) throw Error(`Relation property '${name || "(unnamed)"}' on '${collection.slug}' declares no \`relation\`, and the collection has no relation of that name.`);
|
|
91
|
+
return declared;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Resolve enum aliases for a string or number property
|
|
95
|
+
* @param property
|
|
96
|
+
*/
|
|
97
|
+
function resolvePropertyEnum(property) {
|
|
98
|
+
if (typeof property.enum === "object") return {
|
|
99
|
+
...property,
|
|
100
|
+
enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? []
|
|
101
|
+
};
|
|
102
|
+
return property;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Resolve enums and arrays for properties
|
|
106
|
+
* @param properties
|
|
107
|
+
* @param value
|
|
108
|
+
*/
|
|
109
|
+
function resolveProperties({ propertyKey, properties, ignoreMissingFields, ...props }) {
|
|
110
|
+
return Object.entries(properties).map(([key, property]) => {
|
|
111
|
+
const childResolvedProperty = resolveProperty({
|
|
112
|
+
propertyKey: propertyKey ? `${propertyKey}.${key}` : void 0,
|
|
113
|
+
property,
|
|
114
|
+
ignoreMissingFields,
|
|
115
|
+
...props
|
|
116
|
+
});
|
|
117
|
+
if (!childResolvedProperty) return {};
|
|
118
|
+
return { [key]: childResolvedProperty };
|
|
119
|
+
}).filter((a) => a !== null).reduce((a, b) => ({
|
|
120
|
+
...a,
|
|
121
|
+
...b
|
|
122
|
+
}), {});
|
|
123
|
+
}
|
|
124
|
+
function resolveArrayProperties({ propertyKey, property, ignoreMissingFields = false, ...props }) {
|
|
125
|
+
const propertyValue = propertyKey ? getIn(props.values, propertyKey) : void 0;
|
|
126
|
+
if (property.of) if (Array.isArray(property.of)) return property.of.map((p, index) => {
|
|
127
|
+
return resolveProperty({
|
|
128
|
+
propertyKey: `${propertyKey}.${index}`,
|
|
129
|
+
property: p,
|
|
130
|
+
ignoreMissingFields,
|
|
131
|
+
...props,
|
|
132
|
+
index
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
else {
|
|
136
|
+
const of = property.of;
|
|
137
|
+
const resolvedProperties = getArrayResolvedProperties({
|
|
138
|
+
propertyValue,
|
|
139
|
+
propertyKey,
|
|
140
|
+
property,
|
|
141
|
+
ignoreMissingFields,
|
|
142
|
+
...props
|
|
143
|
+
});
|
|
144
|
+
const { values, previousValues, ...rest } = props;
|
|
145
|
+
if (!resolveProperty({
|
|
146
|
+
property: of,
|
|
147
|
+
ignoreMissingFields,
|
|
148
|
+
...rest
|
|
149
|
+
}) && !ignoreMissingFields) throw Error("When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property");
|
|
150
|
+
return resolvedProperties;
|
|
151
|
+
}
|
|
152
|
+
else if (property.oneOf) {
|
|
153
|
+
const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;
|
|
154
|
+
return Array.isArray(propertyValue) ? propertyValue.map((v, index) => {
|
|
155
|
+
const type = v && v[typeField];
|
|
156
|
+
const childProperty = property.oneOf?.properties[type];
|
|
157
|
+
if (!type || !childProperty) return null;
|
|
158
|
+
return resolveProperty({
|
|
159
|
+
propertyKey: `${propertyKey}.${index}`,
|
|
160
|
+
property: childProperty,
|
|
161
|
+
ignoreMissingFields,
|
|
162
|
+
...props
|
|
163
|
+
});
|
|
164
|
+
}).filter((e) => Boolean(e)) : [];
|
|
165
|
+
} else if (!property.columnType) throw Error(`The array property (${propertyKey}) needs to declare an 'of' or a 'oneOf' property, or a \`columnType\` such as "text[]"`);
|
|
166
|
+
else return [];
|
|
167
|
+
}
|
|
168
|
+
function getArrayResolvedProperties({ propertyKey, propertyValue, property, ...props }) {
|
|
169
|
+
const of = property.of;
|
|
170
|
+
if (!of) throw Error(`Trying to resolve an array property (${propertyKey}) without providing an 'of' property`);
|
|
171
|
+
return Array.isArray(propertyValue) ? propertyValue.map((v, index) => {
|
|
172
|
+
return resolveProperty({
|
|
173
|
+
propertyKey: `${propertyKey}.${index}`,
|
|
174
|
+
property: Array.isArray(of) ? of[index] : of,
|
|
175
|
+
...props,
|
|
176
|
+
index
|
|
177
|
+
});
|
|
178
|
+
}).filter((e) => Boolean(e)) : [];
|
|
179
|
+
}
|
|
180
|
+
function resolveEnumValues(input) {
|
|
181
|
+
if (typeof input === "object") return Object.entries(input).map(([id, value]) => typeof value === "string" ? {
|
|
182
|
+
id,
|
|
183
|
+
label: value
|
|
184
|
+
} : value);
|
|
185
|
+
else if (Array.isArray(input)) return input;
|
|
186
|
+
else return;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The lists rendered inside an entity view of `collection` — its tabs.
|
|
190
|
+
*
|
|
191
|
+
* The single derivation. There used to be two that disagreed: this one, and a
|
|
192
|
+
* copy in `CollectionRegistry.normalizeCollection` that stamped each child with
|
|
193
|
+
* the *target collection's* slug instead of the relation key. Since the
|
|
194
|
+
* registry ran first and cached its answer onto `childCollections`, its version
|
|
195
|
+
* was the one that won, and the frontend addressed child listings by a segment
|
|
196
|
+
* the backend could not resolve.
|
|
197
|
+
*
|
|
198
|
+
* Order of precedence:
|
|
199
|
+
* 1. `childCollections` — the explicit escape hatch for custom drivers.
|
|
200
|
+
* 2. `subcollections` on an engine that has real containment (Firestore).
|
|
201
|
+
* 3. many-relations on an engine that has relations (SQL).
|
|
202
|
+
*/
|
|
203
|
+
function getEntityChildViews(collection) {
|
|
204
|
+
const asSubcollections = (collections) => collections.filter(Boolean).map((child) => ({
|
|
205
|
+
key: child.slug,
|
|
206
|
+
collection: child,
|
|
207
|
+
source: { kind: "subcollection" }
|
|
208
|
+
}));
|
|
209
|
+
if (collection.childCollections) return asSubcollections(collection.childCollections() ?? []);
|
|
210
|
+
const capabilities = getDataSourceCapabilities(collection.engine);
|
|
211
|
+
const declaredSubcollections = getDeclaredSubcollections(collection);
|
|
212
|
+
if (capabilities.supportsSubcollections && declaredSubcollections) return asSubcollections(declaredSubcollections() ?? []);
|
|
213
|
+
if (!capabilities.supportsRelations) return [];
|
|
214
|
+
const resolvedRelations = resolveCollectionRelations(collection);
|
|
215
|
+
const views = [];
|
|
216
|
+
const seen = /* @__PURE__ */ new Set();
|
|
217
|
+
for (const [relationKey, relation] of Object.entries(resolvedRelations)) {
|
|
218
|
+
if (relation.cardinality !== "many") continue;
|
|
219
|
+
const identity = relation.relationName ?? relationKey;
|
|
220
|
+
if (seen.has(identity)) continue;
|
|
221
|
+
let target;
|
|
222
|
+
try {
|
|
223
|
+
target = relation.target();
|
|
224
|
+
} catch {
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
if (!target) continue;
|
|
228
|
+
seen.add(identity);
|
|
229
|
+
const customName = Object.entries(collection.properties ?? {}).find(([propKey, p]) => p.type === "relation" && (p.relation?.relationName ?? propKey) === identity)?.[1]?.name;
|
|
230
|
+
const base = {
|
|
231
|
+
...target,
|
|
232
|
+
slug: relationKey,
|
|
233
|
+
...customName ? {
|
|
234
|
+
name: customName,
|
|
235
|
+
singularName: customName
|
|
236
|
+
} : {}
|
|
237
|
+
};
|
|
238
|
+
views.push({
|
|
239
|
+
key: relationKey,
|
|
240
|
+
collection: relation.overrides ? mergeDeep(base, relation.overrides) : base,
|
|
241
|
+
source: {
|
|
242
|
+
kind: "relation",
|
|
243
|
+
relationKey,
|
|
244
|
+
mode: isJunctionBackedRelation(relation) ? "linked" : "owned",
|
|
245
|
+
targetSlug: target.slug
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
return views;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Each of `collection`'s tabs paired with the property that declared it, when a
|
|
253
|
+
* property declared it: child view key → property key.
|
|
254
|
+
*
|
|
255
|
+
* A many-relation can only be declared as a property — that is the documented
|
|
256
|
+
* and only mechanism — and {@link getEntityChildViews} promotes it to a tab. So
|
|
257
|
+
* one declaration reaches the panel twice, and neither surface knew about the
|
|
258
|
+
* other. The form rendered a relation picker beside the tab, and the collection
|
|
259
|
+
* table rendered *two* columns under one heading: the relation's own column,
|
|
260
|
+
* showing the child rows, and a jump-to-tab button carrying the same name.
|
|
261
|
+
*
|
|
262
|
+
* The pairing is what lets each surface decide which half is redundant, and it
|
|
263
|
+
* has to be a pairing rather than two sets because the two keys differ whenever
|
|
264
|
+
* a relation is named. The match is on the resolved `relationName` — the
|
|
265
|
+
* identity `getEntityChildViews` itself dedupes on — so a relation declared in
|
|
266
|
+
* `relations` and pointed at by a differently-named property is recognised too.
|
|
267
|
+
*
|
|
268
|
+
* A relation with no property of its own is absent here, which is the point: it
|
|
269
|
+
* has exactly one surface already, and nothing to weigh it against.
|
|
270
|
+
*
|
|
271
|
+
* Only top-level properties: a relation nested inside a `map` gets no tab.
|
|
272
|
+
*/
|
|
273
|
+
function getChildViewDeclaringProperties(collection) {
|
|
274
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
275
|
+
const relationProperties = Object.entries(collection.properties ?? {}).filter(([, property]) => property?.type === "relation");
|
|
276
|
+
if (relationProperties.length === 0) return pairs;
|
|
277
|
+
const relationViews = getEntityChildViews(collection).filter((view) => view.source.kind === "relation");
|
|
278
|
+
if (relationViews.length === 0) return pairs;
|
|
279
|
+
const resolvedRelations = resolveCollectionRelations(collection);
|
|
280
|
+
const identityOf = (relationKey) => resolvedRelations[relationKey]?.relationName ?? relationKey;
|
|
281
|
+
const declaringPropertyByIdentity = /* @__PURE__ */ new Map();
|
|
282
|
+
for (const [propertyKey, property] of relationProperties) {
|
|
283
|
+
const relation = property.resolvedRelation ?? resolvedRelations[propertyKey];
|
|
284
|
+
if (relation?.cardinality !== "many") continue;
|
|
285
|
+
const identity = relation.relationName ?? propertyKey;
|
|
286
|
+
if (!declaringPropertyByIdentity.has(identity)) declaringPropertyByIdentity.set(identity, propertyKey);
|
|
287
|
+
}
|
|
288
|
+
for (const view of relationViews) {
|
|
289
|
+
const propertyKey = declaringPropertyByIdentity.get(identityOf(view.source.relationKey));
|
|
290
|
+
if (propertyKey) pairs.set(view.key, propertyKey);
|
|
291
|
+
}
|
|
292
|
+
return pairs;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* The property keys of `collection` whose relation is already one of its tabs.
|
|
296
|
+
*
|
|
297
|
+
* What a form asks: the tab is the treatment for a list of child rows, so the
|
|
298
|
+
* picker beside it is the redundant half. See
|
|
299
|
+
* {@link getChildViewDeclaringProperties}.
|
|
300
|
+
*/
|
|
301
|
+
function getChildViewRelationPropertyKeys(collection) {
|
|
302
|
+
return new Set(getChildViewDeclaringProperties(collection).values());
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* The child views of `collection` as bare collections.
|
|
306
|
+
*
|
|
307
|
+
* The flattened view of {@link getEntityChildViews}, for navigation code that
|
|
308
|
+
* only needs to match a path segment against a slug. Anything that cares *what
|
|
309
|
+
* kind* of list it is showing — chiefly the admin, which must not offer a
|
|
310
|
+
* global delete on a shared row — should read the views instead.
|
|
311
|
+
*/
|
|
312
|
+
function getSubcollections(collection) {
|
|
313
|
+
return getEntityChildViews(collection).map((view) => view.collection);
|
|
314
|
+
}
|
|
315
|
+
//#endregion
|
|
316
|
+
export { getArrayResolvedProperties, getChildViewDeclaringProperties, getChildViewRelationPropertyKeys, getEntityChildViews, getSubcollections, resolveArrayProperties, resolveEnumValues, resolveProperties, resolveProperty, resolvePropertyEnum, resolveRelationProperty };
|
|
317
|
+
|
|
318
|
+
//# sourceMappingURL=resolutions.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolutions.es.js","names":[],"sources":["../../src/util/resolutions.ts"],"sourcesContent":["import {\n ArrayProperty,\n AuthState,\n CollectionConfig,\n EnumValueConfig,\n EnumValues,\n NumberProperty,\n Properties,\n Property,\n RelationProperty,\n ResolvedRelation,\n StringProperty,\n getDataSourceCapabilities,\n getDeclaredSubcollections,\n type EntityChildView\n} from \"@rebasepro/types\";\n\ntype PropertyConfig = { property: unknown; [key: string]: unknown };\nimport { isPropertyBuilder } from \"./entities\";\nimport { enumToObjectEntries } from \"./enums\";\nimport { DEFAULT_ONE_OF_TYPE } from \"./common\";\nimport { isDefaultFieldConfigId } from \"@rebasepro/utils\";\nimport { getIn, mergeDeep } from \"@rebasepro/utils\";\nimport { isJunctionBackedRelation, resolveCollectionRelations } from \"./relations\";\nimport { resolveRelation } from \"./resolve-relation\";\n\n/**\n * Resolve property builders, enums and arrays.\n */\n\nexport type ResolvePropertyProps<M extends Record<string, unknown> = Record<string, unknown>> = {\n property: Property\n propertyKey?: string,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}\n\nexport function resolveProperty<M extends Record<string, unknown> = Record<string, unknown>>(props: ResolvePropertyProps<M>): Property | null {\n\n const {\n property,\n ignoreMissingFields = false,\n ...rest\n } = props;\n\n let resultProperty: Property;\n\n if (isPropertyBuilder(property)) {\n const path = rest.path;\n if (!path) {\n // When path is not available (e.g. in preview contexts), skip dynamic\n // resolution and use the property as-is without dynamic modifications.\n resultProperty = property as Property;\n } else {\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicProps = property.dynamicProps?.({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n resultProperty = mergeDeep(property, dynamicProps ?? {});\n }\n } else {\n resultProperty = property as Property;\n }\n\n // Apply dynamic properties if they exist\n if (resultProperty?.dynamicProps && rest.path) {\n const path = rest.path;\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicPropsResult = resultProperty.dynamicProps({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n\n if (dynamicPropsResult) {\n resultProperty = mergeDeep(resultProperty, dynamicPropsResult);\n }\n }\n\n let resolvedProperty: Property | null;\n\n if (resultProperty?.type === \"map\" && resultProperty.properties) {\n const properties = resolveProperties({\n ignoreMissingFields,\n ...rest,\n properties: resultProperty.properties\n });\n resolvedProperty = {\n ...resultProperty,\n properties\n } as Property;\n } else if (resultProperty?.type === \"array\") {\n resolvedProperty = resultProperty;\n } else if ((resultProperty?.type === \"string\" || resultProperty?.type === \"number\") && resultProperty.enum) {\n resolvedProperty = resolvePropertyEnum(resultProperty);\n } else {\n resolvedProperty = resultProperty;\n }\n\n if (resolvedProperty?.propertyConfig && !isDefaultFieldConfigId(resolvedProperty.propertyConfig)) {\n const cmsFields = rest.propertyConfigs;\n if (!cmsFields && !ignoreMissingFields) {\n throw Error(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property configs were provided. Use the property 'propertyConfigs' in your app config to provide them`);\n }\n const customField: PropertyConfig | undefined = cmsFields?.[resolvedProperty.propertyConfig];\n if (!customField) {\n console.warn(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property config with that key was found. Check the 'propertyConfigs' in your app config`)\n return resolvedProperty;\n }\n if (customField.property) {\n const restConfigProperty = { ...customField.property } as Record<string, unknown>;\n delete restConfigProperty.propertyConfig;\n const customFieldProperty = resolveProperty({\n property: { name: \"\",\n...restConfigProperty } as Property,\n ignoreMissingFields,\n ...rest\n });\n if (customFieldProperty) {\n resolvedProperty = mergeDeep(customFieldProperty, resolvedProperty);\n }\n }\n\n }\n\n return resolvedProperty;\n}\n\n/**\n * The resolved relation a relation property refers to.\n *\n * Normalization stamps `resolvedRelation` onto the property, so this is usually\n * a field read. It falls back to resolving from the collection for properties\n * that never went through the registry — a preview, or a form rendered straight\n * from an authored config.\n */\nexport function resolveRelationProperty(\n property: RelationProperty,\n collection: CollectionConfig,\n propertyKey?: string\n): ResolvedRelation {\n if (property.resolvedRelation) return property.resolvedRelation;\n\n if (property.relation) {\n return resolveRelation(property.relation, collection, propertyKey);\n }\n\n const name = propertyKey ?? \"\";\n const declared = resolveCollectionRelations(collection)[name];\n if (!declared) {\n throw Error(\n `Relation property '${name || \"(unnamed)\"}' on '${collection.slug}' declares no \\`relation\\`, ` +\n \"and the collection has no relation of that name.\"\n );\n }\n return declared;\n}\n\n/**\n * Resolve enum aliases for a string or number property\n * @param property\n */\nexport function resolvePropertyEnum(property: StringProperty | NumberProperty): StringProperty | NumberProperty {\n if (typeof property.enum === \"object\") {\n return {\n ...property,\n enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? []\n };\n }\n return property as StringProperty | NumberProperty;\n}\n\n/**\n * Resolve enums and arrays for properties\n * @param properties\n * @param value\n */\nexport function resolveProperties<M extends Record<string, unknown>>({\n propertyKey,\n properties,\n ignoreMissingFields,\n ...props\n}: {\n propertyKey?: string,\n properties: Properties,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}): Properties {\n return Object.entries<Property>(properties as Record<string, Property>)\n .map(([key, property]) => {\n const childResolvedProperty = resolveProperty({\n propertyKey: propertyKey ? `${propertyKey}.${key}` : undefined,\n property: property,\n ignoreMissingFields,\n ...props\n });\n if (!childResolvedProperty) return {};\n return {\n [key]: childResolvedProperty\n };\n })\n .filter((a) => a !== null)\n .reduce((a, b) => ({ ...a,\n...b }), {}) as Properties;\n}\n\nexport function resolveArrayProperties<M>({\n propertyKey,\n property,\n ignoreMissingFields = false,\n ...props\n}: {\n propertyKey?: string,\n property: ArrayProperty,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}): Property[] {\n const propertyValue = propertyKey ? getIn(props.values, propertyKey) : undefined;\n\n if (property.of) {\n if (Array.isArray(property.of)) {\n return property.of.map((p, index) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: p as Property,\n ignoreMissingFields,\n ...props,\n index\n });\n }) as Property[];\n } else {\n const of = property.of;\n const resolvedProperties = getArrayResolvedProperties({\n propertyValue,\n propertyKey,\n property,\n ignoreMissingFields,\n ...props\n });\n // Destructured to be *excluded* from `...rest`, not to be used —\n // see the comment below. Said explicitly so the discarded-value\n // ratchet does not carry a finding that is working as intended.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { values, previousValues, ...rest } = props;\n const ofProperty = resolveProperty({ // we don't want to pass the values of the parent entity\n property: of,\n ignoreMissingFields,\n ...rest\n });\n if (!ofProperty && !ignoreMissingFields)\n throw Error(\"When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property\")\n return resolvedProperties;\n }\n } else if (property.oneOf) {\n const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;\n const resolvedProperties: Property[] = Array.isArray(propertyValue)\n ? propertyValue.map((v, index) => {\n const type = v && v[typeField];\n const childProperty = property.oneOf?.properties[type];\n if (!type || !childProperty) return null;\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: childProperty,\n ignoreMissingFields,\n ...props\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n return resolvedProperties;\n } else if (!property.columnType) {\n // An array with neither `of`/`oneOf` nor a `columnType` describes no element\n // type, so nothing can be generated or rendered from it.\n //\n // The escape hatch used to be `ui.Field` — \"a custom component can render\n // anything\" — which made a *presentation* field decide whether a schema was\n // valid, in code the Postgres generator runs. `columnType` is the same escape\n // hatch stated as data: `columnType: \"text[]\"` says what the column holds,\n // which is what both the generator and the form actually need.\n throw Error(`The array property (${propertyKey}) needs to declare an 'of' or a 'oneOf' property, or a \\`columnType\\` such as \"text[]\"`);\n } else {\n return [];\n }\n\n}\n\nexport function getArrayResolvedProperties({\n propertyKey,\n propertyValue,\n property,\n ...props\n}: {\n propertyValue: unknown,\n propertyKey?: string,\n property: ArrayProperty,\n ignoreMissingFields: boolean,\n values?: object;\n previousValues?: object;\n path?: string;\n entityId?: string | number;\n index?: number;\n propertyConfigs?: Record<string, PropertyConfig>;\n authController: AuthState;\n}) {\n\n const of = property.of;\n if (!of)\n throw Error(\n `Trying to resolve an array property (${propertyKey}) without providing an 'of' property`\n )\n return Array.isArray(propertyValue)\n ? propertyValue.map((v: unknown, index: number) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: Array.isArray(of) ? of[index] : of,\n ...props,\n index\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n}\n\nexport function resolveEnumValues(input: EnumValues): EnumValueConfig[] | undefined {\n if (typeof input === \"object\") {\n return Object.entries(input).map(([id, value]) =>\n (typeof value === \"string\"\n ? {\n id,\n label: value\n }\n : value));\n } else if (Array.isArray(input)) {\n return input as EnumValueConfig[];\n } else {\n return undefined;\n }\n}\n\n\n/**\n * The lists rendered inside an entity view of `collection` — its tabs.\n *\n * The single derivation. There used to be two that disagreed: this one, and a\n * copy in `CollectionRegistry.normalizeCollection` that stamped each child with\n * the *target collection's* slug instead of the relation key. Since the\n * registry ran first and cached its answer onto `childCollections`, its version\n * was the one that won, and the frontend addressed child listings by a segment\n * the backend could not resolve.\n *\n * Order of precedence:\n * 1. `childCollections` — the explicit escape hatch for custom drivers.\n * 2. `subcollections` on an engine that has real containment (Firestore).\n * 3. many-relations on an engine that has relations (SQL).\n */\nexport function getEntityChildViews<M extends Record<string, unknown> = Record<string, unknown>>(\n collection: CollectionConfig<M>\n): EntityChildView[] {\n const asSubcollections = (collections: CollectionConfig<Record<string, unknown>>[]): EntityChildView[] =>\n collections.filter(Boolean).map(child => ({\n key: child.slug,\n collection: child,\n source: { kind: \"subcollection\" as const }\n }));\n\n if (collection.childCollections) {\n return asSubcollections(collection.childCollections() ?? []);\n }\n\n const capabilities = getDataSourceCapabilities(collection.engine);\n\n const declaredSubcollections = getDeclaredSubcollections(collection);\n if (capabilities.supportsSubcollections && declaredSubcollections) {\n return asSubcollections(declaredSubcollections() ?? []);\n }\n\n if (!capabilities.supportsRelations) return [];\n\n const resolvedRelations = resolveCollectionRelations(collection);\n const views: EntityChildView[] = [];\n const seen = new Set<string>();\n\n // Keyed by the map key, not by `relationName`: the map key is what\n // `findRelation` matches a path segment against, so it is the only one that\n // addresses the same relation on both sides of the wire. The map registers\n // some relations twice — once canonically, once under the declaring\n // property key — so dedupe on the underlying relation.\n for (const [relationKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.cardinality !== \"many\") continue;\n\n const identity = relation.relationName ?? relationKey;\n if (seen.has(identity)) continue;\n\n let target: CollectionConfig | undefined;\n try {\n target = relation.target();\n } catch {\n continue;\n }\n if (!target) continue;\n seen.add(identity);\n\n // A name given to the declaring property is the author naming the tab.\n const declaringProperty = Object.entries((collection.properties ?? {}) as Record<string, Property>)\n .find(([propKey, p]) => p.type === \"relation\" && ((p as RelationProperty).relation?.relationName ?? propKey) === identity);\n const customName = declaringProperty?.[1]?.name;\n\n const base: CollectionConfig<Record<string, unknown>> = {\n ...target,\n slug: relationKey,\n ...(customName ? { name: customName,\nsingularName: customName } : {})\n } as CollectionConfig<Record<string, unknown>>;\n\n views.push({\n key: relationKey,\n collection: (relation.overrides ? mergeDeep(base, relation.overrides) : base) as CollectionConfig<Record<string, unknown>>,\n source: {\n kind: \"relation\",\n relationKey,\n mode: isJunctionBackedRelation(relation) ? \"linked\" : \"owned\",\n targetSlug: target.slug\n }\n });\n }\n\n return views;\n}\n\n/**\n * Each of `collection`'s tabs paired with the property that declared it, when a\n * property declared it: child view key → property key.\n *\n * A many-relation can only be declared as a property — that is the documented\n * and only mechanism — and {@link getEntityChildViews} promotes it to a tab. So\n * one declaration reaches the panel twice, and neither surface knew about the\n * other. The form rendered a relation picker beside the tab, and the collection\n * table rendered *two* columns under one heading: the relation's own column,\n * showing the child rows, and a jump-to-tab button carrying the same name.\n *\n * The pairing is what lets each surface decide which half is redundant, and it\n * has to be a pairing rather than two sets because the two keys differ whenever\n * a relation is named. The match is on the resolved `relationName` — the\n * identity `getEntityChildViews` itself dedupes on — so a relation declared in\n * `relations` and pointed at by a differently-named property is recognised too.\n *\n * A relation with no property of its own is absent here, which is the point: it\n * has exactly one surface already, and nothing to weigh it against.\n *\n * Only top-level properties: a relation nested inside a `map` gets no tab.\n */\nexport function getChildViewDeclaringProperties<M extends Record<string, unknown> = Record<string, unknown>>(\n collection: CollectionConfig<M>\n): Map<string, string> {\n const pairs = new Map<string, string>();\n\n const relationProperties = Object.entries((collection.properties ?? {}) as Record<string, Property>)\n .filter(([, property]) => property?.type === \"relation\");\n if (relationProperties.length === 0) return pairs;\n\n const relationViews = getEntityChildViews(collection)\n .filter(view => view.source.kind === \"relation\");\n if (relationViews.length === 0) return pairs;\n\n const resolvedRelations = resolveCollectionRelations(collection);\n const identityOf = (relationKey: string): string =>\n resolvedRelations[relationKey]?.relationName ?? relationKey;\n\n const declaringPropertyByIdentity = new Map<string, string>();\n for (const [propertyKey, property] of relationProperties) {\n const relation = (property as RelationProperty).resolvedRelation ?? resolvedRelations[propertyKey];\n // A to-one relation is a foreign key the author edits, never a tab. No\n // view will match it — the views here are many-relations only — but\n // reading the cardinality says so where someone is looking.\n if (relation?.cardinality !== \"many\") continue;\n const identity = relation.relationName ?? propertyKey;\n if (!declaringPropertyByIdentity.has(identity)) declaringPropertyByIdentity.set(identity, propertyKey);\n }\n\n for (const view of relationViews) {\n const propertyKey = declaringPropertyByIdentity.get(\n identityOf((view.source as { relationKey: string }).relationKey));\n if (propertyKey) pairs.set(view.key, propertyKey);\n }\n\n return pairs;\n}\n\n/**\n * The property keys of `collection` whose relation is already one of its tabs.\n *\n * What a form asks: the tab is the treatment for a list of child rows, so the\n * picker beside it is the redundant half. See\n * {@link getChildViewDeclaringProperties}.\n */\nexport function getChildViewRelationPropertyKeys<M extends Record<string, unknown> = Record<string, unknown>>(\n collection: CollectionConfig<M>\n): Set<string> {\n return new Set(getChildViewDeclaringProperties(collection).values());\n}\n\n/**\n * The child views of `collection` as bare collections.\n *\n * The flattened view of {@link getEntityChildViews}, for navigation code that\n * only needs to match a path segment against a slug. Anything that cares *what\n * kind* of list it is showing — chiefly the admin, which must not offer a\n * global delete on a shared row — should read the views instead.\n */\nexport function getSubcollections<M extends Record<string, unknown> = Record<string, unknown>>(collection: CollectionConfig<M>): CollectionConfig<Record<string, unknown>>[] {\n return get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AEvC,MAAM,oBAAoB,2BAA2B,UAAU;CAC/D,MAAM,cAAc,gBAChB,kBAAkB,YAAY,EAAE,gBAAgB;CAEpD,MAAM,8CAA8B,IAAI,IAAoB;CAC5D,KAAK,MAAM,CAAC,aAAa,aAAa,oBAAoB;EACtD,MAAM,WAAY,SAA8B,oBAAoB,kBAAkB;EAItF,IAAI,UAAU,gBAAgB,QAAQ;EACtC,MAAM,WAAW,SAAS,gBAAgB;EAC1C,IAAI,CAAC,4BAA4B,IAAI,QAAQ,GAAG,4BAA4B,IAAI,UAAU,WAAW;CACzG;CAEA,KAAK,MAAM,QAAQ,eAAe;EAC9B,MAAM,cAAc,4BAA4B,IAC5C,WAAY,KAAK,OAAmC,WAAW,CAAC;EACpE,IAAI,aAAa,MAAM,IAAI,KAAK,KAAK,WAAW;CACpD;CAEA,OAAO;AACX;;;;;;;;AASA,SAAgB,iCACZ,YACW;CACX,OAAO,IAAI,IAAI,gCAAgC,UAAU,CAAC,CAAC,OAAO,CAAC;AACvE;;;;;;;;;AAUA,SAAgB,kBAA+E,YAA8E;CACzK,OAAO,oBAAoB,UAAU,CAAC,CAAC,KAAI,SAAQ,KAAK,UAAU;AACtE"}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { getTableName } from "./relations.es.js";
|
|
2
|
+
import { generateForeignKeyName, toSnakeCase } from "@rebasepro/utils";
|
|
3
|
+
//#region src/util/resolve-relation.ts
|
|
4
|
+
/**
|
|
5
|
+
* Fill in a relation's defaults.
|
|
6
|
+
*
|
|
7
|
+
* This replaces `sanitizeRelation`, which had to work out *which kind of link
|
|
8
|
+
* you meant* from whichever optional fields happened to be set — 194 lines of
|
|
9
|
+
* it, including a pass that inspected the target collection's own relations to
|
|
10
|
+
* decide whether a `many`/`inverse` pair was a one-to-many or the far side of a
|
|
11
|
+
* many-to-many, wrapped in a `try/catch` that fell through to the wrong answer
|
|
12
|
+
* when it could not tell. Two consumers running that logic at different moments
|
|
13
|
+
* could reach different conclusions about the same relation.
|
|
14
|
+
*
|
|
15
|
+
* With the kind declared there is nothing to work out. What remains is
|
|
16
|
+
* defaulting — a table name, a column name — which is deterministic, depends
|
|
17
|
+
* only on the relation and its two endpoints, and cannot fail. That is why this
|
|
18
|
+
* function returns rather than throws, and why it needs no cache to be
|
|
19
|
+
* consistent.
|
|
20
|
+
*/
|
|
21
|
+
function resolveRelation(relation, sourceCollection, propertyKey) {
|
|
22
|
+
const target = relation.target;
|
|
23
|
+
if (typeof target !== "function") throw new Error(`Relation${relation.relationName ? ` '${relation.relationName}'` : ""} on '${sourceCollection.slug}' has no \`target\`. Give it a thunk: \`target: () => otherCollection\`.`);
|
|
24
|
+
const targetCollection = callTarget(relation, sourceCollection, propertyKey, target);
|
|
25
|
+
const relationName = relation.relationName ?? propertyKey ?? toSnakeCase(targetCollection.slug);
|
|
26
|
+
const shared = {
|
|
27
|
+
relationName,
|
|
28
|
+
target: () => unwrapModuleNamespace(target()),
|
|
29
|
+
targetSlug: targetCollection.slug,
|
|
30
|
+
onUpdate: relation.onUpdate,
|
|
31
|
+
onDelete: relation.onDelete,
|
|
32
|
+
overrides: relation.overrides
|
|
33
|
+
};
|
|
34
|
+
const sourceName = toSnakeCase(sourceCollection.slug ?? sourceCollection.name);
|
|
35
|
+
switch (relation.kind) {
|
|
36
|
+
case "belongsTo": return {
|
|
37
|
+
...shared,
|
|
38
|
+
kind: "belongsTo",
|
|
39
|
+
cardinality: "one",
|
|
40
|
+
writable: true,
|
|
41
|
+
shared: false,
|
|
42
|
+
localKey: relation.localKey ?? generateForeignKeyName(relationName),
|
|
43
|
+
index: relation.index !== false
|
|
44
|
+
};
|
|
45
|
+
case "hasOne": return {
|
|
46
|
+
...shared,
|
|
47
|
+
kind: "hasOne",
|
|
48
|
+
cardinality: "one",
|
|
49
|
+
writable: true,
|
|
50
|
+
shared: false,
|
|
51
|
+
foreignKeyOnTarget: relation.foreignKeyOnTarget ?? generateForeignKeyName(sourceName),
|
|
52
|
+
sourceKey: relation.sourceKey
|
|
53
|
+
};
|
|
54
|
+
case "hasMany": return {
|
|
55
|
+
...shared,
|
|
56
|
+
kind: "hasMany",
|
|
57
|
+
cardinality: "many",
|
|
58
|
+
writable: true,
|
|
59
|
+
shared: false,
|
|
60
|
+
foreignKeyOnTarget: relation.foreignKeyOnTarget ?? generateForeignKeyName(sourceName),
|
|
61
|
+
sourceKey: relation.sourceKey
|
|
62
|
+
};
|
|
63
|
+
case "manyToMany": {
|
|
64
|
+
const sourceTable = getTableName(sourceCollection);
|
|
65
|
+
const targetTable = getTableName(targetCollection);
|
|
66
|
+
return {
|
|
67
|
+
...shared,
|
|
68
|
+
kind: "manyToMany",
|
|
69
|
+
cardinality: "many",
|
|
70
|
+
writable: true,
|
|
71
|
+
shared: true,
|
|
72
|
+
through: {
|
|
73
|
+
table: relation.through?.table ?? [sourceTable, targetTable].sort().join("_"),
|
|
74
|
+
sourceColumn: relation.through?.sourceColumn ?? generateForeignKeyName(sourceName),
|
|
75
|
+
targetColumn: relation.through?.targetColumn ?? generateForeignKeyName(relationName),
|
|
76
|
+
properties: relation.through?.properties ?? {}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
case "via": return {
|
|
81
|
+
...shared,
|
|
82
|
+
kind: "via",
|
|
83
|
+
cardinality: relation.cardinality,
|
|
84
|
+
writable: false,
|
|
85
|
+
shared: true,
|
|
86
|
+
joinPath: relation.joinPath
|
|
87
|
+
};
|
|
88
|
+
default: throw new Error(`Unknown relation kind: ${JSON.stringify(relation)}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** How this relation is addressed in an error message, before it has a resolved name. */
|
|
92
|
+
function describe(relation, sourceCollection, propertyKey) {
|
|
93
|
+
const name = relation.relationName ?? propertyKey;
|
|
94
|
+
return `Relation${name ? ` '${name}'` : ""} on '${sourceCollection.slug}'`;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* A module namespace, unwrapped to the collection it exports.
|
|
98
|
+
*
|
|
99
|
+
* A cycle transpiled to CommonJS does not hand the importing module the
|
|
100
|
+
* *default export* — it hands it the module object, `{ __esModule: true,
|
|
101
|
+
* default: … }`, captured before the exporting module finished evaluating. The
|
|
102
|
+
* `default` slot fills in later, so by the time a lazy `target` thunk runs the
|
|
103
|
+
* collection is sitting right there, one level down. Returning the namespace is
|
|
104
|
+
* never a thing a thunk means to do, and there is exactly one reading of it.
|
|
105
|
+
*
|
|
106
|
+
* Only unwrapped when the inner value is itself a collection: a `default` that
|
|
107
|
+
* is not one is a genuinely wrong thunk, and it should reach the error below
|
|
108
|
+
* rather than be quietly swapped in.
|
|
109
|
+
*/
|
|
110
|
+
function unwrapModuleNamespace(value) {
|
|
111
|
+
if (!value || typeof value !== "object") return value;
|
|
112
|
+
if (value.slug) return value;
|
|
113
|
+
const inner = value.default;
|
|
114
|
+
return inner && typeof inner === "object" && inner.slug ? inner : value;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Call the `target` thunk, and translate the ways an import cycle breaks it into
|
|
118
|
+
* an error that names the cause — or, where the value is recoverable, into the
|
|
119
|
+
* collection the thunk meant.
|
|
120
|
+
*
|
|
121
|
+
* The thunk exists to defer the reference until every module has finished
|
|
122
|
+
* evaluating, and for a cycle that closes at import time it does. Two cycles
|
|
123
|
+
* leave the binding permanently unusable:
|
|
124
|
+
*
|
|
125
|
+
* - **ESM/TDZ.** `const` and `class` bindings in a not-yet-evaluated module are
|
|
126
|
+
* in the temporal dead zone, so reading one throws `ReferenceError: x is not
|
|
127
|
+
* defined`. The stack points at the thunk — a one-line arrow function that is
|
|
128
|
+
* obviously fine — and says nothing about the cycle that made it throw.
|
|
129
|
+
* - **CJS interop, unresolved.** The half-initialised module object has no
|
|
130
|
+
* `default` yet, the import resolves to `undefined`, and the thunk returns it
|
|
131
|
+
* without complaint. That one used to surface here as "did not resolve to a
|
|
132
|
+
* collection", which is true and unhelpful.
|
|
133
|
+
*
|
|
134
|
+
* Both mean the same thing, and the fix for both is the same: break the cycle,
|
|
135
|
+
* or move the relation into the collection that does not close it.
|
|
136
|
+
*
|
|
137
|
+
* A third shape is *not* an error, and used to be reported as one. A loader that
|
|
138
|
+
* transpiles ESM to CJS — jiti, which is what `rebase generate-sdk` and
|
|
139
|
+
* `rebase build` load collections with — gives the module entered second in a
|
|
140
|
+
* cycle a namespace object rather than the default export, and never replaces it
|
|
141
|
+
* with a live binding. The thunk then returns `{ __esModule: true, default: … }`
|
|
142
|
+
* holding the fully-initialised collection. Native ESM resolves the same thunk
|
|
143
|
+
* to the collection directly, so this was a loader artefact reported as an
|
|
144
|
+
* authoring mistake, and the advice it gave — make the target a lazy thunk — was
|
|
145
|
+
* already satisfied by the code it was rejecting. Bidirectional relations make
|
|
146
|
+
* these cycles unavoidable, and the lazy thunk is this framework's own answer to
|
|
147
|
+
* them, so {@link unwrapModuleNamespace} takes the collection and moves on.
|
|
148
|
+
*/
|
|
149
|
+
function callTarget(relation, sourceCollection, propertyKey, target) {
|
|
150
|
+
let targetCollection;
|
|
151
|
+
try {
|
|
152
|
+
targetCollection = unwrapModuleNamespace(target());
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (error instanceof ReferenceError) throw new Error(`${describe(relation, sourceCollection, propertyKey)} targets a collection that is not initialized yet — almost always an import cycle between the two collection files. Break the cycle (move the shared piece into a third module, or import the target lazily) so the target's module finishes evaluating before the registry is built.`, { cause: error });
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
if (!targetCollection?.slug) throw new Error(`${describe(relation, sourceCollection, propertyKey)} has a \`target\` that resolved to ${targetCollection === void 0 ? "`undefined`" : "something that is not a collection"}. ` + (targetCollection === void 0 ? "Under CommonJS interop an import cycle resolves the default import to `undefined`, so check whether this collection and its target import each other. Otherwise the thunk is returning the wrong value — it must return the collection itself, not a promise or a module." : typeof targetCollection.then === "function" ? "The thunk returned a promise — `target: () => import(\"./other\")` is asynchronous. Import the collection at the top of the file and return the binding: `target: () => otherCollection`." : "The thunk must return a collection config with a `slug`."));
|
|
158
|
+
return targetCollection;
|
|
159
|
+
}
|
|
160
|
+
//#endregion
|
|
161
|
+
export { resolveRelation };
|
|
162
|
+
|
|
163
|
+
//# sourceMappingURL=resolve-relation.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-relation.es.js","names":[],"sources":["../../src/util/resolve-relation.ts"],"sourcesContent":["import {\n CollectionConfig,\n Relation,\n ResolvedRelation\n} from \"@rebasepro/types\";\nimport { generateForeignKeyName, toSnakeCase } from \"@rebasepro/utils\";\n\nimport { getTableName } from \"./relations\";\n\n/**\n * Fill in a relation's defaults.\n *\n * This replaces `sanitizeRelation`, which had to work out *which kind of link\n * you meant* from whichever optional fields happened to be set — 194 lines of\n * it, including a pass that inspected the target collection's own relations to\n * decide whether a `many`/`inverse` pair was a one-to-many or the far side of a\n * many-to-many, wrapped in a `try/catch` that fell through to the wrong answer\n * when it could not tell. Two consumers running that logic at different moments\n * could reach different conclusions about the same relation.\n *\n * With the kind declared there is nothing to work out. What remains is\n * defaulting — a table name, a column name — which is deterministic, depends\n * only on the relation and its two endpoints, and cannot fail. That is why this\n * function returns rather than throws, and why it needs no cache to be\n * consistent.\n */\nexport function resolveRelation(\n relation: Relation,\n sourceCollection: CollectionConfig,\n propertyKey?: string\n): ResolvedRelation {\n const target = relation.target;\n if (typeof target !== \"function\") {\n throw new Error(\n `Relation${relation.relationName ? ` '${relation.relationName}'` : \"\"} on ` +\n `'${sourceCollection.slug}' has no \\`target\\`. Give it a thunk: \\`target: () => otherCollection\\`.`\n );\n }\n\n const targetCollection = callTarget(relation, sourceCollection, propertyKey, target);\n\n // The name is the address: the `include` key, the admin tab, and the\n // segment of a nested path. Declared name wins, then the declaring\n // property's key, then the target's slug.\n const relationName = relation.relationName ?? propertyKey ?? toSnakeCase(targetCollection.slug);\n\n const shared: Pick<ResolvedRelation, \"relationName\" | \"target\" | \"targetSlug\" | \"onUpdate\" | \"onDelete\" | \"overrides\"> = {\n relationName,\n // Normalised, not the thunk as written. Resolution reads the target once\n // and every later consumer calls it again — the driver building a join,\n // the DDL and policy generators, the admin's relation fields — so\n // handing back the raw thunk would give all of them the module namespace\n // `callTarget` just looked past, and the fix would hold only for the\n // fields resolution happens to read here. Still lazy: same call at the\n // same moment, one unwrap on the way out.\n target: () => unwrapModuleNamespace(target()) as CollectionConfig,\n targetSlug: targetCollection.slug,\n onUpdate: relation.onUpdate,\n onDelete: relation.onDelete,\n overrides: relation.overrides\n // No `validation`. Whether the link is required is a fact about the\n // *property*, and copying it onto the resolved relation gave the\n // question two answers that were free to disagree. Ask\n // `isRelationRequired(collection, relation)`, which reads the one.\n };\n\n const sourceName = toSnakeCase(sourceCollection.slug ?? sourceCollection.name);\n\n switch (relation.kind) {\n case \"belongsTo\":\n return {\n ...shared,\n kind: \"belongsTo\",\n cardinality: \"one\",\n writable: true,\n shared: false,\n localKey: relation.localKey ?? generateForeignKeyName(relationName),\n index: relation.index !== false\n };\n\n case \"hasOne\":\n return {\n ...shared,\n kind: \"hasOne\",\n cardinality: \"one\",\n writable: true,\n shared: false,\n foreignKeyOnTarget: relation.foreignKeyOnTarget ?? generateForeignKeyName(sourceName),\n sourceKey: relation.sourceKey\n };\n\n case \"hasMany\":\n return {\n ...shared,\n kind: \"hasMany\",\n cardinality: \"many\",\n writable: true,\n shared: false,\n foreignKeyOnTarget: relation.foreignKeyOnTarget ?? generateForeignKeyName(sourceName),\n // Not defaulted: the source's primary key needs the driver's\n // schema to resolve, which resolution does not have. `undefined`\n // means \"the primary key\" — see `ResolvedHasMany.sourceKey`.\n sourceKey: relation.sourceKey\n };\n\n case \"manyToMany\": {\n const sourceTable = getTableName(sourceCollection);\n const targetTable = getTableName(targetCollection);\n return {\n ...shared,\n kind: \"manyToMany\",\n cardinality: \"many\",\n writable: true,\n shared: true,\n through: {\n // Sorted so both sides of the same link derive the same\n // table without having to agree in advance.\n table: relation.through?.table ?? [sourceTable, targetTable].sort().join(\"_\"),\n sourceColumn: relation.through?.sourceColumn ?? generateForeignKeyName(sourceName),\n targetColumn: relation.through?.targetColumn ?? generateForeignKeyName(relationName),\n // `{}` rather than `undefined`, for the reason every other\n // field here is filled in: a consumer reads one shape and\n // does not have to decide what an absent payload means.\n properties: relation.through?.properties ?? {}\n }\n };\n }\n\n case \"via\":\n return {\n ...shared,\n kind: \"via\",\n cardinality: relation.cardinality,\n writable: false,\n // A join chain reaches rows that other parents reach too, and\n // Rebase does not know which hop, if any, is a link it owns.\n shared: true,\n joinPath: relation.joinPath\n };\n\n default: {\n // Exhaustive: a new kind is a compile error here, not a silent\n // fall-through to whatever shape happened to match first.\n const exhaustive: never = relation;\n throw new Error(`Unknown relation kind: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n\n/** How this relation is addressed in an error message, before it has a resolved name. */\nfunction describe(relation: Relation, sourceCollection: CollectionConfig, propertyKey?: string): string {\n const name = relation.relationName ?? propertyKey;\n return `Relation${name ? ` '${name}'` : \"\"} on '${sourceCollection.slug}'`;\n}\n\n/**\n * A module namespace, unwrapped to the collection it exports.\n *\n * A cycle transpiled to CommonJS does not hand the importing module the\n * *default export* — it hands it the module object, `{ __esModule: true,\n * default: … }`, captured before the exporting module finished evaluating. The\n * `default` slot fills in later, so by the time a lazy `target` thunk runs the\n * collection is sitting right there, one level down. Returning the namespace is\n * never a thing a thunk means to do, and there is exactly one reading of it.\n *\n * Only unwrapped when the inner value is itself a collection: a `default` that\n * is not one is a genuinely wrong thunk, and it should reach the error below\n * rather than be quietly swapped in.\n */\nfunction unwrapModuleNamespace(value: unknown): unknown {\n if (!value || typeof value !== \"object\") return value;\n if ((value as { slug?: unknown }).slug) return value;\n const inner = (value as { default?: unknown }).default;\n return inner && typeof inner === \"object\" && (inner as { slug?: unknown }).slug ? inner : value;\n}\n\n/**\n * Call the `target` thunk, and translate the ways an import cycle breaks it into\n * an error that names the cause — or, where the value is recoverable, into the\n * collection the thunk meant.\n *\n * The thunk exists to defer the reference until every module has finished\n * evaluating, and for a cycle that closes at import time it does. Two cycles\n * leave the binding permanently unusable:\n *\n * - **ESM/TDZ.** `const` and `class` bindings in a not-yet-evaluated module are\n * in the temporal dead zone, so reading one throws `ReferenceError: x is not\n * defined`. The stack points at the thunk — a one-line arrow function that is\n * obviously fine — and says nothing about the cycle that made it throw.\n * - **CJS interop, unresolved.** The half-initialised module object has no\n * `default` yet, the import resolves to `undefined`, and the thunk returns it\n * without complaint. That one used to surface here as \"did not resolve to a\n * collection\", which is true and unhelpful.\n *\n * Both mean the same thing, and the fix for both is the same: break the cycle,\n * or move the relation into the collection that does not close it.\n *\n * A third shape is *not* an error, and used to be reported as one. A loader that\n * transpiles ESM to CJS — jiti, which is what `rebase generate-sdk` and\n * `rebase build` load collections with — gives the module entered second in a\n * cycle a namespace object rather than the default export, and never replaces it\n * with a live binding. The thunk then returns `{ __esModule: true, default: … }`\n * holding the fully-initialised collection. Native ESM resolves the same thunk\n * to the collection directly, so this was a loader artefact reported as an\n * authoring mistake, and the advice it gave — make the target a lazy thunk — was\n * already satisfied by the code it was rejecting. Bidirectional relations make\n * these cycles unavoidable, and the lazy thunk is this framework's own answer to\n * them, so {@link unwrapModuleNamespace} takes the collection and moves on.\n */\nfunction callTarget(\n relation: Relation,\n sourceCollection: CollectionConfig,\n propertyKey: string | undefined,\n target: Relation[\"target\"]\n): ReturnType<Relation[\"target\"]> {\n let targetCollection: ReturnType<Relation[\"target\"]> | undefined;\n try {\n targetCollection = unwrapModuleNamespace(target()) as ReturnType<Relation[\"target\"]>;\n } catch (error) {\n // A ReferenceError from inside the thunk is a binding that was never\n // initialised — nothing else in a one-expression arrow can raise one.\n if (error instanceof ReferenceError) {\n throw new Error(\n `${describe(relation, sourceCollection, propertyKey)} targets a collection that is not ` +\n `initialized yet — almost always an import cycle between the two collection files. ` +\n `Break the cycle (move the shared piece into a third module, or import the target ` +\n `lazily) so the target's module finishes evaluating before the registry is built.`,\n { cause: error }\n );\n }\n throw error;\n }\n\n if (!targetCollection?.slug) {\n throw new Error(\n `${describe(relation, sourceCollection, propertyKey)} has a \\`target\\` that resolved to ` +\n `${targetCollection === undefined ? \"`undefined`\" : \"something that is not a collection\"}. ` +\n (targetCollection === undefined\n ? \"Under CommonJS interop an import cycle resolves the default import to `undefined`, \" +\n \"so check whether this collection and its target import each other. Otherwise the thunk \" +\n \"is returning the wrong value — it must return the collection itself, not a promise or a module.\"\n : typeof (targetCollection as { then?: unknown }).then === \"function\"\n ? \"The thunk returned a promise — `target: () => import(\\\"./other\\\")` is asynchronous. \" +\n \"Import the collection at the top of the file and return the binding: \" +\n \"`target: () => otherCollection`.\"\n : \"The thunk must return a collection config with a `slug`.\")\n );\n }\n\n return targetCollection;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,gBACZ,UACA,kBACA,aACgB;CAChB,MAAM,SAAS,SAAS;CACxB,IAAI,OAAO,WAAW,YAClB,MAAM,IAAI,MACN,WAAW,SAAS,eAAe,KAAK,SAAS,aAAa,KAAK,GAAG,OAClE,iBAAiB,KAAK,yEAC9B;CAGJ,MAAM,mBAAmB,WAAW,UAAU,kBAAkB,aAAa,MAAM;CAKnF,MAAM,eAAe,SAAS,gBAAgB,eAAe,YAAY,iBAAiB,IAAI;CAE9F,MAAM,SAAmH;EACrH;EAQA,cAAc,sBAAsB,OAAO,CAAC;EAC5C,YAAY,iBAAiB;EAC7B,UAAU,SAAS;EACnB,UAAU,SAAS;EACnB,WAAW,SAAS;CAKxB;CAEA,MAAM,aAAa,YAAY,iBAAiB,QAAQ,iBAAiB,IAAI;CAE7E,QAAQ,SAAS,MAAjB;EACI,KAAK,aACD,OAAO;GACH,GAAG;GACH,MAAM;GACN,aAAa;GACb,UAAU;GACV,QAAQ;GACR,UAAU,SAAS,YAAY,uBAAuB,YAAY;GAClE,OAAO,SAAS,UAAU;EAC9B;EAEJ,KAAK,UACD,OAAO;GACH,GAAG;GACH,MAAM;GACN,aAAa;GACb,UAAU;GACV,QAAQ;GACR,oBAAoB,SAA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C9B,IAAI;CACJ,IAAI;EACA,mBAAmB,sBAAsB,OAAO,CAAC;CACrD,SAAS,OAAO;EAGZ,IAAI,iBAAiB,gBACjB,MAAM,IAAI,MACN,GAAG,SAAS,UAAU,kBAAkB,WAAW,EAAE,wRAIrD,EAAE,OAAO,MAAM,CACnB;EAEJ,MAAM;CACV;CAEA,IAAI,CAAC,kBAAkB,MACnB,MAAM,IAAI,MACN,GAAG,SAAS,UAAU,kBAAkB,WAAW,EAAE,qCAClD,qBAAqB,KAAA,IAAY,gBAAgB,qCAAqC,OACxF,qBAAqB,KAAA,IAChB,8QAGA,OAAQ,iBAAwC,SAAS,aACrD,8LAGA,2DACd;CAGJ,OAAO;AACX"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files larger than this go up through the resumable (TUS) endpoint, a chunk
|
|
3
|
+
* of this size per request, instead of `POST /storage/upload`.
|
|
4
|
+
*
|
|
5
|
+
* `POST /upload` is one multipart body, which the server parses whole before
|
|
6
|
+
* the route runs: three to five times the file in its memory. A chunk is one
|
|
7
|
+
* request body under the server's global body limit (10 MB by default), so the
|
|
8
|
+
* resumable path holds one chunk at a time whatever the file's size. Below the
|
|
9
|
+
* threshold the multipart request is one round trip and a few megabytes, and
|
|
10
|
+
* stays.
|
|
11
|
+
*
|
|
12
|
+
* In a module of its own: a client compares every upload against it, and only
|
|
13
|
+
* the ones past it need the resumable upload itself (see resumable-upload.ts).
|
|
14
|
+
*/
|
|
15
|
+
export declare const RESUMABLE_UPLOAD_THRESHOLD: number;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region src/util/resumable-upload-threshold.ts
|
|
2
|
+
/**
|
|
3
|
+
* Files larger than this go up through the resumable (TUS) endpoint, a chunk
|
|
4
|
+
* of this size per request, instead of `POST /storage/upload`.
|
|
5
|
+
*
|
|
6
|
+
* `POST /upload` is one multipart body, which the server parses whole before
|
|
7
|
+
* the route runs: three to five times the file in its memory. A chunk is one
|
|
8
|
+
* request body under the server's global body limit (10 MB by default), so the
|
|
9
|
+
* resumable path holds one chunk at a time whatever the file's size. Below the
|
|
10
|
+
* threshold the multipart request is one round trip and a few megabytes, and
|
|
11
|
+
* stays.
|
|
12
|
+
*
|
|
13
|
+
* In a module of its own: a client compares every upload against it, and only
|
|
14
|
+
* the ones past it need the resumable upload itself (see resumable-upload.ts).
|
|
15
|
+
*/
|
|
16
|
+
var RESUMABLE_UPLOAD_THRESHOLD = 8 * 1024 * 1024;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { RESUMABLE_UPLOAD_THRESHOLD };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=resumable-upload-threshold.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resumable-upload-threshold.es.js","names":[],"sources":["../../src/util/resumable-upload-threshold.ts"],"sourcesContent":["/**\n * Files larger than this go up through the resumable (TUS) endpoint, a chunk\n * of this size per request, instead of `POST /storage/upload`.\n *\n * `POST /upload` is one multipart body, which the server parses whole before\n * the route runs: three to five times the file in its memory. A chunk is one\n * request body under the server's global body limit (10 MB by default), so the\n * resumable path holds one chunk at a time whatever the file's size. Below the\n * threshold the multipart request is one round trip and a few megabytes, and\n * stays.\n *\n * In a module of its own: a client compares every upload against it, and only\n * the ones past it need the resumable upload itself (see resumable-upload.ts).\n */\nexport const RESUMABLE_UPLOAD_THRESHOLD = 8 * 1024 * 1024;\n"],"mappings":";;;;;;;;;;;;;;;AAcA,IAAa,6BAA6B,IAAI,OAAO"}
|