styled-map-package 4.0.1 → 5.0.0-pre.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 (85) hide show
  1. package/bin/smp-download.js +10 -6
  2. package/bin/smp-mbtiles.js +5 -7
  3. package/bin/smp-view.js +34 -26
  4. package/lib/reporters.js +92 -0
  5. package/package.json +8 -187
  6. package/LICENSE.md +0 -7
  7. package/README.md +0 -28
  8. package/dist/download.cjs +0 -101
  9. package/dist/download.d.cts +0 -65
  10. package/dist/download.d.ts +0 -65
  11. package/dist/download.js +0 -77
  12. package/dist/from-mbtiles.cjs +0 -91
  13. package/dist/from-mbtiles.d.cts +0 -17
  14. package/dist/from-mbtiles.d.ts +0 -17
  15. package/dist/from-mbtiles.js +0 -57
  16. package/dist/index.cjs +0 -49
  17. package/dist/index.d.cts +0 -27
  18. package/dist/index.d.ts +0 -27
  19. package/dist/index.js +0 -18
  20. package/dist/reader-watch.cjs +0 -135
  21. package/dist/reader-watch.d.cts +0 -24
  22. package/dist/reader-watch.d.ts +0 -24
  23. package/dist/reader-watch.js +0 -101
  24. package/dist/reader.cjs +0 -167
  25. package/dist/reader.d.cts +0 -62
  26. package/dist/reader.d.ts +0 -62
  27. package/dist/reader.js +0 -138
  28. package/dist/reporters.cjs +0 -122
  29. package/dist/reporters.d.cts +0 -10
  30. package/dist/reporters.d.ts +0 -10
  31. package/dist/reporters.js +0 -88
  32. package/dist/server.cjs +0 -78
  33. package/dist/server.d.cts +0 -48
  34. package/dist/server.d.ts +0 -48
  35. package/dist/server.js +0 -54
  36. package/dist/style-downloader.cjs +0 -312
  37. package/dist/style-downloader.d.cts +0 -120
  38. package/dist/style-downloader.d.ts +0 -120
  39. package/dist/style-downloader.js +0 -288
  40. package/dist/tile-downloader.cjs +0 -158
  41. package/dist/tile-downloader.d.cts +0 -84
  42. package/dist/tile-downloader.d.ts +0 -84
  43. package/dist/tile-downloader.js +0 -126
  44. package/dist/types-B4Xn1F9K.d.cts +0 -189
  45. package/dist/types-B4Xn1F9K.d.ts +0 -189
  46. package/dist/utils/errors.cjs +0 -41
  47. package/dist/utils/errors.d.cts +0 -18
  48. package/dist/utils/errors.d.ts +0 -18
  49. package/dist/utils/errors.js +0 -16
  50. package/dist/utils/fetch.cjs +0 -96
  51. package/dist/utils/fetch.d.cts +0 -51
  52. package/dist/utils/fetch.d.ts +0 -51
  53. package/dist/utils/fetch.js +0 -62
  54. package/dist/utils/file-formats.cjs +0 -98
  55. package/dist/utils/file-formats.d.cts +0 -35
  56. package/dist/utils/file-formats.d.ts +0 -35
  57. package/dist/utils/file-formats.js +0 -62
  58. package/dist/utils/geo.cjs +0 -84
  59. package/dist/utils/geo.d.cts +0 -46
  60. package/dist/utils/geo.d.ts +0 -46
  61. package/dist/utils/geo.js +0 -56
  62. package/dist/utils/mapbox.cjs +0 -121
  63. package/dist/utils/mapbox.d.cts +0 -43
  64. package/dist/utils/mapbox.d.ts +0 -43
  65. package/dist/utils/mapbox.js +0 -91
  66. package/dist/utils/misc.cjs +0 -39
  67. package/dist/utils/misc.d.cts +0 -22
  68. package/dist/utils/misc.d.ts +0 -22
  69. package/dist/utils/misc.js +0 -13
  70. package/dist/utils/streams.cjs +0 -130
  71. package/dist/utils/streams.d.cts +0 -73
  72. package/dist/utils/streams.d.ts +0 -73
  73. package/dist/utils/streams.js +0 -103
  74. package/dist/utils/style.cjs +0 -126
  75. package/dist/utils/style.d.cts +0 -69
  76. package/dist/utils/style.d.ts +0 -69
  77. package/dist/utils/style.js +0 -98
  78. package/dist/utils/templates.cjs +0 -114
  79. package/dist/utils/templates.d.cts +0 -78
  80. package/dist/utils/templates.d.ts +0 -78
  81. package/dist/utils/templates.js +0 -79
  82. package/dist/writer.cjs +0 -401
  83. package/dist/writer.d.cts +0 -7
  84. package/dist/writer.d.ts +0 -7
  85. package/dist/writer.js +0 -374
package/dist/writer.js DELETED
@@ -1,374 +0,0 @@
1
- import { validateStyleMin, migrate } from "@maplibre/maplibre-gl-style-spec";
2
- import { bbox } from "@turf/bbox";
3
- import archiver from "archiver";
4
- import { EventEmitter } from "events";
5
- import { excludeKeys } from "filter-obj";
6
- import fs from "fs";
7
- import { pEvent } from "p-event";
8
- import { PassThrough, pipeline } from "readable-stream";
9
- import { Readable } from "stream";
10
- import { getTileFormatFromStream } from "./utils/file-formats.js";
11
- import { MAX_BOUNDS, tileToBBox, unionBBox } from "./utils/geo.js";
12
- import { clone } from "./utils/misc.js";
13
- import { writeStreamFromAsync } from "./utils/streams.js";
14
- import { replaceFontStacks } from "./utils/style.js";
15
- import {
16
- getGlyphFilename,
17
- getSpriteFilename,
18
- getSpriteUri,
19
- getTileFilename,
20
- getTileUri,
21
- GLYPH_URI,
22
- STYLE_FILE
23
- } from "./utils/templates.js";
24
- const SUPPORTED_SOURCE_TYPES = (
25
- /** @type {const} */
26
- [
27
- "raster",
28
- "vector",
29
- "geojson"
30
- ]
31
- );
32
- class Writer extends EventEmitter {
33
- #archive = archiver("zip", { zlib: { level: 9 } }).setMaxListeners(Infinity).on("error", console.error);
34
- /** @type {Set<string>} */
35
- #addedFiles = /* @__PURE__ */ new Set();
36
- /** @type {Set<string>} */
37
- #fonts = /* @__PURE__ */ new Set();
38
- /** @type {Set<string>} */
39
- #addedSpriteIds = /* @__PURE__ */ new Set();
40
- /** @type {Map<string, SourceInfo>} */
41
- #sources = /* @__PURE__ */ new Map();
42
- /** @type {StyleSpecification} */
43
- #style;
44
- #outputStream;
45
- static SUPPORTED_SOURCE_TYPES = SUPPORTED_SOURCE_TYPES;
46
- /**
47
- * @param {any} style A v7 or v8 MapLibre style. v7 styles will be migrated to
48
- * v8. (There are currently no typescript declarations for v7 styles, hence
49
- * this is typed as `any` and validated internally)
50
- * @param {object} opts
51
- * @param {number} [opts.highWaterMark=1048576] The maximum number of bytes to buffer during write
52
- */
53
- constructor(style, { highWaterMark = 1024 * 1024 } = {}) {
54
- super();
55
- if (!style || !("version" in style)) {
56
- throw new Error("Invalid style");
57
- }
58
- if (style.version !== 7 && style.version !== 8) {
59
- throw new Error(`Invalid style: Unsupported version v${style.version}`);
60
- }
61
- if (!Array.isArray(style.layers)) {
62
- throw new Error("Invalid style: missing layers property");
63
- }
64
- const styleCopy = clone(style);
65
- migrate(styleCopy);
66
- const errors = validateStyleMin(styleCopy);
67
- if (errors.length) {
68
- throw new AggregateError(errors, "Invalid style");
69
- }
70
- this.#style = styleCopy;
71
- for (const [sourceId, source] of Object.entries(this.#style.sources)) {
72
- if (source.type !== "geojson") continue;
73
- this.#addSource(sourceId, source);
74
- }
75
- this.#outputStream = new PassThrough({ highWaterMark });
76
- pipeline(this.#archive, this.#outputStream, (err) => {
77
- if (err) this.emit("error", err);
78
- });
79
- }
80
- /**
81
- * @returns {import('stream').Readable} Readable stream of the styled map package
82
- */
83
- get outputStream() {
84
- return this.#outputStream;
85
- }
86
- #getBounds() {
87
- let bounds;
88
- let maxzoom = 0;
89
- for (const { source } of this.#sources.values()) {
90
- if (source.type === "geojson") {
91
- if (isEmptyFeatureCollection(source.data)) continue;
92
- const bbox2 = get2DBBox(source.data.bbox);
93
- bounds = bounds ? unionBBox([bounds, bbox2]) : [...bbox2];
94
- } else {
95
- if (source.maxzoom < maxzoom) continue;
96
- if (source.maxzoom === maxzoom) {
97
- bounds = bounds ? unionBBox([bounds, source.bounds]) : source.bounds;
98
- } else {
99
- bounds = source.bounds;
100
- maxzoom = source.maxzoom;
101
- }
102
- }
103
- }
104
- return bounds;
105
- }
106
- #getMaxZoom() {
107
- let maxzoom = 0;
108
- for (const { source } of this.#sources.values()) {
109
- const sourceMaxzoom = (
110
- // For GeoJSON sources, the maxzoom is 16 unless otherwise set
111
- source.type === "geojson" ? source.maxzoom || 16 : source.maxzoom
112
- );
113
- maxzoom = Math.max(maxzoom, sourceMaxzoom);
114
- }
115
- return maxzoom;
116
- }
117
- /**
118
- * Add a source definition to the styled map package
119
- *
120
- * @param {string} sourceId
121
- * @param {InputSource} source
122
- * @returns {SourceInfo}
123
- */
124
- #addSource(sourceId, source) {
125
- const encodedSourceId = encodeSourceId(this.#sources.size);
126
- const tileSourceOverrides = {
127
- minzoom: 0,
128
- maxzoom: 0,
129
- bounds: (
130
- /** @type {import('./utils/geo.js').BBox} */
131
- [...MAX_BOUNDS]
132
- ),
133
- tiles: (
134
- /** @type {string[]} */
135
- []
136
- )
137
- };
138
- let smpSource;
139
- switch (source.type) {
140
- case "raster":
141
- case "vector":
142
- smpSource = {
143
- ...excludeKeys(source, ["tiles", "url"]),
144
- ...tileSourceOverrides
145
- };
146
- break;
147
- case "geojson":
148
- smpSource = {
149
- ...source,
150
- maxzoom: 0,
151
- data: typeof source.data !== "string" ? (
152
- // Add a bbox property to the GeoJSON data if it doesn't already have one
153
- { ...source.data, bbox: source.data.bbox || bbox(source.data) }
154
- ) : (
155
- // If GeoJSON data is referenced by a URL, start with an empty FeatureCollection
156
- {
157
- type: "FeatureCollection",
158
- features: [],
159
- bbox: [0, 0, 0, 0]
160
- }
161
- )
162
- };
163
- break;
164
- }
165
- const sourceInfo = {
166
- source: smpSource,
167
- encodedSourceId
168
- };
169
- this.#sources.set(sourceId, sourceInfo);
170
- return sourceInfo;
171
- }
172
- /**
173
- * Add a tile to the styled map package
174
- *
175
- * @param {Source} tileData
176
- * @param {TileInfo} opts
177
- */
178
- async addTile(tileData, { z, x, y, sourceId, format }) {
179
- let sourceInfo = this.#sources.get(sourceId);
180
- if (!sourceInfo) {
181
- const source2 = this.#style.sources[sourceId];
182
- if (!source2) {
183
- throw new Error(`Source not referenced in style.json: ${sourceId}`);
184
- }
185
- if (source2.type !== "raster" && source2.type !== "vector") {
186
- throw new Error(`Unsupported source type: ${source2.type}`);
187
- }
188
- sourceInfo = this.#addSource(sourceId, source2);
189
- }
190
- const { source, encodedSourceId } = sourceInfo;
191
- if (source.type !== "raster" && source.type !== "vector") {
192
- throw new Error(`Unsupported source type: ${source.type}`);
193
- }
194
- if (!format) {
195
- const tileDataStream = typeof tileData === "string" ? fs.createReadStream(tileData) : tileData instanceof Uint8Array ? Readable.from(tileData) : tileData;
196
- [format, tileData] = await getTileFormatFromStream(tileDataStream);
197
- }
198
- if (!sourceInfo.format) {
199
- sourceInfo.format = format;
200
- } else if (sourceInfo.format !== format) {
201
- throw new Error(
202
- `Tile format mismatch for source ${sourceId}: expected ${sourceInfo.format}, got ${format}`
203
- );
204
- }
205
- const bbox2 = tileToBBox({ z, x, y });
206
- if (z > source.maxzoom) {
207
- source.maxzoom = z;
208
- source.bounds = bbox2;
209
- } else if (z === source.maxzoom) {
210
- source.bounds = unionBBox([source.bounds, bbox2]);
211
- }
212
- const name = getTileFilename({ sourceId: encodedSourceId, z, x, y, format });
213
- return this.#append(tileData, { name, store: true });
214
- }
215
- /**
216
- * Create a write stream for adding tiles to the styled map package
217
- *
218
- * @param {object} opts
219
- * @param {number} [opts.concurrency=16] The number of concurrent writes
220
- *
221
- * @returns
222
- */
223
- createTileWriteStream({ concurrency = 16 } = {}) {
224
- return writeStreamFromAsync(this.addTile.bind(this), { concurrency });
225
- }
226
- /**
227
- * Add a sprite to the styled map package
228
- *
229
- * @param {object} options
230
- * @param {Source} options.json
231
- * @param {Source} options.png
232
- * @param {number} [options.pixelRatio]
233
- * @param {string} [options.id='default']
234
- * @returns {Promise<void>}
235
- */
236
- async addSprite({ json, png, pixelRatio = 1, id = "default" }) {
237
- this.#addedSpriteIds.add(id);
238
- const jsonName = getSpriteFilename({ id, pixelRatio, ext: ".json" });
239
- const pngName = getSpriteFilename({ id, pixelRatio, ext: ".png" });
240
- await Promise.all([
241
- this.#append(json, { name: jsonName }),
242
- this.#append(png, { name: pngName })
243
- ]);
244
- }
245
- /**
246
- * Add glyphs to the styled map package
247
- *
248
- * @param {Source} glyphData
249
- * @param {GlyphInfo} glyphInfo
250
- * @returns {Promise<void>}
251
- */
252
- addGlyphs(glyphData, { font: fontName, range }) {
253
- this.#fonts.add(fontName);
254
- const name = getGlyphFilename({ fontstack: fontName, range });
255
- return this.#append(glyphData, { name });
256
- }
257
- /**
258
- * Create a write stream for adding glyphs to the styled map package
259
- *
260
- * @param {object} opts
261
- * @param {number} [opts.concurrency=16] The number of concurrent writes
262
- * @returns
263
- */
264
- createGlyphWriteStream({ concurrency = 16 } = {}) {
265
- return writeStreamFromAsync(this.addGlyphs.bind(this), { concurrency });
266
- }
267
- /**
268
- * Finalize the styled map package and write the style to the archive.
269
- * This method must be called to complete the archive.
270
- * You must wait for your destination write stream to 'finish' before using the output.
271
- */
272
- finish() {
273
- this.#prepareStyle();
274
- const style = JSON.stringify(this.#style);
275
- this.#append(style, { name: STYLE_FILE });
276
- this.#archive.finalize();
277
- }
278
- /**
279
- * Mutates the style object to prepare it for writing to the archive.
280
- * Deterministic: can be run more than once with the same result.
281
- */
282
- #prepareStyle() {
283
- if (this.#sources.size === 0) {
284
- throw new Error("Missing sources: add at least one source");
285
- }
286
- if (this.#style.glyphs && this.#fonts.size === 0) {
287
- throw new Error(
288
- "Missing fonts: style references glyphs but no fonts added"
289
- );
290
- }
291
- replaceFontStacks(this.#style, [...this.#fonts]);
292
- if (this.#style.glyphs) {
293
- this.#style.glyphs = GLYPH_URI;
294
- }
295
- if (typeof this.#style.sprite === "string") {
296
- if (!this.#addedSpriteIds.has("default")) {
297
- throw new Error(
298
- "Missing sprite: style references sprite but none added"
299
- );
300
- }
301
- this.#style.sprite = getSpriteUri();
302
- } else if (Array.isArray(this.#style.sprite)) {
303
- this.#style.sprite = this.#style.sprite.map(({ id }) => {
304
- if (!this.#addedSpriteIds.has(id)) {
305
- throw new Error(
306
- `Missing sprite: style references sprite ${id} but none added`
307
- );
308
- }
309
- return { id, url: getSpriteUri(id) };
310
- });
311
- }
312
- this.#style.sources = {};
313
- for (const [sourceId, { source, encodedSourceId, format = "mvt" }] of this.#sources) {
314
- if (source.type === "geojson" && isEmptyFeatureCollection(source.data)) {
315
- continue;
316
- }
317
- this.#style.sources[sourceId] = source;
318
- if (!("tiles" in source)) continue;
319
- source.tiles = [getTileUri({ sourceId: encodedSourceId, format })];
320
- }
321
- this.#style.layers = this.#style.layers.filter(
322
- (layer) => !("source" in layer) || !!this.#style.sources[layer.source]
323
- );
324
- const metadata = this.#style.metadata || (this.#style.metadata = {});
325
- const bounds = this.#getBounds();
326
- if (bounds) {
327
- metadata["smp:bounds"] = bounds;
328
- const [w, s, e, n] = bounds;
329
- this.#style.center = [w + (e - w) / 2, s + (n - s) / 2];
330
- }
331
- metadata["smp:maxzoom"] = this.#getMaxZoom();
332
- metadata["smp:sourceFolders"] = {};
333
- for (const [sourceId, { encodedSourceId }] of this.#sources) {
334
- metadata["smp:sourceFolders"][sourceId] = encodedSourceId;
335
- }
336
- this.#style.zoom = Math.max(0, this.#getMaxZoom() - 2);
337
- }
338
- /**
339
- *
340
- * @param {Source} source
341
- * @param {{ name: string, store?: boolean }} options
342
- * @returns {Promise<void>}
343
- */
344
- async #append(source, { name, store = false }) {
345
- if (this.#addedFiles.has(name)) {
346
- throw new Error(`${name} already added`);
347
- }
348
- this.#addedFiles.add(name);
349
- const onAdded = pEvent(
350
- this.#archive,
351
- "entry",
352
- (entry) => entry.name === name
353
- );
354
- this.#archive.append(convertSource(source), { name, store });
355
- await onAdded;
356
- }
357
- }
358
- function encodeSourceId(sourceIndex) {
359
- return sourceIndex.toString(36);
360
- }
361
- function convertSource(source) {
362
- return !Buffer.isBuffer(source) && source instanceof Uint8Array ? Buffer.from(source.buffer, source.byteOffset, source.length) : source;
363
- }
364
- function isEmptyFeatureCollection(data) {
365
- return data.type === "FeatureCollection" && data.features.length === 0;
366
- }
367
- function get2DBBox(bbox2) {
368
- if (bbox2.length === 4) return bbox2;
369
- return [bbox2[0], bbox2[1], bbox2[3], bbox2[4]];
370
- }
371
- export {
372
- SUPPORTED_SOURCE_TYPES,
373
- Writer
374
- };