@vectoriahq/quac 0.14.0 → 0.15.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.
package/README.md CHANGED
@@ -61,6 +61,18 @@ const catalogue = generateStacCatalogue(project, [], {
61
61
 
62
62
  `selfHref` is the address of the folder the project is published in, and `projectPath` is the project file's path inside that folder. A layer's data files and styles are addressed relative to them, so a catalogue to be published or saved apart from the project needs both. Without `projectPath`, each style's address names no file, and only an application already holding the project can read it; without `selfHref`, the catalogue's relative addresses have no folder to start from.
63
63
 
64
+ `generateStacCatalogue` returns one document, with each Catalog carrying its Collections and nested Catalogs inline. `splitCatalogue` gives the same catalogue as separate documents, each with the path to save it at, for a STAC client that follows `child` links:
65
+
66
+ ```js
67
+ import { splitCatalogue } from '@vectoriahq/quac'
68
+
69
+ for (const { path, document } of splitCatalogue(catalogue, { rootFileName: 'survey.json', childrenFolder: 'survey' })) {
70
+ // path: 'survey.json', 'survey/collections/roads_3f2a….json', …
71
+ }
72
+ ```
73
+
74
+ Each path is relative to the folder the root document is saved in, and every relative address inside a document is rewritten from that document's own path, so a layer's data file keeps its place. Without options, the root is `catalog.json` and the other documents sit beside it. The field reference's [§ The document](https://github.com/vectoriahq/quac/tree/main/packages/quac/spec#the-document) says how the documents are named.
75
+
64
76
  `project.notes` lists the project's settings that the catalogue does not carry, such as a widget it does not read or an expression it cannot read. Each note gives the layer, the field where there is one, a reason code and the setting's own text where it helps; the `ProjectNoteReason` type lists the codes and what each means. The notes are not written into the catalogue.
65
77
 
66
78
  The JSON Schema that checks a catalogue's `quac:` fields is exported as `@vectoriahq/quac/schema`.
@@ -0,0 +1,54 @@
1
+ import type { StacCatalog, StacCollection } from '../model/Stac.ts';
2
+ /**
3
+ * Writes a catalogue as separate documents: the root Catalog, each nested
4
+ * Catalog and each Collection in a document of its own, linked by `child`,
5
+ * `parent` and `root` links, with no `collections` or `catalogs` arrays
6
+ * (`packages/quac/spec/README.md` § "The document").
7
+ */
8
+ /** Where the documents go. */
9
+ export interface SplitCatalogueOptions {
10
+ /**
11
+ * The root Catalog's file name: one file name ending in `.json`, such as
12
+ * `catalog.json` or `Parks.json`. `catalog.json` where it is left off.
13
+ */
14
+ rootFileName?: string;
15
+ /**
16
+ * The folder every other document goes in, relative to the root document's
17
+ * folder, such as `Parks`. Empty, the default, puts them beside the root
18
+ * document.
19
+ */
20
+ childrenFolder?: string;
21
+ }
22
+ /** One document of a catalogue written as separate documents. */
23
+ export interface CatalogueDocument {
24
+ /**
25
+ * Where the document is saved, relative to the root document's folder: file
26
+ * and folder names joined by `/`, not escaped. Always inside that folder.
27
+ */
28
+ path: string;
29
+ document: StacCatalog | StacCollection;
30
+ }
31
+ /**
32
+ * The catalogue `catalogue` holds, one document holding the whole tree, as
33
+ * separate documents, the root first and then each child after its parent, in
34
+ * the order the parent's `child` links list them.
35
+ *
36
+ * A Catalog's Collections go in a `collections` folder beside it and its
37
+ * nested Catalogs in a `catalogs` folder, each in a folder of its own holding
38
+ * its `catalog.json`. The root's go in `childrenFolder`. A document's file or
39
+ * folder name is its id, made safe as a file name on any system (`safeName`),
40
+ * and where two in one folder would take the same name, in any case, the later
41
+ * one is given `-2`, `-3` and so on.
42
+ *
43
+ * Every relative href, in each link and asset, is rewritten from the
44
+ * document's own path. A `self`, `root` or `parent` link names that document's
45
+ * new path, and a `child` link whose href is a child's own `self` href names
46
+ * the child's. Every other relative href is resolved against the root
47
+ * document's folder, as the one document's hrefs are, so a data file keeps its
48
+ * place, even one outside that folder. An absolute href, one starting with `/`,
49
+ * and one holding only a query or a fragment are left as they are. A child that
50
+ * no `child` link names is given one.
51
+ *
52
+ * Throws where `rootFileName` or `childrenFolder` is not a safe relative path.
53
+ */
54
+ export declare function splitCatalogue(catalogue: StacCatalog, options?: SplitCatalogueOptions): CatalogueDocument[];
@@ -0,0 +1,202 @@
1
+ const DEFAULT_ROOT_FILE_NAME = 'catalog.json';
2
+ /**
3
+ * The catalogue `catalogue` holds, one document holding the whole tree, as
4
+ * separate documents, the root first and then each child after its parent, in
5
+ * the order the parent's `child` links list them.
6
+ *
7
+ * A Catalog's Collections go in a `collections` folder beside it and its
8
+ * nested Catalogs in a `catalogs` folder, each in a folder of its own holding
9
+ * its `catalog.json`. The root's go in `childrenFolder`. A document's file or
10
+ * folder name is its id, made safe as a file name on any system (`safeName`),
11
+ * and where two in one folder would take the same name, in any case, the later
12
+ * one is given `-2`, `-3` and so on.
13
+ *
14
+ * Every relative href, in each link and asset, is rewritten from the
15
+ * document's own path. A `self`, `root` or `parent` link names that document's
16
+ * new path, and a `child` link whose href is a child's own `self` href names
17
+ * the child's. Every other relative href is resolved against the root
18
+ * document's folder, as the one document's hrefs are, so a data file keeps its
19
+ * place, even one outside that folder. An absolute href, one starting with `/`,
20
+ * and one holding only a query or a fragment are left as they are. A child that
21
+ * no `child` link names is given one.
22
+ *
23
+ * Throws where `rootFileName` or `childrenFolder` is not a safe relative path.
24
+ */
25
+ export function splitCatalogue(catalogue, options = {}) {
26
+ const rootFileName = options.rootFileName ?? DEFAULT_ROOT_FILE_NAME;
27
+ if (!isSafeName(rootFileName) || !/\.json$/i.test(rootFileName)) {
28
+ throw new Error(`The root document's file name must be one safe file name ending in .json: ${JSON.stringify(rootFileName)}`);
29
+ }
30
+ const childrenFolder = (options.childrenFolder ?? '').replace(/\/$/, '');
31
+ const folderNames = childrenFolder ? childrenFolder.split('/') : [];
32
+ if (!folderNames.every(isSafeName) || folderNames[0]?.toLowerCase() === rootFileName.toLowerCase()) {
33
+ throw new Error(`The children's folder must be a relative path of safe folder names, apart from the root document: ${JSON.stringify(options.childrenFolder)}`);
34
+ }
35
+ const root = placeCatalog(catalogue, rootFileName, folderNames);
36
+ const documents = [];
37
+ writeDocuments(root, null, root, documents);
38
+ return documents;
39
+ }
40
+ /**
41
+ * Places a Catalog at `path` and its children in `folder`, so every path is
42
+ * known before any href is written.
43
+ */
44
+ function placeCatalog(catalog, path, folder) {
45
+ const candidates = [...(catalog.collections ?? []), ...(catalog.catalogs ?? [])];
46
+ const claimed = new Set();
47
+ const ordered = [];
48
+ catalog.links.forEach((link, linkIndex) => {
49
+ if (link.rel !== 'child')
50
+ return;
51
+ const node = candidates.find((candidate) => !claimed.has(candidate) && selfHrefOf(candidate) === link.href);
52
+ if (!node)
53
+ return;
54
+ claimed.add(node);
55
+ ordered.push({ node, linkIndex });
56
+ });
57
+ for (const node of candidates) {
58
+ if (!claimed.has(node))
59
+ ordered.push({ node, linkIndex: -1 });
60
+ }
61
+ const fileNames = new Set();
62
+ const folderNames = new Set();
63
+ const children = ordered.map(({ node, linkIndex }) => {
64
+ if (node.type === 'Collection') {
65
+ const fileName = unclaimedName(safeName(node.id), '.json', fileNames);
66
+ return { placed: { node, path: [...folder, 'collections', fileName].join('/'), children: [] }, linkIndex };
67
+ }
68
+ const childFolder = [...folder, 'catalogs', unclaimedName(safeName(node.id), '', folderNames)];
69
+ return { placed: placeCatalog(node, [...childFolder, 'catalog.json'].join('/'), childFolder), linkIndex };
70
+ });
71
+ return { node: catalog, path, children };
72
+ }
73
+ function writeDocuments(placed, parent, root, into) {
74
+ const folder = placed.path.split('/').slice(0, -1).map(encodeURIComponent);
75
+ const hrefTo = (other) => relativeHref(folder, { ups: 0, segments: other.path.split('/').map(encodeURIComponent) });
76
+ const childAt = new Map(placed.children.filter((child) => child.linkIndex >= 0).map((child) => [child.linkIndex, child.placed]));
77
+ const links = placed.node.links.map((link, index) => {
78
+ if (!isPathHref(link.href))
79
+ return { ...link };
80
+ const child = childAt.get(index);
81
+ if (child)
82
+ return { ...link, href: hrefTo(child) };
83
+ if (link.rel === 'self')
84
+ return { ...link, href: hrefTo(placed) };
85
+ if (link.rel === 'root')
86
+ return { ...link, href: hrefTo(root) };
87
+ if (link.rel === 'parent' && parent)
88
+ return { ...link, href: hrefTo(parent) };
89
+ return { ...link, href: rewriteHref(link.href, folder) };
90
+ });
91
+ for (const child of placed.children) {
92
+ if (child.linkIndex >= 0)
93
+ continue;
94
+ const title = child.placed.node.title;
95
+ links.push({ rel: 'child', href: hrefTo(child.placed), type: 'application/json', ...(title === undefined ? {} : { title }) });
96
+ }
97
+ const document = {};
98
+ for (const [key, value] of Object.entries(placed.node)) {
99
+ if (key === 'collections' || key === 'catalogs')
100
+ continue;
101
+ if (key === 'links')
102
+ document[key] = links;
103
+ else if (key === 'assets' && value && typeof value === 'object')
104
+ document[key] = rewriteAssets(value, folder);
105
+ else
106
+ document[key] = value;
107
+ }
108
+ into.push({ path: placed.path, document: document });
109
+ for (const child of placed.children)
110
+ writeDocuments(child.placed, placed, root, into);
111
+ }
112
+ function rewriteAssets(assets, folder) {
113
+ return Object.fromEntries(Object.entries(assets).map(([key, asset]) => ([key, typeof asset?.href === 'string' ? { ...asset, href: rewriteHref(asset.href, folder) } : asset])));
114
+ }
115
+ function selfHrefOf(node) {
116
+ return node.links.find((link) => link.rel === 'self')?.href;
117
+ }
118
+ /**
119
+ * Whether an href is a relative path, which moves with the document holding
120
+ * it: not an absolute address, not one starting with `/`, and not one holding
121
+ * only a query or a fragment, which names the document it is in.
122
+ */
123
+ function isPathHref(href) {
124
+ return typeof href === 'string' && href !== '' && !/^[a-z][a-z0-9+.-]*:/i.test(href) && !/^[/?#]/.test(href);
125
+ }
126
+ /** A relative href, which resolves against the root document's folder, rewritten from `folder`, a folder inside it. */
127
+ function rewriteHref(href, folder) {
128
+ if (!isPathHref(href))
129
+ return href;
130
+ const cut = href.search(/[?#]/);
131
+ const path = cut < 0 ? href : href.slice(0, cut);
132
+ const rest = cut < 0 ? '' : href.slice(cut);
133
+ return relativeHref(folder, resolvePath(path)) + rest;
134
+ }
135
+ /** A relative path resolved against the root document's folder, its `.` and `..` segments taken out. */
136
+ function resolvePath(path) {
137
+ const segments = [];
138
+ let ups = 0;
139
+ const parts = path.split('/');
140
+ parts.forEach((part, index) => {
141
+ const last = index === parts.length - 1;
142
+ if (part === '.' || part === '..') {
143
+ if (part === '..') {
144
+ if (segments.length > 0)
145
+ segments.pop();
146
+ else
147
+ ups += 1;
148
+ }
149
+ // A path ending in `.` or `..` names a folder.
150
+ if (last)
151
+ segments.push('');
152
+ return;
153
+ }
154
+ segments.push(part);
155
+ });
156
+ return { ups, segments };
157
+ }
158
+ /** The href naming `target` from `folder`, both from the root document's folder. */
159
+ function relativeHref(folder, target) {
160
+ if (target.ups > 0)
161
+ return '../'.repeat(folder.length + target.ups) + target.segments.join('/');
162
+ const targetFolder = target.segments.slice(0, -1);
163
+ let shared = 0;
164
+ while (shared < folder.length && shared < targetFolder.length && folder[shared] === targetFolder[shared])
165
+ shared += 1;
166
+ const rest = target.segments.slice(shared).join('/');
167
+ const ups = folder.length - shared;
168
+ return ups > 0 ? '../'.repeat(ups) + rest : `./${rest}`;
169
+ }
170
+ /** Characters no file name may hold on Windows, macOS or Linux: controls, `/`, and those Windows refuses. */
171
+ const UNSAFE_CHARACTERS = /[\u0000-\u001f\u007f"*/:<>?\\|]/g;
172
+ /** The names Windows keeps for devices, with or without an extension. */
173
+ const RESERVED_NAME = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\.|$)/i;
174
+ /**
175
+ * An id made a file or folder name that is safe on any system: each character
176
+ * a name may not hold, `/` among them, becomes `_`, as does each `.` or space
177
+ * at its end, which Windows drops; an empty name is `_`; and a name Windows
178
+ * keeps for a device, such as `con`, is given a leading `_`. So no name is
179
+ * empty, `.` or `..`.
180
+ */
181
+ function safeName(id) {
182
+ let name = id.replace(UNSAFE_CHARACTERS, '_');
183
+ // Counted from the end, not matched with /[. ]+$/, which takes time growing with the square of a run of spaces that does not end the id.
184
+ let kept = name.length;
185
+ while (kept > 0 && (name[kept - 1] === '.' || name[kept - 1] === ' '))
186
+ kept -= 1;
187
+ name = name.slice(0, kept) + '_'.repeat(name.length - kept);
188
+ if (name === '')
189
+ name = '_';
190
+ return RESERVED_NAME.test(name) ? `_${name}` : name;
191
+ }
192
+ function isSafeName(name) {
193
+ return safeName(name) === name;
194
+ }
195
+ /** `name` and `suffix`, or with `-2`, `-3` and so on before the suffix, whichever is first not in `taken`, compared in lower case. */
196
+ function unclaimedName(name, suffix, taken) {
197
+ let candidate = `${name}${suffix}`;
198
+ for (let count = 2; taken.has(candidate.toLowerCase()); count += 1)
199
+ candidate = `${name}-${count}${suffix}`;
200
+ taken.add(candidate.toLowerCase());
201
+ return candidate;
202
+ }
package/dist/index.d.ts CHANGED
@@ -82,4 +82,6 @@ export { generateServerStacCatalogue, withoutHiddenFields } from './generate/ser
82
82
  export type { HiddenFieldContext } from './generate/serverStacCatalogue.ts';
83
83
  export { serverLayerTree } from './generate/serverLayerTree.ts';
84
84
  export type { ServerLayerTree, ServerLayerTreeGroup, ServerLayerTreeLayer, ServerLayerTreeNode } from './generate/serverLayerTree.ts';
85
+ export { splitCatalogue } from './generate/splitCatalogue.ts';
86
+ export type { CatalogueDocument, SplitCatalogueOptions } from './generate/splitCatalogue.ts';
85
87
  export { PROJ_CODE, PROJECTION_EXTENSION, readCollectionCrs } from './model/stacProjection.ts';
package/dist/index.js CHANGED
@@ -53,4 +53,5 @@ export { DEFAULT_WFS_VERSION, SPOKEN_WFS_VERSIONS, WFS_CAPABILITIES_VERSION, WFS
53
53
  export { QUAC_SCHEMA_URL, declareQuacExtension, isNewerQuacMajor, listQuacExtension, readQuacVersion } from "./model/quacExtension.js";
54
54
  export { generateServerStacCatalogue, withoutHiddenFields } from "./generate/serverStacCatalogue.js";
55
55
  export { serverLayerTree } from "./generate/serverLayerTree.js";
56
+ export { splitCatalogue } from "./generate/splitCatalogue.js";
56
57
  export { PROJ_CODE, PROJECTION_EXTENSION, readCollectionCrs } from "./model/stacProjection.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectoriahq/quac",
3
- "version": "0.14.0",
3
+ "version": "0.15.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.",