@gadicc/loom 2.3.1 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/.loom-source-manifest.json +7 -1
  2. package/esm/src/geo/client.d.ts +74 -0
  3. package/esm/src/geo/client.d.ts.map +1 -0
  4. package/esm/src/geo/client.js +135 -0
  5. package/esm/src/geo/client.js.map +1 -0
  6. package/esm/src/geo/mod.d.ts +5 -0
  7. package/esm/src/geo/mod.d.ts.map +1 -0
  8. package/esm/src/geo/mod.js +5 -0
  9. package/esm/src/geo/mod.js.map +1 -0
  10. package/esm/src/geo/place.d.ts +28 -0
  11. package/esm/src/geo/place.d.ts.map +1 -0
  12. package/esm/src/geo/place.js +41 -0
  13. package/esm/src/geo/place.js.map +1 -0
  14. package/esm/src/geo/places.d.ts +16 -0
  15. package/esm/src/geo/places.d.ts.map +1 -0
  16. package/esm/src/geo/places.js +154 -0
  17. package/esm/src/geo/places.js.map +1 -0
  18. package/esm/src/geo/placesFormat.d.ts +49 -0
  19. package/esm/src/geo/placesFormat.d.ts.map +1 -0
  20. package/esm/src/geo/placesFormat.js +38 -0
  21. package/esm/src/geo/placesFormat.js.map +1 -0
  22. package/esm/src/geo/preference.d.ts +15 -0
  23. package/esm/src/geo/preference.d.ts.map +1 -0
  24. package/esm/src/geo/preference.js +21 -0
  25. package/esm/src/geo/preference.js.map +1 -0
  26. package/esm/src/geo/timeZone.d.ts +20 -0
  27. package/esm/src/geo/timeZone.d.ts.map +1 -0
  28. package/esm/src/geo/timeZone.js +65 -0
  29. package/esm/src/geo/timeZone.js.map +1 -0
  30. package/esm/src/geo/vercel.d.ts +15 -0
  31. package/esm/src/geo/vercel.d.ts.map +1 -0
  32. package/esm/src/geo/vercel.js +64 -0
  33. package/esm/src/geo/vercel.js.map +1 -0
  34. package/package.json +26 -2
  35. package/source/src/geo/client.ts +241 -0
  36. package/source/src/geo/mod.ts +12 -0
  37. package/source/src/geo/place.ts +61 -0
  38. package/source/src/geo/places.ts +195 -0
  39. package/source/src/geo/placesFormat.ts +58 -0
  40. package/source/src/geo/preference.ts +24 -0
  41. package/source/src/geo/timeZone.ts +78 -0
  42. package/source/src/geo/vercel.ts +78 -0
@@ -0,0 +1,15 @@
1
+ import { type Place } from "./place.js";
2
+ /** A future default, distinct from an acquired position or an entry override. */
3
+ export type LocationPreference = {
4
+ version: 2;
5
+ mode: "automatic";
6
+ } | {
7
+ version: 2;
8
+ mode: "fixed";
9
+ place: Place;
10
+ };
11
+ /** The default stores no detected or device coordinates. */
12
+ export declare const AUTOMATIC_LOCATION: LocationPreference;
13
+ /** Validates versioned browser JSON, preserving only explicit fixed-city intent. */
14
+ export declare function toLocationPreference(value: unknown): LocationPreference | null;
15
+ //# sourceMappingURL=preference.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preference.d.ts","sourceRoot":"","sources":["../../../source/src/geo/preference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,KAAK,EAAW,MAAM,YAAY,CAAC;AAEjD,iFAAiF;AACjF,MAAM,MAAM,kBAAkB,GAC1B;IAAE,OAAO,EAAE,CAAC,CAAC;IAAC,IAAI,EAAE,WAAW,CAAA;CAAE,GACjC;IAAE,OAAO,EAAE,CAAC,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,CAAC;AAChD,4DAA4D;AAC5D,eAAO,MAAM,kBAAkB,EAAE,kBAG/B,CAAC;AAEH,oFAAoF;AACpF,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,GACb,kBAAkB,GAAG,IAAI,CAQ3B"}
@@ -0,0 +1,21 @@
1
+ import { toPlace } from "./place.js";
2
+ /** The default stores no detected or device coordinates. */
3
+ export const AUTOMATIC_LOCATION = Object.freeze({
4
+ version: 2,
5
+ mode: "automatic",
6
+ });
7
+ /** Validates versioned browser JSON, preserving only explicit fixed-city intent. */
8
+ export function toLocationPreference(value) {
9
+ if (typeof value !== "object" || value === null)
10
+ return null;
11
+ const v = value;
12
+ if (v.version !== 2)
13
+ return null;
14
+ if (v.mode === "automatic")
15
+ return AUTOMATIC_LOCATION;
16
+ if (v.mode !== "fixed")
17
+ return null;
18
+ const place = toPlace(v.place);
19
+ return place ? { version: 2, mode: "fixed", place } : null;
20
+ }
21
+ //# sourceMappingURL=preference.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preference.js","sourceRoot":"","sources":["../../../source/src/geo/preference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,OAAO,EAAE,MAAM,YAAY,CAAC;AAMjD,4DAA4D;AAC5D,MAAM,CAAC,MAAM,kBAAkB,GAAuB,MAAM,CAAC,MAAM,CAAC;IAClE,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,WAAW;CAClB,CAAC,CAAC;AAEH,oFAAoF;AACpF,MAAM,UAAU,oBAAoB,CAClC,KAAc;IAEd,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC7D,MAAM,CAAC,GAAG,KAAgC,CAAC;IAC3C,IAAI,CAAC,CAAC,OAAO,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACjC,IAAI,CAAC,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,kBAAkB,CAAC;IACtD,IAAI,CAAC,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;IAC/B,OAAO,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7D,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The zone's offset from UTC at `date`, in minutes east (London in summer
3
+ * 60, New York in winter -300). Throws a RangeError for a zone the runtime
4
+ * does not know.
5
+ */
6
+ export declare function utcOffsetMinutes(zone: string, date: Date): number;
7
+ /**
8
+ * The device's IANA time zone, or undefined where the runtime has none or
9
+ * names one it can't then use.
10
+ */
11
+ export declare function deviceTimeZone(): string | undefined;
12
+ /**
13
+ * Whether a clock in `zone` would read differently from one in `deviceZone`
14
+ * at any of `times`. Compares UTC offsets, not names, since sources name the
15
+ * same zone differently (GeoNames' Asia/Kolkata is V8's Asia/Calcutta, and
16
+ * Europe/Kyiv is Europe/Kiev in older data). False when either zone is
17
+ * unknown to the runtime: no note is better than a wrong one.
18
+ */
19
+ export declare function clocksDiffer(zone: string, deviceZone: string, times: readonly Date[]): boolean;
20
+ //# sourceMappingURL=timeZone.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timeZone.d.ts","sourceRoot":"","sources":["../../../source/src/geo/timeZone.ts"],"names":[],"mappings":"AAoBA;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,GAAG,MAAM,CAejE;AAED;;;GAGG;AACH,wBAAgB,cAAc,IAAI,MAAM,GAAG,SAAS,CASnD;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,SAAS,IAAI,EAAE,GACrB,OAAO,CAST"}
@@ -0,0 +1,65 @@
1
+ const formatters = new Map();
2
+ function formatterFor(zone) {
3
+ let formatter = formatters.get(zone);
4
+ if (!formatter) {
5
+ formatter = new Intl.DateTimeFormat("en-US", {
6
+ timeZone: zone,
7
+ hourCycle: "h23",
8
+ year: "numeric",
9
+ month: "numeric",
10
+ day: "numeric",
11
+ hour: "numeric",
12
+ minute: "numeric",
13
+ second: "numeric",
14
+ });
15
+ formatters.set(zone, formatter);
16
+ }
17
+ return formatter;
18
+ }
19
+ /**
20
+ * The zone's offset from UTC at `date`, in minutes east (London in summer
21
+ * 60, New York in winter -300). Throws a RangeError for a zone the runtime
22
+ * does not know.
23
+ */
24
+ export function utcOffsetMinutes(zone, date) {
25
+ const parts = {};
26
+ for (const part of formatterFor(zone).formatToParts(date)) {
27
+ if (part.type !== "literal")
28
+ parts[part.type] = Number(part.value);
29
+ }
30
+ const wall = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
31
+ const instant = Math.floor(date.getTime() / 1000) * 1000;
32
+ return Math.round((wall - instant) / 60_000);
33
+ }
34
+ /**
35
+ * The device's IANA time zone, or undefined where the runtime has none or
36
+ * names one it can't then use.
37
+ */
38
+ export function deviceTimeZone() {
39
+ try {
40
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
41
+ if (!zone)
42
+ return undefined;
43
+ formatterFor(zone);
44
+ return zone;
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ /**
51
+ * Whether a clock in `zone` would read differently from one in `deviceZone`
52
+ * at any of `times`. Compares UTC offsets, not names, since sources name the
53
+ * same zone differently (GeoNames' Asia/Kolkata is V8's Asia/Calcutta, and
54
+ * Europe/Kyiv is Europe/Kiev in older data). False when either zone is
55
+ * unknown to the runtime: no note is better than a wrong one.
56
+ */
57
+ export function clocksDiffer(zone, deviceZone, times) {
58
+ try {
59
+ return times.some((time) => utcOffsetMinutes(zone, time) !== utcOffsetMinutes(deviceZone, time));
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ //# sourceMappingURL=timeZone.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timeZone.js","sourceRoot":"","sources":["../../../source/src/geo/timeZone.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,GAAG,IAAI,GAAG,EAA+B,CAAC;AAE1D,SAAS,YAAY,CAAC,IAAY;IAChC,IAAI,SAAS,GAAG,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACrC,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,SAAS,GAAG,IAAI,IAAI,CAAC,cAAc,CAA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IAAI,CAAC,IAAI;YAAE,OAAO,SAAS,CAAC;QAC5B,YAAY,CAAC,IAAI,CAAC,CAAC;QACnB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAC1B,IAAY,EACZ,UAAkB,EAClB,KAAsB;IAEtB,IAAI,CAAC;QACH,OAAO,KAAK,CAAC,IAAI,CACf,CAAC,IAAI,EAAE,EAAE,CACP,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,gBAAgB,CAAC,UAAU,EAAE,IAAI,CAAC,CACtE,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { type Place } from "./place.js";
2
+ /** `@vercel/functions` has no constant for this one. */
3
+ export declare const TIMEZONE_HEADER_NAME = "x-vercel-ip-timezone";
4
+ /** A request-header reader, including Next's read-only headers. */
5
+ export interface HeaderReader {
6
+ get(name: string): string | null;
7
+ }
8
+ /** A usable IP place and decoded city label, which is not an accuracy guarantee. */
9
+ export interface DetectedPlace {
10
+ place: Place;
11
+ cityName?: string;
12
+ }
13
+ /** Parses Vercel hints without throwing on missing coordinates or encoded cities. */
14
+ export declare function parseVercelLocation(headers: HeaderReader, unnamed?: string): DetectedPlace | null;
15
+ //# sourceMappingURL=vercel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercel.d.ts","sourceRoot":"","sources":["../../../source/src/geo/vercel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,KAAK,EAAW,MAAM,YAAY,CAAC;AAEjD,wDAAwD;AACxD,eAAO,MAAM,oBAAoB,yBAAyB,CAAC;AA2C3D,mEAAmE;AACnE,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;CAClC;AAED,oFAAoF;AACpF,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,KAAK,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,qFAAqF;AACrF,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,YAAY,EACrB,OAAO,SAAc,GACpB,aAAa,GAAG,IAAI,CAgBtB"}
@@ -0,0 +1,64 @@
1
+ import { toPlace } from "./place.js";
2
+ /** `@vercel/functions` has no constant for this one. */
3
+ export const TIMEZONE_HEADER_NAME = "x-vercel-ip-timezone";
4
+ /** A plain decimal, as Vercel sends: no exponent, hex or empty string. */
5
+ const DECIMAL = /^-?\d+(?:\.\d+)?$/;
6
+ function coordinate(headers, name) {
7
+ const value = headers.get(name)?.trim();
8
+ return value && DECIMAL.test(value) ? Number(value) : undefined;
9
+ }
10
+ /** The city, decoded from RFC 3986, or undefined when it doesn't decode. */
11
+ function city(headers) {
12
+ const raw = headers.get("x-vercel-ip-city");
13
+ if (!raw)
14
+ return undefined;
15
+ try {
16
+ return decodeURIComponent(raw).trim() || undefined;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ /** The country's English name ("United Kingdom"), when Intl knows it. */
23
+ function countryName(country) {
24
+ try {
25
+ const name = new Intl.DisplayNames(["en"], { type: "region" }).of(country);
26
+ return name && name !== country ? name : undefined;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ /** The zone when this runtime knows it as an IANA name, else undefined. */
33
+ function timezone(headers) {
34
+ const value = headers.get(TIMEZONE_HEADER_NAME)?.trim();
35
+ if (!value)
36
+ return undefined;
37
+ try {
38
+ new Intl.DateTimeFormat("en", { timeZone: value });
39
+ return value;
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ /** Parses Vercel hints without throwing on missing coordinates or encoded cities. */
46
+ export function parseVercelLocation(headers, unnamed = "Your area") {
47
+ const latitude = coordinate(headers, "x-vercel-ip-latitude");
48
+ const longitude = coordinate(headers, "x-vercel-ip-longitude");
49
+ if (latitude === undefined || longitude === undefined)
50
+ return null;
51
+ const code = headers.get("x-vercel-ip-country")?.trim().toUpperCase();
52
+ const country = code && /^[A-Z]{2}$/.test(code) ? code : undefined;
53
+ const decoded = city(headers);
54
+ const cityName = decoded && decoded.length <= 200 ? decoded : undefined;
55
+ const place = toPlace({
56
+ name: cityName ?? (country ? countryName(country) : undefined) ?? unnamed,
57
+ country,
58
+ latitude,
59
+ longitude,
60
+ timezone: timezone(headers),
61
+ });
62
+ return place ? { place, ...(cityName ? { cityName } : {}) } : null;
63
+ }
64
+ //# sourceMappingURL=vercel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercel.js","sourceRoot":"","sources":["../../../source/src/geo/vercel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,OAAO,EAAE,MAAM,YAAY,CAAC;AAEjD,wDAAwD;AACxD,MAAM,CAAC,MAAM,oBAAoB,GAAG,sBAAsB,CAAC;AAE3D,0EAA0E;AAC1E,MAAM,OAAO,GAAG,mBAAmB,CAAC;AAEpC,SAAS,UAAU,CAAC,OAAqB,EAAE,IAAY;IACrD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;IACxC,OAAO,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAClE,CAAC;AAED,4EAA4E;AAC5E,SAAS,IAAI,CAAC,OAAqB;IACjC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IAC5C,IAAI,CAAC,GAAG;QAAE,OAAO,SAAS,CAAC;IAC3B,IAAI,CAAC;QACH,OAAO,kBAAkB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,IAAI,SAAS,CAAC;IACrD,CAAC;IAAC,MAAM,CAAC;QAC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,OAAO,GAAG,IAAI,IAAI,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACnE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9B,MAAM,QAAQ,GAAG,OAAO,IAAI,OAAO,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;IACxE,MAAM,KAAK,GAAG,OAAO,CAAC;QACpB,IAAI,EAAE,QAAQ,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,OAAO;QACzE,OAAO;QACP,QAAQ;QACR,SAAS;QACT,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC;KAC5B,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gadicc/loom",
3
- "version": "2.3.1",
3
+ "version": "2.4.0",
4
4
  "description": "Shared helpers and verification tooling for Next.js applications.",
5
5
  "homepage": "https://github.com/gadicc/loom#readme",
6
6
  "repository": {
@@ -11,7 +11,7 @@
11
11
  "url": "https://github.com/gadicc/loom/issues"
12
12
  },
13
13
  "loom": {
14
- "gitCommit": "aefcdc95762cffdae8af715ce57f6344f7abc45f"
14
+ "gitCommit": "ad867e27a435b218beba12c31200a1fbe47b8571"
15
15
  },
16
16
  "type": "module",
17
17
  "main": "./esm/mod.js",
@@ -41,6 +41,18 @@
41
41
  "types": "./esm/src/files/mod.d.ts",
42
42
  "import": "./esm/src/files/mod.js"
43
43
  },
44
+ "./src/geo/mod.js": {
45
+ "types": "./esm/src/geo/mod.d.ts",
46
+ "import": "./esm/src/geo/mod.js"
47
+ },
48
+ "./src/geo/client.js": {
49
+ "types": "./esm/src/geo/client.d.ts",
50
+ "import": "./esm/src/geo/client.js"
51
+ },
52
+ "./src/geo/places.js": {
53
+ "types": "./esm/src/geo/places.d.ts",
54
+ "import": "./esm/src/geo/places.js"
55
+ },
44
56
  "./src/mail/mod.js": {
45
57
  "types": "./esm/src/mail/mod.d.ts",
46
58
  "import": "./esm/src/mail/mod.js"
@@ -157,6 +169,18 @@
157
169
  "import": "./db/valibot.js",
158
170
  "default": "./db/valibot.js"
159
171
  },
172
+ "./geo": {
173
+ "types": "./esm/src/geo/mod.d.ts",
174
+ "import": "./esm/src/geo/mod.js"
175
+ },
176
+ "./geo/client": {
177
+ "types": "./esm/src/geo/client.d.ts",
178
+ "import": "./esm/src/geo/client.js"
179
+ },
180
+ "./geo/places": {
181
+ "types": "./esm/src/geo/places.d.ts",
182
+ "import": "./esm/src/geo/places.js"
183
+ },
160
184
  "./files": {
161
185
  "types": "./esm/src/files/mod.d.ts",
162
186
  "import": "./esm/src/files/mod.js"
@@ -0,0 +1,241 @@
1
+ import { type Place, toPlace } from "./place.ts";
2
+
3
+ /** Recoverable acquisition failures; presentation and retry policy belong to apps. */
4
+ export type LocationFailure =
5
+ | "timeout"
6
+ | "cancelled"
7
+ | "denied"
8
+ | "unavailable"
9
+ | "unsupported"
10
+ | "insecure";
11
+
12
+ /** A bounded one-shot request failed without changing the app's current location. */
13
+ export class LocationError extends Error {
14
+ constructor(public readonly code: LocationFailure) {
15
+ super(`Location ${code}`);
16
+ this.name = "LocationError";
17
+ }
18
+ }
19
+
20
+ /** Request controls shared by network and device acquisition. */
21
+ export interface LocationRequest {
22
+ signal?: AbortSignal;
23
+ /** App-level wall-clock deadline, including permission waiting and body parsing. */
24
+ timeoutMs?: number;
25
+ }
26
+
27
+ async function bounded<T>(
28
+ run: (signal: AbortSignal) => Promise<T>,
29
+ options: LocationRequest,
30
+ fallback: number,
31
+ ): Promise<T> {
32
+ const controller = new AbortController();
33
+ let timer: ReturnType<typeof setTimeout> | undefined;
34
+ let abort: (() => void) | undefined;
35
+ const milliseconds = options.timeoutMs ?? fallback;
36
+ if (!Number.isFinite(milliseconds) || milliseconds <= 0)
37
+ throw new RangeError("Invalid location deadline");
38
+ if (options.signal?.aborted) throw new LocationError("cancelled");
39
+ try {
40
+ const deadline = new Promise<never>((_, reject) => {
41
+ abort = () => {
42
+ controller.abort();
43
+ reject(new LocationError("cancelled"));
44
+ };
45
+ options.signal?.addEventListener("abort", abort, { once: true });
46
+ timer = setTimeout(() => {
47
+ controller.abort();
48
+ reject(new LocationError("timeout"));
49
+ }, milliseconds);
50
+ });
51
+ return await Promise.race([
52
+ Promise.resolve().then(() => {
53
+ if (controller.signal.aborted) throw new LocationError("cancelled");
54
+ return run(controller.signal);
55
+ }),
56
+ deadline,
57
+ ]);
58
+ } finally {
59
+ clearTimeout(timer);
60
+ if (abort) options.signal?.removeEventListener("abort", abort);
61
+ controller.abort();
62
+ }
63
+ }
64
+
65
+ /** A server response observation; city availability does not guarantee precision. */
66
+ export interface LocationObservation {
67
+ place: Place | null;
68
+ cityName?: string;
69
+ /** Browser receipt time, never claimed to be the IP provider's measurement time. */
70
+ checkedAt: number;
71
+ }
72
+
73
+ /** Validates the geo route response, keeping explicit null distinct from failure. */
74
+ export function toLocationObservation(
75
+ body: unknown,
76
+ checkedAt = Date.now(),
77
+ ): LocationObservation | null {
78
+ if (typeof body !== "object" || body === null || !Number.isFinite(checkedAt))
79
+ return null;
80
+ const value = body as Record<string, unknown>;
81
+ if (value.place === null) return { place: null, checkedAt };
82
+ const place = toPlace(value.place);
83
+ if (!place) return null;
84
+ const cityName =
85
+ typeof value.cityName === "string" ? value.cityName.trim() : "";
86
+ return {
87
+ place,
88
+ checkedAt,
89
+ ...(cityName && cityName.length <= 200 ? { cityName } : {}),
90
+ };
91
+ }
92
+
93
+ /** A same-origin geo request; no caching or preference side effects. */
94
+ export interface DetectionRequest extends LocationRequest {
95
+ endpoint?: string;
96
+ fetcher?: typeof fetch;
97
+ /** An app-owned early request, already carrying its actual response receipt time. */
98
+ early?: Promise<LocationObservation | null>;
99
+ }
100
+
101
+ /** Fetches fresh IP hints with a deadline even when fetch/body reading ignores abort. */
102
+ export function fetchDetectedPlace(
103
+ options: DetectionRequest = {},
104
+ ): Promise<LocationObservation> {
105
+ return bounded(
106
+ async (signal) => {
107
+ if (options.early) {
108
+ const found = await options.early;
109
+ if (!found) throw new LocationError("unavailable");
110
+ return found;
111
+ }
112
+ const response = await (options.fetcher ?? fetch)(
113
+ options.endpoint ?? "/api/geo",
114
+ { cache: "no-store", signal },
115
+ );
116
+ if (!response.ok) throw new LocationError("unavailable");
117
+ const observation = toLocationObservation(await response.json());
118
+ if (!observation) throw new LocationError("unavailable");
119
+ return observation;
120
+ },
121
+ options,
122
+ 5000,
123
+ );
124
+ }
125
+
126
+ /** A minimal browser position, also usable by injected test devices. */
127
+ export interface DevicePosition {
128
+ coords: { latitude: number; longitude: number };
129
+ timestamp: number;
130
+ }
131
+
132
+ /** Structural browser API: the shared package does not require DOM-only globals. */
133
+ export interface LocationDevice {
134
+ getCurrentPosition(
135
+ success: (position: DevicePosition) => void,
136
+ failure: (error: { code: number }) => void,
137
+ options: {
138
+ enableHighAccuracy: boolean;
139
+ maximumAge: number;
140
+ timeout: number;
141
+ },
142
+ ): void;
143
+ }
144
+
145
+ /** Device acquisition settings, independent of remembered browser permission. */
146
+ export interface DeviceRequest extends LocationRequest {
147
+ device?: LocationDevice;
148
+ secureContext?: boolean;
149
+ maximumAge?: number;
150
+ enableHighAccuracy?: boolean;
151
+ }
152
+
153
+ /** Raw coordinates with their device measurement time; apps choose stored precision. */
154
+ export interface DeviceLocation {
155
+ latitude: number;
156
+ longitude: number;
157
+ timestamp: number;
158
+ }
159
+
160
+ /**
161
+ * Called from an explicit user action only. A cancelled/timed-out request ignores
162
+ * late callbacks; the browser permission prompt itself cannot be dismissed here.
163
+ */
164
+ export function locateDevice(
165
+ options: DeviceRequest = {},
166
+ ): Promise<DeviceLocation> {
167
+ const browser = globalThis as typeof globalThis & {
168
+ navigator?: { geolocation?: LocationDevice };
169
+ isSecureContext?: boolean;
170
+ };
171
+ if ((options.secureContext ?? browser.isSecureContext) === false)
172
+ return Promise.reject(new LocationError("insecure"));
173
+ const device = options.device ?? browser.navigator?.geolocation;
174
+ if (!device) return Promise.reject(new LocationError("unsupported"));
175
+ return bounded(
176
+ (signal) =>
177
+ new Promise<DeviceLocation>((resolve, reject) => {
178
+ device.getCurrentPosition(
179
+ (position) => {
180
+ if (signal.aborted) return;
181
+ const { latitude, longitude } = position.coords;
182
+ if (
183
+ !toPlace({ name: "device", latitude, longitude }) ||
184
+ !Number.isFinite(position.timestamp)
185
+ ) {
186
+ reject(new LocationError("unavailable"));
187
+ return;
188
+ }
189
+ resolve({ latitude, longitude, timestamp: position.timestamp });
190
+ },
191
+ (error) => {
192
+ if (!signal.aborted)
193
+ reject(
194
+ new LocationError(
195
+ error.code === 1
196
+ ? "denied"
197
+ : error.code === 3
198
+ ? "timeout"
199
+ : "unavailable",
200
+ ),
201
+ );
202
+ },
203
+ {
204
+ enableHighAccuracy: options.enableHighAccuracy ?? false,
205
+ maximumAge: options.maximumAge ?? 60_000,
206
+ timeout: options.timeoutMs ?? 12_000,
207
+ },
208
+ );
209
+ }),
210
+ options,
211
+ 12_000,
212
+ );
213
+ }
214
+
215
+ /** Bounded city search, with app-owned debounce and cancellation of superseded queries. */
216
+ export function fetchPlaces(
217
+ query: string,
218
+ options: LocationRequest & { endpoint?: string; fetcher?: typeof fetch } = {},
219
+ ): Promise<Place[]> {
220
+ return bounded(
221
+ async (signal) => {
222
+ const response = await (options.fetcher ?? fetch)(
223
+ `${options.endpoint ?? "/api/places"}?q=${encodeURIComponent(query)}`,
224
+ { signal },
225
+ );
226
+ if (!response.ok) throw new LocationError("unavailable");
227
+ const body: unknown = await response.json();
228
+ if (
229
+ typeof body !== "object" ||
230
+ body === null ||
231
+ !Array.isArray((body as Record<string, unknown>).places)
232
+ )
233
+ throw new LocationError("unavailable");
234
+ return (body as { places: unknown[] }).places
235
+ .map(toPlace)
236
+ .filter((place) => place !== null);
237
+ },
238
+ options,
239
+ 5000,
240
+ );
241
+ }
@@ -0,0 +1,12 @@
1
+ export { type Place, toPlace } from "./place.ts";
2
+ export {
3
+ parseVercelLocation,
4
+ type DetectedPlace,
5
+ type HeaderReader,
6
+ } from "./vercel.ts";
7
+ export {
8
+ AUTOMATIC_LOCATION,
9
+ type LocationPreference,
10
+ toLocationPreference,
11
+ } from "./preference.ts";
12
+ export { clocksDiffer, deviceTimeZone, utcOffsetMinutes } from "./timeZone.ts";
@@ -0,0 +1,61 @@
1
+ /**
2
+ * A place the planetary hours, the moon and the geomancy reading are
3
+ * computed for (plan 072). It comes from the visitor's IP (`/api/geo`),
4
+ * a search of the GeoNames cities (`/api/places`), or the device's own
5
+ * position, and is shared by the server routes and the browser.
6
+ */
7
+ export interface Place {
8
+ /** City or town, or "Your location" for the device's position. */
9
+ name: string;
10
+ /** First-level subdivision's name ("England", "Texas"), when known. */
11
+ region?: string;
12
+ /** ISO 3166-1 alpha-2 country code ("GB"), when known. */
13
+ country?: string;
14
+ /** Degrees, -90 to 90. */
15
+ latitude: number;
16
+ /** Degrees, -180 to 180. */
17
+ longitude: number;
18
+ /** IANA time zone ("Europe/London"), when known. */
19
+ timezone?: string;
20
+ }
21
+
22
+ const COUNTRY = /^[A-Z]{2}$/;
23
+
24
+ function optionalText(value: unknown, max: number): string | undefined {
25
+ if (typeof value !== "string") return undefined;
26
+ const text = value.trim();
27
+ return text && text.length <= max ? text : undefined;
28
+ }
29
+
30
+ /**
31
+ * The value as a `Place`, or null when it is not one: coordinates must be
32
+ * finite numbers in range and the name a non-empty string. Optional fields
33
+ * that are malformed are dropped rather than failing the place. Used on
34
+ * anything that crosses a boundary: stored JSON, another server's answer.
35
+ */
36
+ export function toPlace(value: unknown): Place | null {
37
+ if (typeof value !== "object" || value === null) return null;
38
+ const v = value as Record<string, unknown>;
39
+ const name = optionalText(v.name, 200);
40
+ const { latitude, longitude } = v;
41
+ if (
42
+ !name ||
43
+ typeof latitude !== "number" ||
44
+ typeof longitude !== "number" ||
45
+ !Number.isFinite(latitude) ||
46
+ !Number.isFinite(longitude) ||
47
+ Math.abs(latitude) > 90 ||
48
+ Math.abs(longitude) > 180
49
+ ) {
50
+ return null;
51
+ }
52
+ const place: Place = { name, latitude, longitude };
53
+ const region = optionalText(v.region, 200);
54
+ if (region) place.region = region;
55
+ if (typeof v.country === "string" && COUNTRY.test(v.country)) {
56
+ place.country = v.country;
57
+ }
58
+ const timezone = optionalText(v.timezone, 64);
59
+ if (timezone) place.timezone = timezone;
60
+ return place;
61
+ }