styled-map-package-api 5.0.0-pre.3 → 5.0.0-pre.4

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 (94) hide show
  1. package/README.md +94 -0
  2. package/dist/download.d.ts +11 -21
  3. package/dist/fallbacks.d.ts +32 -0
  4. package/dist/from-mbtiles.d.ts +1 -3
  5. package/dist/index.d.ts +11 -24
  6. package/dist/reader.d.ts +28 -12
  7. package/dist/server.d.ts +23 -14
  8. package/dist/style-downloader.d.ts +13 -19
  9. package/dist/tile-downloader.d.ts +13 -23
  10. package/dist/types.d.ts +61 -0
  11. package/dist/utils/errors.d.ts +2 -4
  12. package/dist/utils/fetch.d.ts +3 -8
  13. package/dist/utils/file-formats.d.ts +3 -10
  14. package/dist/utils/geo.d.ts +17 -9
  15. package/dist/utils/mapbox.d.ts +8 -10
  16. package/dist/utils/misc.d.ts +3 -5
  17. package/dist/utils/streams.d.ts +6 -10
  18. package/dist/utils/style.d.ts +27 -16
  19. package/dist/utils/templates.d.ts +30 -25
  20. package/dist/validator.d.ts +66 -0
  21. package/dist/writer.d.ts +157 -4
  22. package/lib/download.js +125 -0
  23. package/lib/fallbacks.js +157 -0
  24. package/lib/from-mbtiles.js +131 -0
  25. package/lib/index.js +12 -0
  26. package/lib/reader.js +360 -0
  27. package/lib/server.js +222 -0
  28. package/lib/style-downloader.js +369 -0
  29. package/lib/tile-downloader.js +189 -0
  30. package/lib/types.ts +99 -0
  31. package/lib/utils/errors.js +24 -0
  32. package/lib/utils/fetch.js +104 -0
  33. package/lib/utils/file-formats.js +92 -0
  34. package/lib/utils/geo.js +97 -0
  35. package/lib/utils/mapbox.js +155 -0
  36. package/{dist/utils/misc.d.cts → lib/utils/misc.js} +9 -5
  37. package/lib/utils/streams.js +101 -0
  38. package/lib/utils/style.js +206 -0
  39. package/lib/utils/templates.js +165 -0
  40. package/lib/validator.js +789 -0
  41. package/lib/writer.js +652 -0
  42. package/package.json +30 -78
  43. package/dist/download.cjs +0 -100
  44. package/dist/download.d.cts +0 -63
  45. package/dist/download.js +0 -76
  46. package/dist/from-mbtiles.cjs +0 -127
  47. package/dist/from-mbtiles.d.cts +0 -14
  48. package/dist/from-mbtiles.js +0 -103
  49. package/dist/index.cjs +0 -46
  50. package/dist/index.d.cts +0 -24
  51. package/dist/index.js +0 -16
  52. package/dist/reader.cjs +0 -287
  53. package/dist/reader.d.cts +0 -67
  54. package/dist/reader.js +0 -259
  55. package/dist/server.cjs +0 -73
  56. package/dist/server.d.cts +0 -45
  57. package/dist/server.js +0 -49
  58. package/dist/style-downloader.cjs +0 -314
  59. package/dist/style-downloader.d.cts +0 -118
  60. package/dist/style-downloader.js +0 -290
  61. package/dist/tile-downloader.cjs +0 -156
  62. package/dist/tile-downloader.d.cts +0 -82
  63. package/dist/tile-downloader.js +0 -124
  64. package/dist/types-Bhn0-Ldk.d.cts +0 -201
  65. package/dist/types-Bhn0-Ldk.d.ts +0 -201
  66. package/dist/utils/errors.cjs +0 -41
  67. package/dist/utils/errors.d.cts +0 -18
  68. package/dist/utils/errors.js +0 -16
  69. package/dist/utils/fetch.cjs +0 -97
  70. package/dist/utils/fetch.d.cts +0 -50
  71. package/dist/utils/fetch.js +0 -63
  72. package/dist/utils/file-formats.cjs +0 -96
  73. package/dist/utils/file-formats.d.cts +0 -32
  74. package/dist/utils/file-formats.js +0 -70
  75. package/dist/utils/geo.cjs +0 -84
  76. package/dist/utils/geo.d.cts +0 -46
  77. package/dist/utils/geo.js +0 -56
  78. package/dist/utils/mapbox.cjs +0 -121
  79. package/dist/utils/mapbox.d.cts +0 -43
  80. package/dist/utils/mapbox.js +0 -91
  81. package/dist/utils/misc.cjs +0 -39
  82. package/dist/utils/misc.js +0 -13
  83. package/dist/utils/streams.cjs +0 -99
  84. package/dist/utils/streams.d.cts +0 -49
  85. package/dist/utils/streams.js +0 -73
  86. package/dist/utils/style.cjs +0 -126
  87. package/dist/utils/style.d.cts +0 -66
  88. package/dist/utils/style.js +0 -98
  89. package/dist/utils/templates.cjs +0 -124
  90. package/dist/utils/templates.d.cts +0 -79
  91. package/dist/utils/templates.js +0 -85
  92. package/dist/writer.cjs +0 -539
  93. package/dist/writer.d.cts +0 -4
  94. package/dist/writer.js +0 -516
@@ -1,79 +0,0 @@
1
- import * as type_fest from 'type-fest';
2
- import { d as GlyphRange, T as TileInfo, c as TileFormat } from '../types-Bhn0-Ldk.cjs';
3
- import '@maplibre/maplibre-gl-style-spec';
4
- import 'geojson';
5
-
6
- /**
7
- * @param {string} path
8
- * @returns
9
- */
10
- declare function getResourceType(path: string): "sprite" | "style" | "tile" | "glyph";
11
- /**
12
- * Determine the content type of a file based on its extension.
13
- *
14
- * @param {string} path
15
- */
16
- declare function getContentType(path: string): "application/json; charset=utf-8" | "application/x-protobuf" | "image/png" | "image/jpeg" | "image/webp" | "application/vnd.mapbox-vector-tile";
17
- /**
18
- * Get the filename for a tile, given the TileInfo
19
- *
20
- * @param {import("type-fest").SetRequired<import("../writer.js").TileInfo, 'format'>} tileInfo
21
- * @returns
22
- */
23
- declare function getTileFilename({ sourceId, z, x, y, format }: type_fest.SetRequired<TileInfo, "format">): string;
24
- /**
25
- * Get a filename for a sprite file, given the sprite id, pixel ratio and extension
26
- *
27
- * @param {{ id: string, pixelRatio: number, ext: '.json' | '.png'}} spriteInfo
28
- */
29
- declare function getSpriteFilename({ id, pixelRatio, ext }: {
30
- id: string;
31
- pixelRatio: number;
32
- ext: ".json" | ".png";
33
- }): string;
34
- /**
35
- * Get the filename for a glyph file, given the fontstack and range
36
- *
37
- * @param {object} options
38
- * @param {string} options.fontstack
39
- * @param {import("../writer.js").GlyphRange} options.range
40
- */
41
- declare function getGlyphFilename({ fontstack, range }: {
42
- fontstack: string;
43
- range: GlyphRange;
44
- }): string;
45
- /**
46
- * Get the URI template for the sprites in the style
47
- */
48
- declare function getSpriteUri(id?: string): string;
49
- /**
50
- * Get the URI template for tiles in the style
51
- *
52
- * @param {object} opts
53
- * @param {string} opts.sourceId
54
- * @param {import("../writer.js").TileFormat} opts.format
55
- * @returns
56
- */
57
- declare function getTileUri({ sourceId, format }: {
58
- sourceId: string;
59
- format: TileFormat;
60
- }): string;
61
- /**
62
- * Replaces variables in a string with values provided in an object. Variables
63
- * in the string are denoted by curly braces, e.g., {variableName}.
64
- *
65
- * @param {string} template - The string containing variables wrapped in curly braces.
66
- * @param {Record<string, string | number>} variables - An object where the keys correspond to variable names and values correspond to the replacement values.
67
- * @returns {string} The string with the variables replaced by their corresponding values.
68
- */
69
- declare function replaceVariables(template: string, variables: Record<string, string | number>): string;
70
- declare const URI_SCHEME: "smp";
71
- declare const URI_BASE: string;
72
- declare const VERSION_FILE: "VERSION";
73
- declare const FORMAT_VERSION: "1.0";
74
- declare const STYLE_FILE: "style.json";
75
- declare const SOURCES_FOLDER: "s";
76
- declare const FONTS_FOLDER: "fonts";
77
- declare const GLYPH_URI: string;
78
-
79
- export { FONTS_FOLDER, FORMAT_VERSION, GLYPH_URI, SOURCES_FOLDER, STYLE_FILE, URI_BASE, URI_SCHEME, VERSION_FILE, getContentType, getGlyphFilename, getResourceType, getSpriteFilename, getSpriteUri, getTileFilename, getTileUri, replaceVariables };
@@ -1,85 +0,0 @@
1
- const URI_SCHEME = "smp";
2
- const URI_BASE = URI_SCHEME + "://maps.v1/";
3
- const VERSION_FILE = "VERSION";
4
- const FORMAT_VERSION = "1.0";
5
- const STYLE_FILE = "style.json";
6
- const SOURCES_FOLDER = "s";
7
- const SPRITES_FOLDER = "sprites";
8
- const FONTS_FOLDER = "fonts";
9
- const TILE_FILE = SOURCES_FOLDER + "/{sourceId}/{z}/{x}/{y}{ext}";
10
- const SPRITE_FILE = SPRITES_FOLDER + "/{id}/sprite{pixelRatio}{ext}";
11
- const GLYPH_FILE = FONTS_FOLDER + "/{fontstack}/{range}.pbf.gz";
12
- const GLYPH_URI = URI_BASE + GLYPH_FILE;
13
- const pathToResouceType = (
14
- /** @type {const} */
15
- {
16
- [TILE_FILE.split("/")[0] + "/"]: "tile",
17
- [SPRITE_FILE.split("/")[0] + "/"]: "sprite",
18
- [GLYPH_FILE.split("/")[0] + "/"]: "glyph"
19
- }
20
- );
21
- function getResourceType(path) {
22
- if (path === "style.json") return "style";
23
- for (const [prefix, type] of Object.entries(pathToResouceType)) {
24
- if (path.startsWith(prefix)) return type;
25
- }
26
- throw new Error(`Unknown resource type for path: ${path}`);
27
- }
28
- function getContentType(path) {
29
- if (path.endsWith(".json")) return "application/json; charset=utf-8";
30
- if (path.endsWith(".pbf.gz") || path.endsWith(".pbf"))
31
- return "application/x-protobuf";
32
- if (path.endsWith(".png")) return "image/png";
33
- if (path.endsWith(".jpg")) return "image/jpeg";
34
- if (path.endsWith(".webp")) return "image/webp";
35
- if (path.endsWith(".mvt.gz") || path.endsWith(".mvt"))
36
- return "application/vnd.mapbox-vector-tile";
37
- throw new Error(`Unknown content type for path: ${path}`);
38
- }
39
- function getTileFilename({ sourceId, z, x, y, format }) {
40
- const ext = "." + format + (format === "mvt" ? ".gz" : "");
41
- return replaceVariables(TILE_FILE, { sourceId, z, x, y, ext });
42
- }
43
- function getSpriteFilename({ id, pixelRatio, ext }) {
44
- return replaceVariables(SPRITE_FILE, {
45
- id,
46
- pixelRatio: getPixelRatioString(pixelRatio),
47
- ext
48
- });
49
- }
50
- function getGlyphFilename({ fontstack, range }) {
51
- return replaceVariables(GLYPH_FILE, { fontstack, range });
52
- }
53
- function getSpriteUri(id = "default") {
54
- return URI_BASE + replaceVariables(SPRITE_FILE, { id, pixelRatio: "", ext: "" });
55
- }
56
- function getTileUri({ sourceId, format }) {
57
- const ext = "." + format + (format === "mvt" ? ".gz" : "");
58
- return URI_BASE + TILE_FILE.replace("{sourceId}", sourceId).replace("{ext}", ext);
59
- }
60
- function getPixelRatioString(pixelRatio) {
61
- return pixelRatio === 1 ? "" : `@${pixelRatio}x`;
62
- }
63
- function replaceVariables(template, variables) {
64
- return template.replace(/{(.*?)}/g, (match, varName) => {
65
- return varName in variables ? String(variables[varName]) : match;
66
- });
67
- }
68
- export {
69
- FONTS_FOLDER,
70
- FORMAT_VERSION,
71
- GLYPH_URI,
72
- SOURCES_FOLDER,
73
- STYLE_FILE,
74
- URI_BASE,
75
- URI_SCHEME,
76
- VERSION_FILE,
77
- getContentType,
78
- getGlyphFilename,
79
- getResourceType,
80
- getSpriteFilename,
81
- getSpriteUri,
82
- getTileFilename,
83
- getTileUri,
84
- replaceVariables
85
- };
package/dist/writer.cjs DELETED
@@ -1,539 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var writer_exports = {};
30
- __export(writer_exports, {
31
- SUPPORTED_SOURCE_TYPES: () => SUPPORTED_SOURCE_TYPES,
32
- Writer: () => Writer
33
- });
34
- module.exports = __toCommonJS(writer_exports);
35
- var import_maplibre_gl_style_spec = require("@maplibre/maplibre-gl-style-spec");
36
- var import_bbox = require("@turf/bbox");
37
- var import_filter_obj = require("filter-obj");
38
- var import_zip_writer = require("zip-writer");
39
- var import_file_formats = require('./utils/file-formats.cjs');
40
- var import_geo = require('./utils/geo.cjs');
41
- var import_misc = require('./utils/misc.cjs');
42
- var import_streams = require('./utils/streams.cjs');
43
- var import_style = require('./utils/style.cjs');
44
- var import_templates = require('./utils/templates.cjs');
45
- const SUPPORTED_SOURCE_TYPES = (
46
- /** @type {const} */
47
- [
48
- "raster",
49
- "vector",
50
- "geojson"
51
- ]
52
- );
53
- class Writer {
54
- #zipWriter = new import_zip_writer.ZipWriter();
55
- /** @type {Set<string>} */
56
- #addedFiles = /* @__PURE__ */ new Set();
57
- /** @type {Set<string>} */
58
- #fonts = /* @__PURE__ */ new Set();
59
- /** @type {Set<string>} */
60
- #addedSpriteIds = /* @__PURE__ */ new Set();
61
- /** @type {Map<string, SourceInfo>} */
62
- #sources = /* @__PURE__ */ new Map();
63
- /** @type {StyleSpecification} */
64
- #style;
65
- /** @type {ReadableStream<Uint8Array>} */
66
- #outputStream;
67
- /** @type {ReadableStreamDefaultController<Uint8Array>} */
68
- #outputController;
69
- /** @type {boolean} */
70
- #dedupe;
71
- /** @type {Map<string, string>} hash → first entry name */
72
- #tileHashes = /* @__PURE__ */ new Map();
73
- /** @type {Array<{ name: string, originalName: string }>} */
74
- #duplicateEntries = [];
75
- static SUPPORTED_SOURCE_TYPES = SUPPORTED_SOURCE_TYPES;
76
- /**
77
- * @param {any} style A v7 or v8 MapLibre style. v7 styles will be migrated to
78
- * v8. (There are currently no typescript declarations for v7 styles, hence
79
- * this is typed as `any` and validated internally)
80
- * @param {WriterOptions} [options]
81
- */
82
- constructor(style, { dedupe = false } = {}) {
83
- if (!style || !("version" in style)) {
84
- throw new Error("Invalid style");
85
- }
86
- if (style.version !== 7 && style.version !== 8) {
87
- throw new Error(`Invalid style: Unsupported version v${style.version}`);
88
- }
89
- if (!Array.isArray(style.layers)) {
90
- throw new Error("Invalid style: missing layers property");
91
- }
92
- const styleCopy = (0, import_misc.clone)(style);
93
- (0, import_maplibre_gl_style_spec.migrate)(styleCopy);
94
- const errors = (0, import_maplibre_gl_style_spec.validateStyleMin)(styleCopy);
95
- if (errors.length) {
96
- throw new AggregateError(errors, "Invalid style");
97
- }
98
- this.#style = styleCopy;
99
- this.#dedupe = dedupe;
100
- for (const [sourceId, source] of Object.entries(this.#style.sources)) {
101
- if (source.type !== "geojson") continue;
102
- this.#addSource(sourceId, source);
103
- }
104
- const zipReader = this.#zipWriter.readable.getReader();
105
- let outputController;
106
- this.#outputStream = new ReadableStream({
107
- start(controller) {
108
- outputController = controller;
109
- },
110
- async pull(controller) {
111
- try {
112
- const { done, value } = await zipReader.read();
113
- if (done) {
114
- controller.close();
115
- } else {
116
- controller.enqueue(
117
- /** @type {Uint8Array} */
118
- value
119
- );
120
- }
121
- } catch (err) {
122
- controller.error(err);
123
- }
124
- },
125
- cancel(reason) {
126
- zipReader.cancel(reason);
127
- }
128
- });
129
- this.#outputController = outputController;
130
- }
131
- /**
132
- * @returns {ReadableStream<Uint8Array>} Readable stream of the styled map package
133
- */
134
- get outputStream() {
135
- return this.#outputStream;
136
- }
137
- /**
138
- * Abort the output stream with an error. Call this if an error occurs during
139
- * writing to propagate the error to consumers of `outputStream`.
140
- *
141
- * @param {Error} reason
142
- */
143
- abort(reason) {
144
- this.#outputController.error(reason);
145
- }
146
- #getBounds() {
147
- let bounds;
148
- let maxzoom = 0;
149
- for (const { source } of this.#sources.values()) {
150
- if (source.type === "geojson") {
151
- if (isEmptyFeatureCollection(source.data)) continue;
152
- const bbox2 = get2DBBox(source.data.bbox);
153
- bounds = bounds ? (0, import_geo.unionBBox)([bounds, bbox2]) : [...bbox2];
154
- } else {
155
- if (source.maxzoom < maxzoom) continue;
156
- if (source.maxzoom === maxzoom) {
157
- bounds = bounds ? (0, import_geo.unionBBox)([bounds, source.bounds]) : source.bounds;
158
- } else {
159
- bounds = source.bounds;
160
- maxzoom = source.maxzoom;
161
- }
162
- }
163
- }
164
- return bounds;
165
- }
166
- #getMaxZoom() {
167
- let maxzoom = 0;
168
- for (const { source } of this.#sources.values()) {
169
- const sourceMaxzoom = (
170
- // For GeoJSON sources, the maxzoom is 16 unless otherwise set
171
- source.type === "geojson" ? source.maxzoom || 16 : source.maxzoom
172
- );
173
- maxzoom = Math.max(maxzoom, sourceMaxzoom);
174
- }
175
- return maxzoom;
176
- }
177
- /**
178
- * Add a source definition to the styled map package
179
- *
180
- * @param {string} sourceId
181
- * @param {InputSource} source
182
- * @returns {SourceInfo}
183
- */
184
- #addSource(sourceId, source) {
185
- const encodedSourceId = encodeSourceId(this.#sources.size);
186
- const tileSourceOverrides = {
187
- minzoom: 0,
188
- maxzoom: 0,
189
- bounds: (
190
- /** @type {import('./utils/geo.js').BBox} */
191
- [...import_geo.MAX_BOUNDS]
192
- ),
193
- tiles: (
194
- /** @type {string[]} */
195
- []
196
- )
197
- };
198
- let smpSource;
199
- switch (source.type) {
200
- case "raster":
201
- case "vector":
202
- smpSource = {
203
- ...(0, import_filter_obj.excludeKeys)(source, ["tiles", "url"]),
204
- ...tileSourceOverrides
205
- };
206
- break;
207
- case "geojson":
208
- smpSource = {
209
- ...source,
210
- maxzoom: 0,
211
- data: typeof source.data !== "string" ? (
212
- // Add a bbox property to the GeoJSON data if it doesn't already have one
213
- { ...source.data, bbox: source.data.bbox || (0, import_bbox.bbox)(source.data) }
214
- ) : (
215
- // If GeoJSON data is referenced by a URL, start with an empty FeatureCollection
216
- {
217
- type: "FeatureCollection",
218
- features: [],
219
- bbox: [0, 0, 0, 0]
220
- }
221
- )
222
- };
223
- break;
224
- }
225
- const sourceInfo = {
226
- source: smpSource,
227
- encodedSourceId
228
- };
229
- this.#sources.set(sourceId, sourceInfo);
230
- return sourceInfo;
231
- }
232
- /**
233
- * Add a tile to the styled map package
234
- *
235
- * @param {Source} tileData
236
- * @param {TileInfo} opts
237
- */
238
- async addTile(tileData, { z, x, y, sourceId, format }) {
239
- let sourceInfo = this.#sources.get(sourceId);
240
- if (!sourceInfo) {
241
- const source2 = this.#style.sources[sourceId];
242
- if (!source2) {
243
- throw new Error(`Source not referenced in style.json: ${sourceId}`);
244
- }
245
- if (source2.type !== "raster" && source2.type !== "vector") {
246
- throw new Error(`Unsupported source type: ${source2.type}`);
247
- }
248
- sourceInfo = this.#addSource(sourceId, source2);
249
- }
250
- const { source, encodedSourceId } = sourceInfo;
251
- if (source.type !== "raster" && source.type !== "vector") {
252
- throw new Error(`Unsupported source type: ${source.type}`);
253
- }
254
- if (!format) {
255
- ;
256
- [format, tileData] = await (0, import_file_formats.getTileFormatFromStream)(toWebStream(tileData));
257
- }
258
- if (!sourceInfo.format) {
259
- sourceInfo.format = format;
260
- } else if (sourceInfo.format !== format) {
261
- throw new Error(
262
- `Tile format mismatch for source ${sourceId}: expected ${sourceInfo.format}, got ${format}`
263
- );
264
- }
265
- const bbox2 = (0, import_geo.tileToBBox)({ z, x, y });
266
- if (z > source.maxzoom) {
267
- source.maxzoom = z;
268
- source.bounds = bbox2;
269
- } else if (z === source.maxzoom) {
270
- source.bounds = (0, import_geo.unionBBox)([source.bounds, bbox2]);
271
- }
272
- const name = (0, import_templates.getTileFilename)({ sourceId: encodedSourceId, z, x, y, format });
273
- if (this.#dedupe) {
274
- const data = await toUint8Array(tileData);
275
- const hash = await hashData(data);
276
- if (this.#addedFiles.has(name)) {
277
- throw new Error(`${name} already added`);
278
- }
279
- this.#addedFiles.add(name);
280
- const existingName = this.#tileHashes.get(hash);
281
- if (existingName) {
282
- this.#duplicateEntries.push({ name, originalName: existingName });
283
- return;
284
- }
285
- this.#tileHashes.set(hash, name);
286
- const readable = toWebStream(data);
287
- await this.#zipWriter.addEntry({ readable, name, store: true });
288
- return;
289
- }
290
- return this.#append(tileData, { name, store: true });
291
- }
292
- /**
293
- * Create a write stream for adding tiles to the styled map package
294
- *
295
- * @param {object} opts
296
- * @param {number} [opts.concurrency=16] The number of concurrent writes
297
- *
298
- * @returns
299
- */
300
- createTileWriteStream({ concurrency = 16 } = {}) {
301
- return (0, import_streams.writeStreamFromAsync)(this.addTile.bind(this), { concurrency });
302
- }
303
- /**
304
- * Add a sprite to the styled map package
305
- *
306
- * @param {object} options
307
- * @param {Source} options.json
308
- * @param {Source} options.png
309
- * @param {number} [options.pixelRatio]
310
- * @param {string} [options.id='default']
311
- * @returns {Promise<void>}
312
- */
313
- async addSprite({ json, png, pixelRatio = 1, id = "default" }) {
314
- this.#addedSpriteIds.add(id);
315
- const jsonName = (0, import_templates.getSpriteFilename)({ id, pixelRatio, ext: ".json" });
316
- const pngName = (0, import_templates.getSpriteFilename)({ id, pixelRatio, ext: ".png" });
317
- await Promise.all([
318
- this.#append(json, { name: jsonName }),
319
- this.#append(png, { name: pngName })
320
- ]);
321
- }
322
- /**
323
- * Add glyphs to the styled map package
324
- *
325
- * @param {Source} glyphData
326
- * @param {GlyphInfo} glyphInfo
327
- * @returns {Promise<void>}
328
- */
329
- addGlyphs(glyphData, { font: fontName, range }) {
330
- this.#fonts.add(fontName);
331
- const name = (0, import_templates.getGlyphFilename)({ fontstack: fontName, range });
332
- return this.#append(glyphData, { name });
333
- }
334
- /**
335
- * Create a write stream for adding glyphs to the styled map package
336
- *
337
- * @param {object} opts
338
- * @param {number} [opts.concurrency=16] The number of concurrent writes
339
- * @returns
340
- */
341
- createGlyphWriteStream({ concurrency = 16 } = {}) {
342
- return (0, import_streams.writeStreamFromAsync)(this.addGlyphs.bind(this), { concurrency });
343
- }
344
- /**
345
- * Finalize the styled map package and write the style to the archive.
346
- * This method must be called to complete the archive.
347
- * You must wait for your destination write stream to 'finish' before using the output.
348
- */
349
- async finish() {
350
- await this.#append(import_templates.FORMAT_VERSION, { name: import_templates.VERSION_FILE });
351
- this.#prepareStyle();
352
- const style = JSON.stringify(this.#style);
353
- await this.#append(style, { name: import_templates.STYLE_FILE });
354
- let entries = await this.#zipWriter.entries();
355
- if (this.#duplicateEntries.length > 0) {
356
- const entriesByName = new Map(entries.map((e) => [e.name, e]));
357
- for (const { name, originalName } of this.#duplicateEntries) {
358
- const original = entriesByName.get(originalName);
359
- if (!original) {
360
- throw new Error(`Original entry ${originalName} not found`);
361
- }
362
- entries.push({ ...original, name });
363
- }
364
- }
365
- const sortedEntries = sortEntries(entries);
366
- await this.#zipWriter.finalize({ entries: sortedEntries });
367
- }
368
- /**
369
- * Mutates the style object to prepare it for writing to the archive.
370
- * Deterministic: can be run more than once with the same result.
371
- */
372
- #prepareStyle() {
373
- if (this.#sources.size === 0) {
374
- throw new Error("Missing sources: add at least one source");
375
- }
376
- if (this.#style.glyphs && this.#fonts.size === 0) {
377
- throw new Error(
378
- "Missing fonts: style references glyphs but no fonts added"
379
- );
380
- }
381
- (0, import_style.replaceFontStacks)(this.#style, [...this.#fonts]);
382
- if (this.#style.glyphs) {
383
- this.#style.glyphs = import_templates.GLYPH_URI;
384
- }
385
- if (typeof this.#style.sprite === "string") {
386
- if (!this.#addedSpriteIds.has("default")) {
387
- throw new Error(
388
- "Missing sprite: style references sprite but none added"
389
- );
390
- }
391
- this.#style.sprite = (0, import_templates.getSpriteUri)();
392
- } else if (Array.isArray(this.#style.sprite)) {
393
- this.#style.sprite = this.#style.sprite.map(({ id }) => {
394
- if (!this.#addedSpriteIds.has(id)) {
395
- throw new Error(
396
- `Missing sprite: style references sprite ${id} but none added`
397
- );
398
- }
399
- return { id, url: (0, import_templates.getSpriteUri)(id) };
400
- });
401
- }
402
- this.#style.sources = {};
403
- for (const [sourceId, { source, encodedSourceId, format = "mvt" }] of this.#sources) {
404
- if (source.type === "geojson" && isEmptyFeatureCollection(source.data)) {
405
- continue;
406
- }
407
- this.#style.sources[sourceId] = source;
408
- if (!("tiles" in source)) continue;
409
- source.tiles = [(0, import_templates.getTileUri)({ sourceId: encodedSourceId, format })];
410
- }
411
- this.#style.layers = this.#style.layers.filter(
412
- (layer) => !("source" in layer) || !!this.#style.sources[layer.source]
413
- );
414
- const metadata = this.#style.metadata || (this.#style.metadata = {});
415
- const bounds = this.#getBounds();
416
- if (bounds) {
417
- metadata["smp:bounds"] = bounds;
418
- const [w, s, e, n] = bounds;
419
- this.#style.center = [w + (e - w) / 2, s + (n - s) / 2];
420
- }
421
- metadata["smp:maxzoom"] = this.#getMaxZoom();
422
- metadata["smp:sourceFolders"] = {};
423
- for (const [sourceId, { encodedSourceId }] of this.#sources) {
424
- metadata["smp:sourceFolders"][sourceId] = encodedSourceId;
425
- }
426
- this.#style.zoom = Math.max(0, this.#getMaxZoom() - 2);
427
- }
428
- /**
429
- *
430
- * @param {Source} source
431
- * @param {{ name: string, store?: boolean }} options
432
- * @returns {Promise<void>}
433
- */
434
- async #append(source, { name, store = false }) {
435
- if (this.#addedFiles.has(name)) {
436
- throw new Error(`${name} already added`);
437
- }
438
- this.#addedFiles.add(name);
439
- const readable = toWebStream(source);
440
- await this.#zipWriter.addEntry({ readable, name, store });
441
- }
442
- }
443
- function encodeSourceId(sourceIndex) {
444
- return sourceIndex.toString(36);
445
- }
446
- function toWebStream(source) {
447
- if (typeof source === "string") {
448
- const bytes = new TextEncoder().encode(source);
449
- return new ReadableStream({
450
- start(controller) {
451
- controller.enqueue(bytes);
452
- controller.close();
453
- }
454
- });
455
- }
456
- if (source instanceof Uint8Array) {
457
- return new ReadableStream({
458
- start(controller) {
459
- controller.enqueue(
460
- new Uint8Array(source.buffer, source.byteOffset, source.byteLength)
461
- );
462
- controller.close();
463
- }
464
- });
465
- }
466
- return (
467
- /** @type {ReadableStream<Uint8Array>} */
468
- source
469
- );
470
- }
471
- function isEmptyFeatureCollection(data) {
472
- return data.type === "FeatureCollection" && data.features.length === 0;
473
- }
474
- function get2DBBox(bbox2) {
475
- if (bbox2.length === 4) return bbox2;
476
- return [bbox2[0], bbox2[1], bbox2[3], bbox2[4]];
477
- }
478
- async function toUint8Array(source) {
479
- if (source instanceof Uint8Array) return source;
480
- if (typeof source === "string") return new TextEncoder().encode(source);
481
- const reader = (
482
- /** @type {ReadableStream<Uint8Array>} */
483
- source.getReader()
484
- );
485
- const chunks = [];
486
- let totalLength = 0;
487
- while (true) {
488
- const { done, value } = await reader.read();
489
- if (done) break;
490
- chunks.push(value);
491
- totalLength += value.byteLength;
492
- }
493
- const result = new Uint8Array(totalLength);
494
- let offset = 0;
495
- for (const chunk of chunks) {
496
- result.set(chunk, offset);
497
- offset += chunk.byteLength;
498
- }
499
- return result;
500
- }
501
- async function hashData(data) {
502
- let c = globalThis.crypto;
503
- if (!c) {
504
- c = (await import("node:crypto")).webcrypto;
505
- }
506
- const buf = await c.subtle.digest("SHA-256", data);
507
- return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
508
- }
509
- function sortEntries(entries) {
510
- return [...entries].sort((a, b) => {
511
- if (a.name === import_templates.VERSION_FILE) return -1;
512
- if (b.name === import_templates.VERSION_FILE) return 1;
513
- if (a.name === import_templates.STYLE_FILE) return -1;
514
- if (b.name === import_templates.STYLE_FILE) return 1;
515
- const foldersA = a.name.split("/");
516
- const foldersB = b.name.split("/");
517
- const aIsFirst = foldersA[0] === import_templates.FONTS_FOLDER && foldersA[2] === "0-255.pbf.gz";
518
- const bIsFirst = foldersB[0] === import_templates.FONTS_FOLDER && foldersB[2] === "0-255.pbf.gz";
519
- if (aIsFirst && bIsFirst)
520
- return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
521
- if (aIsFirst) return -1;
522
- if (bIsFirst) return 1;
523
- if (foldersA[0] === import_templates.SOURCES_FOLDER && foldersB[0] !== import_templates.SOURCES_FOLDER)
524
- return -1;
525
- if (foldersB[0] === import_templates.SOURCES_FOLDER && foldersA[0] !== import_templates.SOURCES_FOLDER)
526
- return 1;
527
- if (foldersA[0] === import_templates.SOURCES_FOLDER && foldersB[0] === import_templates.SOURCES_FOLDER) {
528
- const zoomA = +foldersA[2];
529
- const zoomB = +foldersB[2];
530
- return zoomA - zoomB;
531
- }
532
- return 0;
533
- });
534
- }
535
- // Annotate the CommonJS export names for ESM import in node:
536
- 0 && (module.exports = {
537
- SUPPORTED_SOURCE_TYPES,
538
- Writer
539
- });