@kiri-orm/core 0.1.2 → 0.1.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kiri-orm/core",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "main": "./src/index.js",
6
6
  "types": "./dist/types/index.d.ts",
@@ -1,33 +1,114 @@
1
1
  import { CastError } from "../errors.js";
2
2
 
3
- function isValidDate(d) {
4
- return d instanceof Date && !Number.isNaN(d.getTime());
3
+ // year first; separators must match; optional time part with optional zone
4
+ const DATE_RE =
5
+ /^(\d{4})([-/.])(\d{1,2})\2(\d{1,2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?\s*(Z|[+-]\d{2}(?::?\d{2})?)?)?$/i;
6
+
7
+ function isLeap(y) {
8
+ return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
9
+ }
10
+
11
+ function daysInMonth(y, m) {
12
+ if (m === 2) return isLeap(y) ? 29 : 28;
13
+ return m === 4 || m === 6 || m === 9 || m === 11 ? 30 : 31;
14
+ }
15
+
16
+ function isRealCalendarDate(y, m, d) {
17
+ return m >= 1 && m <= 12 && d >= 1 && d <= daysInMonth(y, m);
18
+ }
19
+
20
+ function format(y, m, d) {
21
+ return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
22
+ }
23
+
24
+ function normalizeOffset(z) {
25
+ if (z.toUpperCase() === "Z") return "Z";
26
+ const sign = z[0];
27
+ const digits = z.slice(1).replace(":", "");
28
+ const hh = digits.slice(0, 2);
29
+ const mm = digits.slice(2) || "00";
30
+ return `${sign}${hh}:${mm}`;
31
+ }
32
+
33
+ // Calendar day of an instant in a given IANA timezone.
34
+ function dayInZone(instant, timeZone) {
35
+ const parts = new Intl.DateTimeFormat("en-US", {
36
+ timeZone,
37
+ year: "numeric",
38
+ month: "numeric",
39
+ day: "numeric",
40
+ }).formatToParts(instant);
41
+ const get = (t) => Number(parts.find((p) => p.type === t).value);
42
+ return format(get("year"), get("month"), get("day"));
43
+ }
44
+
45
+ function parseString(field, raw) {
46
+ const match = DATE_RE.exec(raw.trim());
47
+ if (!match) return null;
48
+
49
+ const y = Number(match[1]);
50
+ const m = Number(match[3]);
51
+ const d = Number(match[4]);
52
+ if (!isRealCalendarDate(y, m, d)) return null;
53
+
54
+ const hasTime = match[5] !== undefined;
55
+ if (hasTime) {
56
+ const [hh, mi, ss] = [match[5], match[6], match[7] ?? "0"].map(Number);
57
+ if (hh > 23 || mi > 59 || ss > 59) return null;
58
+ }
59
+
60
+ const offset = match[8];
61
+ if (hasTime && offset && field?.timeZone) {
62
+ // The string is an instant: convert it to a day in the field's zone.
63
+ const iso =
64
+ `${format(y, m, d)}T${match[5]}:${match[6]}:${String(match[7] ?? "0").padStart(2, "0")}` +
65
+ normalizeOffset(offset);
66
+ const instant = new Date(iso);
67
+ return Number.isNaN(instant.getTime())
68
+ ? null
69
+ : dayInZone(instant, field.timeZone);
70
+ }
71
+
72
+ // Default: the date exactly as written; time and offset are ignored.
73
+ return format(y, m, d);
74
+ }
75
+
76
+ function fromDateObject(dt) {
77
+ if (Number.isNaN(dt.getTime())) return null;
78
+ return format(dt.getFullYear(), dt.getMonth() + 1, dt.getDate());
5
79
  }
6
80
 
7
- /**
8
- * A calendar date (no time component, though the canonical runtime
9
- * representation is still a JS Date - the schema-sync layer in a later
10
- * phase is what maps this to a DATE vs DATETIME column per dialect).
11
- */
12
81
  export const dateType = {
13
82
  name: "date",
14
83
 
84
+ // validate stays strict: it only accepts the canonical stored form.
15
85
  validate(field, value) {
16
- if (!isValidDate(value)) {
17
- return [`expected a valid Date, got ${JSON.stringify(value)}`];
18
- }
19
- return [];
86
+ const ok =
87
+ typeof value === "string" &&
88
+ /^\d{4}-\d{2}-\d{2}$/.test(value) &&
89
+ isRealCalendarDate(
90
+ +value.slice(0, 4),
91
+ +value.slice(5, 7),
92
+ +value.slice(8, 10),
93
+ );
94
+ return ok
95
+ ? []
96
+ : [
97
+ `expected a real calendar date as "YYYY-MM-DD", got ${JSON.stringify(value)}`,
98
+ ];
20
99
  },
21
100
 
22
101
  cast(field, value) {
23
- if (isValidDate(value)) return value;
24
- if (typeof value === "string" || typeof value === "number") {
25
- const parsed = new Date(value);
26
- if (isValidDate(parsed)) return parsed;
102
+ let result = null;
103
+ if (typeof value === "string") result = parseString(field, value);
104
+ else if (value instanceof Date) result = fromDateObject(value);
105
+
106
+ if (result === null) {
107
+ throw new CastError(`cannot cast ${JSON.stringify(value)} to date`, {
108
+ fieldType: "date",
109
+ value,
110
+ });
27
111
  }
28
- throw new CastError(`cannot cast ${JSON.stringify(value)} to date`, {
29
- fieldType: "date",
30
- value,
31
- });
112
+ return result;
32
113
  },
33
114
  };