@vectoriahq/quac 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -301,6 +301,12 @@ export declare function readCatalogueInitialView(catalog: StacCatalog): Normaliz
301
301
  */
302
302
  /** The field the source nominates as the layer's title attribute. */
303
303
  export declare function readCollectionDisplayField(collection: StacCollection): string | null;
304
+ /**
305
+ * Each entry of a Collection's `table:columns` that is an object with a
306
+ * non-blank `name`, as `[trimmed name, column]`, in declared order. An entry
307
+ * of any other shape, or a `table:columns` that is not a list, yields nothing.
308
+ */
309
+ export declare function declaredColumns(collection: StacCollection): Generator<[string, Record<string, unknown>]>;
304
310
  /** Each field's alias, its column's `title`. A column with a blank or no `title` is absent. */
305
311
  export declare function readCollectionFieldAliases(collection: StacCollection): Record<string, string>;
306
312
  /** Each field's comment, its column's `description`, trimmed. A column with a blank or no `description` is absent. */
@@ -376,7 +376,7 @@ export function readCollectionDisplayField(collection) {
376
376
  * non-blank `name`, as `[trimmed name, column]`, in declared order. An entry
377
377
  * of any other shape, or a `table:columns` that is not a list, yields nothing.
378
378
  */
379
- function* declaredColumns(collection) {
379
+ export function* declaredColumns(collection) {
380
380
  const columns = collection['table:columns'];
381
381
  if (!Array.isArray(columns))
382
382
  return;
@@ -0,0 +1,81 @@
1
+ import type { FieldRange } from '../model/QgsProject.ts';
2
+ import type { StacCollection } from '../model/Stac.ts';
3
+ /**
4
+ * Why a new feature's field is refused:
5
+ *
6
+ * - `unknown-field`: the layer has no such field;
7
+ * - `not-fillable`: the field is read-only, the form never shows it, or the
8
+ * form layout does not place it, so nobody filling in the form could set it;
9
+ * - `required`: the field enforces Not null and is blank;
10
+ * - `wrong-type`: the value is not of the field's type;
11
+ * - `not-a-choice`: the field restricts its values to a list, or is a
12
+ * Checkbox with its own spelling, and the value is not one of them;
13
+ * - `out-of-range`: the value is a number outside the field's range.
14
+ */
15
+ export type NewFeatureProblem = 'unknown-field' | 'not-fillable' | 'required' | 'wrong-type' | 'not-a-choice' | 'out-of-range';
16
+ /**
17
+ * A rule a fillable field has that the layer's Collection alone cannot check:
18
+ *
19
+ * - `constraint-expression`: an enforced constraint expression, which needs an
20
+ * expression evaluator;
21
+ * - `visible-when` / `editable-when`: an expression that hides or locks the
22
+ * field in the form, so whether it is filled in depends on the other values;
23
+ * - `value-relation`: its choices are another layer's records;
24
+ * - `unique`: an enforced Unique constraint, which needs the layer's other features;
25
+ * - `date-format`: it stores dates in a format of its own;
26
+ * - `attachment`: it holds a file's path, and the file is not part of the feature;
27
+ * - `type`: its type is one this does not know.
28
+ */
29
+ export type UncheckedFieldRule = 'constraint-expression' | 'visible-when' | 'editable-when' | 'value-relation' | 'unique' | 'date-format' | 'attachment' | 'type';
30
+ export interface NewFeatureCheck {
31
+ /** The fields refused, in the layer's field order, then the fields the layer does not have. */
32
+ problems: {
33
+ field: string;
34
+ problem: NewFeatureProblem;
35
+ }[];
36
+ /**
37
+ * The rules not checked, for every fillable field that has one, whatever
38
+ * the feature's values. A caller that must not accept a feature unchecked
39
+ * refuses it, or the layer, where this is not empty.
40
+ */
41
+ unchecked: {
42
+ field: string;
43
+ rule: UncheckedFieldRule;
44
+ }[];
45
+ }
46
+ type Properties = Readonly<Record<string, unknown>>;
47
+ /**
48
+ * Checks a new feature's values against the field rules a layer's Collection
49
+ * states (`table:columns`), for an application that adds features to a layer
50
+ * from a form it does not draw itself, such as a server taking features from
51
+ * the public. Each field is checked on its own: whether the layer has it,
52
+ * whether a form could fill it, Not null, its type, its list of values or
53
+ * Checkbox spelling, and its range. A rule that needs more than the Collection
54
+ * to check is listed in `unchecked`, not passed.
55
+ *
56
+ * It checks only what the Collection carries. A catalogue generated from a
57
+ * QGIS project leaves out a setting it cannot read, such as a constraint
58
+ * expression `readQgisExpression` cannot read, and lists it in the project's
59
+ * `notes`, which a caller reads as well.
60
+ *
61
+ * A Collection that declares no fields refuses every value. A warning
62
+ * (`warn`) constraint refuses nothing, as QGIS saves past it. Values are
63
+ * checked as stored, with no conversion: a number field takes a number, not
64
+ * text holding one.
65
+ */
66
+ export declare function validateNewFeature(collection: StacCollection, properties: Properties | null | undefined): NewFeatureCheck;
67
+ /**
68
+ * The fields a form for a new feature can fill, in the layer's field order:
69
+ * each declared field that is not read-only, is shown by the form, and is
70
+ * placed by the form layout where the layer has one.
71
+ */
72
+ export declare function readNewFeatureFields(collection: StacCollection): string[];
73
+ /** A field with no value: null, absent, or text that is only spaces. Not null refuses one. */
74
+ export declare function isBlankFieldValue(value: unknown): boolean;
75
+ /**
76
+ * Whether a value is a number outside a field's range. A blank value, a
77
+ * boolean and text that is not a number are not: Not null and the field's
78
+ * type deal with those. Text holding a number is read as that number.
79
+ */
80
+ export declare function isOutsideFieldRange(value: unknown, range: Pick<FieldRange, 'min' | 'max'>): boolean;
81
+ export {};
@@ -0,0 +1,152 @@
1
+ import { declaredColumns, readCollectionFieldEditRules, readCollectionFieldTypes, readCollectionFieldValues } from "./normalizedProject.js";
2
+ /**
3
+ * Checks a new feature's values against the field rules a layer's Collection
4
+ * states (`table:columns`), for an application that adds features to a layer
5
+ * from a form it does not draw itself, such as a server taking features from
6
+ * the public. Each field is checked on its own: whether the layer has it,
7
+ * whether a form could fill it, Not null, its type, its list of values or
8
+ * Checkbox spelling, and its range. A rule that needs more than the Collection
9
+ * to check is listed in `unchecked`, not passed.
10
+ *
11
+ * It checks only what the Collection carries. A catalogue generated from a
12
+ * QGIS project leaves out a setting it cannot read, such as a constraint
13
+ * expression `readQgisExpression` cannot read, and lists it in the project's
14
+ * `notes`, which a caller reads as well.
15
+ *
16
+ * A Collection that declares no fields refuses every value. A warning
17
+ * (`warn`) constraint refuses nothing, as QGIS saves past it. Values are
18
+ * checked as stored, with no conversion: a number field takes a number, not
19
+ * text holding one.
20
+ */
21
+ export function validateNewFeature(collection, properties) {
22
+ const values = properties ?? {};
23
+ const rules = readCollectionFieldEditRules(collection);
24
+ const types = readCollectionFieldTypes(collection);
25
+ const choices = readCollectionFieldValues(collection);
26
+ const problems = [];
27
+ const unchecked = [];
28
+ const known = new Set();
29
+ const fillable = new Set(readNewFeatureFields(collection));
30
+ for (const [field, column] of declaredColumns(collection)) {
31
+ known.add(field);
32
+ const rule = rules[field];
33
+ const value = values[field];
34
+ const blank = isBlankFieldValue(value);
35
+ if (!fillable.has(field)) {
36
+ if (!blank)
37
+ problems.push({ field, problem: 'not-fillable' });
38
+ continue;
39
+ }
40
+ const type = types[field];
41
+ for (const ruleName of uncheckedRules(column, type, rule?.unique === 'enforced', rule?.dateFormat))
42
+ unchecked.push({ field, rule: ruleName });
43
+ if (blank) {
44
+ if (rule?.notNull === 'enforced')
45
+ problems.push({ field, problem: 'required' });
46
+ continue;
47
+ }
48
+ const problem = !hasType(value, type, rule?.dateFormat)
49
+ ? 'wrong-type'
50
+ : !isAChoice(value, choices[field], rule?.checkbox)
51
+ ? 'not-a-choice'
52
+ : rule?.range && isOutsideFieldRange(value, rule.range)
53
+ ? 'out-of-range'
54
+ : null;
55
+ if (problem)
56
+ problems.push({ field, problem });
57
+ }
58
+ for (const field of Object.keys(values)) {
59
+ if (!known.has(field))
60
+ problems.push({ field, problem: 'unknown-field' });
61
+ }
62
+ return { problems, unchecked };
63
+ }
64
+ /**
65
+ * The fields a form for a new feature can fill, in the layer's field order:
66
+ * each declared field that is not read-only, is shown by the form, and is
67
+ * placed by the form layout where the layer has one.
68
+ */
69
+ export function readNewFeatureFields(collection) {
70
+ const rules = readCollectionFieldEditRules(collection);
71
+ return Array.from(declaredColumns(collection))
72
+ .filter(([field, column]) => !rules[field]?.readOnly && !rules[field]?.hidden && column['quac:in_form'] !== false)
73
+ .map(([field]) => field);
74
+ }
75
+ /** A field with no value: null, absent, or text that is only spaces. Not null refuses one. */
76
+ export function isBlankFieldValue(value) {
77
+ return value === null || value === undefined || (typeof value === 'string' && value.trim() === '');
78
+ }
79
+ /**
80
+ * Whether a value is a number outside a field's range. A blank value, a
81
+ * boolean and text that is not a number are not: Not null and the field's
82
+ * type deal with those. Text holding a number is read as that number.
83
+ */
84
+ export function isOutsideFieldRange(value, range) {
85
+ if (isBlankFieldValue(value) || typeof value === 'boolean')
86
+ return false;
87
+ const number = Number(typeof value === 'string' ? value.trim() : value);
88
+ if (!Number.isFinite(number))
89
+ return false;
90
+ return (range.min !== undefined && number < range.min) || (range.max !== undefined && number > range.max);
91
+ }
92
+ const KNOWN_TYPES = new Set(['string', 'int', 'long', 'double', 'boolean', 'date', 'time', 'timestamp']);
93
+ const DATE_TYPES = new Set(['date', 'time', 'timestamp']);
94
+ function uncheckedRules(column, type, unique, dateFormat) {
95
+ const found = [];
96
+ const constraints = column['quac:constraints'];
97
+ const expression = constraints && typeof constraints === 'object' ? constraints.expression : undefined;
98
+ // Read from the column, not the field's rule, which leaves out an expression it cannot read.
99
+ if (expression && expression.strength !== 'warn')
100
+ found.push('constraint-expression');
101
+ if (Array.isArray(column['quac:visible_when']) && column['quac:visible_when'].length > 0)
102
+ found.push('visible-when');
103
+ if (typeof column['quac:editable_when'] === 'string' && column['quac:editable_when'].trim())
104
+ found.push('editable-when');
105
+ if (column['quac:value_relation'])
106
+ found.push('value-relation');
107
+ if (unique)
108
+ found.push('unique');
109
+ if (dateFormat)
110
+ found.push('date-format');
111
+ if (column['quac:attachment'])
112
+ found.push('attachment');
113
+ if (type !== undefined && !KNOWN_TYPES.has(type))
114
+ found.push('type');
115
+ return found;
116
+ }
117
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
118
+ const ISO_TIME = /^\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
119
+ const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/;
120
+ /**
121
+ * Whether a value that is not blank is of the field's type. A field of no
122
+ * type, or one this does not know, takes text, a number or true or false.
123
+ * A date in a format of the field's own is not checked here.
124
+ */
125
+ function hasType(value, type, dateFormat) {
126
+ const scalar = typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value)) || typeof value === 'boolean';
127
+ if (!scalar)
128
+ return false;
129
+ if (type === undefined || !KNOWN_TYPES.has(type))
130
+ return true;
131
+ if (DATE_TYPES.has(type) && dateFormat)
132
+ return typeof value === 'string';
133
+ switch (type) {
134
+ case 'string': return typeof value === 'string';
135
+ case 'int':
136
+ case 'long': return Number.isInteger(value);
137
+ case 'double': return typeof value === 'number';
138
+ case 'boolean': return typeof value === 'boolean';
139
+ case 'date': return typeof value === 'string' && ISO_DATE.test(value);
140
+ case 'time': return typeof value === 'string' && ISO_TIME.test(value);
141
+ default: return typeof value === 'string' && ISO_TIMESTAMP.test(value);
142
+ }
143
+ }
144
+ /** Whether a value is one of the field's listed values, or one of its Checkbox's spellings; true where it has neither. */
145
+ function isAChoice(value, listed, checkbox) {
146
+ if (listed && listed.length > 0)
147
+ return listed.some((choice) => String(choice.value) === String(value));
148
+ if (checkbox?.checkedValue != null && checkbox.uncheckedValue != null && typeof value !== 'boolean') {
149
+ return String(value) === checkbox.checkedValue || String(value) === checkbox.uncheckedValue;
150
+ }
151
+ return true;
152
+ }
package/dist/index.d.ts CHANGED
@@ -23,6 +23,8 @@ export { readSqlFeatureTest } from './parse/sqlFeatureFilter.ts';
23
23
  export type { FeatureTest } from './parse/sqlFeatureFilter.ts';
24
24
  export { publishLayerFeatures } from './generate/publishLayer.ts';
25
25
  export type { PublishedLayer, PublishRefusal } from './generate/publishLayer.ts';
26
+ export { validateNewFeature, readNewFeatureFields, isBlankFieldValue, isOutsideFieldRange } from './generate/validateNewFeature.ts';
27
+ export type { NewFeatureCheck, NewFeatureProblem, UncheckedFieldRule } from './generate/validateNewFeature.ts';
26
28
  export type { FeatureFilter, FeatureFilterDialect } from './model/featureFilter.ts';
27
29
  export type { DelimitedTextOptions } from './model/delimitedText.ts';
28
30
  export { decodeAssetPath, encodeAssetPath, isRelativeHref, readCollectionDataPath, readCollectionOnlineFile } from './model/stacHref.ts';
@@ -63,7 +65,7 @@ export type { StacWmtsSource } from './model/stacWmts.ts';
63
65
  export { VECTOR_TILE_MEDIA_TYPE, buildXyzLink, readCollectionXyzLink, readCollectionXyzTemplate } from './model/stacXyz.ts';
64
66
  export type { ActiveWfsLayer, WfsCapabilities, WfsDescribeFeatureTypeSchema, WfsFeatureTypeOperationsSupport, WfsFeatureTypeSummary, WfsFieldKind, WfsFieldSchema, WfsOperationName, WfsTransactionOperation, WfsTransactionResult, WfsValidationError, WfsWgs84BoundingBox } from './model/wfs.ts';
65
67
  export { parseProjectMeasurement } from './parse/parseMeasurement.ts';
66
- export { EXPRESSION_VARIABLE, GEOMETRY_VALUES, LAYER_CRS, LAYER_LOOKUP, QGIS_CONDITION, SHAPE_COORDINATE, expressionToGeoStylerFunction, expressionToTemplate, isQgisConditionFilter, qgisConditionToFilter, readCurrentValueFields, readLayerLookups, readQgisExpression } from './parse/qgisExpression.ts';
68
+ export { EXPRESSION_VARIABLE, GEOMETRY_VALUES, LAYER_CRS, LAYER_LOOKUP, QGIS_CONDITION, SHAPE_COORDINATE, expressionToGeoStylerFunction, expressionToTemplate, isQgisConditionFilter, qgisConditionToFilter, readCurrentValueFields, readExpressionFields, readLayerLookups, readQgisExpression } from './parse/qgisExpression.ts';
67
69
  export type { ExpressionNode, LayerLookup } from './parse/qgisExpression.ts';
68
70
  export { formatQtDateTime, qtDatePart, readQtDateTime, splitQtDatePattern } from './parse/qtDateFormat.ts';
69
71
  export { compileQtRegex, replaceQtRegex } from './parse/qtRegex.ts';
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ export { DEFAULT_DELIMITED_TEXT_OPTIONS, QUAC_DELIMITED_TEXT, readCollectionDeli
17
17
  export { QUAC_FEATURE_FILTER, readCollectionFeatureFilter } from "./model/featureFilter.js";
18
18
  export { readSqlFeatureTest } from "./parse/sqlFeatureFilter.js";
19
19
  export { publishLayerFeatures } from "./generate/publishLayer.js";
20
+ export { validateNewFeature, readNewFeatureFields, isBlankFieldValue, isOutsideFieldRange } from "./generate/validateNewFeature.js";
20
21
  export { decodeAssetPath, encodeAssetPath, isRelativeHref, readCollectionDataPath, readCollectionOnlineFile } from "./model/stacHref.js";
21
22
  export { DATA_ROLE, findAssetByRole, readDataAsset } from "./model/stacAssetRoles.js";
22
23
  export { THUMBNAIL_ROLE, readCollectionAttribution, readCollectionDeprecation, readCollectionSelfHref, readCollectionThumbnail } from "./model/stacCollectionNotes.js";
@@ -40,7 +41,7 @@ export { WEB_MAP_LINKS_EXTENSION, buildWmsLink, readCollectionWms, wmsEndpoint }
40
41
  export { readCollectionWmts, wmtsCapabilitiesUrl } from "./model/stacWmts.js";
41
42
  export { VECTOR_TILE_MEDIA_TYPE, buildXyzLink, readCollectionXyzLink, readCollectionXyzTemplate } from "./model/stacXyz.js";
42
43
  export { parseProjectMeasurement } from "./parse/parseMeasurement.js";
43
- export { EXPRESSION_VARIABLE, GEOMETRY_VALUES, LAYER_CRS, LAYER_LOOKUP, QGIS_CONDITION, SHAPE_COORDINATE, expressionToGeoStylerFunction, expressionToTemplate, isQgisConditionFilter, qgisConditionToFilter, readCurrentValueFields, readLayerLookups, readQgisExpression } from "./parse/qgisExpression.js";
44
+ export { EXPRESSION_VARIABLE, GEOMETRY_VALUES, LAYER_CRS, LAYER_LOOKUP, QGIS_CONDITION, SHAPE_COORDINATE, expressionToGeoStylerFunction, expressionToTemplate, isQgisConditionFilter, qgisConditionToFilter, readCurrentValueFields, readExpressionFields, readLayerLookups, readQgisExpression } from "./parse/qgisExpression.js";
44
45
  export { formatQtDateTime, qtDatePart, readQtDateTime, splitQtDatePattern } from "./parse/qtDateFormat.js";
45
46
  export { compileQtRegex, replaceQtRegex } from "./parse/qtRegex.js";
46
47
  export { cloneCatalogShallow, collectAllCollections, resolveDocumentHrefs, withSelfLink } from "./sources/stacDocuments.js";
@@ -223,6 +223,11 @@ export declare function readLayerLookups(node: ExpressionNode): LayerLookup[];
223
223
  * reads no form value.
224
224
  */
225
225
  export declare function readCurrentValueFields(node: ExpressionNode): string[] | null;
226
+ /**
227
+ * The fields an expression names, each once, in the order it first names
228
+ * them.
229
+ */
230
+ export declare function readExpressionFields(node: ExpressionNode): string[];
226
231
  /**
227
232
  * The `{{field}}` template of a label made only of fields, text and joins, or
228
233
  * null where it holds anything else. A template draws a field with no value as
@@ -947,6 +947,14 @@ export function readCurrentValueFields(node) {
947
947
  }
948
948
  return fields;
949
949
  }
950
+ /**
951
+ * The fields an expression names, each once, in the order it first names
952
+ * them.
953
+ */
954
+ export function readExpressionFields(node) {
955
+ const own = node.kind === 'field' ? [node.name] : [];
956
+ return [...new Set([...own, ...childNodes(node).flatMap(readExpressionFields)])];
957
+ }
950
958
  /**
951
959
  * The `{{field}}` template of a label made only of fields, text and joins, or
952
960
  * null where it holds anything else. A template draws a field with no value as
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectoriahq/quac",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Writes and reads QUAC, which adds map layer settings to STAC catalogues.",