@datafn/server 0.1.0 → 0.1.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/dist/index.d.cts CHANGED
@@ -4,6 +4,7 @@ import { DatafnSchema, DatafnPlugin as DatafnPlugin$1 } from '@datafn/core/types
4
4
  import { Route, Router } from '@superfunctions/http';
5
5
  import { ConditionalKVStoreAdapter, IndexedDirectoryStoreAdapter, Adapter, AtomicKVStoreAdapter, RuntimeStores, RowLevelNamespaceConfig } from '@superfunctions/db';
6
6
  import { DatafnError } from '@datafn/core/errors';
7
+ export { DatafnPlacementConstraint, DatafnPlacementConstraintContext, DatafnPlacementDecision, DatafnPlacementDecisionSource, DatafnPlacementLocation, DatafnPlacementRankingInput, DatafnPlacementRegionCandidate, DatafnPlacementSelectionInput, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, selectDatafnPlacementRegion } from './placement.cjs';
7
8
 
8
9
  /**
9
10
  * SearchProvider interface for server-side search integration.
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ import { DatafnSchema, DatafnPlugin as DatafnPlugin$1 } from '@datafn/core/types
4
4
  import { Route, Router } from '@superfunctions/http';
5
5
  import { ConditionalKVStoreAdapter, IndexedDirectoryStoreAdapter, Adapter, AtomicKVStoreAdapter, RuntimeStores, RowLevelNamespaceConfig } from '@superfunctions/db';
6
6
  import { DatafnError } from '@datafn/core/errors';
7
+ export { DatafnPlacementConstraint, DatafnPlacementConstraintContext, DatafnPlacementDecision, DatafnPlacementDecisionSource, DatafnPlacementLocation, DatafnPlacementRankingInput, DatafnPlacementRegionCandidate, DatafnPlacementSelectionInput, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, selectDatafnPlacementRegion } from './placement.js';
7
8
 
8
9
  /**
9
10
  * SearchProvider interface for server-side search integration.
package/dist/index.js CHANGED
@@ -20383,6 +20383,142 @@ function bytesToBase64Url(bytes) {
20383
20383
  return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
20384
20384
  }
20385
20385
 
20386
- export { AtomicSequenceStore, ChainedSequenceStore, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, DatabaseSequenceStore, DatafnExecutorError, DatafnPublicLinkInputError, DatafnRoutingError, claimDatafnNamespacePlacement, createConditionalKvDatafnPlacementDirectory, createDatafnGatewayRouter, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, migrateDatafnNamespace, readDatafnPublicLinkToken, resolveDatafnPublicLink, validateDatafnPlacement, validateDatafnRoutingBodyLimit, withDatafnPublicLinksSchema, withDatafnRoutingAssertion };
20386
+ // src/placement-policy.ts
20387
+ var CONTINENT_CENTERS = {
20388
+ AF: [1.65, 17.68],
20389
+ AN: [-82.86, 135],
20390
+ AS: [34.05, 100.62],
20391
+ EU: [54.53, 15.26],
20392
+ NA: [54.53, -105.26],
20393
+ OC: [-22.74, 140.02],
20394
+ SA: [-14.24, -51.93]
20395
+ };
20396
+ function finiteCoordinate(value, minimum, maximum) {
20397
+ return value !== void 0 && Number.isFinite(value) && value >= minimum && value <= maximum;
20398
+ }
20399
+ function normalizedCandidates(input) {
20400
+ const context = {
20401
+ location: input.location ?? null,
20402
+ preferredRegionId: normalizedPreferredRegionId(input.preferredRegionId)
20403
+ };
20404
+ const seen = /* @__PURE__ */ new Set();
20405
+ const candidates = input.candidates.map((candidate) => {
20406
+ const regionId = candidate.regionId.trim();
20407
+ if (!regionId) throw new Error("DATAFN_PLACEMENT_REGION_ID_REQUIRED");
20408
+ if (seen.has(regionId)) {
20409
+ throw new Error(`DATAFN_PLACEMENT_REGION_DUPLICATE: ${regionId}`);
20410
+ }
20411
+ seen.add(regionId);
20412
+ return regionId === candidate.regionId ? candidate : { ...candidate, regionId };
20413
+ });
20414
+ return candidates.filter(
20415
+ (candidate) => (input.constraints ?? []).every(
20416
+ (constraint) => constraint(candidate, context)
20417
+ )
20418
+ );
20419
+ }
20420
+ function normalizedPreferredRegionId(preferredRegionId) {
20421
+ return preferredRegionId?.trim() || null;
20422
+ }
20423
+ function compareRegionIds(left, right) {
20424
+ return left < right ? -1 : left > right ? 1 : 0;
20425
+ }
20426
+ function sourceCoordinates(location) {
20427
+ if (!location) return null;
20428
+ if (finiteCoordinate(location.latitude, -90, 90) && finiteCoordinate(location.longitude, -180, 180)) {
20429
+ return {
20430
+ coordinates: [location.latitude, location.longitude],
20431
+ source: "coordinates"
20432
+ };
20433
+ }
20434
+ const continent = location.continent?.toUpperCase();
20435
+ const coordinates = continent ? CONTINENT_CENTERS[continent] : void 0;
20436
+ return coordinates ? { coordinates, source: "continent" } : null;
20437
+ }
20438
+ function radians(degrees) {
20439
+ return degrees * Math.PI / 180;
20440
+ }
20441
+ function distanceKilometers(source, target) {
20442
+ const sourceLatitude = radians(source[0]);
20443
+ const targetLatitude = radians(target[0]);
20444
+ const latitudeDelta = radians(target[0] - source[0]);
20445
+ const longitudeDelta = radians(target[1] - source[1]);
20446
+ const haversine = Math.sin(latitudeDelta / 2) ** 2 + Math.cos(sourceLatitude) * Math.cos(targetLatitude) * Math.sin(longitudeDelta / 2) ** 2;
20447
+ const clampedHaversine = Math.min(1, Math.max(0, haversine));
20448
+ return 6371 * 2 * Math.atan2(Math.sqrt(clampedHaversine), Math.sqrt(1 - clampedHaversine));
20449
+ }
20450
+ function rankDatafnPlacementRegions(input) {
20451
+ const candidates = normalizedCandidates(input);
20452
+ const source = sourceCoordinates(input.location ?? null);
20453
+ if (!source) return [];
20454
+ return candidates.flatMap((candidate) => {
20455
+ const { latitude, longitude } = candidate;
20456
+ return finiteCoordinate(latitude, -90, 90) && finiteCoordinate(longitude, -180, 180) ? [
20457
+ {
20458
+ regionId: candidate.regionId,
20459
+ source: source.source,
20460
+ distanceKilometers: distanceKilometers(source.coordinates, [
20461
+ latitude,
20462
+ longitude
20463
+ ])
20464
+ }
20465
+ ] : [];
20466
+ }).sort(
20467
+ (left, right) => (left.distanceKilometers ?? 0) - (right.distanceKilometers ?? 0) || compareRegionIds(left.regionId, right.regionId)
20468
+ );
20469
+ }
20470
+ function stableIndex(key, length) {
20471
+ let hash = 2166136261;
20472
+ for (const byte of new TextEncoder().encode(key)) {
20473
+ hash ^= byte;
20474
+ hash = Math.imul(hash, 16777619) >>> 0;
20475
+ }
20476
+ return hash % length;
20477
+ }
20478
+ function selectDatafnPlacementRegion(input) {
20479
+ const candidates = normalizedCandidates(input);
20480
+ const preferredRegionId = normalizedPreferredRegionId(
20481
+ input.preferredRegionId
20482
+ );
20483
+ if (preferredRegionId && candidates.some((candidate) => candidate.regionId === preferredRegionId)) {
20484
+ return { regionId: preferredRegionId, source: "preferred" };
20485
+ }
20486
+ const ranked = rankDatafnPlacementRegions({
20487
+ candidates,
20488
+ location: input.location ?? null
20489
+ });
20490
+ const nearest = ranked[0];
20491
+ if (nearest) return nearest;
20492
+ if (input.stableKey !== void 0 && candidates.length > 0) {
20493
+ const stableCandidates = [...candidates].sort(
20494
+ (left, right) => compareRegionIds(left.regionId, right.regionId)
20495
+ );
20496
+ const selected = stableCandidates[stableIndex(input.stableKey, stableCandidates.length)];
20497
+ if (selected) {
20498
+ return { regionId: selected.regionId, source: "stable-fallback" };
20499
+ }
20500
+ }
20501
+ return null;
20502
+ }
20503
+ function coordinate(value, minimum, maximum) {
20504
+ const parsed = typeof value === "number" ? value : Number(value);
20505
+ return Number.isFinite(parsed) && parsed >= minimum && parsed <= maximum ? parsed : void 0;
20506
+ }
20507
+ function readDatafnCloudflarePlacementLocation(request) {
20508
+ const cf = request.cf;
20509
+ if (!cf) return null;
20510
+ const latitude = coordinate(cf.latitude, -90, 90);
20511
+ const longitude = coordinate(cf.longitude, -180, 180);
20512
+ const continent = typeof cf.continent === "string" && /^[A-Za-z]{2}$/u.test(cf.continent) ? cf.continent.toUpperCase() : void 0;
20513
+ if (latitude === void 0 && longitude === void 0 && !continent)
20514
+ return null;
20515
+ return {
20516
+ ...latitude === void 0 ? {} : { latitude },
20517
+ ...longitude === void 0 ? {} : { longitude },
20518
+ ...continent ? { continent } : {}
20519
+ };
20520
+ }
20521
+
20522
+ export { AtomicSequenceStore, ChainedSequenceStore, DATAFN_MULTI_REGION_CAPABILITY, DATAFN_ROUTING_ASSERTION_HEADER, DATAFN_ROUTING_INTERNAL_HEADERS, DatabaseSequenceStore, DatafnExecutorError, DatafnPublicLinkInputError, DatafnRoutingError, claimDatafnNamespacePlacement, createConditionalKvDatafnPlacementDirectory, createDatafnGatewayRouter, createDatafnHmacRoutingAssertions, createDatafnMultiRegionPlugin, createDatafnPublicLinksPlugin, createDatafnServer, createMemoryDatafnPlacementDirectory, createMemoryDatafnRoutingReplayStore, createSequenceStore, datafn, datafnMultiRegionPlugin, migrateDatafnNamespace, rankDatafnPlacementRegions, readDatafnCloudflarePlacementLocation, readDatafnPublicLinkToken, resolveDatafnPublicLink, selectDatafnPlacementRegion, validateDatafnPlacement, validateDatafnRoutingBodyLimit, withDatafnPublicLinksSchema, withDatafnRoutingAssertion };
20387
20523
  //# sourceMappingURL=index.js.map
20388
20524
  //# sourceMappingURL=index.js.map