@vectoriahq/quac 0.0.0-stage → 0.1.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.
Files changed (132) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +35 -2
  3. package/dist/generate/arcgisStacCatalogue.d.ts +46 -0
  4. package/dist/generate/arcgisStacCatalogue.js +189 -0
  5. package/dist/generate/externalStacCatalogue.d.ts +53 -0
  6. package/dist/generate/externalStacCatalogue.js +145 -0
  7. package/dist/generate/fileLayerCollection.d.ts +44 -0
  8. package/dist/generate/fileLayerCollection.js +72 -0
  9. package/dist/generate/folderStacCatalogue.d.ts +48 -0
  10. package/dist/generate/folderStacCatalogue.js +69 -0
  11. package/dist/generate/normalizedProject.d.ts +451 -0
  12. package/dist/generate/normalizedProject.js +925 -0
  13. package/dist/generate/ogcFeaturesStacCatalogue.d.ts +49 -0
  14. package/dist/generate/ogcFeaturesStacCatalogue.js +207 -0
  15. package/dist/generate/qmlForLayer.d.ts +17 -0
  16. package/dist/generate/qmlForLayer.js +36 -0
  17. package/dist/generate/serverLayerTree.d.ts +44 -0
  18. package/dist/generate/serverLayerTree.js +50 -0
  19. package/dist/generate/serverStacCatalogue.d.ts +84 -0
  20. package/dist/generate/serverStacCatalogue.js +327 -0
  21. package/dist/generate/stacCatalogue.d.ts +110 -0
  22. package/dist/generate/stacCatalogue.js +882 -0
  23. package/dist/generate/wfsStacCatalogue.d.ts +37 -0
  24. package/dist/generate/wfsStacCatalogue.js +127 -0
  25. package/dist/generate/wmsStacCatalogue.d.ts +46 -0
  26. package/dist/generate/wmsStacCatalogue.js +228 -0
  27. package/dist/index.d.ts +77 -0
  28. package/dist/index.js +52 -0
  29. package/dist/model/QgsProject.d.ts +722 -0
  30. package/dist/model/QgsProject.js +15 -0
  31. package/dist/model/Stac.d.ts +320 -0
  32. package/dist/model/Stac.js +16 -0
  33. package/dist/model/WmsProject.d.ts +105 -0
  34. package/dist/model/WmsProject.js +1 -0
  35. package/dist/model/arcgis.d.ts +134 -0
  36. package/dist/model/arcgis.js +1 -0
  37. package/dist/model/delimitedText.d.ts +38 -0
  38. package/dist/model/delimitedText.js +46 -0
  39. package/dist/model/featureFilter.d.ts +41 -0
  40. package/dist/model/featureFilter.js +24 -0
  41. package/dist/model/fieldIconAddress.d.ts +27 -0
  42. package/dist/model/fieldIconAddress.js +93 -0
  43. package/dist/model/ogcFeatures.d.ts +40 -0
  44. package/dist/model/ogcFeatures.js +6 -0
  45. package/dist/model/quacExtension.d.ts +28 -0
  46. package/dist/model/quacExtension.js +75 -0
  47. package/dist/model/stacAssetRoles.d.ts +33 -0
  48. package/dist/model/stacAssetRoles.js +44 -0
  49. package/dist/model/stacCollectionNotes.d.ts +21 -0
  50. package/dist/model/stacCollectionNotes.js +44 -0
  51. package/dist/model/stacHref.d.ts +56 -0
  52. package/dist/model/stacHref.js +93 -0
  53. package/dist/model/stacPmtiles.d.ts +38 -0
  54. package/dist/model/stacPmtiles.js +69 -0
  55. package/dist/model/stacSizeAndCount.d.ts +14 -0
  56. package/dist/model/stacSizeAndCount.js +20 -0
  57. package/dist/model/stacStyles.d.ts +93 -0
  58. package/dist/model/stacStyles.js +87 -0
  59. package/dist/model/stacTreeWalk.d.ts +36 -0
  60. package/dist/model/stacTreeWalk.js +76 -0
  61. package/dist/model/stacWms.d.ts +18 -0
  62. package/dist/model/stacWms.js +73 -0
  63. package/dist/model/stacWmts.d.ts +34 -0
  64. package/dist/model/stacWmts.js +90 -0
  65. package/dist/model/stacXyz.d.ts +24 -0
  66. package/dist/model/stacXyz.js +46 -0
  67. package/dist/model/wfs.d.ts +136 -0
  68. package/dist/model/wfs.js +1 -0
  69. package/dist/parse/collectLayerVisibility.d.ts +10 -0
  70. package/dist/parse/collectLayerVisibility.js +22 -0
  71. package/dist/parse/customProperties.d.ts +18 -0
  72. package/dist/parse/customProperties.js +43 -0
  73. package/dist/parse/geometrySiblings.d.ts +25 -0
  74. package/dist/parse/geometrySiblings.js +83 -0
  75. package/dist/parse/parseBrandColour.d.ts +14 -0
  76. package/dist/parse/parseBrandColour.js +25 -0
  77. package/dist/parse/parseDataDefinedEditable.d.ts +38 -0
  78. package/dist/parse/parseDataDefinedEditable.js +76 -0
  79. package/dist/parse/parseDataSource.d.ts +53 -0
  80. package/dist/parse/parseDataSource.js +484 -0
  81. package/dist/parse/parseExtent.d.ts +17 -0
  82. package/dist/parse/parseExtent.js +49 -0
  83. package/dist/parse/parseFormLayout.d.ts +26 -0
  84. package/dist/parse/parseFormLayout.js +60 -0
  85. package/dist/parse/parseGetProjectSettings.d.ts +15 -0
  86. package/dist/parse/parseGetProjectSettings.js +172 -0
  87. package/dist/parse/parseLayers.d.ts +23 -0
  88. package/dist/parse/parseLayers.js +1122 -0
  89. package/dist/parse/parseLegendTree.d.ts +20 -0
  90. package/dist/parse/parseLegendTree.js +66 -0
  91. package/dist/parse/parseMeasurement.d.ts +21 -0
  92. package/dist/parse/parseMeasurement.js +67 -0
  93. package/dist/parse/parseMergin.d.ts +19 -0
  94. package/dist/parse/parseMergin.js +51 -0
  95. package/dist/parse/parseProjectVariables.d.ts +9 -0
  96. package/dist/parse/parseProjectVariables.js +19 -0
  97. package/dist/parse/parseQfieldSync.d.ts +47 -0
  98. package/dist/parse/parseQfieldSync.js +95 -0
  99. package/dist/parse/parseQgsXml.d.ts +15 -0
  100. package/dist/parse/parseQgsXml.js +100 -0
  101. package/dist/parse/parseRelations.d.ts +19 -0
  102. package/dist/parse/parseRelations.js +64 -0
  103. package/dist/parse/parseStyle.d.ts +33 -0
  104. package/dist/parse/parseStyle.js +128 -0
  105. package/dist/parse/parseWmsPublishing.d.ts +21 -0
  106. package/dist/parse/parseWmsPublishing.js +38 -0
  107. package/dist/parse/projectProperties.d.ts +15 -0
  108. package/dist/parse/projectProperties.js +27 -0
  109. package/dist/parse/qgisExpression.d.ts +194 -0
  110. package/dist/parse/qgisExpression.js +859 -0
  111. package/dist/parse/qtDateFormat.d.ts +74 -0
  112. package/dist/parse/qtDateFormat.js +324 -0
  113. package/dist/parse/qtRegex.d.ts +67 -0
  114. package/dist/parse/qtRegex.js +397 -0
  115. package/dist/parse/readProjectFile.d.ts +7 -0
  116. package/dist/parse/readProjectFile.js +27 -0
  117. package/dist/sources/qgisServerUrl.d.ts +6 -0
  118. package/dist/sources/qgisServerUrl.js +17 -0
  119. package/dist/sources/stacDocuments.d.ts +40 -0
  120. package/dist/sources/stacDocuments.js +85 -0
  121. package/dist/sources/stacItems.d.ts +109 -0
  122. package/dist/sources/stacItems.js +287 -0
  123. package/dist/util/catalogueFileFormats.d.ts +58 -0
  124. package/dist/util/catalogueFileFormats.js +64 -0
  125. package/dist/util/devLog.d.ts +11 -0
  126. package/dist/util/devLog.js +23 -0
  127. package/dist/util/fileName.d.ts +18 -0
  128. package/dist/util/fileName.js +45 -0
  129. package/dist/util/wfsVersions.d.ts +9 -0
  130. package/dist/util/wfsVersions.js +13 -0
  131. package/package.json +47 -4
  132. package/src/schema/quac.schema.json +935 -0
@@ -0,0 +1,1122 @@
1
+ import { readCustomPropertyList } from "./customProperties.js";
2
+ import { parseDataSource } from "./parseDataSource.js";
3
+ import { parseFormLayout } from "./parseFormLayout.js";
4
+ import { parseQfieldSyncLocks } from "./parseQfieldSync.js";
5
+ import { parseLayerStyles } from "./parseStyle.js";
6
+ import { readQgisExpression, unescapeStringLiteral } from "./qgisExpression.js";
7
+ import { resolveFieldIconAddress } from "../model/fieldIconAddress.js";
8
+ import { devLog } from "../util/devLog.js";
9
+ /**
10
+ * Parses the <projectlayers> block into a list of LayerEntry. Annotation
11
+ * layers (<main-annotation-layer>) are filtered out — they're QGIS's drawing
12
+ * layer, not real data.
13
+ *
14
+ * Each <maplayer> has the shape:
15
+ * <maplayer type="vector" geometry="Point" hasScaleBasedVisibilityFlag="0"
16
+ * minScale="..." maxScale="..." ...>
17
+ * <id>...</id>
18
+ * <datasource>...</datasource>
19
+ * <layername>...</layername>
20
+ * <provider>ogr</provider> ← optional, used as a hint
21
+ * <srs><spatialrefsys><authid>EPSG:4326</authid>...
22
+ * <extent><xmin>...</xmin>...</extent>
23
+ * ...
24
+ * <renderer-v2 ...> ← inline symbology, captured by parseStyle
25
+ * </maplayer>
26
+ *
27
+ * On any per-layer failure the layer is skipped (logged via devLog) so a
28
+ * single bad layer doesn't take down the whole project.
29
+ */
30
+ export function parseProjectLayers(qgisRoot) {
31
+ const projectLayers = qgisRoot.querySelector('projectlayers');
32
+ if (!projectLayers)
33
+ return [];
34
+ const layers = [];
35
+ for (const node of Array.from(projectLayers.children)) {
36
+ if (node.tagName !== 'maplayer')
37
+ continue;
38
+ try {
39
+ const layer = parseMapLayer(node);
40
+ if (layer)
41
+ layers.push(layer);
42
+ }
43
+ catch (err) {
44
+ devLog('qgs/parseLayers', 'failed to parse a maplayer; skipping', {
45
+ error: String(err),
46
+ id: node.querySelector('id')?.textContent ?? '<unknown>'
47
+ });
48
+ }
49
+ }
50
+ return layers;
51
+ }
52
+ function parseMapLayer(maplayer) {
53
+ const id = maplayer.querySelector('id')?.textContent?.trim();
54
+ const name = maplayer.querySelector('layername')?.textContent?.trim() ?? '';
55
+ if (!id)
56
+ return null;
57
+ const type = maplayer.getAttribute('type') ?? '';
58
+ const geometryType = maplayer.getAttribute('geometry') || null;
59
+ const wkbType = maplayer.getAttribute('wkbType') || null;
60
+ const crs = maplayer.querySelector('srs spatialrefsys authid')?.textContent?.trim() || null;
61
+ const extent = parseBoundingBox(maplayer, 'extent');
62
+ const wgs84Extent = parseBoundingBox(maplayer, 'wgs84extent');
63
+ const datasourceText = directChildText(maplayer, 'datasource') ?? '';
64
+ const providerHint = directChildText(maplayer, 'provider') ?? null;
65
+ const dataSource = parseDataSource(datasourceText, providerHint);
66
+ const fieldNames = parseFieldNames(maplayer);
67
+ const fieldAliases = parseFieldAliases(maplayer);
68
+ const { styles, activeIndex } = parseLayerStyles(maplayer);
69
+ return {
70
+ id,
71
+ name,
72
+ type,
73
+ geometryType,
74
+ wkbType,
75
+ shortName: directChildText(maplayer, 'shortname') || null,
76
+ crs,
77
+ extent,
78
+ wgs84Extent,
79
+ dataSource,
80
+ displayField: parseDisplayField(maplayer),
81
+ // isVisible is set later by parseQgsXml after the layer tree is parsed,
82
+ // since visibility flows from the layer-tree-layer's `checked` attribute
83
+ // (and parent groups), not from the maplayer itself.
84
+ isVisible: true,
85
+ queryable: parseQueryable(maplayer),
86
+ opacity: parseOpacity(maplayer),
87
+ editable: maplayer.getAttribute('readOnly') !== '1',
88
+ fieldNames,
89
+ fieldAliases,
90
+ ...serverHiddenFieldsOf(maplayer),
91
+ styles,
92
+ activeStyleIndex: activeIndex,
93
+ resourceMetadata: parseLayerResourceMetadata(maplayer),
94
+ attribution: parseLayerAttribution(maplayer),
95
+ fieldValueMaps: parseFieldValueMaps(maplayer),
96
+ isPrivate: parsePrivate(maplayer),
97
+ legendImage: parseLegendImage(maplayer),
98
+ fieldValueRelations: parseFieldValueRelations(maplayer),
99
+ fieldAttachments: parseFieldAttachments(maplayer),
100
+ fieldEditRules: parseFieldEditRules(maplayer),
101
+ icon: parseLayerIcon(maplayer),
102
+ fieldIcons: parseFieldIcons(maplayer),
103
+ fieldControls: parseFieldControls(maplayer),
104
+ formLayout: parseFormLayout(maplayer),
105
+ scaleRange: parseScaleRange(maplayer),
106
+ locks: parseQfieldSyncLocks(maplayer),
107
+ rawXml: new XMLSerializer().serializeToString(maplayer)
108
+ };
109
+ }
110
+ /**
111
+ * The fields QGIS Server hides from WMS and from WFS. QGIS saves each field's
112
+ * choice as `configurationFlags` on its `<fieldConfiguration><field>`, holding
113
+ * `HideFromWms` and `HideFromWfs` joined by `|`, and a project saved by QGIS
114
+ * 3.14 or older as the lists `<excludeAttributesWMS>` and
115
+ * `<excludeAttributesWFS>` of `<attribute>` names, which QGIS still reads and
116
+ * adds to the flags (`QgsVectorLayer::readSymbology`,
117
+ * `src/core/vector/qgsvectorlayer.cpp`, `qgis/QGIS@master` at `ec40788`, read
118
+ * 2026-11-06). Only the layer's own blocks are read, never a saved style's.
119
+ */
120
+ function serverHiddenFieldsOf(maplayer) {
121
+ const wms = new Set();
122
+ const wfs = new Set();
123
+ const fieldConfig = directChild(maplayer, 'fieldConfiguration');
124
+ for (const field of fieldConfig?.querySelectorAll(':scope > field') ?? []) {
125
+ const name = field.getAttribute('name');
126
+ if (!name)
127
+ continue;
128
+ const flags = (field.getAttribute('configurationFlags') ?? '').split('|').map((flag) => flag.trim());
129
+ if (flags.includes('HideFromWms'))
130
+ wms.add(name);
131
+ if (flags.includes('HideFromWfs'))
132
+ wfs.add(name);
133
+ }
134
+ for (const [element, into] of [['excludeAttributesWMS', wms], ['excludeAttributesWFS', wfs]]) {
135
+ for (const attribute of directChild(maplayer, element)?.querySelectorAll(':scope > attribute') ?? []) {
136
+ const name = attribute.textContent?.trim();
137
+ if (name)
138
+ into.add(name);
139
+ }
140
+ }
141
+ if (wms.size === 0 && wfs.size === 0)
142
+ return {};
143
+ return { serverHiddenFields: { wms: [...wms], wfs: [...wfs] } };
144
+ }
145
+ /**
146
+ * Reads a `<resourceMetadata>` block — a direct child of `<maplayer>`, sibling
147
+ * to `<srs>`. Both `<maplayer>` elements in
148
+ * `packages/quac/src/tests/fixtures/qgis/graffiti/graffiti.qgs` have one, empty fields and
149
+ * all; an absent block (a layer saved by something other than QGIS) reads the
150
+ * same as one with nothing filled in.
151
+ *
152
+ * `license` reads the first non-blank `<license>` element: QGIS writes each
153
+ * licence as its own sibling element under `<resourceMetadata>` rather than a
154
+ * wrapper holding several (`QgsLayerMetadata::writeMetadataXml`,
155
+ * `src/core/metadata/qgslayermetadata.cpp`, `qgis/QGIS@master`, read
156
+ * 2026-08-12) — this repo's fixtures never populate one, so the element name
157
+ * is checked against that source rather than a sample file.
158
+ */
159
+ function parseLayerResourceMetadata(maplayer) {
160
+ const block = directChild(maplayer, 'resourceMetadata');
161
+ if (!block) {
162
+ return { abstract: null, license: null, keywords: [], contacts: [], temporalInterval: null };
163
+ }
164
+ const abstractText = directChildText(block, 'abstract');
165
+ const license = Array.from(block.querySelectorAll(':scope > license'))
166
+ .map((node) => node.textContent?.trim() ?? '')
167
+ .find((text) => text.length > 0) ?? null;
168
+ const keywords = [];
169
+ const seenKeywords = new Set();
170
+ for (const keyword of block.querySelectorAll(':scope > keywords > keyword')) {
171
+ const text = keyword.textContent?.trim();
172
+ if (!text || seenKeywords.has(text))
173
+ continue;
174
+ seenKeywords.add(text);
175
+ keywords.push(text);
176
+ }
177
+ const contacts = [];
178
+ for (const contact of block.querySelectorAll(':scope > contact')) {
179
+ const contactName = directChildText(contact, 'name') ?? '';
180
+ const organization = directChildText(contact, 'organization') ?? '';
181
+ const email = directChildText(contact, 'email') ?? '';
182
+ if (!contactName && !organization)
183
+ continue;
184
+ contacts.push({ name: contactName, organization, email });
185
+ }
186
+ return {
187
+ abstract: abstractText && abstractText.length > 0 ? abstractText : null,
188
+ license,
189
+ keywords,
190
+ contacts,
191
+ temporalInterval: parseResourceMetadataTemporal(block)
192
+ };
193
+ }
194
+ /**
195
+ * Reads `<resourceMetadata><extent><temporal>`'s declared range: a
196
+ * `<period><start>`/`<end>` — the shape `graffiti.qgs` writes, empty — or a
197
+ * single `<instant>` read as both ends of the interval. No fixture in this
198
+ * repo has an `<instant>`, so that alternative is checked instead against
199
+ * `QgsLayerMetadata::writeMetadataXml` (`src/core/metadata/qgslayermetadata.cpp`,
200
+ * `qgis/QGIS@master`, read 2026-08-12), which writes one or the other. Null
201
+ * when the block declares neither, or declares them blank.
202
+ */
203
+ function parseResourceMetadataTemporal(block) {
204
+ const temporal = block.querySelector(':scope > extent > temporal');
205
+ if (!temporal)
206
+ return null;
207
+ const period = directChild(temporal, 'period');
208
+ if (period) {
209
+ const start = directChildText(period, 'start');
210
+ const end = directChildText(period, 'end');
211
+ if (!start && !end)
212
+ return null;
213
+ return [start || null, end || null];
214
+ }
215
+ const instant = directChildText(temporal, 'instant');
216
+ return instant ? [instant, instant] : null;
217
+ }
218
+ /**
219
+ * Reads `<attribution href="...">text</attribution>` — a direct child of
220
+ * `<maplayer>`, separate from `<resourceMetadata>` (verified against
221
+ * a saved QGIS project, where it sits alongside
222
+ * `<resourceMetadata>` and `<provider>`). Null when the layer declares none.
223
+ */
224
+ function parseLayerAttribution(maplayer) {
225
+ const node = directChild(maplayer, 'attribution');
226
+ const text = node?.textContent?.trim();
227
+ if (!text)
228
+ return null;
229
+ const href = node?.getAttribute('href')?.trim();
230
+ return { text, href: href && href.length > 0 ? href : null };
231
+ }
232
+ /** `QgsValueMapFieldFormatter::NULL_VALUE`: the stored value of a value map's blank entry. */
233
+ const VALUE_MAP_NULL_CODE = '{2839923C-8B7D-419E-B84B-CA2FE9B80EC7}';
234
+ /**
235
+ * Reads every field's ValueMap edit widget into its picklist, keyed by field
236
+ * name. QGIS 3.x writes a widget's config as a generic `<Option>` tree
237
+ * (verified in this project's own fixtures, e.g.
238
+ * a saved QGIS project's `TextEdit`/`CheckBox` field
239
+ * configs); for `ValueMap` specifically, each entry is a nested
240
+ * `<Option type="Map">` holding one `<Option>` whose `name` is the display
241
+ * label and `value` is what QGIS stores
242
+ * (`QgsValueMapConfigDlg`, `src/gui/editorwidgets/qgsvaluemapconfigdlg.cpp`,
243
+ * `qgis/QGIS@master`, read 2026-08-12 — no fixture in this repo has a
244
+ * ValueMap widget to check the shape against directly):
245
+ *
246
+ * <editWidget type="ValueMap">
247
+ * <config>
248
+ * <Option type="Map">
249
+ * <Option type="List" name="map">
250
+ * <Option type="Map">
251
+ * <Option type="QString" name="Waiting" value="waiting"/>
252
+ * </Option>
253
+ * </Option>
254
+ * </Option>
255
+ * </config>
256
+ * </editWidget>
257
+ *
258
+ * Older projects write the map flat instead, as one `<Option type="Map"
259
+ * name="map">` whose children are the entries; QGIS reads both
260
+ * (`QgsValueMapFieldFormatter::representValue`,
261
+ * `src/core/fieldformatter/qgsvaluemapfieldformatter.cpp`, read 2026-10-23).
262
+ *
263
+ * QGIS writes the blank entry's value as the fixed code
264
+ * `QgsValueMapFieldFormatter::NULL_VALUE` (same file); it is read as an empty
265
+ * string, the blank choice's label.
266
+ *
267
+ * A field with no ValueMap widget, or one with no entries, is absent from the
268
+ * returned map.
269
+ */
270
+ function parseFieldValueMaps(maplayer) {
271
+ const result = {};
272
+ // Scoped to the layer's own top-level block: `maplayer.querySelectorAll`
273
+ // would also match a `<fieldConfiguration>` nested inside
274
+ // `<map-layer-style-manager>`'s embedded per-style documents, whose field
275
+ // configs can genuinely disagree with the layer's own (verified against
276
+ // `packages/quac/src/tests/fixtures/qgis/graffiti/graffiti.qgs`, whose Graffiti Reports
277
+ // layer has `incident_uid` as `UuidGenerator` in a saved style and
278
+ // `TextEdit` at the layer's own level).
279
+ const fieldConfig = directChild(maplayer, 'fieldConfiguration');
280
+ for (const field of fieldConfig?.querySelectorAll(':scope > field') ?? []) {
281
+ const name = field.getAttribute('name');
282
+ if (!name || result[name])
283
+ continue;
284
+ const editWidget = directChild(field, 'editWidget');
285
+ if (editWidget?.getAttribute('type') !== 'ValueMap')
286
+ continue;
287
+ const mapList = editWidget.querySelector(':scope > config > Option[type="Map"] > Option[type="List"][name="map"]');
288
+ const flatMap = editWidget.querySelector(':scope > config > Option[type="Map"] > Option[type="Map"][name="map"]');
289
+ const options = mapList
290
+ ? mapList.querySelectorAll(':scope > Option[type="Map"] > Option')
291
+ : flatMap?.querySelectorAll(':scope > Option') ?? [];
292
+ const entries = [];
293
+ for (const entry of options) {
294
+ const label = entry.getAttribute('name');
295
+ const value = entry.getAttribute('value');
296
+ if (label && value !== null)
297
+ entries.push({ value: value === VALUE_MAP_NULL_CODE ? '' : value, label });
298
+ }
299
+ if (entries.length > 0)
300
+ result[name] = entries;
301
+ }
302
+ return result;
303
+ }
304
+ /**
305
+ * Reads every field's Value Relation edit widget, keyed by field name. QGIS
306
+ * writes the widget's config as the same flat `<Option>` map the `TextEdit`
307
+ * and `CheckBox` widgets use (`QgsValueRelationConfigDlg::config`,
308
+ * `src/gui/editorwidgets/qgsvaluerelationconfigdlg.cpp`, `qgis/QGIS@master`,
309
+ * read 2026-10-24):
310
+ *
311
+ * <editWidget type="ValueRelation">
312
+ * <config>
313
+ * <Option type="Map">
314
+ * <Option type="QString" value="asset_types_1" name="Layer"/>
315
+ * <Option type="QString" value="Asset types" name="LayerName"/>
316
+ * <Option type="QString" value="name" name="Key"/>
317
+ * <Option type="QString" value="name" name="Value"/>
318
+ * <Option type="bool" value="false" name="AllowNull"/>
319
+ * <Option type="bool" value="true" name="OrderByValue"/>
320
+ * </Option>
321
+ * </config>
322
+ * </editWidget>
323
+ *
324
+ * The lookup is named by `Layer` (its id) and `LayerName`; a widget naming
325
+ * neither, or with no `Key` or no `Value`, is skipped, since no list can come
326
+ * from it. The order follows the formatter's: `OrderByValue` first, then
327
+ * `OrderByField` where it names a field, and the key otherwise
328
+ * (`QgsValueRelationFieldFormatter::createCache`,
329
+ * `src/core/fieldformatter/qgsvaluerelationfieldformatter.cpp`, same commit).
330
+ * `Group`, `DisplayGroupName`, `Description`, `NofColumns`, `UseCompleter` and
331
+ * `CompleterMatchFlags` are not read.
332
+ *
333
+ * A field with no ValueRelation widget is absent from the returned map.
334
+ */
335
+ function parseFieldValueRelations(maplayer) {
336
+ const result = {};
337
+ // The layer's own block, not a saved alternate style's.
338
+ const fieldConfig = directChild(maplayer, 'fieldConfiguration');
339
+ for (const field of fieldConfig?.querySelectorAll(':scope > field') ?? []) {
340
+ const name = field.getAttribute('name');
341
+ if (!name || result[name])
342
+ continue;
343
+ const editWidget = directChild(field, 'editWidget');
344
+ if (editWidget?.getAttribute('type') !== 'ValueRelation')
345
+ continue;
346
+ const options = new Map();
347
+ for (const option of editWidget.querySelectorAll(':scope > config > Option[type="Map"] > Option')) {
348
+ const key = option.getAttribute('name');
349
+ const value = option.getAttribute('value');
350
+ if (key && value !== null)
351
+ options.set(key, value);
352
+ }
353
+ const isOn = (key) => options.get(key) === 'true' || options.get(key) === '1';
354
+ const layerId = readTrimmedOption(options, 'Layer') ?? '';
355
+ const layerName = readTrimmedOption(options, 'LayerName') ?? '';
356
+ const keyField = readTrimmedOption(options, 'Key');
357
+ const valueField = readTrimmedOption(options, 'Value');
358
+ if ((!layerId && !layerName) || !keyField || !valueField)
359
+ continue;
360
+ const orderField = isOn('OrderByField') ? readTrimmedOption(options, 'OrderByFieldName') : null;
361
+ result[name] = {
362
+ layerId,
363
+ layerName,
364
+ keyField,
365
+ valueField,
366
+ filterExpression: readTrimmedOption(options, 'FilterExpression') ?? '',
367
+ allowNull: isOn('AllowNull'),
368
+ allowMulti: isOn('AllowMulti'),
369
+ orderBy: isOn('OrderByValue') ? 'value' : orderField ? 'field' : 'key',
370
+ orderField: isOn('OrderByValue') ? null : orderField,
371
+ descending: isOn('OrderByDescending')
372
+ };
373
+ }
374
+ return result;
375
+ }
376
+ /**
377
+ * QGIS's `DocumentViewerContent`, by its own order from zero
378
+ * (`src/gui/qgsexternalresourcewidget.h`, `qgis/QGIS@master`, read
379
+ * 2026-08-29). `NoContent` is index 0 and reads as null.
380
+ */
381
+ const DOCUMENT_VIEWERS = [null, 'image', 'web', 'audio', 'video'];
382
+ /**
383
+ * QGIS's `QgsFileWidget::RelativeStorage`, by its own order from zero
384
+ * (`src/gui/qgsfilewidget.h`, same commit).
385
+ */
386
+ const RELATIVE_STORAGE = ['absolute', 'project', 'default-root'];
387
+ /**
388
+ * The `QgsFileWidget::StorageMode` values that pick one file — `GetFile` and
389
+ * `SaveFile`, indices 0 and 3 of `GetFile, GetDirectory, GetMultipleFiles,
390
+ * SaveFile` (`src/gui/qgsfilewidget.h`, same commit). A widget set to either
391
+ * of the other two stores a directory or a list, neither of which is the
392
+ * single path `quac:attachment` declares.
393
+ */
394
+ const SINGLE_FILE_STORAGE_MODES = new Set([0, 3]);
395
+ /**
396
+ * Reads every field's Attachment edit widget into what Groundwork acts on,
397
+ * keyed by field name. QGIS registers the widget as `ExternalResource`
398
+ * (`QgsEditorWidgetRegistry::initEditors`,
399
+ * `src/gui/editorwidgets/core/qgseditorwidgetregistry.cpp`, `qgis/QGIS@master`,
400
+ * read 2026-08-29) and writes its config as the same flat `<Option>` map the
401
+ * `TextEdit` and `CheckBox` widgets use in
402
+ * `packages/quac/src/tests/fixtures/qgis/graffiti/graffiti.qgs`:
403
+ *
404
+ * <editWidget type="ExternalResource">
405
+ * <config>
406
+ * <Option type="Map">
407
+ * <Option type="QString" value="photos" name="DefaultRoot"/>
408
+ * <Option type="int" value="1" name="DocumentViewer"/>
409
+ * <Option type="int" value="1" name="RelativeStorage"/>
410
+ * </Option>
411
+ * </config>
412
+ * </editWidget>
413
+ *
414
+ * The widget writes more keys than these four; the rest are left behind
415
+ * because nothing in the app acts on them. A value-less `<Option type="invalid">`,
416
+ * which QGIS writes for an unset key, is skipped rather than read as blank.
417
+ * A widget whose `StorageMode` picks a directory or several files is not an
418
+ * attachment here.
419
+ *
420
+ * A field with no ExternalResource widget is absent from the returned map.
421
+ */
422
+ function parseFieldAttachments(maplayer) {
423
+ const result = {};
424
+ // A saved alternate style embeds its own <fieldConfiguration>, which can
425
+ // disagree with the layer's own.
426
+ const fieldConfig = directChild(maplayer, 'fieldConfiguration');
427
+ for (const field of fieldConfig?.querySelectorAll(':scope > field') ?? []) {
428
+ const name = field.getAttribute('name');
429
+ if (!name || result[name])
430
+ continue;
431
+ const editWidget = directChild(field, 'editWidget');
432
+ if (editWidget?.getAttribute('type') !== 'ExternalResource')
433
+ continue;
434
+ const options = new Map();
435
+ for (const option of editWidget.querySelectorAll(':scope > config > Option[type="Map"] > Option')) {
436
+ const key = option.getAttribute('name');
437
+ const value = option.getAttribute('value');
438
+ if (key && value !== null)
439
+ options.set(key, value);
440
+ }
441
+ const storageMode = options.get('StorageMode');
442
+ if (storageMode !== undefined && !SINGLE_FILE_STORAGE_MODES.has(Number(storageMode)))
443
+ continue;
444
+ result[name] = {
445
+ viewer: DOCUMENT_VIEWERS[Number(options.get('DocumentViewer'))] ?? null,
446
+ filter: readTrimmedOption(options, 'FileWidgetFilter'),
447
+ defaultRoot: readTrimmedOption(options, 'DefaultRoot'),
448
+ relativeStorage: RELATIVE_STORAGE[Number(options.get('RelativeStorage'))] ?? 'absolute'
449
+ };
450
+ }
451
+ return result;
452
+ }
453
+ /**
454
+ * The default-value expressions read as `now`, compared with spaces removed
455
+ * and in lower case. `$now` is QGIS's older spelling of `now()`.
456
+ */
457
+ const NOW_EXPRESSIONS = new Set(['now()', '$now', 'to_date(now())', 'to_datetime(now())']);
458
+ /**
459
+ * Reads the Attributes Form settings Groundwork acts on for every field, keyed
460
+ * by field name. QGIS writes them as blocks of the layer's own, shown here as
461
+ * `packages/quac/src/tests/fixtures/qgis/graffiti/graffiti.qgs` writes them:
462
+ *
463
+ * <fieldConfiguration>
464
+ * <field name="date_report"><editWidget type="Hidden">…</editWidget></field>
465
+ * </fieldConfiguration>
466
+ * <defaults>
467
+ * <default field="date_report" expression="" applyOnUpdate="0"/>
468
+ * </defaults>
469
+ * <constraints>
470
+ * <constraint field="date_report" constraints="0" notnull_strength="0" unique_strength="0" exp_strength="0"/>
471
+ * </constraints>
472
+ * <editable>
473
+ * <field editable="1" name="date_report"/>
474
+ * </editable>
475
+ * <reuseLastValuePolicy>
476
+ * <field name="date_report" reuseLastValuePolicy="AllowedDefaultOn"/>
477
+ * </reuseLastValuePolicy>
478
+ * <duplicatePolicies>
479
+ * <policy field="date_report" policy="DefaultValue"/>
480
+ * </duplicatePolicies>
481
+ * <constraintExpressions>
482
+ * <constraint field="date_report" exp="" desc=""/>
483
+ * </constraintExpressions>
484
+ *
485
+ * A default is kept as a `defaultValue` where `parseDefaultExpression` reads it,
486
+ * as a `defaultExpression` where only `readQgisExpression` does, and otherwise
487
+ * left out: the app evaluates no other expression. A constraint expression
488
+ * follows the same rule. A field the `<editable>` block does not list
489
+ * is editable. A field with none of these settings is absent from the
490
+ * returned map.
491
+ */
492
+ function parseFieldEditRules(maplayer) {
493
+ const result = {};
494
+ const ruleFor = (name) => {
495
+ result[name] ??= { readOnly: false, defaultValue: null, notNull: null, unique: null, hidden: false, reuseLastValue: false, duplicatePolicy: null };
496
+ return result[name];
497
+ };
498
+ // Scoped to the layer's own blocks, as the field configuration is above: a
499
+ // saved alternate style embeds its own copies.
500
+ const fieldsWithExpression = new Set();
501
+ for (const node of directChild(maplayer, 'defaults')?.querySelectorAll(':scope > default') ?? []) {
502
+ const name = node.getAttribute('field');
503
+ const expression = node.getAttribute('expression') ?? '';
504
+ if (!name || !expression.trim())
505
+ continue;
506
+ fieldsWithExpression.add(name);
507
+ const onUpdate = node.getAttribute('applyOnUpdate') === '1';
508
+ const defaultValue = parseDefaultExpression(expression, onUpdate);
509
+ if (defaultValue)
510
+ ruleFor(name).defaultValue = defaultValue;
511
+ else if (readQgisExpression(expression, { geometry: true, aggregates: true, lookups: true }))
512
+ ruleFor(name).defaultExpression = { expression: expression.trim(), onUpdate };
513
+ }
514
+ // The UUID Generator widget disables its line edit and fills a null field
515
+ // with `QUuid::createUuid().toString()`, which has braces
516
+ // (`QgsUuidWidgetWrapper`, `src/gui/editorwidgets/qgsuuidwidgetwrapper.cpp`,
517
+ // `qgis/QGIS@master`, read 2026-10-23). A default expression fills the field
518
+ // first, so the widget's identifier stands only where there is none. The
519
+ // widget's shortening to a string field's declared length is not followed:
520
+ // a `.qgs` file does not carry a WFS field's length.
521
+ const fieldConfig = directChild(maplayer, 'fieldConfiguration');
522
+ const seenWidgets = new Set();
523
+ const allowNullOff = new Set();
524
+ for (const field of fieldConfig?.querySelectorAll(':scope > field') ?? []) {
525
+ const name = field.getAttribute('name');
526
+ if (!name || seenWidgets.has(name))
527
+ continue;
528
+ seenWidgets.add(name);
529
+ const widgetType = directChild(field, 'editWidget')?.getAttribute('type');
530
+ if (widgetType === 'Hidden')
531
+ ruleFor(name).hidden = true;
532
+ // The widget has no settings of its own (`QgsColorWidgetFactory::configWidget`,
533
+ // `src/gui/editorwidgets/qgscolorwidgetfactory.cpp`, `qgis/QGIS@master`,
534
+ // read 2026-10-25).
535
+ if (widgetType === 'Color')
536
+ ruleFor(name).colour = true;
537
+ if (widgetType === 'CheckBox' || widgetType === 'Range' || widgetType === 'DateTime') {
538
+ readWidgetOptions(field, name, widgetType, ruleFor, allowNullOff);
539
+ }
540
+ if (widgetType === 'UuidGenerator') {
541
+ const rule = ruleFor(name);
542
+ rule.readOnly = true;
543
+ if (!fieldsWithExpression.has(name))
544
+ rule.defaultValue = { kind: 'uuid', format: 'with_braces', onUpdate: false };
545
+ }
546
+ }
547
+ // `constraints` is a bit mask with Not null as 1, Unique as 2 and Expression
548
+ // as 4, and a missing strength reads as 1, hard; 2 is soft and 0 not set
549
+ // (`QgsVectorLayer::readSymbology`, `src/core/vector/qgsvectorlayer.cpp`, and
550
+ // `QgsFieldConstraints`, `src/core/qgsfieldconstraints.h`, `qgis/QGIS@master`,
551
+ // read 2026-10-23). An expression is kept only where `readQgisExpression`
552
+ // reads it: the app evaluates no other.
553
+ const constraintExpressions = new Map();
554
+ for (const node of directChild(maplayer, 'constraintExpressions')?.querySelectorAll(':scope > constraint') ?? []) {
555
+ const name = node.getAttribute('field');
556
+ const expression = (node.getAttribute('exp') ?? '').trim();
557
+ if (name && expression)
558
+ constraintExpressions.set(name, { expression, description: (node.getAttribute('desc') ?? '').trim() });
559
+ }
560
+ for (const node of directChild(maplayer, 'constraints')?.querySelectorAll(':scope > constraint') ?? []) {
561
+ const name = node.getAttribute('field');
562
+ const constraints = Number(node.getAttribute('constraints') ?? '0');
563
+ if (!name || !Number.isInteger(constraints))
564
+ continue;
565
+ if (constraints & 1) {
566
+ const notNull = constraintStrength(node.getAttribute('notnull_strength'));
567
+ if (notNull)
568
+ ruleFor(name).notNull = notNull;
569
+ }
570
+ if (constraints & 2) {
571
+ const unique = constraintStrength(node.getAttribute('unique_strength'));
572
+ if (unique)
573
+ ruleFor(name).unique = unique;
574
+ }
575
+ const written = constraintExpressions.get(name);
576
+ if (constraints & 4 && written && readQgisExpression(written.expression, { geometry: true })) {
577
+ const strength = constraintStrength(node.getAttribute('exp_strength'));
578
+ if (strength) {
579
+ const expression = { expression: written.expression, strength };
580
+ if (written.description)
581
+ expression.description = written.description;
582
+ ruleFor(name).constraintExpression = expression;
583
+ }
584
+ }
585
+ }
586
+ // A Range with Allow NULL off, or a Date/Time with it off, is a required
587
+ // field.
588
+ // It also raises a Not null that only warns.
589
+ for (const name of allowNullOff)
590
+ ruleFor(name).notNull = 'enforced';
591
+ // A field absent from `<duplicatePolicies>`, or holding a key QGIS does not
592
+ // know, reads as `Duplicate` (`QgsVectorLayer::readSymbology`,
593
+ // `src/core/vector/qgsvectorlayer.cpp`, `qgis/QGIS@master`, read 2026-10-23).
594
+ for (const node of directChild(maplayer, 'duplicatePolicies')?.querySelectorAll(':scope > policy') ?? []) {
595
+ const name = node.getAttribute('field');
596
+ const policy = node.getAttribute('policy');
597
+ if (name && (policy === 'DefaultValue' || policy === 'UnsetField')) {
598
+ ruleFor(name).duplicatePolicy = policy === 'DefaultValue' ? 'default' : 'unset';
599
+ }
600
+ }
601
+ for (const node of directChild(maplayer, 'editable')?.querySelectorAll(':scope > field') ?? []) {
602
+ const name = node.getAttribute('name');
603
+ if (name && node.getAttribute('editable') === '0')
604
+ ruleFor(name).readOnly = true;
605
+ }
606
+ for (const [name, reuse] of parseReuseLastValue(maplayer)) {
607
+ if (reuse)
608
+ ruleFor(name).reuseLastValue = true;
609
+ }
610
+ return result;
611
+ }
612
+ /**
613
+ * Reads a Checkbox, Range or Date/Time widget's config into the field's rule.
614
+ * QGIS writes the config as a flat `<Option type="Map">` and an untouched
615
+ * widget writes an empty `<Option/>`, which reads as every default
616
+ * (`QgsCheckboxConfigDlg`, `QgsRangeConfigDlg` and `QgsDateTimeEditConfig`,
617
+ * `src/gui/editorwidgets/`, `qgis/QGIS@master`, read 2026-10-23). A value-less
618
+ * `<Option type="invalid">` reads as unset. Range's `AllowNull` and Date/Time's
619
+ * `allow_null` both default to true; a field with either off goes in `allowNullOff`.
620
+ */
621
+ function readWidgetOptions(field, name, widgetType, ruleFor, allowNullOff) {
622
+ const options = new Map();
623
+ for (const option of directChild(field, 'editWidget')?.querySelectorAll(':scope > config > Option[type="Map"] > Option') ?? []) {
624
+ const key = option.getAttribute('name');
625
+ const value = option.getAttribute('value');
626
+ if (key && value !== null)
627
+ options.set(key, value);
628
+ }
629
+ const flag = (key, fallback) => {
630
+ const value = options.get(key);
631
+ return value === undefined ? fallback : value === 'true' || value === '1';
632
+ };
633
+ const number = (key) => {
634
+ const text = options.get(key)?.trim();
635
+ if (!text)
636
+ return undefined;
637
+ const value = Number(text);
638
+ return Number.isFinite(value) ? value : undefined;
639
+ };
640
+ switch (widgetType) {
641
+ case 'CheckBox':
642
+ ruleFor(name).checkbox = {
643
+ checkedValue: readTrimmedOption(options, 'CheckedState'),
644
+ uncheckedValue: readTrimmedOption(options, 'UncheckedState'),
645
+ showStoredValue: options.get('TextDisplayMethod') === '1',
646
+ allowNull: flag('AllowNullState', false)
647
+ };
648
+ return;
649
+ case 'Range': {
650
+ const range = {};
651
+ const min = number('Min');
652
+ const max = number('Max');
653
+ const step = number('Step');
654
+ const precision = number('Precision');
655
+ const suffix = options.get('Suffix');
656
+ if (min !== undefined)
657
+ range.min = min;
658
+ if (max !== undefined)
659
+ range.max = max;
660
+ if (step !== undefined)
661
+ range.step = step;
662
+ if (precision !== undefined && Number.isInteger(precision) && precision >= 0)
663
+ range.precision = precision;
664
+ if (suffix)
665
+ range.suffix = suffix;
666
+ if (Object.keys(range).length > 0)
667
+ ruleFor(name).range = range;
668
+ if (!flag('AllowNull', true))
669
+ allowNullOff.add(name);
670
+ return;
671
+ }
672
+ case 'DateTime': {
673
+ // A date or date-time field ignores `field_format`, which Groundwork
674
+ // cannot tell here. ISO 8601 and the default for a date are what the
675
+ // app already reads, so they write nothing.
676
+ const format = options.get('field_format')?.trim();
677
+ if (format && format !== 'yyyy-MM-dd' && !flag('field_iso_format', false))
678
+ ruleFor(name).dateFormat = format;
679
+ if (!flag('allow_null', true))
680
+ allowNullOff.add(name);
681
+ }
682
+ }
683
+ }
684
+ /** A constraint's strength: 1, or absent, is hard; 2 is soft; 0 or anything else is not set. */
685
+ function constraintStrength(strength) {
686
+ switch (strength ?? '1') {
687
+ case '1': return 'enforced';
688
+ case '2': return 'warn';
689
+ default: return null;
690
+ }
691
+ }
692
+ /**
693
+ * Which fields offer a new feature the value last entered, from either of
694
+ * QGIS's two forms. An older project writes
695
+ * `<reuseLastValue><field name reuseLastValue="1"/></reuseLastValue>`; QGIS now
696
+ * writes `<reuseLastValuePolicy><field name reuseLastValuePolicy="AllowedDefaultOn"/></reuseLastValuePolicy>`,
697
+ * and reads the older block first so the newer one wins
698
+ * (`QgsEditFormConfig::readXml`, `src/core/editform/qgseditformconfig.cpp`,
699
+ * `qgis/QGIS@master`, read 2026-10-23). `AllowedDefaultOff` reads as not
700
+ * reused: it is off until someone ticks it in QGIS's own form, which
701
+ * Groundwork's form has no tick for.
702
+ */
703
+ function parseReuseLastValue(maplayer) {
704
+ const reuse = new Map();
705
+ for (const node of directChild(maplayer, 'reuseLastValue')?.querySelectorAll(':scope > field') ?? []) {
706
+ const name = node.getAttribute('name');
707
+ const flag = Number(node.getAttribute('reuseLastValue'));
708
+ if (name)
709
+ reuse.set(name, Number.isInteger(flag) && flag !== 0);
710
+ }
711
+ for (const node of directChild(maplayer, 'reuseLastValuePolicy')?.querySelectorAll(':scope > field') ?? []) {
712
+ const name = node.getAttribute('name');
713
+ if (name)
714
+ reuse.set(name, node.getAttribute('reuseLastValuePolicy') === 'AllowedDefaultOn');
715
+ }
716
+ return reuse;
717
+ }
718
+ /**
719
+ * Reads a default-value expression Groundwork can fill: one of
720
+ * `NOW_EXPRESSIONS`, `uuid()` or `$uuid` with an optional format, or a lone
721
+ * literal. Anything else, such as a field reference, a variable or a
722
+ * calculation, is null.
723
+ *
724
+ * `uuid()` takes `format` (`WithBraces` by default, `WithoutBraces`, `Id128`,
725
+ * compared ignoring case, with any other text read as `WithBraces`) and
726
+ * `version` (4 by default, or 7), by position or by name (`format:='Id128'`)
727
+ * (`fcnUuid` and its registration, `src/core/expression/qgsexpressionfunction.cpp`,
728
+ * `qgis/QGIS@master`, read 2026-10-23). A version other than 4 is null: the
729
+ * app makes version 4 identifiers only.
730
+ */
731
+ function parseDefaultExpression(expression, onUpdate) {
732
+ if (NOW_EXPRESSIONS.has(expression.replace(/\s+/g, '').toLowerCase()))
733
+ return { kind: 'now', onUpdate };
734
+ const tokens = tokenizeExpression(expression);
735
+ if (!tokens)
736
+ return null;
737
+ const literal = readLiteral(tokens, 0);
738
+ if (literal && literal.next === tokens.length)
739
+ return { kind: 'fixed', value: literal.value, onUpdate };
740
+ const format = readUuidCall(tokens);
741
+ return format ? { kind: 'uuid', format, onUpdate } : null;
742
+ }
743
+ /**
744
+ * Splits an expression into the tokens a literal or a `uuid()` call is made
745
+ * of, following QGIS's lexer (`src/core/qgsexpressionlexer.ll`,
746
+ * `qgis/QGIS@master`, read 2026-10-23), which ignores case. Null where the
747
+ * expression holds anything else, such as an operator, a quoted field name or
748
+ * a comment.
749
+ */
750
+ function tokenizeExpression(expression) {
751
+ const pattern = /\s+|'((?:''|\\.|[^'\\])*)'|(\d*(?:\.\d+(?:[eE][-+]?\d+)?|[eE][-+]?\d+)|\d+)|([A-Za-z_\x80-\uFFFF$][A-Za-z0-9_\x80-\uFFFF]*)(\s*:=\s*)?|([(),-])/y;
752
+ const tokens = [];
753
+ pattern.lastIndex = 0;
754
+ while (pattern.lastIndex < expression.length) {
755
+ const match = pattern.exec(expression);
756
+ if (!match)
757
+ return null;
758
+ const [, text, number, name, named, punct] = match;
759
+ if (text !== undefined)
760
+ tokens.push({ type: 'string', value: unescapeStringLiteral(text) });
761
+ else if (number !== undefined)
762
+ tokens.push({ type: 'number', value: Number(number) });
763
+ else if (name !== undefined)
764
+ tokens.push({ type: named ? 'named' : 'name', value: name.toLowerCase() });
765
+ else if (punct !== undefined)
766
+ tokens.push({ type: 'punct', value: punct });
767
+ }
768
+ return tokens;
769
+ }
770
+ /** The literal starting at `index` — a string, a number with or without a minus, `TRUE`, `FALSE` or `NULL` — and the index after it. */
771
+ function readLiteral(tokens, index) {
772
+ const token = tokens[index];
773
+ const after = tokens[index + 1];
774
+ if (token?.type === 'punct' && token.value === '-' && after?.type === 'number')
775
+ return { value: -after.value, next: index + 2 };
776
+ if (token?.type === 'string' || token?.type === 'number')
777
+ return { value: token.value, next: index + 1 };
778
+ if (token?.type !== 'name')
779
+ return null;
780
+ if (token.value === 'true')
781
+ return { value: true, next: index + 1 };
782
+ if (token.value === 'false')
783
+ return { value: false, next: index + 1 };
784
+ if (token.value === 'null')
785
+ return { value: null, next: index + 1 };
786
+ return null;
787
+ }
788
+ /** The format of a whole-expression `uuid()` or `$uuid`, or null where the expression is not one. */
789
+ function readUuidCall(tokens) {
790
+ const [head, open] = tokens;
791
+ if (head?.type !== 'name')
792
+ return null;
793
+ if (head.value === '$uuid')
794
+ return tokens.length === 1 ? 'with_braces' : null;
795
+ if (head.value !== 'uuid' || open?.type !== 'punct' || open.value !== '(')
796
+ return null;
797
+ const close = tokens[tokens.length - 1];
798
+ if (close?.type !== 'punct' || close.value !== ')')
799
+ return null;
800
+ const args = {};
801
+ const positions = ['format', 'version'];
802
+ let index = 2;
803
+ let position = 0;
804
+ while (index < tokens.length - 1) {
805
+ if (position > 0) {
806
+ const comma = tokens[index];
807
+ if (comma?.type !== 'punct' || comma.value !== ',')
808
+ return null;
809
+ index += 1;
810
+ }
811
+ const token = tokens[index];
812
+ let parameter = positions[position];
813
+ if (token?.type === 'named') {
814
+ if (token.value !== 'format' && token.value !== 'version')
815
+ return null;
816
+ parameter = token.value;
817
+ index += 1;
818
+ }
819
+ const literal = readLiteral(tokens, index);
820
+ if (!parameter || !literal || parameter in args)
821
+ return null;
822
+ args[parameter] = literal.value;
823
+ index = literal.next;
824
+ position += 1;
825
+ }
826
+ if (args.version !== undefined && args.version !== 4)
827
+ return null;
828
+ if (args.format === undefined)
829
+ return 'with_braces';
830
+ if (typeof args.format !== 'string')
831
+ return null;
832
+ const format = args.format.toLowerCase();
833
+ return format === 'withoutbraces' ? 'without_braces' : format === 'id128' ? 'id128' : 'with_braces';
834
+ }
835
+ function readTrimmedOption(options, key) {
836
+ const value = options.get(key)?.trim();
837
+ return value ? value : null;
838
+ }
839
+ function parseBoundingBox(maplayer, tag) {
840
+ const node = directChild(maplayer, tag);
841
+ if (!node)
842
+ return null;
843
+ const xmin = readNumber(node, 'xmin');
844
+ const ymin = readNumber(node, 'ymin');
845
+ const xmax = readNumber(node, 'xmax');
846
+ const ymax = readNumber(node, 'ymax');
847
+ if (xmin === null || ymin === null || xmax === null || ymax === null)
848
+ return null;
849
+ return { xmin, ymin, xmax, ymax };
850
+ }
851
+ /**
852
+ * Parses <fieldConfiguration> into the canonical list of field names.
853
+ *
854
+ * <fieldConfiguration>
855
+ * <field name="objectid" configurationFlags="...">
856
+ * <editWidget type="...">...</editWidget>
857
+ * </field>
858
+ * ...
859
+ * </fieldConfiguration>
860
+ *
861
+ * Modern QGIS may write fieldConfiguration both at the maplayer level and
862
+ * inside the active <map-layer-style> block — we collect from anywhere
863
+ * inside the maplayer and dedupe, preserving first-seen order.
864
+ *
865
+ * QGIS does not declare field types here for WFS layers (those come from
866
+ * DescribeFeatureType at runtime), so this function only returns names.
867
+ */
868
+ function parseFieldNames(maplayer) {
869
+ const seen = new Set();
870
+ const ordered = [];
871
+ const fields = maplayer.querySelectorAll('fieldConfiguration > field');
872
+ for (const node of Array.from(fields)) {
873
+ const name = node.getAttribute('name');
874
+ if (!name)
875
+ continue;
876
+ if (seen.has(name))
877
+ continue;
878
+ seen.add(name);
879
+ ordered.push(name);
880
+ }
881
+ return ordered;
882
+ }
883
+ /**
884
+ * Parses <aliases> into a { fieldName: aliasText } map.
885
+ *
886
+ * <aliases>
887
+ * <alias field="incident_uid" name="Incident UID" index="0"/>
888
+ * ...
889
+ * </aliases>
890
+ *
891
+ * Modern QGIS supports per-style aliases — they live inside the active
892
+ * <map-layer-style> block under the style manager. Legacy QGIS put them
893
+ * at the maplayer level. Same project can have both, and the maplayer-
894
+ * level copy may have empty `name=""` placeholders. We collect every
895
+ * <alias> anywhere inside the maplayer and keep the last non-empty value
896
+ * per field, which is the active-style block's when both are present.
897
+ */
898
+ function parseFieldAliases(maplayer) {
899
+ const out = {};
900
+ const nodes = maplayer.querySelectorAll('aliases > alias');
901
+ for (const node of Array.from(nodes)) {
902
+ const field = node.getAttribute('field');
903
+ const name = node.getAttribute('name');
904
+ if (!field || !name)
905
+ continue;
906
+ out[field] = name;
907
+ }
908
+ return out;
909
+ }
910
+ /** The start of the name of a layer variable that sets a field's icon: `quac_icon_species`. */
911
+ const FIELD_ICON_VARIABLE_PREFIX = 'quac_icon_';
912
+ /**
913
+ * Reads the field icons the layer's variables set, as an address for each
914
+ * field (`resolveFieldIconAddress`). A variable whose value names no icon is
915
+ * left out; whether the layer has the field is for the reader of the result.
916
+ *
917
+ * QGIS keeps a layer's variables as two lists of the same length in its custom
918
+ * properties, `variableNames` and `variableValues`
919
+ * (`QgsExpressionContextUtils::setLayerVariable`,
920
+ * `src/core/expression/qgsexpressioncontextutils.cpp`), saved as a direct
921
+ * child of `<maplayer>`:
922
+ *
923
+ * <customproperties>
924
+ * <Option type="Map">
925
+ * <Option name="variableNames" type="StringList">
926
+ * <Option type="QString" value="quac_icon_species"/>
927
+ * </Option>
928
+ * <Option name="variableValues" type="StringList">
929
+ * <Option type="QString" value="tabler:tree"/>
930
+ * </Option>
931
+ * </Option>
932
+ * </customproperties>
933
+ *
934
+ * A project saved before QGIS 3.20 holds `<property key="variableNames">`
935
+ * with a `<value>` per entry, or a `value` attribute for a single one, which
936
+ * QGIS still reads (`QgsObjectCustomProperties::readXml`,
937
+ * `src/core/qgsobjectcustomproperties.cpp`, `qgis/QGIS@master`, read
938
+ * 2026-10-25).
939
+ */
940
+ function parseFieldIcons(maplayer) {
941
+ const icons = {};
942
+ for (const [field, value] of readFieldVariables(maplayer, FIELD_ICON_VARIABLE_PREFIX)) {
943
+ const address = resolveFieldIconAddress(value);
944
+ if (address)
945
+ icons[field] = address;
946
+ }
947
+ return icons;
948
+ }
949
+ /** The name of the layer variable that sets the layer's own icon. */
950
+ const LAYER_ICON_VARIABLE = 'quac_icon';
951
+ /**
952
+ * Reads the icon the layer's `quac_icon` variable sets, as an address
953
+ * (`resolveFieldIconAddress`), held in the same lists as the field icons.
954
+ * Null where the layer has no such variable or its value names no icon.
955
+ */
956
+ function parseLayerIcon(maplayer) {
957
+ const properties = directChild(maplayer, 'customproperties');
958
+ if (!properties)
959
+ return null;
960
+ const names = readCustomPropertyList(properties, 'variableNames');
961
+ const values = readCustomPropertyList(properties, 'variableValues');
962
+ const index = names.indexOf(LAYER_ICON_VARIABLE);
963
+ return index === -1 || index >= values.length ? null : resolveFieldIconAddress(values[index]);
964
+ }
965
+ /** The start of the name of a layer variable that chooses a field's control: `quac_control_condition`. */
966
+ const FIELD_CONTROL_VARIABLE_PREFIX = 'quac_control_';
967
+ /**
968
+ * Reads the control each field's `quac_control_<field>` variable asks for,
969
+ * held in the same lists as the field icons. The value is compared without
970
+ * regard to case or surrounding spaces, and one that names no control is left
971
+ * out.
972
+ */
973
+ function parseFieldControls(maplayer) {
974
+ const controls = {};
975
+ for (const [field, value] of readFieldVariables(maplayer, FIELD_CONTROL_VARIABLE_PREFIX)) {
976
+ const control = value.trim().toLowerCase();
977
+ if (control === 'buttons' || control === 'dropdown')
978
+ controls[field] = control;
979
+ }
980
+ return controls;
981
+ }
982
+ /** Each of the layer's variables named `prefix` and a field's name, as that field's name and the variable's value. */
983
+ function readFieldVariables(maplayer, prefix) {
984
+ const properties = directChild(maplayer, 'customproperties');
985
+ if (!properties)
986
+ return [];
987
+ const names = readCustomPropertyList(properties, 'variableNames');
988
+ const values = readCustomPropertyList(properties, 'variableValues');
989
+ return names.flatMap((variable, index) => {
990
+ if (!variable.startsWith(prefix) || index >= values.length)
991
+ return [];
992
+ const field = variable.slice(prefix.length);
993
+ return field ? [[field, values[index]]] : [];
994
+ });
995
+ }
996
+ /**
997
+ * Reads the layer's preview/display field from `<previewExpression>`. QGIS
998
+ * writes the value as a quoted field reference, e.g.
999
+ * `<previewExpression>"location_description"</previewExpression>`. We strip
1000
+ * the surrounding quotes to recover the field name. More complex expressions
1001
+ * (concatenations, conditionals) are not a single field reference, so they
1002
+ * return null.
1003
+ */
1004
+ function parseDisplayField(maplayer) {
1005
+ const node = directChild(maplayer, 'previewExpression');
1006
+ const text = node?.textContent?.trim();
1007
+ if (!text)
1008
+ return null;
1009
+ const match = /^"([^"]+)"$/.exec(text);
1010
+ return match ? match[1] : null;
1011
+ }
1012
+ /**
1013
+ * Reads the layer's queryable flag from `<flags><Identifiable>1</Identifiable></flags>`.
1014
+ * "1" means queryable; "0" means not. Defaults to true when the flags
1015
+ * element is absent (matches QGIS's default behaviour).
1016
+ */
1017
+ function parseQueryable(maplayer) {
1018
+ const flags = directChild(maplayer, 'flags');
1019
+ if (!flags)
1020
+ return true;
1021
+ const identifiable = directChild(flags, 'Identifiable');
1022
+ if (!identifiable)
1023
+ return true;
1024
+ return identifiable.textContent?.trim() === '1';
1025
+ }
1026
+ /** The image types an embedded legend image is read as, by the bytes it opens with. */
1027
+ const IMAGE_SIGNATURES = [
1028
+ ['image/png', (bytes) => bytes.startsWith('\x89PNG')],
1029
+ ['image/jpeg', (bytes) => bytes.startsWith('\xff\xd8\xff')],
1030
+ ['image/gif', (bytes) => bytes.startsWith('GIF8')],
1031
+ ['image/webp', (bytes) => bytes.startsWith('RIFF') && bytes.slice(8, 12) === 'WEBP'],
1032
+ ['image/svg+xml', (bytes) => /^\s*(?:<\?xml|<svg)/.test(bytes)]
1033
+ ];
1034
+ /**
1035
+ * Reads the layer's legend placeholder image where QGIS embeds it. **Embed
1036
+ * File…** saves the file as `base64:` and its contents, with no type
1037
+ * (`QgsFileContentSourceLineEdit`, `src/gui/qgsfilecontentsourcelineedit.cpp`),
1038
+ * so the type is read from the bytes the image opens with. QGIS's image cache
1039
+ * also reads a `data:` URL (`QgsAbstractContentCacheBase::parseBase64DataUrl`,
1040
+ * `src/core/qgsabstractcontentcache.cpp`), so one is kept as written. Both
1041
+ * read at qgis/QGIS@master, 2026-10-25. A file path or web address is not
1042
+ * read: it names a file rather than holding one.
1043
+ */
1044
+ function parseLegendImage(maplayer) {
1045
+ const source = maplayer.getAttribute('legendPlaceholderImage')?.trim() ?? '';
1046
+ if (/^data:image\/[\w+.-]+;base64,[A-Za-z0-9+/=\s]+$/.test(source))
1047
+ return source;
1048
+ const match = /^base64:([A-Za-z0-9+/=\s]+)$/i.exec(source);
1049
+ if (!match)
1050
+ return null;
1051
+ const data = match[1].replace(/\s/g, '');
1052
+ let opening;
1053
+ try {
1054
+ opening = atob(data.slice(0, 24));
1055
+ }
1056
+ catch {
1057
+ return null;
1058
+ }
1059
+ const type = IMAGE_SIGNATURES.find(([, matches]) => matches(opening))?.[0];
1060
+ return type ? `data:${type};base64,${data}` : null;
1061
+ }
1062
+ /**
1063
+ * Reads the layer's Private flag from `<flags><Private>1</Private></flags>`,
1064
+ * the **Private** column of QGIS's Project Properties → Data Sources
1065
+ * (`QgsMapLayer::writeCommonStyle`, `src/core/qgsmaplayer.cpp`,
1066
+ * `qgis/QGIS@master`, read 2026-10-24). QGIS writes every flag, each as 0 or 1.
1067
+ * A layer with no flags, or no Private flag, is not private.
1068
+ */
1069
+ function parsePrivate(maplayer) {
1070
+ const flags = directChild(maplayer, 'flags');
1071
+ if (!flags)
1072
+ return false;
1073
+ return directChild(flags, 'Private')?.textContent?.trim() === '1';
1074
+ }
1075
+ /**
1076
+ * Reads scale-dependent visibility from the `<maplayer>` attributes. QGIS
1077
+ * writes `minScale` and `maxScale` whether or not the flag is on, so both are
1078
+ * ignored unless `hasScaleBasedVisibilityFlag` is "1". A value of 0 means no
1079
+ * limit on that side.
1080
+ */
1081
+ function parseScaleRange(maplayer) {
1082
+ if (maplayer.getAttribute('hasScaleBasedVisibilityFlag') !== '1')
1083
+ return null;
1084
+ const minScale = parseScaleDenominator(maplayer.getAttribute('minScale'));
1085
+ const maxScale = parseScaleDenominator(maplayer.getAttribute('maxScale'));
1086
+ if (minScale === null && maxScale === null)
1087
+ return null;
1088
+ return { minScale, maxScale };
1089
+ }
1090
+ function parseScaleDenominator(text) {
1091
+ const value = Number(text);
1092
+ return text && Number.isFinite(value) && value > 0 ? value : null;
1093
+ }
1094
+ /**
1095
+ * Reads the layer's opacity from `<layerOpacity>`. Defaults to 1 when the
1096
+ * element is absent or unparseable.
1097
+ */
1098
+ function parseOpacity(maplayer) {
1099
+ const text = directChildText(maplayer, 'layerOpacity')
1100
+ ?? maplayer.querySelector('pipe > rasterrenderer')?.getAttribute('opacity');
1101
+ if (!text)
1102
+ return 1;
1103
+ const value = Number(text);
1104
+ return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 1;
1105
+ }
1106
+ function directChild(parent, tag) {
1107
+ for (const child of Array.from(parent.children)) {
1108
+ if (child.tagName === tag)
1109
+ return child;
1110
+ }
1111
+ return null;
1112
+ }
1113
+ function directChildText(parent, tag) {
1114
+ return directChild(parent, tag)?.textContent?.trim() ?? null;
1115
+ }
1116
+ function readNumber(parent, tag) {
1117
+ const text = parent.querySelector(tag)?.textContent?.trim();
1118
+ if (!text)
1119
+ return null;
1120
+ const value = Number(text);
1121
+ return Number.isFinite(value) ? value : null;
1122
+ }