@basemaps/server 6.32.0 → 6.32.1
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/CHANGELOG.md +8 -0
- package/bin/basemaps-server.cjs +2 -2
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,14 @@
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
5
|
|
|
6
|
+
## [6.32.1](https://github.com/linz/basemaps/compare/v6.32.0...v6.32.1) (2022-07-28)
|
|
7
|
+
|
|
8
|
+
**Note:** Version bump only for package @basemaps/server
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
6
14
|
# [6.32.0](https://github.com/linz/basemaps/compare/v6.31.0...v6.32.0) (2022-07-28)
|
|
7
15
|
|
|
8
16
|
**Note:** Version bump only for package @basemaps/server
|
package/bin/basemaps-server.cjs
CHANGED
|
@@ -805,11 +805,11 @@ PARAMETER["false_easting",1600000],
|
|
|
805
805
|
PARAMETER["false_northing",10000000],
|
|
806
806
|
UNIT["metre",1,
|
|
807
807
|
AUTHORITY["EPSG","9001"]],
|
|
808
|
-
AUTHORITY["EPSG","2193"]]`;Ed.default.defs(Ut.Nztm2000.toEpsgString(),mq);Ed.default.defs(Ut.Citm2000.toEpsgString(),pq);var X9=new Map;function $0e(t){return t==null?null:typeof t=="number"?t:"code"in t?t.code:"projection"in t?t.projection.code:null}var $a=class{constructor(e){this.epsg=e;try{this.projection=(0,Ed.default)(e.toEpsgString(),Ut.Wgs84.toEpsgString())}catch(r){throw new mn(`Failed to create projection: ${e.toEpsgString()}, ${Ut.Wgs84.toEpsgString()}`,500,r)}}static define(e,r){if(X9.get(e.code)!=null)throw new Error("Duplicate projection definition: "+e.toEpsgString());Ed.default.defs(e.toEpsgString(),r)}static get(e){let r=this.tryGet(e);if(r==null)throw new Error(`Invalid projection: ${e}`);return r}static tryGet(e){let r=$0e(e);if(r==null)return null;let i=X9.get(r);if(i!=null)return i;let n=Ut.tryGet(r);return n==null||Ed.default.defs(n.toEpsgString())==null?null:(i=new $a(n),X9.set(r,i),i)}projectMultipolygon(e,r){if(r.epsg.code===this.epsg.code)return e;let{toWgs84:i}=this,{fromWgs84:n}=r;return e.map(s=>s.map(a=>a.map(o=>n(i(o)))))}get toWgs84(){return this.projection.forward}get fromWgs84(){return this.projection.inverse}boundsToWgs84BoundingBox(e){let r=this.toWgs84([e.x,e.y]),i=this.toWgs84([e.x+e.width,e.y+e.height]);return[r[0],r[1],i[0],i[1]]}boundsToGeoJsonFeature(e,r={}){let i=[e.x,e.y],n=[e.x+e.width,e.y],s=[e.x,e.y+e.height],a=[e.x+e.width,e.y+e.height],o=jv([[[i,s,a,n,i]]],this.toWgs84),u=o.length===1?fq(o[0],r):hq(o,r);return u.bbox=this.boundsToWgs84BoundingBox(e),u}toGeoJson(e){return{type:"FeatureCollection",features:e.map(r=>this.boundsToGeoJsonFeature(r,{name:r.name}))}}static getTiffResZoom(e,r,i=1){let n=0;for(;n<e.zooms.length;++n)if(e.pixelScale(n)<=r*i)return n;if(n===e.zooms.length)return n-1;throw new Error("ResZoom not found")}static tileToWgs84Bbox(e,r){let i=e.tileToSource(r),n=e.tileToSource({x:r.x+1,y:r.y+1,z:r.z}),s=this.get(e),[a,o]=s.toWgs84([i.x,n.y]),[u,f]=s.toWgs84([n.x,i.y]);return[a,o,u,f]}static tileCenterToLatLon(e,r){let i=e.tileToSource({x:r.x+.5,y:r.y+.5,z:r.z}),[n,s]=this.get(e).toWgs84([i.x,i.y]);return $a.wrapLatLon(s,n)}static wrapLatLon(e,r){let i={lat:e,lon:r},n=Math.floor(Math.abs(e)/90)%4,s=e>0?90:-90,a=e%90;switch(n){case 0:i.lat=a;break;case 1:i.lat=s-a,i.lon+=180;break;case 2:i.lat=-a,i.lon+=180;break;case 3:i.lat=-s+a;break}return(i.lon>180||i.lon<-180)&&(i.lon-=Math.floor((i.lon+180)/360)*360),i}static findAlignmentLevels(e,r,i){return Math.max(0,this.getTiffResZoom(e,i,2)-r.z)}static getImagePixelWidth(e,r,i){let n=e.tileToSource(r),s=e.tileToSource({x:r.x+1,y:r.y+1,z:r.z});return Math.round((s.x-n.x)/e.pixelScale(i))*2}};function gq(t){return t==null||typeof t=="string"?!1:"roleArn"in t&&typeof t.roleArn=="string"}var kq=at(qe(),1),Oq=at(Y9(),1);function xd(t){return"promise"in t?t.promise():t}function Cd(t,e){return lu(t)?typeof t.statusCode!="number"?new mn(e,500,t):new mn(e,t.statusCode,t):new mn(e,500,t)}var us=class extends gi{constructor(e,r,i){super(),this.type=us.type,this.protocol="s3",this.chunkSize=us.DefaultChunkSize,this.maxChunkCount=us.DefaultMaxChunkCount,this.bucket=e,this.key=r,this.remote=i}get uri(){return this.name}get name(){return`s3://${this.bucket}/${this.key}`}static isSource(e){return e.type===us.type}get size(){return this._size?this._size:(this._size=Promise.resolve().then(async()=>(await xd(this.remote.headObject({Bucket:this.bucket,Key:this.key}))).ContentLength||-1),this._size)}static fromUri(e,r){let i=mo(e);return i==null||i.key==null||i.protocol!=="s3"?null:new us(i.bucket,i.key,r)}async fetchBytes(e,r){let i=this.toRange(e,r);try{let n=await this.remote.getObject({Bucket:this.bucket,Key:this.key,Range:i}).promise();if(!Buffer.isBuffer(n.Body))throw new Error("Failed to fetch object, Body is not a buffer");n.ContentRange!=null&&this._size==null&&(this._size=Promise.resolve(this.parseContentRange(n.ContentRange)));let s=n.Body;return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}catch(n){throw Cd(n,`Failed to fetch ${this.name} ${i}`)}}};us.type="aws:s3";us.DefaultChunkSize=64*1024;us.DefaultMaxChunkCount=32;var ls=class{constructor(e){this.protocol=ls.protocol,this.s3=e}source(e){let r=us.fromUri(e,this.s3);if(r==null)throw new Error(`Failed to create aws s3 source from uri: ${e}`);return r}static is(e){return e.protocol===ls.protocol}static isPath(e){return e==null?!1:e.startsWith("s3://")}async*list(e,r){for await(let i of this.details(e,r))yield i.path}async*details(e,r){let i=mo(e);if(i==null)return;let n,s=r?.recursive===!1?"/":void 0,a=i.bucket,o=i.key,u=0;try{for(;;){u++;let f=await xd(this.s3.listObjectsV2({Bucket:a,Prefix:o,ContinuationToken:n,Delimiter:s}));if(f.CommonPrefixes!=null)for(let l of f.CommonPrefixes)l.Prefix!=null&&(yield{path:`s3://${a}/${l.Prefix}`,isDirectory:!0});if(f.Contents!=null)for(let l of f.Contents)l.Key!=null&&(yield{path:`s3://${a}/${l.Key}`,size:l.Size});if(!f.IsTruncated)break;if(u>=ls.MaxListCount)throw new Error(`Failed to finish listing within ${ls.MaxListCount} list attempts`);n=f.NextContinuationToken}}catch(f){throw Cd(f,`Failed to list: "${e}"`)}}async read(e){let r=mo(e);if(r==null||r.key==null)throw new Error(`Failed to read: "${e}"`);try{return(await this.s3.getObject({Bucket:r.bucket,Key:r.key}).promise()).Body}catch(i){throw Cd(i,`Failed to read: "${e}"`)}}async write(e,r,i){let n=mo(e);if(n==null||n.key==null)throw new Error(`Failed to write: "${e}"`);try{await xd(this.s3.upload({Bucket:n.bucket,Key:n.key,Body:r,ContentEncoding:i?.contentEncoding,ContentType:i?.contentType}))}catch(s){throw Cd(s,`Failed to write: "${e}"`)}}exists(e){return this.head(e).then(r=>r!=null)}stream(e){let r=mo(e);if(r==null||r.key==null)throw new Error(`S3: Unable to read "${e}"`);return this.s3.getObject({Bucket:r.bucket,Key:r.key}).createReadStream()}async head(e){let r=mo(e);if(r==null||r.key==null)throw new Error(`Failed to exists: "${e}"`);try{return{size:(await xd(this.s3.headObject({Bucket:r.bucket,Key:r.key}))).ContentLength,path:e}}catch(i){if(lu(i)&&i.code==="NotFound")return null;throw Cd(i,`Failed to exists: "${e}"`)}}};ls.protocol="s3";ls.MaxListCount=100;var cs=class{static fsFromRole(e,r,i){if(typeof e=="object")return cs.fsFromRole(e.roleArn,e.externalId,e.durationSeconds);let n=cs.role(e,r,i);return new ls(new Oq.default({credentials:n}))}static role(e,r,i){i=i??cs.DefaultRoleDurationSeconds;let n=`role::${e}::${r}::${i}`,s=cs.cache.get(n);return s==null&&(s=new kq.default.ChainableTemporaryCredentials({params:{RoleArn:e,ExternalId:r,RoleSessionName:"fsa-"+Math.random().toString(32)+"-"+Date.now(),DurationSeconds:i}}),cs.cache.set(n,s)),s}};cs.DefaultRoleDurationSeconds=3600;cs.cache=new Map;var Mq=at(Y9(),1),Lq=require("util"),Hv=require("zlib");var V0e=(0,Lq.promisify)(Hv.gunzip),bi=$r;bi.readJson=async function(e){let r=await this.read(e);return e.endsWith(".gz")?JSON.parse((await V0e(r)).toString()):JSON.parse(r.toString())};bi.writeJson=async function(e,r){let i=Buffer.from(JSON.stringify(r,void 0,2));if(e.endsWith(".gz")){let n=(0,Hv.createGzip)();return n.end(i),this.write(e,n)}else return this.write(e,i)};bi.configure=function(e){if(e.type!=="s3"||!gq(e))return;let r=mo(e.path);if(r==null)throw new Error("Failed to parse URI: "+e.path);let i=`s3://${r.bucket}/`;this.register(i,cs.fsFromRole(e.roleArn,e.externalId))};bi.register("s3://",new ls(new Mq.default));function Z9(t){return t[0].toUpperCase()+t.slice(1).replace(/_(\d+)-(\d+)m/g," $1.$2m").replace(/_/g," ")}function Dq(t){let e=/(?:^|\D)(\d{4})(?:-(\d{2}))?(?:$|\D)/g,r=[];for(let i=e.exec(t);i!=null;i=e.exec(t))r.push(parseInt(i[1])),i[2]!=null&&r.push(parseInt(i[1].slice(0,2)+i[2]));return r.length===0?[-1,-1]:(r.sort(),[r[0],r[r.length-1]+1])}process.env.AWS_NODEJS_CONNECTION_REUSE_ENABLED="1";Ke.setConfigProvider(new Fc(Yc.TileMetadata.TableName));var ex=require("child_process");function tx(){return{version:(0,ex.execFileSync)("git",["describe","--tags","--always","--match","v*"]).toString().trim(),hash:(0,ex.execFileSync)("git",["rev-parse","HEAD"]).toString().trim()}}var fF=at(NB(),1);cF().install();var hF=at(uu(),1),p4,m4,g4={package:"@basemaps/cli",version:(p4="v6.32.0")!==null&&p4!==void 0?p4:tx().version,hash:(m4="cf9e8d4e61f7634acf51b9a837bbab6889761f1b")!==null&&m4!==void 0?m4:tx().hash},Eve=hF.ulid(),Nb=class extends fF.CommandLineParser{constructor(e){super(e),this.verbose=this.defineFlagParameter({parameterLongName:"--verbose",parameterShortName:"-v",description:"Show extra logging detail"}),this.extraVerbose=this.defineFlagParameter({parameterLongName:"--vv",parameterShortName:"-V",description:"Show extra extra logging detail"}),this.toolName=e.toolFilename,this.toolDescription=e.toolDescription}onExecute(){this.verbose.value?os.get().level="debug":this.extraVerbose.value?os.get().level="trace":os.get().level="info";let e=os.get().child({id:Eve});return e.info({package:g4,cli:this.toolName},"Cli:Start"),os.set(e),super.onExecute()}onDefineParameters(){}run(){this.executeWithoutErrorHandling().catch(e=>{e instanceof g1?os.get().fatal(e.obj,e.message):os.get().fatal({err:e,cli:this.toolName},"Cli:Failed"),process.exit(1)})}};var sj=at(JE(),1);var Tl="application/json",Xe;(function(t){t.CacheControl="Cache-Control",t.ContentEncoding="Content-Encoding",t.ContentType="Content-Type",t.Cors="Access-Control-Allow-Origin",t.ETag="ETag",t.IfNoneMatch="If-None-Match",t.Server="Server",t.ServerTiming="Server-Timing"})(Xe||(Xe={}));var jd;(function(t){t.CloudfrontId="X-Amz-Cf-Id",t.TraceId="X-Amzn-Trace-Id"})(jd||(jd={}));var za;(function(t){t.CorrelationId="X-LINZ-Correlation-Id",t.RequestId="X-LINZ-Request-Id"})(za||(za={}));var wf=class{constructor(){if(this.timers=new Map,typeof process<"u"&&typeof process.hrtime.bigint=="function"){let e=BigInt(1e6);this.getTime=()=>Number(process.hrtime.bigint()/e)}else typeof typeof performance<"u"?this.getTime=()=>performance.now():this.getTime=()=>Date.now()}start(e){let r=this.timers.get(e);if(r!=null&&r.duration==null)throw new Error(`Duplicate startTime for "${e}"`);this.timers.set(e,{start:this.getTime()})}end(e){let r=this.timers.get(e);if(r==null)throw new Error(`Missing startTime information for "${e}"`);let i=this.getTime()-r.start;return r.duration=i,i}get metrics(){if(this.timers.size===0)return;let e={};for(let[r,i]of this.timers.entries())i.duration!=null&&(e[r]=i.duration);return e}get unfinished(){let e=[];for(let[r,i]of this.timers.entries())i.duration==null&&e.push(r);if(e.length!==0)return e}};var dF=at(uu(),1);function $i(t){return!(typeof t!="object"||t==null)}var _f=class{constructor(e,r,i){this.logContext={},this.timer=new wf,this.headers=new Map,this.context=r,this.event=e,this.id=(0,dF.ulid)(),this.log=i,this.timer=new wf,this.log=i.child({id:this.id,aws:{lambdaId:r.awsRequestId}})}set(e,r){r==null&&(r=void 0),this.logContext[e]=r}toResponse(e){return e?.body}};var mF=require("url");var pF=at(uu(),1);var Rs=class extends _f{constructor(e,r,i){var n;super(e,r,i),this.headers=new Map,this.correlationId=(n=this.header(za.CorrelationId))!==null&&n!==void 0?n:pF.ulid(),this.set("correlationId",this.correlationId)}header(e){return this._isHeadersLoaded!==!0&&(this.loadHeaders(),this._isHeadersLoaded=!0),this.headers.get(e.toLowerCase())}json(){var e;if(this.header(Xe.ContentType)!==Tl)throw new Error(`Invalid Content-Type: "${this.header("content-type")}"`);if(this.body==null)throw new Error("Cannot parse empty body as JSON");try{return this.isBase64Encoded?JSON.parse(Buffer.from((e=this.body)!==null&&e!==void 0?e:"","base64").toString()):JSON.parse(this.body)}catch{throw new Error("Body is not a JSON object")}}get query(){return this._query==null&&(this._query=this.loadQueryString()),this._query}get url(){return this.path}};var zd=class extends Rs{static is(e){return $i(e)&&$i(e.requestContext)&&$i(e.requestContext.elb)}toResponse(e){return{statusCode:e.status,statusDescription:e.statusDescription,body:e.body,headers:this.toHeaders(e.headers),isBase64Encoded:e.isBase64Encoded}}toHeaders(e){if(e.size===0)return;let r={};for(let i of e)r[i[0]]=i[1];return r}loadHeaders(){if(this.event.headers!=null)for(let[e,r]of Object.entries(this.event.headers))r!=null&&this.headers.set(e.toLowerCase(),r)}loadQueryString(){let e=new mF.URLSearchParams;if(this.event.queryStringParameters==null)return e;for(let[r,i]of Object.entries(this.event.queryStringParameters))e.append(r.toLowerCase(),i??"true");return e}get method(){return this.event.httpMethod.toUpperCase()}get path(){return this.event.path}get body(){return this.event.body}get isBase64Encoded(){return this.event.isBase64Encoded}};var gF=require("url");var Io=class extends Rs{static is(e){return!(!$i(e)||!$i(e.requestContext)||typeof e.requestContext.apiId!="string"||typeof e.requestContext.resourceId!="string"||typeof e.requestContext.httpMethod!="string")}toResponse(e){return{statusCode:e.status,body:e.body,headers:Io.toHeaders(e),isBase64Encoded:e.isBase64Encoded}}static toHeaders(e){if(e.headers.size===0)return;let r={};for(let i of e.headers)r[i[0]]=i[1];return r}loadHeaders(){if(this.event.headers!=null)for(let[e,r]of Object.entries(this.event.headers))r!=null&&this.headers.set(e.toLowerCase(),r)}loadQueryString(){let e=new gF.URLSearchParams;if(this.event.multiValueQueryStringParameters==null)return e;for(let[r,i]of Object.entries(this.event.multiValueQueryStringParameters))if(i!=null)for(let n of i)e.append(r.toLowerCase(),n);return e}get path(){return this.event.path}get method(){return this.event.httpMethod.toUpperCase()}get body(){return this.event.body}get isBase64Encoded(){return this.event.isBase64Encoded}};var y4=require("url");var Ud=class extends Rs{static is(e){if(!$i(e)||!Array.isArray(e.Records))return!1;let r=e.Records[0];return $i(r)?$i(r.cf):!1}toResponse(e){if(e.status===100&&this.event!=null){let r=this.event.Records[0].cf.request;for(let[i,n]of e.headers)r.headers[i.toLowerCase()]=[{key:i,value:String(n)}];return this.event.Records[0].cf.request}return{status:String(e.status),statusDescription:e.statusDescription,body:e.body,headers:this.toHeaders(e),bodyEncoding:"text"}}toHeaders(e){if(e.headers.size===0)return{};let r={};for(let i of e.headers)r[i[0]]=[{key:i[0],value:String(i[1])}];return r}loadHeaders(){var e;for(let[r,i]of Object.entries(this.event.Records[0].cf.request.headers))this.headers.set(r.toLowerCase(),(e=i[0])===null||e===void 0?void 0:e.value)}loadQueryString(){let e=this.event.Records[0].cf.request.querystring;return e==null?new y4.URLSearchParams:new y4.URLSearchParams(e.toLowerCase())}get path(){return this.event.Records[0].cf.request.uri}get method(){return this.event.Records[0].cf.request.method.toUpperCase()}get body(){let e=this.event.Records[0].cf.request.body;return e==null?null:e.data}get isBase64Encoded(){var e;return((e=this.event.Records[0].cf.request.body)===null||e===void 0?void 0:e.encoding)==="base64"}};var Be=class{constructor(e,r,i){if(this._body=null,this.headers=new Map,this.status=e,this.statusDescription=r,i!=null)for(let n of Object.keys(i))this.header(n,i[n])}static is(e){return e instanceof Be}static ok(e=200,r="Ok"){return new Be(e,r)}header(e,r){let i=e.toLowerCase();if(r==null)return this.headers.get(i);this.headers.set(i,r)}get isBase64Encoded(){return Buffer.isBuffer(this._body)}json(e){return this.buffer(JSON.stringify(e),Tl),this}buffer(e,r=Tl){return this.header(Xe.ContentType,r),this._body=e,this}get body(){return this._body==null?(this.header(Xe.ContentType,Tl),JSON.stringify({id:this.header(za.RequestId),status:this.status,message:this.statusDescription,correlationId:this.header(za.CorrelationId)})):Buffer.isBuffer(this._body)?this._body.toString("base64"):this._body}};var tj=at(ej(),1);var Fb=class{constructor(){this.hooks={request:[],response:[]},this.router=(0,tj.default)({defaultRoute:()=>new Be(404,"Not found")})}register(e,r,i){this.router.on(e,r,async(n,s,a)=>n instanceof Rs?(n.params=a,jb(n,i)):new Be(500,"Internal server error"))}hook(e,r){this.hooks[e].push(r)}get(e,r){return this.register("GET",e,r)}post(e,r){return this.register("POST",e,r)}delete(e,r){return this.register("DELETE",e,r)}options(e,r){return this.register("OPTIONS",e,r)}patch(e,r){return this.register("PATCH",e,r)}head(e,r){return this.register("HEAD",e,r)}put(e,r){return this.register("PUT",e,r)}async after(e,r){try{for(let i of this.hooks.response)await i(e,r)}catch(i){return Be.is(i)?i:(e.set("err",i),new Be(500,"Internal Server Error"))}return r}async handle(e){for(let i of this.hooks.request){let n=await jb(e,i);if(n)return this.after(e,n)}let r=await this.router.lookup(e,null);return r?this.after(e,r):this.after(e,new Be(404,"Not found"))}};var rj=require("url");var Il=class extends Rs{toResponse(e){return{statusCode:e.status,body:e.body,headers:Io.toHeaders(e),isBase64Encoded:e.isBase64Encoded}}loadHeaders(){for(let[e,r]of Object.entries(this.event.headers))this.headers.set(e.toLowerCase(),r)}loadQueryString(){return new rj.URLSearchParams(this.event.rawQueryString)}get method(){return this.event.requestContext.http.method.toUpperCase()}get path(){return this.event.rawPath}get isBase64Encoded(){return this.event.isBase64Encoded}get body(){return this.event.body==null?null:this.event.body}static is(e){return!(!$i(e)||!$i(e.requestContext)||!$i(e.requestContext.http))}};var aj="v6.32.0",Jve="cf9e8d4e61f7634acf51b9a837bbab6889761f1b",nj={version:aj,hash:Jve};async function jb(t,e){t.timer.timers.has("lambda")||t.timer.start("lambda");try{return await e(t)}catch(r){return Be.is(r)?r:(t.set("err",r),new Be(500,"Internal Server Error"))}}function ij(t,e){let r=200;Be.is(e)&&(r=e.status,t.set("description",e.statusDescription)),t.set("status",r),t.timer.timers.size>0&&t.set("metrics",t.timer.metrics),nj.hash&&t.set("package",nj);let i=t.timer.timers.has("lambda")?t.timer.end("lambda"):0;return t.set("unfinished",t.timer.unfinished),t.set("duration",i),t.set("@type","report"),r>499?t.log.error(t.logContext,"Lambda:Done"):r>399?t.log.warn(t.logContext,"Lambda:Done"):t.log.info(t.logContext,"Lambda:Done"),e}function Yve(t){let e={rejectOnError:!0,tracePercent:0,...t};if(isNaN(e.tracePercent)||e.tracePercent>1)throw new Error("tracePercent is not between 0-1 :"+e.tracePercent);return e}var Bi=class{static request(e,r,i){if(zd.is(e))return new zd(e,r,i);if(Il.is(e))return new Il(e,r,i);if(Io.is(e))return new Io(e,r,i);if(Ud.is(e))return new Ud(e,r,i);throw new Error("Request is not a a ALB, ApiGateway or Cloudfront event")}static handler(e,r,i){let n=Yve(r);function s(a,o,u){let f=new _f(a,o,i??Bi.Logger);n.tracePercent>0&&Math.random()<n.tracePercent&&(f.log.level="trace"),process.env.TRACE_LAMBDA&&(f.log.level="trace"),f.log.trace({event:a},"Lambda:Start");let l=o.awsRequestId;f.set("aws",{lambdaId:l}),jb(f,e).then(h=>{if(ij(f,h),Be.is(h)&&n.rejectOnError){if(f.logContext.err)return u(f.logContext.err);if(h.status>399)return u(f.toResponse(h))}return u(null,f.toResponse(h))})}return s}static http(e){let r=new Fb;function i(n,s,a){let o=Bi.request(n,s,e??Bi.Logger),u=o.header(jd.CloudfrontId),f=o.header(jd.TraceId),l=s.awsRequestId;(u||f||l)&&o.set("aws",{cloudFrontId:u,traceId:f,lambdaId:l}),o.set("method",o.method),o.set("path",o.path),r.handle(o).then(h=>{var d;h.status===500&&h.header(Xe.CacheControl,"no-store"),h.header(za.RequestId,o.id),h.header(za.CorrelationId,o.correlationId);let c=(d=o.timer.metrics)===null||d===void 0?void 0:d.lambda;c!=null&&h.header(Xe.ServerTiming,`total;dur=${c}`),!h.isBase64Encoded&&h.header(Xe.ContentType)==null&&h.header(Xe.ContentType,Tl),Bi.ServerName&&h.header(Xe.Server,`${Bi.ServerName}-${aj}`),ij(o,h),a(null,o.toResponse(h))})}return i.router=r,i}};Bi.Logger=(0,sj.default)();Bi.ServerName="linz";var Nr={key(t){return Buffer.isBuffer(t)||typeof t=="string"?al(t):al(JSON.stringify(t))},isNotModified(t,e){let r=t.header(Xe.IfNoneMatch);return r!=null&&r.indexOf(e)>-1?(t.set("cache",{hit:!0,match:r}),!0):!1}};var Ot=()=>new Be(404,"Not Found"),Rn=()=>new Be(304,"Not modified");var Zve=.2,Xd=class{constructor(e){this.tms=e}async tile(e,r,i,n){let s=[];for(let a of e){let o=this.getTiles(a,r,i,n);o!=null&&(s=s.concat(o))}return s}getRasterTiffIntersection(e,r,i,n){let s=this.tms.tileToPixels(r,i),a=new xt(s.x,s.y,this.tms.tileSize,this.tms.tileSize),o=e.images[0].bbox,u=this.tms.sourceToPixels(o[0],o[3],n),f=this.tms.sourceToPixels(o[2],o[1],n),l=xt.fromUpperLeftLowerRight(u,f),h=l.intersection(a);return h==null?null:{tiff:l,intersection:h,tile:a}}createComposition(e,r,i,n,s){let a=xt.fromJson(e.getTileBounds(r,i)),o=a.scale(n,n).add(s.tiff).round(Zve),u=o.intersection(s.tile);if(u==null)return null;let f=u.subtract(o);if(f.height<.5||f.width<.5)return null;let l=o.subtract(s.tile),h={tiff:e.tif,source:{x:r,y:i,imageId:e.id,width:a.width,height:a.height},y:Math.max(0,Math.round(l.y)),x:Math.max(0,Math.round(l.x))};if((a.width<e.tileSize.width||a.height<e.tileSize.height)&&(h.extract={width:a.width,height:a.height}),a.width!==o.width||a.height!==o.height){let d=a.width!==o.width?o.width/a.width:o.height/a.height;h.resize={width:o.width,height:o.height,scale:d}}return(f.y!==0||f.x!==0||f.height!==o.height||f.width!==o.width)&&(h.crop=f),h}getTiles(e,r,i,n){let s=this.getRasterTiffIntersection(e,r,i,n);if(s==null)return null;let a=this.tms.pixelScale(n),o=e.getImageByResolution(a),u=a/o.resolution[0],f=s.intersection.subtract(s.tiff),{tileSize:l,tileCount:h}=o,d=[],c=1/u;for(let m of Xd.getRequiredTiles(f,u,l,h)){let p=this.createComposition(o,m.x,m.y,c,s);p!=null&&d.push(p)}return d.length===0?null:d}static*getRequiredTiles(e,r,i,n){let s=Math.max(Math.floor(e.x/i.width*r),0),a=Math.min(Math.ceil(e.right/i.width*r),n.x),o=Math.max(Math.floor(e.y/i.height*r),0),u=Math.min(Math.ceil(e.bottom/i.height*r),n.y);for(let f=s;f<a;f++)for(let l=o;l<u;l++)yield{x:f,y:l}}};var oj=[cr.Jpeg,cr.Webp,cr.Png];function O4(t){if(t==null)return null;let e=t.toLowerCase();return e===cr.Png?cr.Png:e===cr.Webp?cr.Webp:e===cr.Jpeg||e==="jpg"?cr.Jpeg:e===cr.Avif?cr.Avif:null}var uj=at(uu(),1),ebe=60*60*1e3,tbe=24*ebe,rbe=91*tbe;function nbe(t){if(t==null)return{valid:!1,message:"missing"};if(!t.startsWith("c")&&!t.startsWith("d"))return{valid:!1,message:"malformed"};let e=t.slice(1).toUpperCase();try{let r=uj.decodeTime(e);if(t.startsWith("d"))return{valid:!0,message:"ok"};if(Date.now()-r>rbe)return{valid:!1,message:"expired"}}catch{return{valid:!1,message:"malformed"}}return{valid:!0,message:"ok"}}var ei={apiKey(t){var e;let r=(e=t.query.get(Yc.ApiKey.QueryString))!==null&&e!==void 0?e:t.header("X-LINZ-Api-Key"),i=nbe(r);if(!i.valid)throw new Be(400,"API Key Invalid: "+i.message);return t.set("api",r),r},getTileMatrixSet(t){return jc.find(t)},getRequestedFormats(t){let e=[...t.query.getAll("format"),...t.query.getAll("tileFormat")];if(e.length===0)return null;let r=new Set;for(let i of e){let n=O4(i);n!=null&&r.add(n)}return r.size===0?null:[...r.values()]},getTileFormat(t){let e=O4(t);return e||(t===es.MapboxVectorTiles?es.MapboxVectorTiles:null)},xyz(t){ei.apiKey(t),t.set("tileSet",t.params.tileSet);let e=parseInt(t.params.x,10),r=parseInt(t.params.y,10),i=parseInt(t.params.z,10),n=ei.getTileMatrixSet(t.params.tileMatrix);if(n==null)throw new Be(404,"Tile Matrix not found");t.set("tileMatrix",n.identifier),t.set("projection",n.projection.code);let s=ei.getTileFormat(t.params.tileType);if(s==null)throw new Be(404,"Tile extension not found");if(t.set("extension",s),isNaN(i)||i>n.maxZoom||i<0)throw new Be(404,`Zoom not found: ${i}`);let a=n.zooms[i];if(isNaN(e)||e<0||e>a.matrixWidth)throw new Be(404,`X not found: ${e}`);if(isNaN(r)||r<0||r>a.matrixHeight)throw new Be(404,`Y not found: ${r}`);let o={tile:{x:e,y:r,z:i},tileSet:t.params.tileSet,tileMatrix:n,tileType:s};t.set("xyz",o.tile);let u=$a.tileCenterToLatLon(n,o.tile);return t.set("location",u),o}};var ibe=1+1e-10,lj=10**8;function M4(t){return Math.round(t*lj)/lj}function sbe(t){return[M4(t[0]),M4(t[1])]}function abe(t,e,r){if(Cl.delta(t[0],t[2])<=0)return Cl.bboxToMultiPolygon(t);let i=[];for(let s of e){let a=[xt.fromJson(s).pad(ibe).toPolygon()];i=cq(i,a)}return jv(i,s=>sbe(r.toWgs84(s)))}async function obe(t,e,r){var i,n,s,a;let o=$a.get(r),u=[],f=[],l=await Ke.getAllImagery(e.layers,[r.projection]),h=await Ke.Provider.get(Ke.Provider.id("linz"));if(h==null)return null;for(let d of e.layers){let c=d[o.epsg.code];if(c==null)continue;let m=l.get(c);if(m==null)continue;let p=o.boundsToWgs84BoundingBox(m.bounds).map(M4),y=Dq(m.name);if(y[0]===-1)throw new Error("Missing date in imagery name: "+m.name);let v=[y.map(P=>`${P}-01-01T00:00:00Z`)],w={spatial:{bbox:[p]},temporal:{interval:v}};f.push({type:"Feature",stac_version:zm.Version,id:c+"_item",collection:c,assets:{},links:[],bbox:p,geometry:{type:"MultiPolygon",coordinates:abe(p,m.files,o)},properties:{title:(i=m.title)!==null&&i!==void 0?i:Z9(m.name),category:m.category,datetime:null,start_datetime:v[0][0],end_datetime:v[0][1]}});let _=pi.convertZoomLevel(d.minZoom?d.minZoom:0,bn,r,!0),C=pi.convertZoomLevel(d.maxZoom?d.maxZoom:32,bn,r,!0);u.push({stac_version:zm.Version,license:zm.License,id:m.id,providers:[{name:h.serviceProvider.name,url:h.serviceProvider.site,roles:["host"]}],title:(n=m.title)!==null&&n!==void 0?n:Z9(m.name),description:"No description",extent:w,links:[],summaries:{"linz:category":m.category,"linz:zoom":{min:_,max:C},"linz:priority":[1e3+e.layers.indexOf(d)]}})}return{id:e.id,type:"FeatureCollection",stac_version:zm.Version,stac_extensions:["single-file-stac"],title:(s=e.title)!==null&&s!==void 0?s:"No title",description:(a=e.description)!==null&&a!==void 0?a:"No Description",features:f,collections:u,links:[]}}async function L4(t){let e=ei.getTileMatrixSet(t.params.tileMatrix);if(e==null)throw new Be(404,"Tile Matrix not found");t.timer.start("tileset:load");let r=await Ke.TileSet.get(Ke.TileSet.id(t.params.tileSet));if(t.timer.end("tileset:load"),r==null||r.type===Gr.Vector)return Ot();let i=Nr.key(r);if(Nr.isNotModified(t,i))return Rn();t.timer.start("stac:load");let n=await obe(t,r,e);if(t.timer.end("stac:load"),n==null)return Ot();let s=new Be(200,"ok");return s.header(Xe.ETag,i),s.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),s.json(n),s}var l2=at(require("path"),1);var oa;(function(t){t.NONE="application/octet-stream",t.JPEG="image/jpeg",t.JP2="image/jp2",t.WEBP="image/webp",t.LZW="application/lzw",t.DEFLATE="application/deflate"})(oa||(oa={}));var D4={1:oa.NONE,5:oa.LZW,6:oa.JPEG,7:oa.JPEG,8:oa.DEFLATE,34712:oa.JP2,50001:oa.WEBP};var nt;(function(t){t[t.Artist=315]="Artist",t[t.BitsPerSample=258]="BitsPerSample",t[t.CellLength=265]="CellLength",t[t.CellWidth=264]="CellWidth",t[t.ColorMap=320]="ColorMap",t[t.Compression=259]="Compression",t[t.Copyright=33432]="Copyright",t[t.DateTime=306]="DateTime",t[t.ExtraSamples=338]="ExtraSamples",t[t.FillOrder=266]="FillOrder",t[t.FreeByteCounts=289]="FreeByteCounts",t[t.FreeOffsets=288]="FreeOffsets",t[t.GrayResponseCurve=291]="GrayResponseCurve",t[t.GrayResponseUnit=290]="GrayResponseUnit",t[t.HostComputer=316]="HostComputer",t[t.ImageDescription=270]="ImageDescription",t[t.ImageHeight=257]="ImageHeight",t[t.ImageWidth=256]="ImageWidth",t[t.Make=271]="Make",t[t.MaxSampleValue=281]="MaxSampleValue",t[t.MinSampleValue=280]="MinSampleValue",t[t.Model=272]="Model",t[t.NewSubFileType=254]="NewSubFileType",t[t.Orientation=274]="Orientation",t[t.PhotometricInterpretation=262]="PhotometricInterpretation",t[t.PlanarConfiguration=284]="PlanarConfiguration",t[t.ResolutionUnit=296]="ResolutionUnit",t[t.RowsPerStrip=278]="RowsPerStrip",t[t.SamplesPerPixel=277]="SamplesPerPixel",t[t.Software=305]="Software",t[t.StripByteCounts=279]="StripByteCounts",t[t.StripOffsets=273]="StripOffsets",t[t.SubFileType=255]="SubFileType",t[t.Threshholding=263]="Threshholding",t[t.XResolution=282]="XResolution",t[t.YResolution=283]="YResolution",t[t.BadFaxLines=326]="BadFaxLines",t[t.CleanFaxData=327]="CleanFaxData",t[t.ClipPath=343]="ClipPath",t[t.ConsecutiveBadFaxLines=328]="ConsecutiveBadFaxLines",t[t.Decode=433]="Decode",t[t.DefaultImageColor=434]="DefaultImageColor",t[t.DocumentName=269]="DocumentName",t[t.DotRange=336]="DotRange",t[t.HalftoneHints=321]="HalftoneHints",t[t.Indexed=346]="Indexed",t[t.JPEGTables=347]="JPEGTables",t[t.PageName=285]="PageName",t[t.PageNumber=297]="PageNumber",t[t.Predictor=317]="Predictor",t[t.PrimaryChromaticities=319]="PrimaryChromaticities",t[t.ReferenceBlackWhite=532]="ReferenceBlackWhite",t[t.SampleFormat=339]="SampleFormat",t[t.SMinSampleValue=340]="SMinSampleValue",t[t.SMaxSampleValue=341]="SMaxSampleValue",t[t.StripRowCounts=559]="StripRowCounts",t[t.SubIFDs=330]="SubIFDs",t[t.T4Options=292]="T4Options",t[t.T6Options=293]="T6Options",t[t.TileByteCounts=325]="TileByteCounts",t[t.TileHeight=323]="TileHeight",t[t.TileOffsets=324]="TileOffsets",t[t.TileWidth=322]="TileWidth",t[t.TransferFunction=301]="TransferFunction",t[t.WhitePoint=318]="WhitePoint",t[t.XClipPathUnits=344]="XClipPathUnits",t[t.XPosition=286]="XPosition",t[t.YCbCrCoefficients=529]="YCbCrCoefficients",t[t.YCbCrPositioning=531]="YCbCrPositioning",t[t.YCbCrSubSampling=530]="YCbCrSubSampling",t[t.YClipPathUnits=345]="YClipPathUnits",t[t.YPosition=287]="YPosition",t[t.ApertureValue=37378]="ApertureValue",t[t.ColorSpace=40961]="ColorSpace",t[t.DateTimeDigitized=36868]="DateTimeDigitized",t[t.DateTimeOriginal=36867]="DateTimeOriginal",t[t.ExifIFD=34665]="ExifIFD",t[t.ExifVersion=36864]="ExifVersion",t[t.ExposureTime=33434]="ExposureTime",t[t.FileSource=41728]="FileSource",t[t.Flash=37385]="Flash",t[t.FlashpixVersion=40960]="FlashpixVersion",t[t.FNumber=33437]="FNumber",t[t.ImageUniqueID=42016]="ImageUniqueID",t[t.LightSource=37384]="LightSource",t[t.MakerNote=37500]="MakerNote",t[t.ShutterSpeedValue=37377]="ShutterSpeedValue",t[t.UserComment=37510]="UserComment",t[t.IPTC=33723]="IPTC",t[t.ICCProfile=34675]="ICCProfile",t[t.XMP=700]="XMP",t[t.GDAL_METADATA=42112]="GDAL_METADATA",t[t.GDAL_NODATA=42113]="GDAL_NODATA",t[t.Photoshop=34377]="Photoshop",t[t.ModelPixelScale=33550]="ModelPixelScale",t[t.ModelTiePoint=33922]="ModelTiePoint",t[t.ModelTransformation=34264]="ModelTransformation",t[t.GeoKeyDirectory=34735]="GeoKeyDirectory",t[t.GeoDoubleParams=34736]="GeoDoubleParams",t[t.GeoAsciiParams=34737]="GeoAsciiParams"})(nt||(nt={}));var L1;(function(t){t[t.GTModelTypeGeoKey=1024]="GTModelTypeGeoKey",t[t.GTRasterTypeGeoKey=1025]="GTRasterTypeGeoKey",t[t.GTCitationGeoKey=1026]="GTCitationGeoKey",t[t.GeographicTypeGeoKey=2048]="GeographicTypeGeoKey",t[t.GeogCitationGeoKey=2049]="GeogCitationGeoKey",t[t.GeogGeodeticDatumGeoKey=2050]="GeogGeodeticDatumGeoKey",t[t.GeogPrimeMeridianGeoKey=2051]="GeogPrimeMeridianGeoKey",t[t.GeogLinearUnitsGeoKey=2052]="GeogLinearUnitsGeoKey",t[t.GeogLinearUnitSizeGeoKey=2053]="GeogLinearUnitSizeGeoKey",t[t.GeogAngularUnitsGeoKey=2054]="GeogAngularUnitsGeoKey",t[t.GeogAngularUnitSizeGeoKey=2055]="GeogAngularUnitSizeGeoKey",t[t.GeogEllipsoidGeoKey=2056]="GeogEllipsoidGeoKey",t[t.GeogSemiMajorAxisGeoKey=2057]="GeogSemiMajorAxisGeoKey",t[t.GeogSemiMinorAxisGeoKey=2058]="GeogSemiMinorAxisGeoKey",t[t.GeogInvFlatteningGeoKey=2059]="GeogInvFlatteningGeoKey",t[t.GeogAzimuthUnitsGeoKey=2060]="GeogAzimuthUnitsGeoKey",t[t.GeogPrimeMeridianLongGeoKey=2061]="GeogPrimeMeridianLongGeoKey",t[t.GeogTOWGS84GeoKey=2062]="GeogTOWGS84GeoKey",t[t.ProjectedCSTypeGeoKey=3072]="ProjectedCSTypeGeoKey",t[t.PCSCitationGeoKey=3073]="PCSCitationGeoKey",t[t.ProjectionGeoKey=3074]="ProjectionGeoKey",t[t.ProjCoordTransGeoKey=3075]="ProjCoordTransGeoKey",t[t.ProjLinearUnitsGeoKey=3076]="ProjLinearUnitsGeoKey",t[t.ProjLinearUnitSizeGeoKey=3077]="ProjLinearUnitSizeGeoKey",t[t.ProjStdParallel1GeoKey=3078]="ProjStdParallel1GeoKey",t[t.ProjStdParallel2GeoKey=3079]="ProjStdParallel2GeoKey",t[t.ProjNatOriginLongGeoKey=3080]="ProjNatOriginLongGeoKey",t[t.ProjNatOriginLatGeoKey=3081]="ProjNatOriginLatGeoKey",t[t.ProjFalseEastingGeoKey=3082]="ProjFalseEastingGeoKey",t[t.ProjFalseNorthingGeoKey=3083]="ProjFalseNorthingGeoKey",t[t.ProjFalseOriginLongGeoKey=3084]="ProjFalseOriginLongGeoKey",t[t.ProjFalseOriginLatGeoKey=3085]="ProjFalseOriginLatGeoKey",t[t.ProjFalseOriginEastingGeoKey=3086]="ProjFalseOriginEastingGeoKey",t[t.ProjFalseOriginNorthingGeoKey=3087]="ProjFalseOriginNorthingGeoKey",t[t.ProjCenterLongGeoKey=3088]="ProjCenterLongGeoKey",t[t.ProjCenterLatGeoKey=3089]="ProjCenterLatGeoKey",t[t.ProjCenterEastingGeoKey=3090]="ProjCenterEastingGeoKey",t[t.ProjCenterNorthingGeoKey=3091]="ProjCenterNorthingGeoKey",t[t.ProjScaleAtNatOriginGeoKey=3092]="ProjScaleAtNatOriginGeoKey",t[t.ProjScaleAtCenterGeoKey=3093]="ProjScaleAtCenterGeoKey",t[t.ProjAzimuthAngleGeoKey=3094]="ProjAzimuthAngleGeoKey",t[t.ProjStraightVertPoleLongGeoKey=3095]="ProjStraightVertPoleLongGeoKey",t[t.ProjRectifiedGridAngleGeoKey=3096]="ProjRectifiedGridAngleGeoKey",t[t.VerticalCSTypeGeoKey=4096]="VerticalCSTypeGeoKey",t[t.VerticalCitationGeoKey=4097]="VerticalCitationGeoKey",t[t.VerticalDatumGeoKey=4098]="VerticalDatumGeoKey",t[t.VerticalUnitsGeoKey=4099]="VerticalUnitsGeoKey"})(L1||(L1={}));var Gt;(function(t){t[t.BYTE=1]="BYTE",t[t.ASCII=2]="ASCII",t[t.SHORT=3]="SHORT",t[t.LONG=4]="LONG",t[t.RATIONAL=5]="RATIONAL",t[t.SBYTE=6]="SBYTE",t[t.UNDEFINED=7]="UNDEFINED",t[t.SSHORT=8]="SSHORT",t[t.SLONG=9]="SLONG",t[t.SRATIONAL=10]="SRATIONAL",t[t.FLOAT=11]="FLOAT",t[t.DOUBLE=12]="DOUBLE",t[t.LONG8=16]="LONG8",t[t.SLONG8=17]="SLONG8",t[t.IFD8=18]="IFD8"})(Gt||(Gt={}));var Mt;(function(t){t[t.UInt8=1]="UInt8",t[t.UInt16=2]="UInt16",t[t.UInt32=4]="UInt32",t[t.UInt64=8]="UInt64",t[t.Double=8]="Double",t[t.Float=4]="Float"})(Mt||(Mt={}));var cj=2**32,ube=typeof setImmediate>"u"?setTimeout:setImmediate,Fi=()=>{throw new Error("Method not implemented.")},ko=class{constructor(){this.isLittleEndian=!0,this.delayMs=ko.DefaultDelayMs,this.maxChunkCount=10,this.chunks=ko.DefaultChunkCache(),this.blankFillCount=16,this.maxConcurrentRequests=50,this.toFetch=new Set,this.toFetchPromise=null,this.byteOffset=0,this.getFloat32=Fi,this.getFloat64=Fi,this.getInt8=Fi,this.getInt16=Fi,this.getInt32=Fi,this.setFloat32=Fi,this.setFloat64=Fi,this.setInt8=Fi,this.setInt16=Fi,this.setInt32=Fi,this.setUint8=Fi,this.setUint16=Fi,this.setUint32=Fi,this.setBigInt64=Fi,this.setBigUint64=Fi}static getByteRanges(e,r=32,i=16){if(e.size===0)return{chunks:[],blankFill:[]};let n=[...e.values()].sort((u,f)=>u-f),s=[],a=[];s.push(a);let o=[];for(let u=0;u<n.length;++u){let f=n[u],l=n[u-1];if(a.length>=r)a=[f],s.push(a);else if(u===0||f===l+1)a.push(f);else if(f<l+i){for(let h=l;h<f;h++)a.push(h+1),o.push(h+1);o.pop()}else a=[f],s.push(a)}return{chunks:s,blankFill:o}}async fetchData(){if(this.toFetch.size===0)return;let e=this.toFetch;this.toFetch=new Set,this.toFetchPromise=null;let r=ko.getByteRanges(e,this.maxChunkCount,this.blankFillCount),i=[];for(let n of r.chunks){let s=n[0],a=n[n.length-1],o=s*this.chunkSize,u=a*this.chunkSize+this.chunkSize-o,f=await this.fetchBytes(o,u);if(n.length===1){i[s]=f,this.chunks.set(s,new DataView(f));continue}let l=s*this.chunkSize;for(let h of n){let d=h*this.chunkSize-l,c=f.slice(d,d+this.chunkSize);i[h]=c,this.chunks.set(h,new DataView(c))}}}async loadBytes(e,r){if(e<0)throw new Error("Offset must be positive");let i=Math.floor(e/this.chunkSize),n=Math.ceil((e+r)/this.chunkSize)-1;for(let s=i;s<=n;s++)this.chunks.has(s)||this.toFetch.add(s);if(this.toFetch.size!==0){if(this.toFetchPromise==null&&(this.toFetchPromise=new Promise(s=>ube(s,this.delayMs)).then(()=>this.fetchData())),this.toFetch.size>this.maxConcurrentRequests)throw new Error("Too many outstanding requests");await this.toFetchPromise}}getChunkId(e){return Math.floor(e/this.chunkSize)}getUint(e,r){switch(r){case Mt.UInt8:return this.getUint8(e);case Mt.UInt16:return this.getUint16(e);case Mt.UInt32:return this.getUint32(e);case Mt.UInt64:return this.getUint64(e)}}bytes(e,r){let i=this.isOneChunk(e,r);if(i){let f=this.getView(i),l=e-i*this.chunkSize;return new Uint8Array(f.buffer.slice(l,l+r))}let n=new Uint8Array(r),s=e+r,a=Math.floor(e/this.chunkSize),o=Math.ceil((e+r)/this.chunkSize)-1,u=0;for(let f=a;f<=o;f++){let l=e+u,h=f*this.chunkSize,d=this.getView(f),c=Math.min(s,h+this.chunkSize),m=d.buffer.slice(l-h,c-h);n.set(new Uint8Array(m),u),u+=m.byteLength}return n}getView(e){let r=this.chunks.get(e);if(r==null)throw new Error(`Chunk:${e} is not ready`);return r}isOneChunk(e,r){let i=e+r-1,n=Math.floor(e/this.chunkSize);return Math.floor(i/this.chunkSize)-n<1?n:null}hasBytes(e,r=1){let i=Math.floor(e/this.chunkSize),n=Math.ceil((e+r)/this.chunkSize)-1;for(let s=i;s<=n;s++)if(!this.chunks.has(s))return!1;return!0}toRange(e,r){if(r==null)return`bytes=${e}`;if(e<0)throw new Error("Cannot read from remote source with negative offset and length");return`bytes=${e}-${e+r}`}parseContentRange(e){let[r,i]=e.split(" ");if(r!=="bytes")throw new Error("Failed to parse content-range: "+e);if(i==null)throw new Error("Failed to parse content-range: "+e);let[,n]=i.split("/"),s=Number(n);if(isNaN(s))throw new Error("Failed to parse content-range: "+e);return s}get buffer(){throw new Error("Method not implemented.")}get byteLength(){if(this._byteLength)return this._byteLength;throw Error(".size() has not been fetched.")}getUint8(e){let r=Math.floor(e/this.chunkSize),i=this.chunks.get(r);if(i==null)throw new Error(`Chunk:${r} is not ready`);return i.getUint8(e-r*this.chunkSize)}getUint16(e){let r=this.isOneChunk(e,Mt.UInt16);if(r!=null)return this.getView(r).getUint16(e-r*this.chunkSize,this.isLittleEndian);let i=this.getUint8(e),n=this.getUint8(e+Mt.UInt8);return this.isLittleEndian?i+(n<<8):(i<<8)+n}getUint32(e){let r=this.isOneChunk(e,Mt.UInt32);if(r!=null)return this.getView(r).getUint32(e-r*this.chunkSize,this.isLittleEndian);let i=this.getUint16(e),n=this.getUint16(e+Mt.UInt16);return this.isLittleEndian?i+n*65536:i*65536+n}getUint64(e){let r=this.isOneChunk(e,Mt.UInt64);if(r!=null){let s=this.getView(r);return Number(s.getBigUint64(e-r*this.chunkSize,this.isLittleEndian))}let i=this.getUint32(e),n=this.getUint32(e+Mt.UInt32);return this.isLittleEndian?i+n*cj:i*cj+n}getBigUint64(e){let r=this.isOneChunk(e,Mt.UInt64);if(r!=null)return this.getView(r).getBigUint64(e-r*this.chunkSize,this.isLittleEndian);let i=BigInt(this.getUint32(e)),n=BigInt(this.getUint32(e+Mt.UInt32));return this.isLittleEndian?i+(n<<BigInt(32)):(i<<BigInt(32))+n}getBigInt64(){throw new Error("Not implemented.")}};ko.DefaultChunkCache=()=>new Map;ko.DefaultDelayMs=1;var fj=at($4(),1);function hj(t){switch(t){case Gt.BYTE:case Gt.ASCII:case Gt.SBYTE:case Gt.UNDEFINED:return 1;case Gt.SHORT:case Gt.SSHORT:return 2;case Gt.LONG:case Gt.SLONG:case Gt.FLOAT:return 4;case Gt.RATIONAL:case Gt.SRATIONAL:case Gt.DOUBLE:case Gt.LONG8:case Gt.SLONG8:case Gt.IFD8:return 8;default:throw new Error(`Invalid fieldType ${t}`)}}var Cf={char:(t,e)=>String.fromCharCode(t.getUint8(e)),uint8:(t,e)=>t.getUint8(e),uint16:(t,e)=>t.getUint16(e),uint32:(t,e)=>t.getUint32(e),uint64:(t,e)=>t.getUint64(e),double:(t,e)=>fj.read(t.bytes(e,Mt.Double),0,t.isLittleEndian,52,8),rational:(t,e)=>[t.getUint32(e),t.getUint32(e+4)]};function zb(t){switch(t){case Gt.ASCII:return Cf.char;case Gt.BYTE:case Gt.UNDEFINED:case Gt.SBYTE:return Cf.uint8;case Gt.SHORT:case Gt.SSHORT:return Cf.uint16;case Gt.LONG:case Gt.SLONG:return Cf.uint32;case Gt.RATIONAL:case Gt.SRATIONAL:return Cf.rational;case Gt.DOUBLE:return Cf.double;case Gt.LONG8:return Cf.uint64;default:throw new Error(`Unknown read type "${t}" "${Gt[t]}"`)}}var kl=class{constructor(e,r,i){this.tiff=r,this.byteOffset=i,this.id=e,this.name=nt[this.id],this.dataType=this.tiff.source.getUint16(i+2),this.dataCount=this.tiff.source.getUint(i+4,this.tiff.ifdConfig.pointer),this.dataTypeSize=hj(this.dataType),this.dataLength=this.dataTypeSize*this.dataCount}get hasBytes(){return this.tiff.source.hasBytes(this.valuePointer,this.dataLength)}get isReady(){return!0}get dataTypeName(){return Gt[this.dataType]}get valuePointer(){let e=this.size-this.tiff.ifdConfig.pointer;return this.isValueInline?this.byteOffset+e:this.tiff.source.getUint(this.byteOffset+e,this.tiff.ifdConfig.pointer)}get size(){return this.tiff.ifdConfig.ifd}get isValueInline(){return this.dataLength<=this.tiff.ifdConfig.pointer}readValue(){let e=this.valuePointer,r=this.dataTypeSize,i=zb(this.dataType),n=this.dataCount,s=n*r;if(n===1)return i(this.tiff.source,e);let a=[];for(let o=0;o<s;o+=r)a.push(i(this.tiff.source,e+o));return this.dataType===Gt.ASCII?a.join("").trim():a}toJSON(){return{id:this.id,name:this.name,offset:this.byteOffset,isReady:this.isReady,type:this.dataTypeName,value:this.value}}};var Pf=class extends kl{constructor(){super(...arguments),this.value=null}get isReady(){return this.value!=null}async fetch(){return this.tiff.source.hasBytes(this.valuePointer,this.dataLength)===!1&&await this.tiff.source.loadBytes(this.valuePointer,this.dataLength),this.value=this.readValue(),this.value}};var D1=class extends kl{constructor(e,r,i){super(e,r,i),this.loadedValues=null}get value(){return this.loadedValues!=null?this.loadedValues:this.hasBytes?(this.readValue(),this.loadedValues):null}async load(){await this.tiff.source.loadBytes(this.valuePointer,this.dataLength),this.readValue()}readValue(){let e=super.readValue();return typeof e=="number"?this.loadedValues=[e]:this.loadedValues=e,this.loadedValues}async getValueAt(e){if(this.loadedValues)return this.loadedValues[e];let r=this.dataTypeSize,i=this.valuePointer+r*e,n=zb(this.dataType);return this.tiff.source.hasBytes(i,r)||await this.tiff.source.loadBytes(i,r),n(this.tiff.source,i)}};var q1=class extends kl{constructor(){super(...arguments),this._isRead=!1,this._value=null}get value(){return this._isRead===!1&&(this._value=this.readValue(),this._isRead=!0),this._value}};var Ub={create(t,e){let r=t.source.getUint16(e);if(r===nt.TileOffsets||r===nt.TileByteCounts||r===nt.StripByteCounts||r===nt.StripOffsets)return new D1(r,t,e);let i=new q1(r,t,e);return i.hasBytes?i:new Pf(r,t,e)},isStatic(t){return t instanceof q1},isLazy(t){return t instanceof Pf},isOffsetArray(t){return t instanceof D1}};var lbe=32767,Hb=class{constructor(e,r,i){this.tagsGeoLoaded=!1,this.tagsGeo=new Map,this.tif=e,this.id=r,this.tags=i}async init(e=!1){let r=[this.fetch(nt.Compression),this.fetch(nt.ImageHeight),this.fetch(nt.ImageWidth),this.fetch(nt.ModelPixelScale),this.fetch(nt.ModelTiePoint),this.fetch(nt.ModelTransformation),this.fetch(nt.TileHeight),this.fetch(nt.TileWidth)];e&&(r.push(this.fetch(nt.GeoKeyDirectory)),r.push(this.fetch(nt.GeoAsciiParams)),r.push(this.fetch(nt.GeoDoubleParams))),await Promise.all(r),e&&await this.loadGeoTiffTags()}value(e){let r=this.tags.get(e);return r==null?null:r.value}async loadGeoTiffTags(){if(this.tagsGeoLoaded)return;let e=this.tags.get(nt.GeoKeyDirectory);if(e==null){this.tagsGeoLoaded=!0;return}if(!e.isReady&&e instanceof Pf&&await Promise.all([this.fetch(nt.GeoKeyDirectory),this.fetch(nt.GeoAsciiParams),this.fetch(nt.GeoDoubleParams)]),this.tagsGeoLoaded=!0,e.value==null)return;let r=e.value;if(!Array.isArray(r))throw new Error("Invalid geo tags found");for(let i=4;i<=r[3]*4;i+=4){let n=r[i],s=r[i+1],a=r[i+3];if(s===0){this.tagsGeo.set(n,a);continue}let o=this.tags.get(s);if(o==null||o.value==null)continue;let u=r[i+2];Array.isArray(o.value)?this.tagsGeo.set(n,o.value[a+u-1]):typeof o.value=="string"&&this.tagsGeo.set(n,o.value.substr(a,a+u-1).trim())}}valueGeo(e){if(this.tagsGeoLoaded===!1)throw new Error("loadGeoTiffTags() has not been called");return this.tagsGeo.get(e)}async fetch(e){let r=this.tags.get(e);return r==null?null:Ub.isLazy(r)?r.fetch():r.value}get origin(){let e=this.value(nt.ModelTiePoint);if(e!=null&&e.length===6)return[e[3],e[4],e[5]];let r=this.value(nt.ModelTransformation);if(r!=null)return[r[3],r[7],r[11]];if(this.value(nt.NewSubFileType)===1&&this.id!==0)return this.tif.images[0].origin;throw new Error("Image does not have a geo transformation.")}get isGeoLocated(){return this.value(nt.ModelPixelScale)!=null||this.value(nt.ModelTransformation)!=null?!0:this.value(nt.NewSubFileType)===1&&this.id!==0?this.tif.images[0].isGeoLocated:!1}get resolution(){let e=this.value(nt.ModelPixelScale);if(e!=null)return[e[0],-e[1],e[2]];let r=this.value(nt.ModelTransformation);if(r!=null)return[r[0],r[5],r[10]];if(this.value(nt.NewSubFileType)===1&&this.id!==0){let i=this.tif.images[0],[n,s,a]=i.resolution,o=i.size,u=this.size;return[n*o.width/u.width,s*o.height/u.height,a]}throw new Error("Image does not have a geo transformation.")}get bbox(){let e=this.size,r=this.origin,i=this.resolution;if(r==null||e==null||i==null)throw new Error("Unable to calculate bounding box");let n=r[0],s=r[1],a=n+i[0]*e.width,o=s+i[1]*e.height;return[Math.min(n,a),Math.min(s,o),Math.max(n,a),Math.max(s,o)]}get compression(){let e=this.value(nt.Compression);return e==null||typeof e!="number"?null:D4[e]}get epsg(){let e=this.valueGeo(L1.ProjectedCSTypeGeoKey);return e===lbe?null:e}get size(){return{width:this.value(nt.ImageWidth),height:this.value(nt.ImageHeight)}}get tagList(){return[...this.tags.keys()].map(e=>nt[e])}isTiled(){return this.value(nt.TileWidth)!==null}get tileSize(){return{width:this.value(nt.TileWidth),height:this.value(nt.TileHeight)}}get tileCount(){let e=this.size,r=this.tileSize,i=Math.ceil(e.width/r.width),n=Math.ceil(e.height/r.height);return{x:i,y:n}}get tileOffset(){let e=this.tags.get(nt.TileOffsets);if(e==null)throw new Error("No tile offsets found");return e}get stripCount(){let e=this.tags.get(nt.StripByteCounts);return e==null?0:e.dataCount}async getTileOffset(e){let r=this.tileOffset;if(e<0||e>r.dataCount)throw new Error(`Tile offset: ${e} out of range: 0 -> ${r.dataCount}`);return r.getValueAt(e)}getTileBounds(e,r){let{size:i,tileSize:n}=this,s=r*n.height,a=e*n.width,o=a+n.width>=i.width?i.width-a:n.width,u=s+n.height>=i.height?i.height-s:n.height;return{x:a,y:s,width:o,height:u}}async getStrip(e){if(this.isTiled())throw new Error("Cannot read stripes, tiff is tiled");let r=this.tags.get(nt.StripByteCounts),i=this.tags.get(nt.StripOffsets);if(e>=r.dataCount)throw new Error("Cannot read strip, index out of bounds");let[n,s]=await Promise.all([i.getValueAt(e),r.getValueAt(e)]);return this.getBytes(n,s)}getJpegHeader(e){let r=this.value(nt.JPEGTables);if(r==null)throw new Error("Unable to find Jpeg header");let i=r.slice(0,r.length-2),n=new Uint8Array(e.byteLength+i.length-2);return n.set(i,0),n.set(e.slice(2),i.length),n}async getBytes(e,r){let i=this.compression;if(i==null)throw new Error("Unsupported compression: "+this.value(nt.Compression));if(r===0)return null;await this.tif.source.loadBytes(e,r);let n=this.tif.source.bytes(e,r);return this.compression===oa.JPEG?{mimeType:i,bytes:this.getJpegHeader(n)}:{mimeType:i,bytes:n}}async getTile(e,r){let i=this.compression,n=this.size,s=this.tileSize;if(s==null)throw new Error("Tiff is not tiled");if(i==null)throw new Error("Unsupported compression: "+this.value(nt.Compression));let a=Math.ceil(n.height/s.height),o=Math.ceil(n.width/s.width);if(e>=o||r>=a)throw new Error(`Tile index is outside of range x:${e} >= ${o} or y:${r} >= ${a}`);let u=r*o+e,f=o*a;if(u>=f)throw new Error(`Tile index is outside of tile range: ${u} >= ${f}`);let{offset:l,imageSize:h}=await this.getTileSize(u);return this.getBytes(l,h)}async getTileSize(e){if(this.tif.options.tileLeaderByteSize){let s=await this.getTileOffset(e);if(s===0)return{offset:0,imageSize:0};let a=this.tif.options.tileLeaderByteSize;return await this.tif.source.loadBytes(s-a,a),{offset:s,imageSize:this.tif.source.getUint(s-a,a)}}let r=this.tags.get(nt.TileByteCounts);if(r==null)throw new Error("No tile byte counts found");let[i,n]=await Promise.all([this.getTileOffset(e),r.getValueAt(e)]);return{offset:i,imageSize:n}}};var $1;(function(t){t[t.Big=19789]="Big",t[t.Little=18761]="Little"})($1||($1={}));var ua;(function(t){t[t.BigTiff=43]="BigTiff",t[t.Tiff=42]="Tiff"})(ua||(ua={}));var B4="__reverse";function dj(t,e){if(t[B4]==null){let r={};for(let i of Object.keys(t)){let n=t[i];r[n]=i}Object.defineProperty(t,B4,{enumerable:!1,value:r,writable:!1})}return t[B4][e]}var Ol;(function(t){t.GDAL_STRUCTURAL_METADATA_SIZE="GDAL_STRUCTURAL_METADATA_SIZE",t.LAYOUT="LAYOUT",t.BLOCK_ORDER="BLOCK_ORDER",t.BLOCK_LEADER="BLOCK_LEADER",t.BLOCK_TRAILER="BLOCK_TRAILER",t.KNOWN_INCOMPATIBLE_EDITION="KNOWN_INCOMPATIBLE_EDITION",t.MASK_INTERLEAVED_WITH_IMAGERY="MASK_INTERLEAVED_WITH_IMAGERY"})(Ol||(Ol={}));var F4;(function(t){t.RowMajor="ROW_MAJOR"})(F4||(F4={}));var j4;(function(t){t.uint32="SIZE_AS_UINT4"})(j4||(j4={}));var cbe={uint32:Mt.UInt32},Vb=class{constructor(){this.options=new Map}get isCogOptimized(){return this.isBroken?!1:this.options.get(Ol.LAYOUT)==="IFDS_BEFORE_DATA"}get isBroken(){return this.options.get(Ol.KNOWN_INCOMPATIBLE_EDITION)==="YES"}set(e,r){this.options.set(e,r)}process(e,r,i){let n=[];for(let a=r;a<r+i;a++){let o=e.getUint8(a);o!==0&&n.push(String.fromCharCode(o))}let s=n.join("").trim().split(`
|
|
808
|
+
AUTHORITY["EPSG","2193"]]`;Ed.default.defs(Ut.Nztm2000.toEpsgString(),mq);Ed.default.defs(Ut.Citm2000.toEpsgString(),pq);var X9=new Map;function $0e(t){return t==null?null:typeof t=="number"?t:"code"in t?t.code:"projection"in t?t.projection.code:null}var $a=class{constructor(e){this.epsg=e;try{this.projection=(0,Ed.default)(e.toEpsgString(),Ut.Wgs84.toEpsgString())}catch(r){throw new mn(`Failed to create projection: ${e.toEpsgString()}, ${Ut.Wgs84.toEpsgString()}`,500,r)}}static define(e,r){if(X9.get(e.code)!=null)throw new Error("Duplicate projection definition: "+e.toEpsgString());Ed.default.defs(e.toEpsgString(),r)}static get(e){let r=this.tryGet(e);if(r==null)throw new Error(`Invalid projection: ${e}`);return r}static tryGet(e){let r=$0e(e);if(r==null)return null;let i=X9.get(r);if(i!=null)return i;let n=Ut.tryGet(r);return n==null||Ed.default.defs(n.toEpsgString())==null?null:(i=new $a(n),X9.set(r,i),i)}projectMultipolygon(e,r){if(r.epsg.code===this.epsg.code)return e;let{toWgs84:i}=this,{fromWgs84:n}=r;return e.map(s=>s.map(a=>a.map(o=>n(i(o)))))}get toWgs84(){return this.projection.forward}get fromWgs84(){return this.projection.inverse}boundsToWgs84BoundingBox(e){let r=this.toWgs84([e.x,e.y]),i=this.toWgs84([e.x+e.width,e.y+e.height]);return[r[0],r[1],i[0],i[1]]}boundsToGeoJsonFeature(e,r={}){let i=[e.x,e.y],n=[e.x+e.width,e.y],s=[e.x,e.y+e.height],a=[e.x+e.width,e.y+e.height],o=jv([[[i,s,a,n,i]]],this.toWgs84),u=o.length===1?fq(o[0],r):hq(o,r);return u.bbox=this.boundsToWgs84BoundingBox(e),u}toGeoJson(e){return{type:"FeatureCollection",features:e.map(r=>this.boundsToGeoJsonFeature(r,{name:r.name}))}}static getTiffResZoom(e,r,i=1){let n=0;for(;n<e.zooms.length;++n)if(e.pixelScale(n)<=r*i)return n;if(n===e.zooms.length)return n-1;throw new Error("ResZoom not found")}static tileToWgs84Bbox(e,r){let i=e.tileToSource(r),n=e.tileToSource({x:r.x+1,y:r.y+1,z:r.z}),s=this.get(e),[a,o]=s.toWgs84([i.x,n.y]),[u,f]=s.toWgs84([n.x,i.y]);return[a,o,u,f]}static tileCenterToLatLon(e,r){let i=e.tileToSource({x:r.x+.5,y:r.y+.5,z:r.z}),[n,s]=this.get(e).toWgs84([i.x,i.y]);return $a.wrapLatLon(s,n)}static wrapLatLon(e,r){let i={lat:e,lon:r},n=Math.floor(Math.abs(e)/90)%4,s=e>0?90:-90,a=e%90;switch(n){case 0:i.lat=a;break;case 1:i.lat=s-a,i.lon+=180;break;case 2:i.lat=-a,i.lon+=180;break;case 3:i.lat=-s+a;break}return(i.lon>180||i.lon<-180)&&(i.lon-=Math.floor((i.lon+180)/360)*360),i}static findAlignmentLevels(e,r,i){return Math.max(0,this.getTiffResZoom(e,i,2)-r.z)}static getImagePixelWidth(e,r,i){let n=e.tileToSource(r),s=e.tileToSource({x:r.x+1,y:r.y+1,z:r.z});return Math.round((s.x-n.x)/e.pixelScale(i))*2}};function gq(t){return t==null||typeof t=="string"?!1:"roleArn"in t&&typeof t.roleArn=="string"}var kq=at(qe(),1),Oq=at(Y9(),1);function xd(t){return"promise"in t?t.promise():t}function Cd(t,e){return lu(t)?typeof t.statusCode!="number"?new mn(e,500,t):new mn(e,t.statusCode,t):new mn(e,500,t)}var us=class extends gi{constructor(e,r,i){super(),this.type=us.type,this.protocol="s3",this.chunkSize=us.DefaultChunkSize,this.maxChunkCount=us.DefaultMaxChunkCount,this.bucket=e,this.key=r,this.remote=i}get uri(){return this.name}get name(){return`s3://${this.bucket}/${this.key}`}static isSource(e){return e.type===us.type}get size(){return this._size?this._size:(this._size=Promise.resolve().then(async()=>(await xd(this.remote.headObject({Bucket:this.bucket,Key:this.key}))).ContentLength||-1),this._size)}static fromUri(e,r){let i=mo(e);return i==null||i.key==null||i.protocol!=="s3"?null:new us(i.bucket,i.key,r)}async fetchBytes(e,r){let i=this.toRange(e,r);try{let n=await this.remote.getObject({Bucket:this.bucket,Key:this.key,Range:i}).promise();if(!Buffer.isBuffer(n.Body))throw new Error("Failed to fetch object, Body is not a buffer");n.ContentRange!=null&&this._size==null&&(this._size=Promise.resolve(this.parseContentRange(n.ContentRange)));let s=n.Body;return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}catch(n){throw Cd(n,`Failed to fetch ${this.name} ${i}`)}}};us.type="aws:s3";us.DefaultChunkSize=64*1024;us.DefaultMaxChunkCount=32;var ls=class{constructor(e){this.protocol=ls.protocol,this.s3=e}source(e){let r=us.fromUri(e,this.s3);if(r==null)throw new Error(`Failed to create aws s3 source from uri: ${e}`);return r}static is(e){return e.protocol===ls.protocol}static isPath(e){return e==null?!1:e.startsWith("s3://")}async*list(e,r){for await(let i of this.details(e,r))yield i.path}async*details(e,r){let i=mo(e);if(i==null)return;let n,s=r?.recursive===!1?"/":void 0,a=i.bucket,o=i.key,u=0;try{for(;;){u++;let f=await xd(this.s3.listObjectsV2({Bucket:a,Prefix:o,ContinuationToken:n,Delimiter:s}));if(f.CommonPrefixes!=null)for(let l of f.CommonPrefixes)l.Prefix!=null&&(yield{path:`s3://${a}/${l.Prefix}`,isDirectory:!0});if(f.Contents!=null)for(let l of f.Contents)l.Key!=null&&(yield{path:`s3://${a}/${l.Key}`,size:l.Size});if(!f.IsTruncated)break;if(u>=ls.MaxListCount)throw new Error(`Failed to finish listing within ${ls.MaxListCount} list attempts`);n=f.NextContinuationToken}}catch(f){throw Cd(f,`Failed to list: "${e}"`)}}async read(e){let r=mo(e);if(r==null||r.key==null)throw new Error(`Failed to read: "${e}"`);try{return(await this.s3.getObject({Bucket:r.bucket,Key:r.key}).promise()).Body}catch(i){throw Cd(i,`Failed to read: "${e}"`)}}async write(e,r,i){let n=mo(e);if(n==null||n.key==null)throw new Error(`Failed to write: "${e}"`);try{await xd(this.s3.upload({Bucket:n.bucket,Key:n.key,Body:r,ContentEncoding:i?.contentEncoding,ContentType:i?.contentType}))}catch(s){throw Cd(s,`Failed to write: "${e}"`)}}exists(e){return this.head(e).then(r=>r!=null)}stream(e){let r=mo(e);if(r==null||r.key==null)throw new Error(`S3: Unable to read "${e}"`);return this.s3.getObject({Bucket:r.bucket,Key:r.key}).createReadStream()}async head(e){let r=mo(e);if(r==null||r.key==null)throw new Error(`Failed to exists: "${e}"`);try{return{size:(await xd(this.s3.headObject({Bucket:r.bucket,Key:r.key}))).ContentLength,path:e}}catch(i){if(lu(i)&&i.code==="NotFound")return null;throw Cd(i,`Failed to exists: "${e}"`)}}};ls.protocol="s3";ls.MaxListCount=100;var cs=class{static fsFromRole(e,r,i){if(typeof e=="object")return cs.fsFromRole(e.roleArn,e.externalId,e.durationSeconds);let n=cs.role(e,r,i);return new ls(new Oq.default({credentials:n}))}static role(e,r,i){i=i??cs.DefaultRoleDurationSeconds;let n=`role::${e}::${r}::${i}`,s=cs.cache.get(n);return s==null&&(s=new kq.default.ChainableTemporaryCredentials({params:{RoleArn:e,ExternalId:r,RoleSessionName:"fsa-"+Math.random().toString(32)+"-"+Date.now(),DurationSeconds:i}}),cs.cache.set(n,s)),s}};cs.DefaultRoleDurationSeconds=3600;cs.cache=new Map;var Mq=at(Y9(),1),Lq=require("util"),Hv=require("zlib");var V0e=(0,Lq.promisify)(Hv.gunzip),bi=$r;bi.readJson=async function(e){let r=await this.read(e);return e.endsWith(".gz")?JSON.parse((await V0e(r)).toString()):JSON.parse(r.toString())};bi.writeJson=async function(e,r){let i=Buffer.from(JSON.stringify(r,void 0,2));if(e.endsWith(".gz")){let n=(0,Hv.createGzip)();return n.end(i),this.write(e,n)}else return this.write(e,i)};bi.configure=function(e){if(e.type!=="s3"||!gq(e))return;let r=mo(e.path);if(r==null)throw new Error("Failed to parse URI: "+e.path);let i=`s3://${r.bucket}/`;this.register(i,cs.fsFromRole(e.roleArn,e.externalId))};bi.register("s3://",new ls(new Mq.default));function Z9(t){return t[0].toUpperCase()+t.slice(1).replace(/_(\d+)-(\d+)m/g," $1.$2m").replace(/_/g," ")}function Dq(t){let e=/(?:^|\D)(\d{4})(?:-(\d{2}))?(?:$|\D)/g,r=[];for(let i=e.exec(t);i!=null;i=e.exec(t))r.push(parseInt(i[1])),i[2]!=null&&r.push(parseInt(i[1].slice(0,2)+i[2]));return r.length===0?[-1,-1]:(r.sort(),[r[0],r[r.length-1]+1])}process.env.AWS_NODEJS_CONNECTION_REUSE_ENABLED="1";Ke.setConfigProvider(new Fc(Yc.TileMetadata.TableName));var ex=require("child_process");function tx(){return{version:(0,ex.execFileSync)("git",["describe","--tags","--always","--match","v*"]).toString().trim(),hash:(0,ex.execFileSync)("git",["rev-parse","HEAD"]).toString().trim()}}var fF=at(NB(),1);cF().install();var hF=at(uu(),1),p4,m4,g4={package:"@basemaps/cli",version:(p4="v6.32.1")!==null&&p4!==void 0?p4:tx().version,hash:(m4="4544a7d98667c5274142f1bb6bf61f02e4e5f618")!==null&&m4!==void 0?m4:tx().hash},Eve=hF.ulid(),Nb=class extends fF.CommandLineParser{constructor(e){super(e),this.verbose=this.defineFlagParameter({parameterLongName:"--verbose",parameterShortName:"-v",description:"Show extra logging detail"}),this.extraVerbose=this.defineFlagParameter({parameterLongName:"--vv",parameterShortName:"-V",description:"Show extra extra logging detail"}),this.toolName=e.toolFilename,this.toolDescription=e.toolDescription}onExecute(){this.verbose.value?os.get().level="debug":this.extraVerbose.value?os.get().level="trace":os.get().level="info";let e=os.get().child({id:Eve});return e.info({package:g4,cli:this.toolName},"Cli:Start"),os.set(e),super.onExecute()}onDefineParameters(){}run(){this.executeWithoutErrorHandling().catch(e=>{e instanceof g1?os.get().fatal(e.obj,e.message):os.get().fatal({err:e,cli:this.toolName},"Cli:Failed"),process.exit(1)})}};var sj=at(JE(),1);var Tl="application/json",Xe;(function(t){t.CacheControl="Cache-Control",t.ContentEncoding="Content-Encoding",t.ContentType="Content-Type",t.Cors="Access-Control-Allow-Origin",t.ETag="ETag",t.IfNoneMatch="If-None-Match",t.Server="Server",t.ServerTiming="Server-Timing"})(Xe||(Xe={}));var jd;(function(t){t.CloudfrontId="X-Amz-Cf-Id",t.TraceId="X-Amzn-Trace-Id"})(jd||(jd={}));var za;(function(t){t.CorrelationId="X-LINZ-Correlation-Id",t.RequestId="X-LINZ-Request-Id"})(za||(za={}));var wf=class{constructor(){if(this.timers=new Map,typeof process<"u"&&typeof process.hrtime.bigint=="function"){let e=BigInt(1e6);this.getTime=()=>Number(process.hrtime.bigint()/e)}else typeof typeof performance<"u"?this.getTime=()=>performance.now():this.getTime=()=>Date.now()}start(e){let r=this.timers.get(e);if(r!=null&&r.duration==null)throw new Error(`Duplicate startTime for "${e}"`);this.timers.set(e,{start:this.getTime()})}end(e){let r=this.timers.get(e);if(r==null)throw new Error(`Missing startTime information for "${e}"`);let i=this.getTime()-r.start;return r.duration=i,i}get metrics(){if(this.timers.size===0)return;let e={};for(let[r,i]of this.timers.entries())i.duration!=null&&(e[r]=i.duration);return e}get unfinished(){let e=[];for(let[r,i]of this.timers.entries())i.duration==null&&e.push(r);if(e.length!==0)return e}};var dF=at(uu(),1);function $i(t){return!(typeof t!="object"||t==null)}var _f=class{constructor(e,r,i){this.logContext={},this.timer=new wf,this.headers=new Map,this.context=r,this.event=e,this.id=(0,dF.ulid)(),this.log=i,this.timer=new wf,this.log=i.child({id:this.id,aws:{lambdaId:r.awsRequestId}})}set(e,r){r==null&&(r=void 0),this.logContext[e]=r}toResponse(e){return e?.body}};var mF=require("url");var pF=at(uu(),1);var Rs=class extends _f{constructor(e,r,i){var n;super(e,r,i),this.headers=new Map,this.correlationId=(n=this.header(za.CorrelationId))!==null&&n!==void 0?n:pF.ulid(),this.set("correlationId",this.correlationId)}header(e){return this._isHeadersLoaded!==!0&&(this.loadHeaders(),this._isHeadersLoaded=!0),this.headers.get(e.toLowerCase())}json(){var e;if(this.header(Xe.ContentType)!==Tl)throw new Error(`Invalid Content-Type: "${this.header("content-type")}"`);if(this.body==null)throw new Error("Cannot parse empty body as JSON");try{return this.isBase64Encoded?JSON.parse(Buffer.from((e=this.body)!==null&&e!==void 0?e:"","base64").toString()):JSON.parse(this.body)}catch{throw new Error("Body is not a JSON object")}}get query(){return this._query==null&&(this._query=this.loadQueryString()),this._query}get url(){return this.path}};var zd=class extends Rs{static is(e){return $i(e)&&$i(e.requestContext)&&$i(e.requestContext.elb)}toResponse(e){return{statusCode:e.status,statusDescription:e.statusDescription,body:e.body,headers:this.toHeaders(e.headers),isBase64Encoded:e.isBase64Encoded}}toHeaders(e){if(e.size===0)return;let r={};for(let i of e)r[i[0]]=i[1];return r}loadHeaders(){if(this.event.headers!=null)for(let[e,r]of Object.entries(this.event.headers))r!=null&&this.headers.set(e.toLowerCase(),r)}loadQueryString(){let e=new mF.URLSearchParams;if(this.event.queryStringParameters==null)return e;for(let[r,i]of Object.entries(this.event.queryStringParameters))e.append(r.toLowerCase(),i??"true");return e}get method(){return this.event.httpMethod.toUpperCase()}get path(){return this.event.path}get body(){return this.event.body}get isBase64Encoded(){return this.event.isBase64Encoded}};var gF=require("url");var Io=class extends Rs{static is(e){return!(!$i(e)||!$i(e.requestContext)||typeof e.requestContext.apiId!="string"||typeof e.requestContext.resourceId!="string"||typeof e.requestContext.httpMethod!="string")}toResponse(e){return{statusCode:e.status,body:e.body,headers:Io.toHeaders(e),isBase64Encoded:e.isBase64Encoded}}static toHeaders(e){if(e.headers.size===0)return;let r={};for(let i of e.headers)r[i[0]]=i[1];return r}loadHeaders(){if(this.event.headers!=null)for(let[e,r]of Object.entries(this.event.headers))r!=null&&this.headers.set(e.toLowerCase(),r)}loadQueryString(){let e=new gF.URLSearchParams;if(this.event.multiValueQueryStringParameters==null)return e;for(let[r,i]of Object.entries(this.event.multiValueQueryStringParameters))if(i!=null)for(let n of i)e.append(r.toLowerCase(),n);return e}get path(){return this.event.path}get method(){return this.event.httpMethod.toUpperCase()}get body(){return this.event.body}get isBase64Encoded(){return this.event.isBase64Encoded}};var y4=require("url");var Ud=class extends Rs{static is(e){if(!$i(e)||!Array.isArray(e.Records))return!1;let r=e.Records[0];return $i(r)?$i(r.cf):!1}toResponse(e){if(e.status===100&&this.event!=null){let r=this.event.Records[0].cf.request;for(let[i,n]of e.headers)r.headers[i.toLowerCase()]=[{key:i,value:String(n)}];return this.event.Records[0].cf.request}return{status:String(e.status),statusDescription:e.statusDescription,body:e.body,headers:this.toHeaders(e),bodyEncoding:"text"}}toHeaders(e){if(e.headers.size===0)return{};let r={};for(let i of e.headers)r[i[0]]=[{key:i[0],value:String(i[1])}];return r}loadHeaders(){var e;for(let[r,i]of Object.entries(this.event.Records[0].cf.request.headers))this.headers.set(r.toLowerCase(),(e=i[0])===null||e===void 0?void 0:e.value)}loadQueryString(){let e=this.event.Records[0].cf.request.querystring;return e==null?new y4.URLSearchParams:new y4.URLSearchParams(e.toLowerCase())}get path(){return this.event.Records[0].cf.request.uri}get method(){return this.event.Records[0].cf.request.method.toUpperCase()}get body(){let e=this.event.Records[0].cf.request.body;return e==null?null:e.data}get isBase64Encoded(){var e;return((e=this.event.Records[0].cf.request.body)===null||e===void 0?void 0:e.encoding)==="base64"}};var Be=class{constructor(e,r,i){if(this._body=null,this.headers=new Map,this.status=e,this.statusDescription=r,i!=null)for(let n of Object.keys(i))this.header(n,i[n])}static is(e){return e instanceof Be}static ok(e=200,r="Ok"){return new Be(e,r)}header(e,r){let i=e.toLowerCase();if(r==null)return this.headers.get(i);this.headers.set(i,r)}get isBase64Encoded(){return Buffer.isBuffer(this._body)}json(e){return this.buffer(JSON.stringify(e),Tl),this}buffer(e,r=Tl){return this.header(Xe.ContentType,r),this._body=e,this}get body(){return this._body==null?(this.header(Xe.ContentType,Tl),JSON.stringify({id:this.header(za.RequestId),status:this.status,message:this.statusDescription,correlationId:this.header(za.CorrelationId)})):Buffer.isBuffer(this._body)?this._body.toString("base64"):this._body}};var tj=at(ej(),1);var Fb=class{constructor(){this.hooks={request:[],response:[]},this.router=(0,tj.default)({defaultRoute:()=>new Be(404,"Not found")})}register(e,r,i){this.router.on(e,r,async(n,s,a)=>n instanceof Rs?(n.params=a,jb(n,i)):new Be(500,"Internal server error"))}hook(e,r){this.hooks[e].push(r)}get(e,r){return this.register("GET",e,r)}post(e,r){return this.register("POST",e,r)}delete(e,r){return this.register("DELETE",e,r)}options(e,r){return this.register("OPTIONS",e,r)}patch(e,r){return this.register("PATCH",e,r)}head(e,r){return this.register("HEAD",e,r)}put(e,r){return this.register("PUT",e,r)}async after(e,r){try{for(let i of this.hooks.response)await i(e,r)}catch(i){return Be.is(i)?i:(e.set("err",i),new Be(500,"Internal Server Error"))}return r}async handle(e){for(let i of this.hooks.request){let n=await jb(e,i);if(n)return this.after(e,n)}let r=await this.router.lookup(e,null);return r?this.after(e,r):this.after(e,new Be(404,"Not found"))}};var rj=require("url");var Il=class extends Rs{toResponse(e){return{statusCode:e.status,body:e.body,headers:Io.toHeaders(e),isBase64Encoded:e.isBase64Encoded}}loadHeaders(){for(let[e,r]of Object.entries(this.event.headers))this.headers.set(e.toLowerCase(),r)}loadQueryString(){return new rj.URLSearchParams(this.event.rawQueryString)}get method(){return this.event.requestContext.http.method.toUpperCase()}get path(){return this.event.rawPath}get isBase64Encoded(){return this.event.isBase64Encoded}get body(){return this.event.body==null?null:this.event.body}static is(e){return!(!$i(e)||!$i(e.requestContext)||!$i(e.requestContext.http))}};var aj="v6.32.1",Jve="4544a7d98667c5274142f1bb6bf61f02e4e5f618",nj={version:aj,hash:Jve};async function jb(t,e){t.timer.timers.has("lambda")||t.timer.start("lambda");try{return await e(t)}catch(r){return Be.is(r)?r:(t.set("err",r),new Be(500,"Internal Server Error"))}}function ij(t,e){let r=200;Be.is(e)&&(r=e.status,t.set("description",e.statusDescription)),t.set("status",r),t.timer.timers.size>0&&t.set("metrics",t.timer.metrics),nj.hash&&t.set("package",nj);let i=t.timer.timers.has("lambda")?t.timer.end("lambda"):0;return t.set("unfinished",t.timer.unfinished),t.set("duration",i),t.set("@type","report"),r>499?t.log.error(t.logContext,"Lambda:Done"):r>399?t.log.warn(t.logContext,"Lambda:Done"):t.log.info(t.logContext,"Lambda:Done"),e}function Yve(t){let e={rejectOnError:!0,tracePercent:0,...t};if(isNaN(e.tracePercent)||e.tracePercent>1)throw new Error("tracePercent is not between 0-1 :"+e.tracePercent);return e}var Bi=class{static request(e,r,i){if(zd.is(e))return new zd(e,r,i);if(Il.is(e))return new Il(e,r,i);if(Io.is(e))return new Io(e,r,i);if(Ud.is(e))return new Ud(e,r,i);throw new Error("Request is not a a ALB, ApiGateway or Cloudfront event")}static handler(e,r,i){let n=Yve(r);function s(a,o,u){let f=new _f(a,o,i??Bi.Logger);n.tracePercent>0&&Math.random()<n.tracePercent&&(f.log.level="trace"),process.env.TRACE_LAMBDA&&(f.log.level="trace"),f.log.trace({event:a},"Lambda:Start");let l=o.awsRequestId;f.set("aws",{lambdaId:l}),jb(f,e).then(h=>{if(ij(f,h),Be.is(h)&&n.rejectOnError){if(f.logContext.err)return u(f.logContext.err);if(h.status>399)return u(f.toResponse(h))}return u(null,f.toResponse(h))})}return s}static http(e){let r=new Fb;function i(n,s,a){let o=Bi.request(n,s,e??Bi.Logger),u=o.header(jd.CloudfrontId),f=o.header(jd.TraceId),l=s.awsRequestId;(u||f||l)&&o.set("aws",{cloudFrontId:u,traceId:f,lambdaId:l}),o.set("method",o.method),o.set("path",o.path),r.handle(o).then(h=>{var d;h.status===500&&h.header(Xe.CacheControl,"no-store"),h.header(za.RequestId,o.id),h.header(za.CorrelationId,o.correlationId);let c=(d=o.timer.metrics)===null||d===void 0?void 0:d.lambda;c!=null&&h.header(Xe.ServerTiming,`total;dur=${c}`),!h.isBase64Encoded&&h.header(Xe.ContentType)==null&&h.header(Xe.ContentType,Tl),Bi.ServerName&&h.header(Xe.Server,`${Bi.ServerName}-${aj}`),ij(o,h),a(null,o.toResponse(h))})}return i.router=r,i}};Bi.Logger=(0,sj.default)();Bi.ServerName="linz";var Nr={key(t){return Buffer.isBuffer(t)||typeof t=="string"?al(t):al(JSON.stringify(t))},isNotModified(t,e){let r=t.header(Xe.IfNoneMatch);return r!=null&&r.indexOf(e)>-1?(t.set("cache",{hit:!0,match:r}),!0):!1}};var Ot=()=>new Be(404,"Not Found"),Rn=()=>new Be(304,"Not modified");var Zve=.2,Xd=class{constructor(e){this.tms=e}async tile(e,r,i,n){let s=[];for(let a of e){let o=this.getTiles(a,r,i,n);o!=null&&(s=s.concat(o))}return s}getRasterTiffIntersection(e,r,i,n){let s=this.tms.tileToPixels(r,i),a=new xt(s.x,s.y,this.tms.tileSize,this.tms.tileSize),o=e.images[0].bbox,u=this.tms.sourceToPixels(o[0],o[3],n),f=this.tms.sourceToPixels(o[2],o[1],n),l=xt.fromUpperLeftLowerRight(u,f),h=l.intersection(a);return h==null?null:{tiff:l,intersection:h,tile:a}}createComposition(e,r,i,n,s){let a=xt.fromJson(e.getTileBounds(r,i)),o=a.scale(n,n).add(s.tiff).round(Zve),u=o.intersection(s.tile);if(u==null)return null;let f=u.subtract(o);if(f.height<.5||f.width<.5)return null;let l=o.subtract(s.tile),h={tiff:e.tif,source:{x:r,y:i,imageId:e.id,width:a.width,height:a.height},y:Math.max(0,Math.round(l.y)),x:Math.max(0,Math.round(l.x))};if((a.width<e.tileSize.width||a.height<e.tileSize.height)&&(h.extract={width:a.width,height:a.height}),a.width!==o.width||a.height!==o.height){let d=a.width!==o.width?o.width/a.width:o.height/a.height;h.resize={width:o.width,height:o.height,scale:d}}return(f.y!==0||f.x!==0||f.height!==o.height||f.width!==o.width)&&(h.crop=f),h}getTiles(e,r,i,n){let s=this.getRasterTiffIntersection(e,r,i,n);if(s==null)return null;let a=this.tms.pixelScale(n),o=e.getImageByResolution(a),u=a/o.resolution[0],f=s.intersection.subtract(s.tiff),{tileSize:l,tileCount:h}=o,d=[],c=1/u;for(let m of Xd.getRequiredTiles(f,u,l,h)){let p=this.createComposition(o,m.x,m.y,c,s);p!=null&&d.push(p)}return d.length===0?null:d}static*getRequiredTiles(e,r,i,n){let s=Math.max(Math.floor(e.x/i.width*r),0),a=Math.min(Math.ceil(e.right/i.width*r),n.x),o=Math.max(Math.floor(e.y/i.height*r),0),u=Math.min(Math.ceil(e.bottom/i.height*r),n.y);for(let f=s;f<a;f++)for(let l=o;l<u;l++)yield{x:f,y:l}}};var oj=[cr.Jpeg,cr.Webp,cr.Png];function O4(t){if(t==null)return null;let e=t.toLowerCase();return e===cr.Png?cr.Png:e===cr.Webp?cr.Webp:e===cr.Jpeg||e==="jpg"?cr.Jpeg:e===cr.Avif?cr.Avif:null}var uj=at(uu(),1),ebe=60*60*1e3,tbe=24*ebe,rbe=91*tbe;function nbe(t){if(t==null)return{valid:!1,message:"missing"};if(!t.startsWith("c")&&!t.startsWith("d"))return{valid:!1,message:"malformed"};let e=t.slice(1).toUpperCase();try{let r=uj.decodeTime(e);if(t.startsWith("d"))return{valid:!0,message:"ok"};if(Date.now()-r>rbe)return{valid:!1,message:"expired"}}catch{return{valid:!1,message:"malformed"}}return{valid:!0,message:"ok"}}var ei={apiKey(t){var e;let r=(e=t.query.get(Yc.ApiKey.QueryString))!==null&&e!==void 0?e:t.header("X-LINZ-Api-Key"),i=nbe(r);if(!i.valid)throw new Be(400,"API Key Invalid: "+i.message);return t.set("api",r),r},getTileMatrixSet(t){return jc.find(t)},getRequestedFormats(t){let e=[...t.query.getAll("format"),...t.query.getAll("tileFormat")];if(e.length===0)return null;let r=new Set;for(let i of e){let n=O4(i);n!=null&&r.add(n)}return r.size===0?null:[...r.values()]},getTileFormat(t){let e=O4(t);return e||(t===es.MapboxVectorTiles?es.MapboxVectorTiles:null)},xyz(t){ei.apiKey(t),t.set("tileSet",t.params.tileSet);let e=parseInt(t.params.x,10),r=parseInt(t.params.y,10),i=parseInt(t.params.z,10),n=ei.getTileMatrixSet(t.params.tileMatrix);if(n==null)throw new Be(404,"Tile Matrix not found");t.set("tileMatrix",n.identifier),t.set("projection",n.projection.code);let s=ei.getTileFormat(t.params.tileType);if(s==null)throw new Be(404,"Tile extension not found");if(t.set("extension",s),isNaN(i)||i>n.maxZoom||i<0)throw new Be(404,`Zoom not found: ${i}`);let a=n.zooms[i];if(isNaN(e)||e<0||e>a.matrixWidth)throw new Be(404,`X not found: ${e}`);if(isNaN(r)||r<0||r>a.matrixHeight)throw new Be(404,`Y not found: ${r}`);let o={tile:{x:e,y:r,z:i},tileSet:t.params.tileSet,tileMatrix:n,tileType:s};t.set("xyz",o.tile);let u=$a.tileCenterToLatLon(n,o.tile);return t.set("location",u),o}};var ibe=1+1e-10,lj=10**8;function M4(t){return Math.round(t*lj)/lj}function sbe(t){return[M4(t[0]),M4(t[1])]}function abe(t,e,r){if(Cl.delta(t[0],t[2])<=0)return Cl.bboxToMultiPolygon(t);let i=[];for(let s of e){let a=[xt.fromJson(s).pad(ibe).toPolygon()];i=cq(i,a)}return jv(i,s=>sbe(r.toWgs84(s)))}async function obe(t,e,r){var i,n,s,a;let o=$a.get(r),u=[],f=[],l=await Ke.getAllImagery(e.layers,[r.projection]),h=await Ke.Provider.get(Ke.Provider.id("linz"));if(h==null)return null;for(let d of e.layers){let c=d[o.epsg.code];if(c==null)continue;let m=l.get(c);if(m==null)continue;let p=o.boundsToWgs84BoundingBox(m.bounds).map(M4),y=Dq(m.name);if(y[0]===-1)throw new Error("Missing date in imagery name: "+m.name);let v=[y.map(P=>`${P}-01-01T00:00:00Z`)],w={spatial:{bbox:[p]},temporal:{interval:v}};f.push({type:"Feature",stac_version:zm.Version,id:c+"_item",collection:c,assets:{},links:[],bbox:p,geometry:{type:"MultiPolygon",coordinates:abe(p,m.files,o)},properties:{title:(i=m.title)!==null&&i!==void 0?i:Z9(m.name),category:m.category,datetime:null,start_datetime:v[0][0],end_datetime:v[0][1]}});let _=pi.convertZoomLevel(d.minZoom?d.minZoom:0,bn,r,!0),C=pi.convertZoomLevel(d.maxZoom?d.maxZoom:32,bn,r,!0);u.push({stac_version:zm.Version,license:zm.License,id:m.id,providers:[{name:h.serviceProvider.name,url:h.serviceProvider.site,roles:["host"]}],title:(n=m.title)!==null&&n!==void 0?n:Z9(m.name),description:"No description",extent:w,links:[],summaries:{"linz:category":m.category,"linz:zoom":{min:_,max:C},"linz:priority":[1e3+e.layers.indexOf(d)]}})}return{id:e.id,type:"FeatureCollection",stac_version:zm.Version,stac_extensions:["single-file-stac"],title:(s=e.title)!==null&&s!==void 0?s:"No title",description:(a=e.description)!==null&&a!==void 0?a:"No Description",features:f,collections:u,links:[]}}async function L4(t){let e=ei.getTileMatrixSet(t.params.tileMatrix);if(e==null)throw new Be(404,"Tile Matrix not found");t.timer.start("tileset:load");let r=await Ke.TileSet.get(Ke.TileSet.id(t.params.tileSet));if(t.timer.end("tileset:load"),r==null||r.type===Gr.Vector)return Ot();let i=Nr.key(r);if(Nr.isNotModified(t,i))return Rn();t.timer.start("stac:load");let n=await obe(t,r,e);if(t.timer.end("stac:load"),n==null)return Ot();let s=new Be(200,"ok");return s.header(Xe.ETag,i),s.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),s.json(n),s}var l2=at(require("path"),1);var oa;(function(t){t.NONE="application/octet-stream",t.JPEG="image/jpeg",t.JP2="image/jp2",t.WEBP="image/webp",t.LZW="application/lzw",t.DEFLATE="application/deflate"})(oa||(oa={}));var D4={1:oa.NONE,5:oa.LZW,6:oa.JPEG,7:oa.JPEG,8:oa.DEFLATE,34712:oa.JP2,50001:oa.WEBP};var nt;(function(t){t[t.Artist=315]="Artist",t[t.BitsPerSample=258]="BitsPerSample",t[t.CellLength=265]="CellLength",t[t.CellWidth=264]="CellWidth",t[t.ColorMap=320]="ColorMap",t[t.Compression=259]="Compression",t[t.Copyright=33432]="Copyright",t[t.DateTime=306]="DateTime",t[t.ExtraSamples=338]="ExtraSamples",t[t.FillOrder=266]="FillOrder",t[t.FreeByteCounts=289]="FreeByteCounts",t[t.FreeOffsets=288]="FreeOffsets",t[t.GrayResponseCurve=291]="GrayResponseCurve",t[t.GrayResponseUnit=290]="GrayResponseUnit",t[t.HostComputer=316]="HostComputer",t[t.ImageDescription=270]="ImageDescription",t[t.ImageHeight=257]="ImageHeight",t[t.ImageWidth=256]="ImageWidth",t[t.Make=271]="Make",t[t.MaxSampleValue=281]="MaxSampleValue",t[t.MinSampleValue=280]="MinSampleValue",t[t.Model=272]="Model",t[t.NewSubFileType=254]="NewSubFileType",t[t.Orientation=274]="Orientation",t[t.PhotometricInterpretation=262]="PhotometricInterpretation",t[t.PlanarConfiguration=284]="PlanarConfiguration",t[t.ResolutionUnit=296]="ResolutionUnit",t[t.RowsPerStrip=278]="RowsPerStrip",t[t.SamplesPerPixel=277]="SamplesPerPixel",t[t.Software=305]="Software",t[t.StripByteCounts=279]="StripByteCounts",t[t.StripOffsets=273]="StripOffsets",t[t.SubFileType=255]="SubFileType",t[t.Threshholding=263]="Threshholding",t[t.XResolution=282]="XResolution",t[t.YResolution=283]="YResolution",t[t.BadFaxLines=326]="BadFaxLines",t[t.CleanFaxData=327]="CleanFaxData",t[t.ClipPath=343]="ClipPath",t[t.ConsecutiveBadFaxLines=328]="ConsecutiveBadFaxLines",t[t.Decode=433]="Decode",t[t.DefaultImageColor=434]="DefaultImageColor",t[t.DocumentName=269]="DocumentName",t[t.DotRange=336]="DotRange",t[t.HalftoneHints=321]="HalftoneHints",t[t.Indexed=346]="Indexed",t[t.JPEGTables=347]="JPEGTables",t[t.PageName=285]="PageName",t[t.PageNumber=297]="PageNumber",t[t.Predictor=317]="Predictor",t[t.PrimaryChromaticities=319]="PrimaryChromaticities",t[t.ReferenceBlackWhite=532]="ReferenceBlackWhite",t[t.SampleFormat=339]="SampleFormat",t[t.SMinSampleValue=340]="SMinSampleValue",t[t.SMaxSampleValue=341]="SMaxSampleValue",t[t.StripRowCounts=559]="StripRowCounts",t[t.SubIFDs=330]="SubIFDs",t[t.T4Options=292]="T4Options",t[t.T6Options=293]="T6Options",t[t.TileByteCounts=325]="TileByteCounts",t[t.TileHeight=323]="TileHeight",t[t.TileOffsets=324]="TileOffsets",t[t.TileWidth=322]="TileWidth",t[t.TransferFunction=301]="TransferFunction",t[t.WhitePoint=318]="WhitePoint",t[t.XClipPathUnits=344]="XClipPathUnits",t[t.XPosition=286]="XPosition",t[t.YCbCrCoefficients=529]="YCbCrCoefficients",t[t.YCbCrPositioning=531]="YCbCrPositioning",t[t.YCbCrSubSampling=530]="YCbCrSubSampling",t[t.YClipPathUnits=345]="YClipPathUnits",t[t.YPosition=287]="YPosition",t[t.ApertureValue=37378]="ApertureValue",t[t.ColorSpace=40961]="ColorSpace",t[t.DateTimeDigitized=36868]="DateTimeDigitized",t[t.DateTimeOriginal=36867]="DateTimeOriginal",t[t.ExifIFD=34665]="ExifIFD",t[t.ExifVersion=36864]="ExifVersion",t[t.ExposureTime=33434]="ExposureTime",t[t.FileSource=41728]="FileSource",t[t.Flash=37385]="Flash",t[t.FlashpixVersion=40960]="FlashpixVersion",t[t.FNumber=33437]="FNumber",t[t.ImageUniqueID=42016]="ImageUniqueID",t[t.LightSource=37384]="LightSource",t[t.MakerNote=37500]="MakerNote",t[t.ShutterSpeedValue=37377]="ShutterSpeedValue",t[t.UserComment=37510]="UserComment",t[t.IPTC=33723]="IPTC",t[t.ICCProfile=34675]="ICCProfile",t[t.XMP=700]="XMP",t[t.GDAL_METADATA=42112]="GDAL_METADATA",t[t.GDAL_NODATA=42113]="GDAL_NODATA",t[t.Photoshop=34377]="Photoshop",t[t.ModelPixelScale=33550]="ModelPixelScale",t[t.ModelTiePoint=33922]="ModelTiePoint",t[t.ModelTransformation=34264]="ModelTransformation",t[t.GeoKeyDirectory=34735]="GeoKeyDirectory",t[t.GeoDoubleParams=34736]="GeoDoubleParams",t[t.GeoAsciiParams=34737]="GeoAsciiParams"})(nt||(nt={}));var L1;(function(t){t[t.GTModelTypeGeoKey=1024]="GTModelTypeGeoKey",t[t.GTRasterTypeGeoKey=1025]="GTRasterTypeGeoKey",t[t.GTCitationGeoKey=1026]="GTCitationGeoKey",t[t.GeographicTypeGeoKey=2048]="GeographicTypeGeoKey",t[t.GeogCitationGeoKey=2049]="GeogCitationGeoKey",t[t.GeogGeodeticDatumGeoKey=2050]="GeogGeodeticDatumGeoKey",t[t.GeogPrimeMeridianGeoKey=2051]="GeogPrimeMeridianGeoKey",t[t.GeogLinearUnitsGeoKey=2052]="GeogLinearUnitsGeoKey",t[t.GeogLinearUnitSizeGeoKey=2053]="GeogLinearUnitSizeGeoKey",t[t.GeogAngularUnitsGeoKey=2054]="GeogAngularUnitsGeoKey",t[t.GeogAngularUnitSizeGeoKey=2055]="GeogAngularUnitSizeGeoKey",t[t.GeogEllipsoidGeoKey=2056]="GeogEllipsoidGeoKey",t[t.GeogSemiMajorAxisGeoKey=2057]="GeogSemiMajorAxisGeoKey",t[t.GeogSemiMinorAxisGeoKey=2058]="GeogSemiMinorAxisGeoKey",t[t.GeogInvFlatteningGeoKey=2059]="GeogInvFlatteningGeoKey",t[t.GeogAzimuthUnitsGeoKey=2060]="GeogAzimuthUnitsGeoKey",t[t.GeogPrimeMeridianLongGeoKey=2061]="GeogPrimeMeridianLongGeoKey",t[t.GeogTOWGS84GeoKey=2062]="GeogTOWGS84GeoKey",t[t.ProjectedCSTypeGeoKey=3072]="ProjectedCSTypeGeoKey",t[t.PCSCitationGeoKey=3073]="PCSCitationGeoKey",t[t.ProjectionGeoKey=3074]="ProjectionGeoKey",t[t.ProjCoordTransGeoKey=3075]="ProjCoordTransGeoKey",t[t.ProjLinearUnitsGeoKey=3076]="ProjLinearUnitsGeoKey",t[t.ProjLinearUnitSizeGeoKey=3077]="ProjLinearUnitSizeGeoKey",t[t.ProjStdParallel1GeoKey=3078]="ProjStdParallel1GeoKey",t[t.ProjStdParallel2GeoKey=3079]="ProjStdParallel2GeoKey",t[t.ProjNatOriginLongGeoKey=3080]="ProjNatOriginLongGeoKey",t[t.ProjNatOriginLatGeoKey=3081]="ProjNatOriginLatGeoKey",t[t.ProjFalseEastingGeoKey=3082]="ProjFalseEastingGeoKey",t[t.ProjFalseNorthingGeoKey=3083]="ProjFalseNorthingGeoKey",t[t.ProjFalseOriginLongGeoKey=3084]="ProjFalseOriginLongGeoKey",t[t.ProjFalseOriginLatGeoKey=3085]="ProjFalseOriginLatGeoKey",t[t.ProjFalseOriginEastingGeoKey=3086]="ProjFalseOriginEastingGeoKey",t[t.ProjFalseOriginNorthingGeoKey=3087]="ProjFalseOriginNorthingGeoKey",t[t.ProjCenterLongGeoKey=3088]="ProjCenterLongGeoKey",t[t.ProjCenterLatGeoKey=3089]="ProjCenterLatGeoKey",t[t.ProjCenterEastingGeoKey=3090]="ProjCenterEastingGeoKey",t[t.ProjCenterNorthingGeoKey=3091]="ProjCenterNorthingGeoKey",t[t.ProjScaleAtNatOriginGeoKey=3092]="ProjScaleAtNatOriginGeoKey",t[t.ProjScaleAtCenterGeoKey=3093]="ProjScaleAtCenterGeoKey",t[t.ProjAzimuthAngleGeoKey=3094]="ProjAzimuthAngleGeoKey",t[t.ProjStraightVertPoleLongGeoKey=3095]="ProjStraightVertPoleLongGeoKey",t[t.ProjRectifiedGridAngleGeoKey=3096]="ProjRectifiedGridAngleGeoKey",t[t.VerticalCSTypeGeoKey=4096]="VerticalCSTypeGeoKey",t[t.VerticalCitationGeoKey=4097]="VerticalCitationGeoKey",t[t.VerticalDatumGeoKey=4098]="VerticalDatumGeoKey",t[t.VerticalUnitsGeoKey=4099]="VerticalUnitsGeoKey"})(L1||(L1={}));var Gt;(function(t){t[t.BYTE=1]="BYTE",t[t.ASCII=2]="ASCII",t[t.SHORT=3]="SHORT",t[t.LONG=4]="LONG",t[t.RATIONAL=5]="RATIONAL",t[t.SBYTE=6]="SBYTE",t[t.UNDEFINED=7]="UNDEFINED",t[t.SSHORT=8]="SSHORT",t[t.SLONG=9]="SLONG",t[t.SRATIONAL=10]="SRATIONAL",t[t.FLOAT=11]="FLOAT",t[t.DOUBLE=12]="DOUBLE",t[t.LONG8=16]="LONG8",t[t.SLONG8=17]="SLONG8",t[t.IFD8=18]="IFD8"})(Gt||(Gt={}));var Mt;(function(t){t[t.UInt8=1]="UInt8",t[t.UInt16=2]="UInt16",t[t.UInt32=4]="UInt32",t[t.UInt64=8]="UInt64",t[t.Double=8]="Double",t[t.Float=4]="Float"})(Mt||(Mt={}));var cj=2**32,ube=typeof setImmediate>"u"?setTimeout:setImmediate,Fi=()=>{throw new Error("Method not implemented.")},ko=class{constructor(){this.isLittleEndian=!0,this.delayMs=ko.DefaultDelayMs,this.maxChunkCount=10,this.chunks=ko.DefaultChunkCache(),this.blankFillCount=16,this.maxConcurrentRequests=50,this.toFetch=new Set,this.toFetchPromise=null,this.byteOffset=0,this.getFloat32=Fi,this.getFloat64=Fi,this.getInt8=Fi,this.getInt16=Fi,this.getInt32=Fi,this.setFloat32=Fi,this.setFloat64=Fi,this.setInt8=Fi,this.setInt16=Fi,this.setInt32=Fi,this.setUint8=Fi,this.setUint16=Fi,this.setUint32=Fi,this.setBigInt64=Fi,this.setBigUint64=Fi}static getByteRanges(e,r=32,i=16){if(e.size===0)return{chunks:[],blankFill:[]};let n=[...e.values()].sort((u,f)=>u-f),s=[],a=[];s.push(a);let o=[];for(let u=0;u<n.length;++u){let f=n[u],l=n[u-1];if(a.length>=r)a=[f],s.push(a);else if(u===0||f===l+1)a.push(f);else if(f<l+i){for(let h=l;h<f;h++)a.push(h+1),o.push(h+1);o.pop()}else a=[f],s.push(a)}return{chunks:s,blankFill:o}}async fetchData(){if(this.toFetch.size===0)return;let e=this.toFetch;this.toFetch=new Set,this.toFetchPromise=null;let r=ko.getByteRanges(e,this.maxChunkCount,this.blankFillCount),i=[];for(let n of r.chunks){let s=n[0],a=n[n.length-1],o=s*this.chunkSize,u=a*this.chunkSize+this.chunkSize-o,f=await this.fetchBytes(o,u);if(n.length===1){i[s]=f,this.chunks.set(s,new DataView(f));continue}let l=s*this.chunkSize;for(let h of n){let d=h*this.chunkSize-l,c=f.slice(d,d+this.chunkSize);i[h]=c,this.chunks.set(h,new DataView(c))}}}async loadBytes(e,r){if(e<0)throw new Error("Offset must be positive");let i=Math.floor(e/this.chunkSize),n=Math.ceil((e+r)/this.chunkSize)-1;for(let s=i;s<=n;s++)this.chunks.has(s)||this.toFetch.add(s);if(this.toFetch.size!==0){if(this.toFetchPromise==null&&(this.toFetchPromise=new Promise(s=>ube(s,this.delayMs)).then(()=>this.fetchData())),this.toFetch.size>this.maxConcurrentRequests)throw new Error("Too many outstanding requests");await this.toFetchPromise}}getChunkId(e){return Math.floor(e/this.chunkSize)}getUint(e,r){switch(r){case Mt.UInt8:return this.getUint8(e);case Mt.UInt16:return this.getUint16(e);case Mt.UInt32:return this.getUint32(e);case Mt.UInt64:return this.getUint64(e)}}bytes(e,r){let i=this.isOneChunk(e,r);if(i){let f=this.getView(i),l=e-i*this.chunkSize;return new Uint8Array(f.buffer.slice(l,l+r))}let n=new Uint8Array(r),s=e+r,a=Math.floor(e/this.chunkSize),o=Math.ceil((e+r)/this.chunkSize)-1,u=0;for(let f=a;f<=o;f++){let l=e+u,h=f*this.chunkSize,d=this.getView(f),c=Math.min(s,h+this.chunkSize),m=d.buffer.slice(l-h,c-h);n.set(new Uint8Array(m),u),u+=m.byteLength}return n}getView(e){let r=this.chunks.get(e);if(r==null)throw new Error(`Chunk:${e} is not ready`);return r}isOneChunk(e,r){let i=e+r-1,n=Math.floor(e/this.chunkSize);return Math.floor(i/this.chunkSize)-n<1?n:null}hasBytes(e,r=1){let i=Math.floor(e/this.chunkSize),n=Math.ceil((e+r)/this.chunkSize)-1;for(let s=i;s<=n;s++)if(!this.chunks.has(s))return!1;return!0}toRange(e,r){if(r==null)return`bytes=${e}`;if(e<0)throw new Error("Cannot read from remote source with negative offset and length");return`bytes=${e}-${e+r}`}parseContentRange(e){let[r,i]=e.split(" ");if(r!=="bytes")throw new Error("Failed to parse content-range: "+e);if(i==null)throw new Error("Failed to parse content-range: "+e);let[,n]=i.split("/"),s=Number(n);if(isNaN(s))throw new Error("Failed to parse content-range: "+e);return s}get buffer(){throw new Error("Method not implemented.")}get byteLength(){if(this._byteLength)return this._byteLength;throw Error(".size() has not been fetched.")}getUint8(e){let r=Math.floor(e/this.chunkSize),i=this.chunks.get(r);if(i==null)throw new Error(`Chunk:${r} is not ready`);return i.getUint8(e-r*this.chunkSize)}getUint16(e){let r=this.isOneChunk(e,Mt.UInt16);if(r!=null)return this.getView(r).getUint16(e-r*this.chunkSize,this.isLittleEndian);let i=this.getUint8(e),n=this.getUint8(e+Mt.UInt8);return this.isLittleEndian?i+(n<<8):(i<<8)+n}getUint32(e){let r=this.isOneChunk(e,Mt.UInt32);if(r!=null)return this.getView(r).getUint32(e-r*this.chunkSize,this.isLittleEndian);let i=this.getUint16(e),n=this.getUint16(e+Mt.UInt16);return this.isLittleEndian?i+n*65536:i*65536+n}getUint64(e){let r=this.isOneChunk(e,Mt.UInt64);if(r!=null){let s=this.getView(r);return Number(s.getBigUint64(e-r*this.chunkSize,this.isLittleEndian))}let i=this.getUint32(e),n=this.getUint32(e+Mt.UInt32);return this.isLittleEndian?i+n*cj:i*cj+n}getBigUint64(e){let r=this.isOneChunk(e,Mt.UInt64);if(r!=null)return this.getView(r).getBigUint64(e-r*this.chunkSize,this.isLittleEndian);let i=BigInt(this.getUint32(e)),n=BigInt(this.getUint32(e+Mt.UInt32));return this.isLittleEndian?i+(n<<BigInt(32)):(i<<BigInt(32))+n}getBigInt64(){throw new Error("Not implemented.")}};ko.DefaultChunkCache=()=>new Map;ko.DefaultDelayMs=1;var fj=at($4(),1);function hj(t){switch(t){case Gt.BYTE:case Gt.ASCII:case Gt.SBYTE:case Gt.UNDEFINED:return 1;case Gt.SHORT:case Gt.SSHORT:return 2;case Gt.LONG:case Gt.SLONG:case Gt.FLOAT:return 4;case Gt.RATIONAL:case Gt.SRATIONAL:case Gt.DOUBLE:case Gt.LONG8:case Gt.SLONG8:case Gt.IFD8:return 8;default:throw new Error(`Invalid fieldType ${t}`)}}var Cf={char:(t,e)=>String.fromCharCode(t.getUint8(e)),uint8:(t,e)=>t.getUint8(e),uint16:(t,e)=>t.getUint16(e),uint32:(t,e)=>t.getUint32(e),uint64:(t,e)=>t.getUint64(e),double:(t,e)=>fj.read(t.bytes(e,Mt.Double),0,t.isLittleEndian,52,8),rational:(t,e)=>[t.getUint32(e),t.getUint32(e+4)]};function zb(t){switch(t){case Gt.ASCII:return Cf.char;case Gt.BYTE:case Gt.UNDEFINED:case Gt.SBYTE:return Cf.uint8;case Gt.SHORT:case Gt.SSHORT:return Cf.uint16;case Gt.LONG:case Gt.SLONG:return Cf.uint32;case Gt.RATIONAL:case Gt.SRATIONAL:return Cf.rational;case Gt.DOUBLE:return Cf.double;case Gt.LONG8:return Cf.uint64;default:throw new Error(`Unknown read type "${t}" "${Gt[t]}"`)}}var kl=class{constructor(e,r,i){this.tiff=r,this.byteOffset=i,this.id=e,this.name=nt[this.id],this.dataType=this.tiff.source.getUint16(i+2),this.dataCount=this.tiff.source.getUint(i+4,this.tiff.ifdConfig.pointer),this.dataTypeSize=hj(this.dataType),this.dataLength=this.dataTypeSize*this.dataCount}get hasBytes(){return this.tiff.source.hasBytes(this.valuePointer,this.dataLength)}get isReady(){return!0}get dataTypeName(){return Gt[this.dataType]}get valuePointer(){let e=this.size-this.tiff.ifdConfig.pointer;return this.isValueInline?this.byteOffset+e:this.tiff.source.getUint(this.byteOffset+e,this.tiff.ifdConfig.pointer)}get size(){return this.tiff.ifdConfig.ifd}get isValueInline(){return this.dataLength<=this.tiff.ifdConfig.pointer}readValue(){let e=this.valuePointer,r=this.dataTypeSize,i=zb(this.dataType),n=this.dataCount,s=n*r;if(n===1)return i(this.tiff.source,e);let a=[];for(let o=0;o<s;o+=r)a.push(i(this.tiff.source,e+o));return this.dataType===Gt.ASCII?a.join("").trim():a}toJSON(){return{id:this.id,name:this.name,offset:this.byteOffset,isReady:this.isReady,type:this.dataTypeName,value:this.value}}};var Pf=class extends kl{constructor(){super(...arguments),this.value=null}get isReady(){return this.value!=null}async fetch(){return this.tiff.source.hasBytes(this.valuePointer,this.dataLength)===!1&&await this.tiff.source.loadBytes(this.valuePointer,this.dataLength),this.value=this.readValue(),this.value}};var D1=class extends kl{constructor(e,r,i){super(e,r,i),this.loadedValues=null}get value(){return this.loadedValues!=null?this.loadedValues:this.hasBytes?(this.readValue(),this.loadedValues):null}async load(){await this.tiff.source.loadBytes(this.valuePointer,this.dataLength),this.readValue()}readValue(){let e=super.readValue();return typeof e=="number"?this.loadedValues=[e]:this.loadedValues=e,this.loadedValues}async getValueAt(e){if(this.loadedValues)return this.loadedValues[e];let r=this.dataTypeSize,i=this.valuePointer+r*e,n=zb(this.dataType);return this.tiff.source.hasBytes(i,r)||await this.tiff.source.loadBytes(i,r),n(this.tiff.source,i)}};var q1=class extends kl{constructor(){super(...arguments),this._isRead=!1,this._value=null}get value(){return this._isRead===!1&&(this._value=this.readValue(),this._isRead=!0),this._value}};var Ub={create(t,e){let r=t.source.getUint16(e);if(r===nt.TileOffsets||r===nt.TileByteCounts||r===nt.StripByteCounts||r===nt.StripOffsets)return new D1(r,t,e);let i=new q1(r,t,e);return i.hasBytes?i:new Pf(r,t,e)},isStatic(t){return t instanceof q1},isLazy(t){return t instanceof Pf},isOffsetArray(t){return t instanceof D1}};var lbe=32767,Hb=class{constructor(e,r,i){this.tagsGeoLoaded=!1,this.tagsGeo=new Map,this.tif=e,this.id=r,this.tags=i}async init(e=!1){let r=[this.fetch(nt.Compression),this.fetch(nt.ImageHeight),this.fetch(nt.ImageWidth),this.fetch(nt.ModelPixelScale),this.fetch(nt.ModelTiePoint),this.fetch(nt.ModelTransformation),this.fetch(nt.TileHeight),this.fetch(nt.TileWidth)];e&&(r.push(this.fetch(nt.GeoKeyDirectory)),r.push(this.fetch(nt.GeoAsciiParams)),r.push(this.fetch(nt.GeoDoubleParams))),await Promise.all(r),e&&await this.loadGeoTiffTags()}value(e){let r=this.tags.get(e);return r==null?null:r.value}async loadGeoTiffTags(){if(this.tagsGeoLoaded)return;let e=this.tags.get(nt.GeoKeyDirectory);if(e==null){this.tagsGeoLoaded=!0;return}if(!e.isReady&&e instanceof Pf&&await Promise.all([this.fetch(nt.GeoKeyDirectory),this.fetch(nt.GeoAsciiParams),this.fetch(nt.GeoDoubleParams)]),this.tagsGeoLoaded=!0,e.value==null)return;let r=e.value;if(!Array.isArray(r))throw new Error("Invalid geo tags found");for(let i=4;i<=r[3]*4;i+=4){let n=r[i],s=r[i+1],a=r[i+3];if(s===0){this.tagsGeo.set(n,a);continue}let o=this.tags.get(s);if(o==null||o.value==null)continue;let u=r[i+2];Array.isArray(o.value)?this.tagsGeo.set(n,o.value[a+u-1]):typeof o.value=="string"&&this.tagsGeo.set(n,o.value.substr(a,a+u-1).trim())}}valueGeo(e){if(this.tagsGeoLoaded===!1)throw new Error("loadGeoTiffTags() has not been called");return this.tagsGeo.get(e)}async fetch(e){let r=this.tags.get(e);return r==null?null:Ub.isLazy(r)?r.fetch():r.value}get origin(){let e=this.value(nt.ModelTiePoint);if(e!=null&&e.length===6)return[e[3],e[4],e[5]];let r=this.value(nt.ModelTransformation);if(r!=null)return[r[3],r[7],r[11]];if(this.value(nt.NewSubFileType)===1&&this.id!==0)return this.tif.images[0].origin;throw new Error("Image does not have a geo transformation.")}get isGeoLocated(){return this.value(nt.ModelPixelScale)!=null||this.value(nt.ModelTransformation)!=null?!0:this.value(nt.NewSubFileType)===1&&this.id!==0?this.tif.images[0].isGeoLocated:!1}get resolution(){let e=this.value(nt.ModelPixelScale);if(e!=null)return[e[0],-e[1],e[2]];let r=this.value(nt.ModelTransformation);if(r!=null)return[r[0],r[5],r[10]];if(this.value(nt.NewSubFileType)===1&&this.id!==0){let i=this.tif.images[0],[n,s,a]=i.resolution,o=i.size,u=this.size;return[n*o.width/u.width,s*o.height/u.height,a]}throw new Error("Image does not have a geo transformation.")}get bbox(){let e=this.size,r=this.origin,i=this.resolution;if(r==null||e==null||i==null)throw new Error("Unable to calculate bounding box");let n=r[0],s=r[1],a=n+i[0]*e.width,o=s+i[1]*e.height;return[Math.min(n,a),Math.min(s,o),Math.max(n,a),Math.max(s,o)]}get compression(){let e=this.value(nt.Compression);return e==null||typeof e!="number"?null:D4[e]}get epsg(){let e=this.valueGeo(L1.ProjectedCSTypeGeoKey);return e===lbe?null:e}get size(){return{width:this.value(nt.ImageWidth),height:this.value(nt.ImageHeight)}}get tagList(){return[...this.tags.keys()].map(e=>nt[e])}isTiled(){return this.value(nt.TileWidth)!==null}get tileSize(){return{width:this.value(nt.TileWidth),height:this.value(nt.TileHeight)}}get tileCount(){let e=this.size,r=this.tileSize,i=Math.ceil(e.width/r.width),n=Math.ceil(e.height/r.height);return{x:i,y:n}}get tileOffset(){let e=this.tags.get(nt.TileOffsets);if(e==null)throw new Error("No tile offsets found");return e}get stripCount(){let e=this.tags.get(nt.StripByteCounts);return e==null?0:e.dataCount}async getTileOffset(e){let r=this.tileOffset;if(e<0||e>r.dataCount)throw new Error(`Tile offset: ${e} out of range: 0 -> ${r.dataCount}`);return r.getValueAt(e)}getTileBounds(e,r){let{size:i,tileSize:n}=this,s=r*n.height,a=e*n.width,o=a+n.width>=i.width?i.width-a:n.width,u=s+n.height>=i.height?i.height-s:n.height;return{x:a,y:s,width:o,height:u}}async getStrip(e){if(this.isTiled())throw new Error("Cannot read stripes, tiff is tiled");let r=this.tags.get(nt.StripByteCounts),i=this.tags.get(nt.StripOffsets);if(e>=r.dataCount)throw new Error("Cannot read strip, index out of bounds");let[n,s]=await Promise.all([i.getValueAt(e),r.getValueAt(e)]);return this.getBytes(n,s)}getJpegHeader(e){let r=this.value(nt.JPEGTables);if(r==null)throw new Error("Unable to find Jpeg header");let i=r.slice(0,r.length-2),n=new Uint8Array(e.byteLength+i.length-2);return n.set(i,0),n.set(e.slice(2),i.length),n}async getBytes(e,r){let i=this.compression;if(i==null)throw new Error("Unsupported compression: "+this.value(nt.Compression));if(r===0)return null;await this.tif.source.loadBytes(e,r);let n=this.tif.source.bytes(e,r);return this.compression===oa.JPEG?{mimeType:i,bytes:this.getJpegHeader(n)}:{mimeType:i,bytes:n}}async getTile(e,r){let i=this.compression,n=this.size,s=this.tileSize;if(s==null)throw new Error("Tiff is not tiled");if(i==null)throw new Error("Unsupported compression: "+this.value(nt.Compression));let a=Math.ceil(n.height/s.height),o=Math.ceil(n.width/s.width);if(e>=o||r>=a)throw new Error(`Tile index is outside of range x:${e} >= ${o} or y:${r} >= ${a}`);let u=r*o+e,f=o*a;if(u>=f)throw new Error(`Tile index is outside of tile range: ${u} >= ${f}`);let{offset:l,imageSize:h}=await this.getTileSize(u);return this.getBytes(l,h)}async getTileSize(e){if(this.tif.options.tileLeaderByteSize){let s=await this.getTileOffset(e);if(s===0)return{offset:0,imageSize:0};let a=this.tif.options.tileLeaderByteSize;return await this.tif.source.loadBytes(s-a,a),{offset:s,imageSize:this.tif.source.getUint(s-a,a)}}let r=this.tags.get(nt.TileByteCounts);if(r==null)throw new Error("No tile byte counts found");let[i,n]=await Promise.all([this.getTileOffset(e),r.getValueAt(e)]);return{offset:i,imageSize:n}}};var $1;(function(t){t[t.Big=19789]="Big",t[t.Little=18761]="Little"})($1||($1={}));var ua;(function(t){t[t.BigTiff=43]="BigTiff",t[t.Tiff=42]="Tiff"})(ua||(ua={}));var B4="__reverse";function dj(t,e){if(t[B4]==null){let r={};for(let i of Object.keys(t)){let n=t[i];r[n]=i}Object.defineProperty(t,B4,{enumerable:!1,value:r,writable:!1})}return t[B4][e]}var Ol;(function(t){t.GDAL_STRUCTURAL_METADATA_SIZE="GDAL_STRUCTURAL_METADATA_SIZE",t.LAYOUT="LAYOUT",t.BLOCK_ORDER="BLOCK_ORDER",t.BLOCK_LEADER="BLOCK_LEADER",t.BLOCK_TRAILER="BLOCK_TRAILER",t.KNOWN_INCOMPATIBLE_EDITION="KNOWN_INCOMPATIBLE_EDITION",t.MASK_INTERLEAVED_WITH_IMAGERY="MASK_INTERLEAVED_WITH_IMAGERY"})(Ol||(Ol={}));var F4;(function(t){t.RowMajor="ROW_MAJOR"})(F4||(F4={}));var j4;(function(t){t.uint32="SIZE_AS_UINT4"})(j4||(j4={}));var cbe={uint32:Mt.UInt32},Vb=class{constructor(){this.options=new Map}get isCogOptimized(){return this.isBroken?!1:this.options.get(Ol.LAYOUT)==="IFDS_BEFORE_DATA"}get isBroken(){return this.options.get(Ol.KNOWN_INCOMPATIBLE_EDITION)==="YES"}set(e,r){this.options.set(e,r)}process(e,r,i){let n=[];for(let a=r;a<r+i;a++){let o=e.getUint8(a);o!==0&&n.push(String.fromCharCode(o))}let s=n.join("").trim().split(`
|
|
809
809
|
`).map(a=>a.split("="));for(let[a,o]of s)this.options.set(Ol[a],o)}_getReverse(e,r){let i=this.options.get(r);return i==null?null:dj(e,i)}get tileOrder(){return this._getReverse(F4,Ol.BLOCK_ORDER)}get tileLeader(){return this._getReverse(j4,Ol.BLOCK_LEADER)}get tileLeaderByteSize(){return this.tileLeader==null?null:cbe[this.tileLeader]}get isMaskInterleaved(){return this.options.get(Ol.MASK_INTERLEAVED_WITH_IMAGERY)==="YES"}};var z4={version:ua.Tiff,pointer:Mt.UInt32,offset:Mt.UInt16,ifd:Mt.UInt16+Mt.UInt16+2*Mt.UInt32},U4={version:ua.BigTiff,pointer:Mt.UInt64,offset:Mt.UInt64,ifd:Mt.UInt16+Mt.UInt16+2*Mt.UInt64},TKe={[ua.BigTiff]:U4,[ua.Tiff]:z4};var H4=at($4(),1),Gb=class{constructor(e,r=0){this.tiff=e,this.byteOffset=r,this.relativeOffset=0}get currentOffset(){return this.byteOffset+this.relativeOffset}seekTo(e){return this.byteOffset=e,this.relativeOffset=0,this}seek(e){let r=this.currentOffset;return this.relativeOffset+=e,r}bytes(e){return this.tiff.source.bytes(this.seek(e),e)}uint(e){return this.tiff.source.getUint(this.seek(e),e)}uint8(){return this.tiff.source.getUint8(this.seek(Mt.UInt8))}uint16(){return this.tiff.source.getUint16(this.seek(Mt.UInt16))}uint32(){return this.tiff.source.getUint32(this.seek(Mt.UInt32))}uint64(){return this.tiff.source.getUint64(this.seek(Mt.UInt64))}pointer(){let e=this.tiff.ifdConfig.pointer;return this.tiff.source.getUint(this.seek(e),e)}offset(){let e=this.tiff.ifdConfig.offset;return this.tiff.source.getUint(this.seek(e),e)}float(){return H4.read(this.bytes(Mt.Float),0,this.tiff.source.isLittleEndian,23,4)}double(){return H4.read(this.bytes(Mt.Double),0,this.tiff.source.isLittleEndian,52,8)}};function pj(t,e=4,r=!0){let i=t.toString(16).padStart(e,"0");return r?"0x"+i:i}var Qd=class{constructor(e){this.version=ua.Tiff,this.images=[],this.options=new Vb,this.ifdConfig=z4,this.isInitialized=!1,this.source=e,this.cursor=new Gb(this)}static create(e){return new Qd(e).init()}init(e=!1){return this._initPromise?this._initPromise:(this._initPromise=this.doInit(e),this._initPromise)}async doInit(e=!1){return this.isInitialized?this:(await this.source.loadBytes(0,this.source.chunkSize),await this.fetchIfd(),await Promise.all(this.images.map(r=>r.init(e))),this.isInitialized=!0,this)}async fetchIfd(){let e=this.cursor.seekTo(0),r=e.uint16();if(this.source.isLittleEndian=r===$1.Little,!this.source.isLittleEndian)throw new Error("Only little endian is supported");this.version=e.uint16();let i;if(this.version===ua.BigTiff){if(this.ifdConfig=U4,e.uint16()!==8)throw new Error("Only 8byte pointers are supported");if(e.uint16()!==0)throw new Error("Invalid big tiff header");i=e.pointer()}else if(this.version===ua.Tiff)i=e.pointer();else throw new Error(`Only tiff supported version:${this.version}`);let n=i-this.cursor.currentOffset;return n>0&&n<16*1024,this.processIfd(i)}getImage(e){return this.images[e]}getImageByResolution(e){let r=this.images[0],i=r.size,[n]=r.resolution,s=n*i.width;for(let a=this.images.length-1;a>0;a--){let o=this.images[a],u=o.size;if(s/u.width-e<=.01)return o}return r}async getTile(e,r,i){let n=this.getImage(i);if(n==null)throw new Error(`Missing z: ${i}`);if(!n.isTiled())throw new Error("Tif is not tiled");return n.getTile(e,r)}async processIfd(e){this.source.hasBytes(e,4096)||await this.source.loadBytes(e,4096);let{image:r,nextOffset:i}=await this.readIfd(e);this.images.push(r),i&&await this.processIfd(i)}async readIfd(e){this.source.hasBytes(e,1024)||await this.source.loadBytes(e,this.source.chunkSize);let i=this.cursor.seekTo(e).offset(),n=e+this.ifdConfig.offset,s=new Map,a=n;for(let f=0;f<i;f++){let l=Ub.create(this,a);if(a+=l.size,l.name==null)throw new Error("Unknown IFD Tag: "+pj(l.id));s.set(l.id,l)}let o=new Hb(this,this.images.length,s);return{nextOffset:this.source.getUint(a,this.ifdConfig.pointer),image:o}}async close(){var e,r;await((r=(e=this.source)===null||e===void 0?void 0:e.close)===null||r===void 0?void 0:r.call(e))}};var hr=class{constructor(e){this.name=e}raw(e,r=0){return this.parse(e,{offset:r,startOffset:0})}read(e,r=0){let i={offset:r,startOffset:r};return{value:this.parse(e,i),offset:i.offset}}refine(e){return new V4(this,e)}},V4=class extends hr{constructor(e,r){super("Function:"+e.name),this.input=e,this.cb=r}get size(){return this.input.size}parse(e,r){let i=this.input.parse(e,r);return this.cb(i,e,r)}};var Wb=class extends hr{constructor(e,r,i){super(`Array:${e}:${r.name}x${i}`),this.count=i,this.type=r}get size(){return this.count*this.type.size}parse(e,r){let i=[];for(let n=0;n<this.count;n++)i.push(this.type.parse(e,r));return i}},Kb=class extends hr{constructor(e,r,i,n){super("Array:Offset:"+e),this.isLookupRequired=!0,this.isMaxLength=n,this.lengthName=i,this.type=r}get size(){throw new Error("Unable to calculate size of dynamic object: "+this.name)}parse(e,r,i){let n=[],s=i?.[this.lengthName];if(s==null||typeof s!="number")throw new Error(`${this.name}: Missing variable a "${this.lengthName}"`);this.isMaxLength&&(s-=r.offset-r.startOffset);for(let a=0;a<s;a++)n.push(this.type.parse(e,r));return n}};var mj=[];for(let t=0;t<64;t++)mj[t]=Math.pow(2,t);var B1=class{constructor(e,r=0,i=e.length,n=!0){if(this.buffer=e,this.offset=r*8,this.maxOffset=i*8,this.isLittleEndian=n,!this.isLittleEndian)throw new Error("BigEndian is not supported")}get remainingBits(){return this.maxOffset-this.offset}getBitValue(e,r,i){return(e&((1<<r+i)-1&~((1<<r)-1)))>>r}skip(e){this.offset+=e}bit(){if(this.remainingBits<0)throw new Error("BitStream: Overflow "+this.remainingBits);let e=Math.floor(this.offset/8),r=this.offset%8,i=this.buffer[e];return this.offset++,this.getBitValue(i,r,1)}bool(){return this.bit()===1}bits(e){let r=e,i=0;for(;e>0;)this.bit()===1&&(i+=mj[r-e]),e--;return i}string(e){let r=[];e==null&&(e=Math.floor(this.remainingBits/8));for(let i=0;i<e;i++){let n=this.bits(8);if(n===0)break;r.push(String.fromCharCode(n))}return r.join("")}};var Xb=class extends hr{constructor(e,r){super("Bits:"+e);let i=0;this.fields=Object.keys(r).map(n=>{let s=r[n];return i+=s,{key:n,bits:s}}),this.size=Math.ceil(i/8)}parse(e,r){let i=r.offset,n={},s=new B1(e,i,i+this.size);for(let{key:a,bits:o}of this.fields)n[a]=s.bits(o);return r.offset+=this.size,n}},Qb=class extends hr{constructor(e,r,i){super("BitsFlags:"+e),this.type=r,this.fields=Object.entries(i)}get size(){return this.type.size}parse(e,r){let i=this.type.parse(e,r),n={};for(let[s,a]of this.fields){let o=(i&a)===a;o&&(n[s]=o)}return n}};var Jb=class extends hr{constructor(e){super("Bytes:"+e),this.size=e}parse(e,r){let i=e.slice(r.offset,r.offset+this.size);return r.offset+=this.size,i}};var G4=class extends hr{constructor(){super(...arguments),this.size=1}parse(e,r){let i=r.offset;return r.offset+=this.size,e[i]}},W4=class extends hr{constructor(){super(...arguments),this.size=2}parse(e,r){let i=r.offset,n=e[i++],s=e[i++]<<8;return r.offset+=2,n|s}},K4=class extends hr{constructor(){super(...arguments),this.size=4}parse(e,r){let i=r.offset,n=e[i++],s=e[i++]<<8,a=e[i++]<<16,o=e[i++]*16777216;return r.offset=i,(n|s|a)+o}},fbe=2**32,X4=class extends hr{constructor(){super(...arguments),this.size=8}parse(e,r){let i=Jd.parse(e,r),n=Jd.parse(e,r);return i+n*fbe}},Q4=class extends hr{constructor(){super(...arguments),this.size=8}parse(e,r){let i=BigInt(Jd.parse(e,r)),n=BigInt(Jd.parse(e,r));return i+(n<<BigInt(32))}},gj=new G4("UInt8"),yj=new W4("LUInt16"),Jd=new K4("LUInt32"),vj=new X4("LUInt64"),bj=new Q4("BigLUInt64");var Yb=class extends hr{constructor(e,r,i){super("Lookup:"+e),this.lookup=i,this.type=r}get size(){return this.type.size}parse(e,r){let i=this.type.parse(e,r),n=this.lookup(i);if(n==null)throw new Error(`${this.name}: Failed to lookup ${i}`);return{id:i,name:n}}},Zb=class extends hr{constructor(e,r,i){super("Enum:"+e),this.enumeration=i,this.type=r}get size(){return this.type.size}parse(e,r){let i=this.type.parse(e,r),n=this.enumeration[i];if(n==null)throw new Error(`${this.name}: Failed to lookup ${i}`);return{id:i,name:n}}};var Yd=class extends hr{constructor(e,r){super(e),this._size=-1,this.fields=[];for(let[i,n]of Object.entries(r))this.fields.push({key:i,parser:n})}get size(){if(this._size>-1)return this._size;let e=0;for(let r of this.fields)e+=r.parser.size;return this._size=e,this._size}parse(e,r){let i={};for(let n of this.fields)i[n.key]=n.parser.parse(e,r,i);return i}},e2=class extends hr{constructor(e,r){super(e),this.fields=[],this._size=-1;let i=Object.entries(r),n=!1;for(let[s,a]of i)a.isLookupRequired&&(n=!0),this.fields.push({key:s,parser:a});i.length!==0&&(n?this.generateObjectAssign():this.generateSingleObject())}generateSingleObject(){let e=[],r='"use strict"; return {';for(let n=0;n<this.fields.length;n++)e.push(this.fields[n].parser),r+=` ${JSON.stringify(this.fields[n].key)}: _bp[${n}].parse(buf, ctx),`;r+=" };";let i=new Function("_bp","buf","ctx",r);this.parse=i.bind(null,e)}generateObjectAssign(){let e=[],r=`"use strict"; const ret = {};
|
|
810
810
|
`;for(let n=0;n<this.fields.length;n++)e.push(this.fields[n].parser),r+=`ret[${JSON.stringify(this.fields[n].key)}] = _bp[${n}].parse(buf, ctx, ret)
|
|
811
811
|
`;r+="return ret";let i=new Function("_bp","buf","ctx",r);this.parse=i.bind(null,e)}get size(){if(this._size>-1)return this._size;let e=0;for(let r of this.fields)e+=r.parser.size;return this._size=e,this._size}parse(e,r){return{}}};function Zd(t,e=2){return"0x"+t.toString(16).padStart(e,"0")}var t2=class extends hr{constructor(e,r){super("Offset:"+e.name+":"+r.name),this.type=r,this.offset=e}get size(){return this.type.size}parse(e,r){let i=this.offset.parse(e,r);if(i>e.length||i<0)throw new Error(`[${this.name}]: BufferOverflow attempted read at ${Zd(i)}`);return this.type.parse(e,{offset:i,startOffset:i})}};var r2=class extends hr{constructor(e){super("Skip:"+e),this.size=e}parse(e,r){r.offset+=this.size}};var n2=class extends hr{constructor(){super("String")}get size(){throw new Error("Unable to calculate size from dynamic object")}parse(e,r){let i=r.offset,n=[],s=0;for(;s+i<e.length;){let a=e[i+s];if(a===0)break;n.push(String.fromCharCode(a)),s++}return r.offset+=s+1,n.join("")}},i2=class extends hr{constructor(e){super("String:"+e),this.size=e}parse(e,r){let i=r.offset;if(this.size+i>e.length)throw new Error(`BufferOverflow: ${this.name} offset: ${Zd(r.offset)}`);let n=[],s=0;for(;s<this.size;){let a=e[i+s];if(a===0)break;n.push(String.fromCharCode(a)),s++}return r.offset+=this.size,n.join("")}};function hbe(t,e,r,i){return typeof r=="number"?new Wb(t,e,r):new Kb(t,e,r,i??!1)}var As={u8:gj,lu16:yj,lu32:Jd,lu64:vj,blu64:bj,empty:new Yd("Empty",{}),offset(t,e){return new t2(t,e)},string(t){return t==null?new n2:new i2(t)},bits(t,e){return new Xb(t,e)},flags(t,e,r){return new Qb(t,e,r)},object(t,e){return new e2(t,e)},static(t,e){return new Yd(t,e)},lookup(t,e,r){return new Yb(t,e,r)},enum(t,e,r){return new Zb(t,e,r)},bytes(t){return new Jb(t)},skip(t){return new r2(t)},array:hbe};var Sj;(function(t){t[t.File="0".charCodeAt(0)]="File",t[t.HardLink="1".charCodeAt(0)]="HardLink",t[t.SymLink="2".charCodeAt(0)]="SymLink",t[t.CharDeviceNode="3".charCodeAt(0)]="CharDeviceNode",t[t.BlockDeviceNode="4".charCodeAt(0)]="BlockDeviceNode",t[t.Directory="5".charCodeAt(0)]="Directory",t[t.FifoNode="6".charCodeAt(0)]="FifoNode",t[t.Reserved="7".charCodeAt(0)]="Reserved",t[t.LongName="L".charCodeAt(0)]="LongName",t[t.LongLink="K".charCodeAt(0)]="LongLink"})(Sj||(Sj={}));var dbe=As.object("TarHeader",{path:As.string(100),skip1:As.skip(24),size:As.bytes(12).refine(t=>parseInt(t.toString(),8)),skip2:As.skip(20),type:As.u8,linkName:As.string(100)});var wj={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},pbe={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n};function J4(t,{size:e=32}={}){if(!wj[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");let r=pbe[e],i=wj[e],n=!1;for(let s=0;s<t.length;s++){let a=t.charCodeAt(s);a>127&&!n&&(t=unescape(encodeURIComponent(t)),a=t.charCodeAt(s),n=!0),r^=BigInt(a),r=BigInt.asUintN(e,r*i)}return r}var s2="COT";var mbe=BigInt(0),gbe=BigInt(32),ybe=BigInt(2**32-1),_j=As.object("CotarMetadata",{magic:As.string(s2.length),version:As.u8,count:As.lu32}),Ua=class{constructor(e,r,i=0){this.isHeader=!0,this.source=e,this.sourceOffset=i,this.metadata=r}static hash(e){return J4(e,{size:64})}static async loadMetadata(e,r,i){if(i){await e.loadBytes(r,e.chunkSize);let s=e.bytes(r,8);return _j.read(s).value}let n=await e.fetchBytes(-8);return _j.read(new Uint8Array(n)).value}static async getMetadata(e,r,i){let n=await this.loadMetadata(e,r,i);if(n.magic!==s2)throw new Error(`Invalid source: ${e.uri} invalid magic found: ${n.magic}`);if(n.version===1||n.version===2)return n;throw new Error(`Invalid source: ${e.uri} invalid version found: ${n.version}`)}static async create(e,r=0,i=!0){let n=await this.getMetadata(e,r,i);return new Ua(e,n,r)}async find(e){if(this.metadata.version===1)return this._findV1(e);if(this.metadata.version===2)return this._findV2(e);throw new Error("Invalid metadata version")}async _findV2(e){let r=Ua.hash(e),i=this.metadata.count,n=Number(r%BigInt(i)),s=Number(r>>gbe),a=Number(r&ybe),o=null,u=null,f=n;for(;;){let l=this.sourceOffset+f*16+8;if(await this.source.loadBytes(l,16),u=this.source.getUint32(l),o=this.source.getUint32(l+4),o===s&&u===a){let h=this.source.getUint32(l+8)*512,d=this.source.getUint32(l+12);return{offset:h,size:d}}if(o===0&&u===0||(f++,f>=i&&(f=0),f===n))return null}}async _findV1(e){let r=Ua.hash(e),i=this.metadata.count,n=Number(r%BigInt(i)),s=null,a=n;for(;;){let o=this.sourceOffset+a*24+8;if(await this.source.loadBytes(o,24),s=this.source.getBigUint64(o),s===r){let u=this.source.getUint64(o+8),f=this.source.getUint64(o+16);return{offset:u,size:f}}if(s===mbe||(a++,a>=i&&(a=0),a===n))return null}}};var JXe=BigInt(0);var Rf=class{constructor(e,r){this.source=e,this.index=r}static async fromTar(e){let r=await Ua.getMetadata(e,0,!1),i=await e.size,n=r.version===1?24:16,s=i-(r.count*n+16),a=new Ua(e,r,s);return new Rf(e,a)}async get(e){let r=await this.index.find(e);return r==null?null:(await this.source.loadBytes(r.offset,r.size),this.source.bytes(r.offset,r.size))}};var Y4=class{constructor(){this.requests=[]}reset(){this.requests=[]}trace(e){let r=e.fetchBytes;e.fetchBytes=async(i,n)=>{let s={source:e.uri,offset:i,length:n},a=al(`${s.source}:${s.offset}:${s.length}`);s.id=a,this.requests.push(s);let o=Date.now(),u=await r.apply(e,[i,n]);return s.duration=Date.now()-o,u}}},Ml=new Y4;var o2=class{constructor(e){this.cacheA=new Map,this.cacheB=new Map,this.hits=0,this.misses=0,this.resets=0,this._lastCheckedAt=-1,this.maxSize=e}get(e){let r=this.cacheA.get(e);if(r)return this.hits++,r;let i=this.cacheB.get(e);return i==null?(this.misses++,null):(this.hits++,this.cacheA.set(e,i),this.cacheB.delete(e),i)}clear(){this.cacheA.clear(),this.cacheB.clear()}set(e,r){this.cacheA.set(e,r),this.check()}check(){this._lastCheckedAt=Date.now(),!(this.maxSize<=0)&&(this.currentSize<=this.maxSize||(this.resets++,this.cacheB=this.cacheA,this.cacheA=new Map))}get currentSize(){let e=0;for(let r of this.cacheA.values())e+=r.size;return e}};var u2=class{constructor(e){this.ob=e,this.ob._value==null&&this.ob.value.then(r=>this.ob._value=r)}get size(){let e=this.ob._value;return e==null?0:e.source.chunkSize*e.source.chunks.size}},Z4=class{constructor(e){this.cache=new o2(e)}getCog(e){var r;let i=(r=this.cache.get(e))===null||r===void 0?void 0:r.ob;if(i!=null){if(i.type==="cog")return i.value;throw new Error(`Existing object of type: ${i.type} made for location: ${e}`)}let n=bi.source(e);Ml.trace(n);let s=Qd.create(n);return this.cache.set(e,new u2({type:"cog",value:s})),s}getCotar(e){var r;let i=(r=this.cache.get(e))===null||r===void 0?void 0:r.ob;if(i!=null){if(i.type==="cotar")return i.value;throw new Error(`Existing object of type: ${i.type} made for location: ${e}`)}let n=bi.source(e);Ml.trace(n);let s=Rf.fromTar(n);return this.cache.set(e,new u2({type:"cotar",value:s})),s}},Ts=new Z4(256*1024*1024);async function z1(t,e,r,i){let n=await Ts.getCotar(e);if(n==null)return Ot();let s=await n.get(r);if(s==null)return Ot();let a=Buffer.from(s),o=Nr.key(a);if(Nr.isNotModified(t,o))return Rn();let u=Be.ok().buffer(a,i);return u.header(Xe.ETag,o),u.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Au(a)&&u.header(Xe.ContentEncoding,"gzip"),u}function Au(t){return t[0]===31&&t[1]===139}async function xj(t){let e=xr.get(xr.AssetLocation);if(e==null)return Ot();let r=l2.default.join("fonts",t.params.fontStack,t.params.range)+".pbf";if(e.endsWith(".tar.co"))return z1(t,e,r,"application/x-protobuf");try{let i=$r.join(e,r),n=await $r.read(i),s=Nr.key(n);if(Nr.isNotModified(t,s))return Rn();let a=Be.ok().buffer(n,"application/x-protobuf");return a.header(Xe.ETag,s),a.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Au(n)&&a.header(Xe.ContentEncoding,"gzip"),a}catch(i){if(i.code===404)return Ot();throw i}}async function bbe(t){let e=new Set;for await(let r of $r.list(t)){if(!r.endsWith(".pbf"))continue;let i=l2.default.basename(l2.default.dirname(r));i.includes("/")||e.add(i)}return[...e].sort()}async function Cj(t){let e=xr.get(xr.AssetLocation);if(e==null)return Ot();if(e.endsWith(".tar.co"))return z1(t,e,"fonts.json","application/json");try{let r=$r.join(e,"/fonts"),i=await bbe(r),n=Nr.key(i);if(Nr.isNotModified(t,n))return Rn();let s=Be.ok().buffer(JSON.stringify(i),"application/json");return s.header(Xe.ETag,n),s.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),s}catch(r){if(r.code===404)return Ot();throw r}}var s6=at(require("fs"),1),p2=at(require("path"),1),Mj=at(kj(),1),a6=at(require("sharp"),1),Lj=at(require("url"),1);var h2=at(require("sharp"),1);function _be(t){return t!=null}var f2=new Map,Ll=class{constructor(e){this.tileSize=e}isTooLarge(e){return!!(e.resize&&(e.resize.width>=Ll.MaxImageSize||e.resize.height>=Ll.MaxImageSize))}getEmptyImage(e,r){let i=[e,r.r,r.g,r.b,r.alpha].join("-"),n=f2.get(i);return n||(n=this.toImage(e,this.createImage(r)),f2.size>128&&f2.clear(),f2.set(i,n),n)}toImage(e,r){switch(e){case cr.Jpeg:return r.jpeg().toBuffer();case cr.Png:return r.png().toBuffer();case cr.Webp:return r.webp().toBuffer();case cr.Avif:return r.avif().toBuffer();default:throw new Error(`Invalid image format "${e}"`)}}async getImageBuffer(e,r,i){return e.length===0?this.getEmptyImage(r,i):this.toImage(r,this.createImage(i).composite(e))}isDirectImage(e){var r;if(e.layers.length!==1)return!1;let i=e.layers[0];if(i.x!==0||i.y!==0||i.crop!=null||i.extract!=null||i.resize!=null)return!1;let n=i.tiff.getImage(i.source.imageId),s=n.tileSize;return!(s.height!==this.tileSize||s.width!==this.tileSize||!(!((r=n.compression)===null||r===void 0)&&r.includes(e.format))||e.background.alpha!==0)}async compose(e){var r;let i=(r=e.metrics)!==null&&r!==void 0?r:new wf;if(i.start("compose:overlay"),this.isDirectImage(e)){let o=e.layers[0],u=await o.tiff.getTile(o.source.x,o.source.y,o.source.imageId);return i.end("compose:overlay"),u==null?{buffer:await this.getEmptyImage(e.format,e.background),metrics:i,layers:0}:(i.start("compose:direct"),i.end("compose:direct"),{buffer:Buffer.from(u.bytes),metrics:i,layers:1})}let n=[];for(let o of e.layers)this.isTooLarge(o)||n.push(this.composeTile(o,e.resizeKernel));let s=await Promise.all(n).then(o=>o.filter(_be));i.end("compose:overlay"),i.start("compose:compress");let a=await this.getImageBuffer(s,e.format,e.background);return i.end("compose:compress"),{buffer:a,metrics:i,layers:s.length}}async composeTile(e,r){let i=await e.tiff.getTile(e.source.x,e.source.y,e.source.imageId);if(i==null)return null;let n=(0,h2.default)(Buffer.from(i.bytes)),{extract:s,resize:a,crop:o}=e;if(s&&n.extract({top:0,left:0,width:s.width,height:s.height}),a){let u={fit:h2.default.fit.cover,kernel:a.scale>1?r.in:r.out};n.resize(a.width,a.height,u)}return o&&n.extract({top:o.y,left:o.x,width:o.width,height:o.height}),{input:await n.toBuffer(),top:e.y,left:e.x}}createImage(e){return(0,h2.default)({create:{width:this.tileSize,height:this.tileSize,channels:4,background:e}})}};Ll.MaxImageSize=256*2**15;var n6=class{constructor(e){Bw(this,"value");Bw(this,"next");this.value=e}},Oo,Tf,Nf,U1=class{constructor(){Gn(this,Oo,void 0);Gn(this,Tf,void 0);Gn(this,Nf,void 0);this.clear()}enqueue(e){let r=new n6(e);zt(this,Oo)?(zt(this,Tf).next=r,Vr(this,Tf,r)):(Vr(this,Oo,r),Vr(this,Tf,r)),Fw(this,Nf)._++}dequeue(){let e=zt(this,Oo);if(!!e)return Vr(this,Oo,zt(this,Oo).next),Fw(this,Nf)._--,e.value}clear(){Vr(this,Oo,void 0),Vr(this,Tf,void 0),Vr(this,Nf,0)}get size(){return zt(this,Nf)}*[Symbol.iterator](){let e=zt(this,Oo);for(;e;)yield e.value,e=e.next}};Oo=new WeakMap,Tf=new WeakMap,Nf=new WeakMap;function i6(t){if(!((Number.isInteger(t)||t===Number.POSITIVE_INFINITY)&&t>0))throw new TypeError("Expected `concurrency` to be a number from 1 and up");let e=new U1,r=0,i=()=>{r--,e.size>0&&e.dequeue()()},n=async(o,u,f)=>{r++;let l=(async()=>o(...f))();u(l);try{await l}catch{}i()},s=(o,u,f)=>{e.enqueue(n.bind(void 0,o,u,f)),(async()=>(await Promise.resolve(),r<t&&e.size>0&&e.dequeue()()))()},a=(o,...u)=>new Promise(f=>{s(o,f,u)});return Object.defineProperties(a,{activeCount:{get:()=>r},pendingCount:{get:()=>e.size},clearQueue:{value:()=>{e.clear()}}}),a}var Ebe=i6(xr.getNumber(xr.TiffConcurrency,25));function xbe(t){let e=t.toLowerCase();return e.endsWith(".tif")||e.endsWith(".tiff")?t:`${t}.tiff`}var Cbe=new Ll(256),Pbe={in:"lanczos3",out:"lanczos3"},Rbe={r:0,g:0,b:0,alpha:0},d2={async getTiffsForTile(t,e,r){let i=await Ke.getAllImagery(e.layers,[r.tileMatrix.projection]),n=[],s=r.tileMatrix.tileToSourceBounds(r.tile),a=pi.convertZoomLevel(r.tile.z,r.tileMatrix,jc.get(Ut.Google));for(let o of e.layers){if(o.maxZoom!=null&&a>o.maxZoom||o.minZoom!=null&&a<o.minZoom)continue;let u=o[r.tileMatrix.projection.code];if(u==null){t.log.warn({layer:o.name,projection:r.tileMatrix.projection.code},"Failed to lookup imagery");continue}let f=i.get(u);if(f==null){t.log.warn({layer:o.name,projection:r.tileMatrix.projection.code,imgId:u},"Failed to lookup imagery");continue}if(!!s.intersects(xt.fromJson(f.bounds)))for(let l of f.files){if(!s.intersects(xt.fromJson(l)))continue;let h=bi.join(f.uri,xbe(l.name));n.push(h)}}return n},async tile(t,e,r){var i,n;if(r.tileType===es.MapboxVectorTiles)return Ot();let s=await this.getTiffsForTile(t,e,r),a=Nr.key(s);if(Nr.isNotModified(t,a))return Rn();let o=[];for(let c of s)o.push(Ebe(()=>Ts.getCog(c).catch(m=>(t.log.warn({error:m,tiff:c},"TiffLoadFailed"),null))));let u=(await Promise.all(o)).filter(c=>c!=null),l=await new Xd(r.tileMatrix).tile(u,r.tile.x,r.tile.y,r.tile.z),h=await Cbe.compose({layers:l,format:r.tileType,background:(i=e.background)!==null&&i!==void 0?i:Rbe,resizeKernel:(n=e.resizeKernel)!==null&&n!==void 0?n:Pbe,metrics:t.timer});t.set("layersUsed",h.layers),t.set("bytes",h.buffer.byteLength);let d=new Be(200,"ok");return d.header(Xe.ETag,a),d.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),d.buffer(h.buffer,"image/"+r.tileType),d}};var Nbe={},Abe=[{tileSet:"health",tileMatrix:bn,tileType:cr.Png,tile:{x:252,y:156,z:8}},{tileSet:"health",tileMatrix:ou,tileType:cr.Png,tile:{x:30,y:33,z:6}}],Oj=256;async function Tbe(t){if(Buffer.isBuffer(t.buf))return t.buf;let e=t.tile,r=`static/expected_tile_${t.tileMatrix.identifier}_${e.x}_${e.y}_z${e.z}.${t.tileType}`;try{return await s6.promises.readFile(r)}catch(i){if(i.code!=="ENOENT")throw i;let n=p2.join(p2.dirname(Lj.default.fileURLToPath(Nbe.url)),"..","..",r);return await s6.promises.readFile(n)}}async function o6(t){let e=await Ke.TileSet.get(Ke.TileSet.id("health"));if(e==null)throw new Be(500,'TileSet: "health" not found');for(let i of Abe){let n=await d2.tile(t,e,i);if(n.status!==200)return new Be(500,n.statusDescription);if(!Buffer.isBuffer(n._body))throw new Be(500,"Not a Buffer response content.");let s=await(0,a6.default)(n._body).raw().toBuffer(),a=await Tbe(i);i.buf=a;let o=await(0,a6.default)(a).raw().toBuffer(),u=Buffer.alloc(o.length),f=(0,Mj.default)(o,s,u,Oj,Oj);if(f)return t.log.error({missMatchedPixels:f,projection:i.tileMatrix.identifier,xyz:i.tile},"Health:MissMatch"),new Be(500,"TileSet does not match.")}let r=new Be(200,"ok");return r.header(Xe.CacheControl,"no-store"),r}var Dj=require("util"),qj=require("zlib");var Ibe=(0,Dj.promisify)(qj.gzip);function kbe(t){return t==null?!1:!!(t.endsWith(".geojson")||t.endsWith(".json"))}async function $j(t){let e=t.params.fileName;if(!kbe(e))return Ot();let r=await Ke.Imagery.get(Ke.Imagery.id(t.params.imageryId));if(r==null)return Ot();let i=bi.join(r.uri,e);try{let n=await bi.read(i),s=Nr.key(n);if(Nr.isNotModified(t,s))return Rn();let a=new Be(200,"ok");return a.header(Xe.ETag,s),a.header(Xe.ContentEncoding,"gzip"),a.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),a.buffer(Au(n)?n:await Ibe(n),"application/json"),t.set("bytes",n.byteLength),a}catch{return t.log.warn({targetPath:i},"ImageryMetadata:Failed"),Ot()}}var Bj=new Be(200,"ok");Bj.header(Xe.CacheControl,"no-store");async function u6(){return Bj}var Fj=at(require("path"),1);var l6=new Map;l6.set(".png","image/png");l6.set(".json","application/json");async function jj(t){let e=xr.get(xr.AssetLocation);if(e==null)return Ot();let r=Fj.default.extname(t.params.spriteName),i=l6.get(r);if(i==null)return Ot();let n=$r.join("sprites",t.params.spriteName);if(e.endsWith(".tar.co"))return z1(t,e,n,i);try{let s=$r.join(e,n);t.set("target",s);let a=await $r.read(s),o=Nr.key(a);if(Nr.isNotModified(t,o))return Rn();let u=Be.ok().buffer(a,i);return u.header(Xe.ETag,o),u.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Au(a)&&u.header(Xe.ContentEncoding,"gzip"),u}catch(s){if(s.code===404)return Ot();throw s}}async function zj(t){var e,r,i,n;let s=ei.getTileMatrixSet(t.params.tileMatrix);if(s==null)return Ot();let a=ei.apiKey(t);t.timer.start("tileset:load");let o=await Ke.TileSet.get(Ke.TileSet.id(t.params.tileSet));if(t.timer.end("tileset:load"),o==null)return Ot();let u=(e=ei.getRequestedFormats(t))!==null&&e!==void 0?e:[o.format],h={tiles:[[(r=xr.get(xr.PublicUrlBase))!==null&&r!==void 0?r:"","v1","tiles",o.name,s.identifier,"{z}","{x}","{y}"].join("/")+`.${u[0]}?api=${a}`],tilejson:"3.0.0"},d=pi.convertZoomLevel((i=o.maxZoom)!==null&&i!==void 0?i:30,bn,s,!0),c=pi.convertZoomLevel((n=o.minZoom)!==null&&n!==void 0?n:0,bn,s,!0);o.maxZoom&&(h.maxzoom=d),o.minZoom&&(h.minzoom=c);let m=JSON.stringify(h),p=Buffer.from(m),y=new Be(200,"ok");return y.header(Xe.CacheControl,"no-store"),y.buffer(p,"application/json"),t.set("bytes",p.byteLength),y}var Uj=require("url");function m2(t,e){var r;if(t==null)return"";let i=(r=xr.get(xr.PublicUrlBase))!==null&&r!==void 0?r:"";if(!t.startsWith("/"))return t;let n=new Uj.URL($r.join(i,t));return e&&n.searchParams.set("api",e),n.toString().replace(/%7B/g,"{").replace(/%7D/g,"}")}function Obe(t,e){var r;let i=JSON.parse(JSON.stringify(t.sources));for(let[n,s]of Object.entries(i)){if(s.type==="vector")s.url=m2(s.url,e);else if(s.type==="raster"&&Array.isArray(s.tiles))for(let a=0;a<s.tiles.length;a++)s.tiles[a]=m2(s.tiles[a],e);i[n]=s}return{version:8,id:t.id,name:t.name,sources:i,layers:t.layers,metadata:(r=t.metadata)!==null&&r!==void 0?r:{},glyphs:m2(t.glyphs),sprite:m2(t.sprite)}}async function c6(t){let e=ei.apiKey(t),r=t.params.styleName,i=Ke.Style.id(r),n=await Ke.Style.get(i);if(n==null)return Ot();let s=Obe(n.style,e),a=Buffer.from(JSON.stringify(s)),o=Nr.key(a);if(Nr.isNotModified(t,o))return Rn();let u=new Be(200,"ok");return u.header(Xe.ETag,o),u.header(Xe.CacheControl,"no-store"),u.buffer(a,"application/json"),t.set("bytes",a.byteLength),u}var Kj=require("crypto");var Mbe={xmlns:"http://www.opengis.net/wmts/1.0","xmlns:ows":"http://www.opengis.net/ows/1.1","xmlns:xlink":"http://www.w3.org/1999/xlink","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","xmlns:gml":"http://www.opengis.net/gml","xsi:schemaLocation":"http://www.opengis.net/wmts/1.0 http://schemas.opengis.net/wmts/1.0/wmtsGetCapabilities_response.xsd",version:"1.0.0"};function Hj(t,e){return $a.get(t).boundsToWgs84BoundingBox(e)}var Vj=6,Gj=4;function Wj(t,e){return Number(t.toFixed(e)).toString()}function g2(t,e,r){return`${Wj(t,r)} ${Wj(e,r)}`}var y2=class{constructor(e){var r;this.tileMatrixSets=new Map,this.isIndividualLayers=!1,this.httpBase=e.httpBase,this.provider=e.provider,this.tileSet=e.tileSet,this.isIndividualLayers=e.isIndividualLayers;for(let i of e.tileMatrix)this.tileMatrixSets.set(i.identifier,i);this.apiKey=e.apiKey,this.formats=(r=e.formats)!==null&&r!==void 0?r:oj,this.imagery=e.imagery}async loadImagery(){let e=new Set;for(let r of this.tileMatrixSets.values())for(let i of this.tileSet.layers){let n=i[r.projection.code];n!=null&&e.add(n)}this.imagery=await Ke.Imagery.getAll(e)}buildWgs84BoundingBox(e,r){let i;if(r.length>0){let n=r[0];for(let s=1;s<r.length;s++)n=n.union(r[s]);i=Hj(e,n.toJson())}else i=Hj(e,e.extent);return i[2]<i[0]&&(i[0]=-180,i[2]=180),De("ows:WGS84BoundingBox",{crs:"urn:ogc:def:crs:OGC:2:84"},[De("ows:LowerCorner",g2(i[0],i[1],Vj)),De("ows:UpperCorner",g2(i[2],i[3],Vj))])}buildBoundingBoxFromImagery(e,r){let i;for(let s of r){let a=s[e.projection.code];if(a==null)continue;let o=this.imagery.get(a);o!=null&&(i==null?i=xt.fromJson(o.bounds):i=i.union(xt.fromJson(o.bounds)))}if(i==null)return null;let n=i.toBbox();return De("ows:BoundingBox",{crs:e.projection.toUrn()},[De("ows:LowerCorner",g2(n[e.indexX],n[e.indexY],Gj)),De("ows:UpperCorner",g2(n[e.indexX+2],n[e.indexY+2],Gj))])}buildProvider(){if(this.provider==null)return[];let{serviceIdentification:e,serviceProvider:r}=this.provider,{contact:i}=r;return[De("ows:ServiceIdentification",[De("ows:Title",e.title),De("ows:Abstract",e.description),De("ows:ServiceType","OGC WMTS"),De("ows:ServiceTypeVersion","1.0.0"),De("ows:Fees",e.fees),De("ows:AccessConstraints",e.accessConstraints)]),De("ows:ServiceProvider",[De("ows:ProviderName",r.name),De("ows:ProviderSite",{"xlink:href":r.site}),De("ows:ServiceContact",[De("ows:IndividualName",i.individualName),De("ows:PositionName",i.position),De("ows:ContactInfo",[De("ows:Phone",[De("ows:Voice",i.phone)]),De("ows:Address",[De("ows:DeliveryPoint",i.address.deliveryPoint),De("ows:City",i.address.city),De("ows:PostalCode",i.address.postalCode),De("ows:Country",i.address.country),De("ows:ElectronicMailAddress",i.address.email)])])])])]}buildTileUrl(e,r){let i=this.apiKey?`?api=${this.apiKey}`:"";return[this.httpBase,"v1","tiles",e,"{TileMatrixSet}","{TileMatrix}","{TileCol}",`{TileRow}.${r}${i}`].join("/")}buildResourceUrl(e,r){return De("ResourceURL",{format:"image/"+r,resourceType:"tile",template:this.buildTileUrl(e,r)})}buildLayerFromImagery(e){var r,i;let n=new Set,s=[];for(let l of this.tileMatrixSets.values()){let h=e[l.projection.code];h==null||this.imagery.get(h)==null||(s.push(De("TileMatrixSetLink",[De("TileMatrixSet",l.identifier)])),n.add(l))}let a=sl(e.name),o=[...n.values()],u=o[0];if(u==null)return null;let f=this.imagery.get((r=e[u.projection.code])!==null&&r!==void 0?r:"");return f==null?null:De("Layer",[De("ows:Title",(i=e.title)!==null&&i!==void 0?i:a),De("ows:Abstract",""),De("ows:Identifier",a),this.buildKeywords(f),...o.map(l=>this.buildBoundingBoxFromImagery(l,[e])),this.buildWgs84BoundingBox(u,[xt.fromJson(f.bounds)]),this.buildStyle(),...this.formats.map(l=>De("Format","image/"+l)),...s,...this.formats.map(l=>this.buildResourceUrl(a,l))])}buildLayer(e){var r,i,n,s;let a=new Set,o=[];for(let c of this.tileMatrixSets.values())e.layers.find(m=>m[c.projection.code]!=null)&&(o.push(De("TileMatrixSetLink",[De("TileMatrixSet",c.identifier)])),a.add(c));let u=sl(e.name),f=[...a.values()],l=f[0];if(l==null)throw new Error("No matrix sets found for layer "+e.name);let h=(r=f.find(c=>c.identifier===bn.identifier))!==null&&r!==void 0?r:l,d=[];for(let c of e.layers){let m=this.imagery.get((i=c[h.projection.code])!==null&&i!==void 0?i:"");m!=null&&d.push(xt.fromJson(m.bounds))}return De("Layer",[De("ows:Title",(n=e.title)!==null&&n!==void 0?n:u),De("ows:Abstract",(s=e.description)!==null&&s!==void 0?s:""),De("ows:Identifier",u),this.buildKeywords(e),...[...a.values()].map(c=>this.buildBoundingBoxFromImagery(c,e.layers)),this.buildWgs84BoundingBox(h,d),this.buildStyle(),...this.formats.map(c=>De("Format","image/"+c)),...o,...this.formats.map(c=>this.buildResourceUrl(u,c))])}buildKeywords(e){return e.category==null?De("ows:Keywords"):De("ows:Keywords",[De("ows:Keyword",e.category)])}buildStyle(){return De("Style",{isDefault:"true"},[De("ows:Title","Default Style"),De("ows:Identifier","default")])}buildTileMatrixSet(e){return De("TileMatrixSet",[De("ows:Title",e.def.title),e.def.abstract?De("ows:Abstract",e.def.abstract):null,De("ows:Identifier",e.identifier),De("ows:SupportedCRS",e.projection.toUrn()),e.def.wellKnownScaleSet?De("WellKnownScaleSet",e.def.wellKnownScaleSet):null,...e.def.tileMatrix.map(r=>De("TileMatrix",[De("ows:Identifier",r.identifier),De("ScaleDenominator",r.scaleDenominator),De("TopLeftCorner",r.topLeftCorner.join(" ")),De("TileWidth",r.tileWidth),De("TileHeight",r.tileHeight),De("MatrixWidth",r.matrixWidth),De("MatrixHeight",r.matrixHeight)]))])}toVNode(){let e=[];if(e.push(this.buildLayer(this.tileSet)),this.isIndividualLayers){let r=new Map;for(let n of this.tileSet.layers)r.set(sl(n.name),n);let i=Array.from(r.values()).sort((n,s)=>{var a,o;return((a=n.title)!==null&&a!==void 0?a:n.name).localeCompare((o=s.title)!==null&&o!==void 0?o:s.name)});for(let n of i)e.push(this.buildLayerFromImagery(n))}for(let r of this.tileMatrixSets.values())e.push(this.buildTileMatrixSet(r));return De("Capabilities",Mbe,[...this.buildProvider(),De("Contents",e)])}toXml(){return`<?xml version="1.0" encoding="utf-8"?>
|
|
812
|
-
`+this.toVNode().toString()}};function Lbe(t){if(t==null)return[bn,ou];let e=ei.getTileMatrixSet(t);return e==null?null:[e]}async function v2(t){var e,r;let i=ei.apiKey(t),n=(e=t.params.tileSet)!==null&&e!==void 0?e:"aerial",s=Lbe(t.params.tileMatrix);if(s==null)return Ot();let a=(r=xr.get(xr.PublicUrlBase))!==null&&r!==void 0?r:"";t.timer.start("tileset:load");let o=await Ke.TileSet.get(Ke.TileSet.id(n??"aerial"));if(t.timer.end("tileset:load"),o==null||o.type!==Gr.Raster)return Ot();let u=await Ke.Provider.get(Ke.Provider.id("linz"));t.timer.start("imagery:load");let f=await Ke.getAllImagery(o.layers,s.map(m=>m.projection));t.timer.end("imagery:load");let l=new y2({httpBase:a,provider:u??void 0,tileSet:o,tileMatrix:s,isIndividualLayers:t.params.tileMatrix==null,imagery:f,apiKey:i,formats:ei.getRequestedFormats(t)}).toXml();if(l==null)return Ot();let h=Buffer.from(l),d=(0,Kj.createHash)("sha256").update(h).digest("base64");if(Nr.isNotModified(t,d))return Rn();let c=new Be(200,"ok");return c.header(Xe.ETag,d),c.header(Xe.CacheControl,"no-store"),c.buffer(h,"text/xml"),t.set("bytes",h.byteLength),c}var Xj={async tile(t,e,r){if(r.tileType!==es.MapboxVectorTiles)return Ot();if(r.tileMatrix.identifier!==bn.identifier)return Ot();if(e.layers.length>1)return new Be(500,"Too many layers in tileset");let[i]=e.layers,n=i[3857];if(n==null)return new Be(500,"Layer url not found from tileset Config");let s=(1<<r.tile.z)-1-r.tile.y,a=`tiles/${r.tile.z}/${r.tile.x}/${s}.pbf.gz`,o=`${n}#${a}`,u=Nr.key(o);if(Nr.isNotModified(t,u))return Rn();t.timer.start("cotar:load");let f=await Ts.getCotar(n);if(f==null)return new Be(500,"Failed to load VectorTiles");t.timer.end("cotar:load"),t.timer.start("cotar:tile");let l=await f.get(a);if(l==null)return Ot();t.timer.end("cotar:tile");let h=Buffer.from(l),d=Be.ok().buffer(h,"application/x-protobuf");return d.header(Xe.ETag,u),d.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Au(h)&&d.header(Xe.ContentEncoding,"gzip"),d}};async function Qj(t){let e=ei.xyz(t);t.timer.start("tileset:load");let r=await Ke.TileSet.get(Ke.TileSet.id(e.tileSet));if(t.timer.end("tileset:load"),r==null)return Ot();switch(r.type){case Gr.Vector:return Xj.tile(t,r,e);case Gr.Raster:return d2.tile(t,r,e);default:return new Be(400,"Invalid tileset")}}async function f6(){var t;let e=new Be(200,"ok");return e.header(Xe.CacheControl,"no-store"),e.json({version:(t="v6.32.
|
|
812
|
+
`+this.toVNode().toString()}};function Lbe(t){if(t==null)return[bn,ou];let e=ei.getTileMatrixSet(t);return e==null?null:[e]}async function v2(t){var e,r;let i=ei.apiKey(t),n=(e=t.params.tileSet)!==null&&e!==void 0?e:"aerial",s=Lbe(t.params.tileMatrix);if(s==null)return Ot();let a=(r=xr.get(xr.PublicUrlBase))!==null&&r!==void 0?r:"";t.timer.start("tileset:load");let o=await Ke.TileSet.get(Ke.TileSet.id(n??"aerial"));if(t.timer.end("tileset:load"),o==null||o.type!==Gr.Raster)return Ot();let u=await Ke.Provider.get(Ke.Provider.id("linz"));t.timer.start("imagery:load");let f=await Ke.getAllImagery(o.layers,s.map(m=>m.projection));t.timer.end("imagery:load");let l=new y2({httpBase:a,provider:u??void 0,tileSet:o,tileMatrix:s,isIndividualLayers:t.params.tileMatrix==null,imagery:f,apiKey:i,formats:ei.getRequestedFormats(t)}).toXml();if(l==null)return Ot();let h=Buffer.from(l),d=(0,Kj.createHash)("sha256").update(h).digest("base64");if(Nr.isNotModified(t,d))return Rn();let c=new Be(200,"ok");return c.header(Xe.ETag,d),c.header(Xe.CacheControl,"no-store"),c.buffer(h,"text/xml"),t.set("bytes",h.byteLength),c}var Xj={async tile(t,e,r){if(r.tileType!==es.MapboxVectorTiles)return Ot();if(r.tileMatrix.identifier!==bn.identifier)return Ot();if(e.layers.length>1)return new Be(500,"Too many layers in tileset");let[i]=e.layers,n=i[3857];if(n==null)return new Be(500,"Layer url not found from tileset Config");let s=(1<<r.tile.z)-1-r.tile.y,a=`tiles/${r.tile.z}/${r.tile.x}/${s}.pbf.gz`,o=`${n}#${a}`,u=Nr.key(o);if(Nr.isNotModified(t,u))return Rn();t.timer.start("cotar:load");let f=await Ts.getCotar(n);if(f==null)return new Be(500,"Failed to load VectorTiles");t.timer.end("cotar:load"),t.timer.start("cotar:tile");let l=await f.get(a);if(l==null)return Ot();t.timer.end("cotar:tile");let h=Buffer.from(l),d=Be.ok().buffer(h,"application/x-protobuf");return d.header(Xe.ETag,u),d.header(Xe.CacheControl,"public, max-age=604800, stale-while-revalidate=86400"),Au(h)&&d.header(Xe.ContentEncoding,"gzip"),d}};async function Qj(t){let e=ei.xyz(t);t.timer.start("tileset:load");let r=await Ke.TileSet.get(Ke.TileSet.id(e.tileSet));if(t.timer.end("tileset:load"),r==null)return Ot();switch(r.type){case Gr.Vector:return Xj.tile(t,r,e);case Gr.Raster:return d2.tile(t,r,e);default:return new Be(400,"Invalid tileset")}}async function f6(){var t;let e=new Be(200,"ok");return e.header(Xe.CacheControl,"no-store"),e.json({version:(t="v6.32.1")!==null&&t!==void 0?t:"dev",hash:"4544a7d98667c5274142f1bb6bf61f02e4e5f618"}),e}var jr=Bi.http(os.get());jr.router.hook("request",t=>{t.set("name","LambdaTiler"),Ml.reset()});jr.router.hook("response",(t,e)=>{Ml.requests.length>0&&(t.set("requests",Ml.requests.slice(0,100)),t.set("requestCount",Ml.requests.length)),t.set("sources",{hits:Ts.cache.hits,misses:Ts.cache.misses,size:Ts.cache.currentSize,resets:Ts.cache.resets,cacheA:Ts.cache.cacheA.size,cacheB:Ts.cache.cacheB.size}),!(t instanceof Il)&&t.headers.has("origin")&&e.header("access-control-allow-origin","*")});jr.router.options("*",t=>jr.router.router.find("GET",t.path)==null?Ot():Be.ok());jr.router.get("/ping",u6);jr.router.get("/health",o6);jr.router.get("/version",f6);jr.router.get("/v1/ping",u6);jr.router.get("/v1/health",o6);jr.router.get("/v1/version",f6);jr.router.get("/v1/imagery/:imageryId/:fileName",$j);jr.router.get("/v1/sprites/:spriteName",jj);jr.router.get("/v1/fonts.json",Cj);jr.router.get("/v1/fonts/:fontStack/:range.pbf",xj);jr.router.get("/v1/styles/:styleName.json",c6);jr.router.get("/v1/tiles/:tileSet/:tileMatrix/style/:styleName.json",c6);jr.router.get("/v1/tiles/:tileSet/:tileMatrix/tile.json",zj);jr.router.get("/v1/tiles/:tileSet/:tileMatrix/:z/:x/:y.:tileType",Qj);jr.router.get("/v1/tiles/:tileSet/:tileMatrix/attribution.json",L4);jr.router.get("/v1/attribution/:tileSet/:tileMatrix/summary.json",L4);jr.router.get("/v1/tiles/:tileSet/:tileMatrix/WMTSCapabilities.xml",v2);jr.router.get("/v1/tiles/:tileSet/WMTSCapabilities.xml",v2);jr.router.get("/v1/tiles/WMTSCapabilities.xml",v2);var iie=at(SH(),1);var sie=at(nie(),1),aie=require("module"),gA=at(require("path"),1),oie=at(uu(),1),uie=require("url"),sLe={};function rLe(t){return typeof t!="object"||t==null?!1:"statusCode"in t}var nLe=oie.default.ulid();function iLe(){try{return typeof require<"u"&&typeof require.resolve=="function"?require.resolve("@basemaps/landing/dist"):(0,aie.createRequire)(sLe.url).resolve("@basemaps/landing/dist")}catch{return null}}async function lie(t,e){let r=(0,sie.default)();if(t.config.startsWith("dynamodb://")){let n=t.config.slice(11);e.info({path:t.config,table:n,mode:"dynamo"},"Starting Server"),Ke.setConfigProvider(new Fc(n))}else if(t.config.startsWith(Ke.ConfigBundle.prefix)){let n=await Ke.ConfigBundle.get(t.config);if(n==null)throw new Error(`Config bunble not exists for ${t.config}`);let s=await bi.readJson(n.path),a=ka.fromJson(s);a.createVirtualTileSets(),Ke.setConfigProvider(a)}else if(t.config.endsWith(".json")||t.config.endsWith(".json.gz")){e.info({path:t.config,mode:"config:bundle"},"Starting Server");let n=await bi.readJson(t.config),s=ka.fromJson(n);s.createVirtualTileSets(),Ke.setConfigProvider(s)}else{let n=await Jc.fromPath(t.config,e);e.info({path:t.config,mode:"config"},"Starting Server"),n.createVirtualTileSets(),Ke.setConfigProvider(n)}if(t.assets){if(!await bi.exists(t.assets))throw new Error(`--assets path "${t.assets}" does not exist`);e.info({path:t.assets},"Config:Assets"),process.env[xr.AssetLocation]=t.assets}let i=iLe();if(i==null)e.warn("Server:Landing:Failed");else{let n=gA.default.join(gA.default.dirname(i),"..","dist");e.info({path:n},"Server:Landing"),r.register(iie.default,{root:n})}return r.get("/v1/*",async(n,s)=>{let a=new uie.URL(`${n.protocol}://${n.hostname}${n.url}`),o={httpMethod:"GET",requestContext:{elb:{targetGroupArn:"arn:fake"}},path:a.pathname,headers:n.headers,queryStringParameters:n.query,body:null,isBase64Encoded:!1};n.query.api==null&&(n.query.api="c"+nLe),jr(o,{},(u,f)=>{if(u||!rLe(f)){Bi.Logger.fatal({err:u},"RequestFailed"),s.send(u);return}s.status(f.statusCode);for(let[l,h]of Object.entries(f.headers??{}))s.header(l,String(h));f.body?s.send(Buffer.from(f.body,f.isBase64Encoded?"base64":"utf8")):s.send("Not found")})}),r}g4.package="basemaps/server";var cie=5e3,ew=class extends Nb{constructor(){super({toolFilename:"basemaps-server",toolDescription:"Create a WMTS/XYZ Tile server from basemaps config"});this.config=this.defineStringParameter({argumentName:"CONFIG",parameterLongName:"--config",description:"Configuration source to use"});this.assets=this.defineStringParameter({argumentName:"ASSETS",parameterLongName:"--assets",description:"Where the assets (sprites, fonts) are located"});this.port=this.defineIntegerParameter({argumentName:"PORT",parameterLongName:"--port",description:"port to use",defaultValue:cie})}async onExecute(){await super.onExecute();let r=os.get();r.level="debug";let i=this.config.value??"dynamodb://"+Yc.TileMetadata.TableName,n=this.port.value,s=this.assets.value,a=xr.get(xr.PublicUrlBase)??`http://localhost:${n}`;process.env[xr.PublicUrlBase]=a,(await lie({config:i,assets:s},r)).listen(n??cie,"0.0.0.0",()=>{r.info({url:a},"ServerStarted")})}};Error.stackTraceLimit=100;new ew().run();
|
|
813
813
|
/*!
|
|
814
814
|
* content-disposition
|
|
815
815
|
* Copyright(c) 2014-2017 Douglas Christopher Wilson
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@basemaps/server",
|
|
3
|
-
"version": "6.32.
|
|
3
|
+
"version": "6.32.1",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/linz/basemaps.git",
|
|
@@ -44,20 +44,20 @@
|
|
|
44
44
|
"bin/"
|
|
45
45
|
],
|
|
46
46
|
"optionalDependencies": {
|
|
47
|
-
"@basemaps/landing": "^6.32.
|
|
47
|
+
"@basemaps/landing": "^6.32.1"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
50
|
"sharp": "^0.30.7"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
|
-
"@basemaps/config": "^6.32.
|
|
54
|
-
"@basemaps/geo": "^6.
|
|
55
|
-
"@basemaps/lambda-tiler": "^6.32.
|
|
53
|
+
"@basemaps/config": "^6.32.1",
|
|
54
|
+
"@basemaps/geo": "^6.32.1",
|
|
55
|
+
"@basemaps/lambda-tiler": "^6.32.1",
|
|
56
56
|
"@basemaps/landing": "^6.27.0",
|
|
57
|
-
"@basemaps/shared": "^6.32.
|
|
57
|
+
"@basemaps/shared": "^6.32.1",
|
|
58
58
|
"@fastify/static": "^5.0.2",
|
|
59
59
|
"fastify": "^3.27.4",
|
|
60
60
|
"pretty-json-log": "^1.0.0"
|
|
61
61
|
},
|
|
62
|
-
"gitHead": "
|
|
62
|
+
"gitHead": "4544a7d98667c5274142f1bb6bf61f02e4e5f618"
|
|
63
63
|
}
|