@freecorps/ember-values 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FreeCorps
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,12 @@
1
- # Temporary Holding Version
1
+ # @freecorps/ember-values
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ember validators (v.*), shapes, JSON Schema and order-preserving index key encoding.
4
+
5
+ Part of [Ember](https://github.com/freecorps/ember), a Convex-style backend on Cloudflare Workers and Durable
6
+ Objects. Source: [`packages/values`](https://github.com/freecorps/ember/tree/main/packages/values).
7
+
8
+ ```sh
9
+ npm install @freecorps/ember-values
10
+ ```
11
+
12
+ License: MIT.
@@ -0,0 +1,7 @@
1
+ export * from "./shape.ts";
2
+ export * from "./validators.ts";
3
+ export * from "./validate.ts";
4
+ export * from "./key.ts";
5
+ export * from "./json.ts";
6
+ export * from "./sql.ts";
7
+ export * from "./rowdiff.ts";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./shape.js";
2
+ export * from "./validators.js";
3
+ export * from "./validate.js";
4
+ export * from "./key.js";
5
+ export * from "./json.js";
6
+ export * from "./sql.js";
7
+ export * from "./rowdiff.js";
package/dist/json.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { type Shape } from "./shape.ts";
2
+ export type JSONValue = null | boolean | number | string | JSONValue[] | {
3
+ [k: string]: JSONValue;
4
+ };
5
+ /** Standard base64 (with padding). `url` = base64url without padding. Pure JS: no Buffer/btoa. */
6
+ export declare function bytesToBase64(bytes: Uint8Array, url?: boolean): string;
7
+ export declare function base64ToBytes(s: string): Uint8Array;
8
+ /** Ember value -> JSON-safe value (tags for bigint, bytes and non-finite / negative-zero numbers). */
9
+ export declare function toJSONValue(x: unknown): JSONValue;
10
+ /** Inverse of `toJSONValue`. */
11
+ export declare function fromJSONValue(x: unknown): unknown;
12
+ export declare const stringifyValue: (x: unknown) => string;
13
+ export declare const parseValue: (s: string) => unknown;
14
+ /**
15
+ * The canonical tagged JSON text of an Ember value (wire protocol, change log, `_json` column):
16
+ * `{"$int64":"…"}`, `{"$bytes":"<base64>"}`, `{"$float":"NaN"|"Infinity"|"-Infinity"|"-0"}`.
17
+ */
18
+ export declare const encodeJson: (x: unknown) => string;
19
+ /** Inverse of `encodeJson`. */
20
+ export declare const decodeJson: (s: string) => unknown;
21
+ /** Like `encodeJson` but with object keys sorted (stable cache keys, hashing). */
22
+ export declare function encodeJsonStable(x: unknown): string;
23
+ export type JsonSchema = Record<string, unknown>;
24
+ /** JSON Schema (2020-12) of the wire form of `shape`. */
25
+ export declare function toJsonSchema(shape: Shape): JsonSchema;
package/dist/json.js ADDED
@@ -0,0 +1,175 @@
1
+ // JSON forms of Ember values.
2
+ // - Wire/storage JSON: plain JSON with tagged objects for what JSON cannot carry:
3
+ // bigint -> {"$int64": "123"}, Uint8Array -> {"$bytes": "<base64>"},
4
+ // NaN / Infinity / -Infinity / -0 -> {"$float": "NaN" | "Infinity" | "-Infinity" | "-0"}.
5
+ // Field names starting with "$" are rejected by validation, so tags cannot collide with user data.
6
+ // - JSON Schema of a Shape (for OpenAPI / tooling), describing the wire form.
7
+ import { literalValue } from "./shape.js";
8
+ import { isPlainObject } from "./validate.js";
9
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
10
+ const B64_INDEX = new Map([...B64].map((c, i) => [c, i]));
11
+ /** Standard base64 (with padding). `url` = base64url without padding. Pure JS: no Buffer/btoa. */
12
+ export function bytesToBase64(bytes, url = false) {
13
+ let out = "";
14
+ let i = 0;
15
+ for (; i + 2 < bytes.length; i += 3) {
16
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
17
+ out += B64[n >> 18] + B64[(n >> 12) & 63] + B64[(n >> 6) & 63] + B64[n & 63];
18
+ }
19
+ const rest = bytes.length - i;
20
+ if (rest === 1) {
21
+ const n = bytes[i] << 16;
22
+ out += B64[n >> 18] + B64[(n >> 12) & 63] + "==";
23
+ }
24
+ else if (rest === 2) {
25
+ const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
26
+ out += B64[n >> 18] + B64[(n >> 12) & 63] + B64[(n >> 6) & 63] + "=";
27
+ }
28
+ return url ? out.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") : out;
29
+ }
30
+ export function base64ToBytes(s) {
31
+ const clean = s.replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
32
+ if (!/^[A-Za-z0-9+/]*$/.test(clean) || clean.length % 4 === 1)
33
+ throw new Error("Invalid base64");
34
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
35
+ let o = 0;
36
+ for (let i = 0; i < clean.length; i += 4) {
37
+ const a = B64_INDEX.get(clean[i]);
38
+ const b = B64_INDEX.get(clean[i + 1]);
39
+ const c = i + 2 < clean.length ? B64_INDEX.get(clean[i + 2]) : 0;
40
+ const d = i + 3 < clean.length ? B64_INDEX.get(clean[i + 3]) : 0;
41
+ const n = (a << 18) | (b << 12) | (c << 6) | d;
42
+ out[o++] = n >> 16;
43
+ if (i + 2 < clean.length)
44
+ out[o++] = (n >> 8) & 255;
45
+ if (i + 3 < clean.length)
46
+ out[o++] = n & 255;
47
+ }
48
+ return out;
49
+ }
50
+ /** Ember value -> JSON-safe value (tags for bigint, bytes and non-finite / negative-zero numbers). */
51
+ export function toJSONValue(x) {
52
+ switch (typeof x) {
53
+ case "string":
54
+ case "boolean":
55
+ return x;
56
+ case "number":
57
+ if (Number.isFinite(x) && !Object.is(x, -0))
58
+ return x;
59
+ return { $float: Number.isNaN(x) ? "NaN" : Object.is(x, -0) ? "-0" : x > 0 ? "Infinity" : "-Infinity" };
60
+ case "bigint":
61
+ return { $int64: x.toString() };
62
+ case "undefined":
63
+ return null;
64
+ case "object": {
65
+ if (x === null)
66
+ return null;
67
+ if (x instanceof Uint8Array)
68
+ return { $bytes: bytesToBase64(x) };
69
+ if (Array.isArray(x))
70
+ return x.map(toJSONValue);
71
+ const out = {};
72
+ for (const [k, item] of Object.entries(x))
73
+ if (item !== undefined)
74
+ out[k] = toJSONValue(item);
75
+ return out;
76
+ }
77
+ default:
78
+ throw new Error(`Cannot convert ${typeof x} to JSON`);
79
+ }
80
+ }
81
+ /** Inverse of `toJSONValue`. */
82
+ export function fromJSONValue(x) {
83
+ if (Array.isArray(x))
84
+ return x.map(fromJSONValue);
85
+ if (!isPlainObject(x))
86
+ return x;
87
+ const keys = Object.keys(x);
88
+ if (keys.length === 1) {
89
+ const k = keys[0];
90
+ const val = x[k];
91
+ if (k === "$int64" && typeof val === "string")
92
+ return BigInt(val);
93
+ if (k === "$bytes" && typeof val === "string")
94
+ return base64ToBytes(val);
95
+ if (k === "$float" && typeof val === "string") {
96
+ if (val === "-0")
97
+ return -0;
98
+ return Number(val);
99
+ }
100
+ }
101
+ const out = {};
102
+ for (const [k, item] of Object.entries(x))
103
+ out[k] = fromJSONValue(item);
104
+ return out;
105
+ }
106
+ export const stringifyValue = (x) => JSON.stringify(toJSONValue(x));
107
+ export const parseValue = (s) => fromJSONValue(JSON.parse(s));
108
+ /**
109
+ * The canonical tagged JSON text of an Ember value (wire protocol, change log, `_json` column):
110
+ * `{"$int64":"…"}`, `{"$bytes":"<base64>"}`, `{"$float":"NaN"|"Infinity"|"-Infinity"|"-0"}`.
111
+ */
112
+ export const encodeJson = stringifyValue;
113
+ /** Inverse of `encodeJson`. */
114
+ export const decodeJson = parseValue;
115
+ /** Like `encodeJson` but with object keys sorted (stable cache keys, hashing). */
116
+ export function encodeJsonStable(x) {
117
+ const sort = (j) => Array.isArray(j) ? j.map(sort) : j && typeof j === "object" ? Object.fromEntries(Object.keys(j).sort().map((k) => [k, sort(j[k])])) : j;
118
+ return JSON.stringify(sort(toJSONValue(x)));
119
+ }
120
+ /** JSON Schema (2020-12) of the wire form of `shape`. */
121
+ export function toJsonSchema(shape) {
122
+ switch (shape.kind) {
123
+ case "string":
124
+ return { type: "string" };
125
+ case "file":
126
+ return { type: "string", "x-ember-file": true };
127
+ case "id":
128
+ return { type: "string", "x-ember-id": shape.table };
129
+ case "number":
130
+ return {
131
+ anyOf: [
132
+ { type: "number" },
133
+ { type: "object", properties: { $float: { enum: ["NaN", "Infinity", "-Infinity", "-0"] } }, required: ["$float"], additionalProperties: false },
134
+ ],
135
+ };
136
+ case "int64":
137
+ return int64Schema;
138
+ case "boolean":
139
+ return { type: "boolean" };
140
+ case "null":
141
+ return { type: "null" };
142
+ case "bytes":
143
+ return { type: "object", properties: { $bytes: { type: "string", contentEncoding: "base64" } }, required: ["$bytes"], additionalProperties: false };
144
+ case "any":
145
+ return {};
146
+ case "literal": {
147
+ const val = literalValue(shape);
148
+ return typeof val === "bigint"
149
+ ? { type: "object", properties: { $int64: { const: val.toString() } }, required: ["$int64"], additionalProperties: false }
150
+ : { const: val };
151
+ }
152
+ case "array":
153
+ return { type: "array", items: toJsonSchema(shape.item) };
154
+ case "record":
155
+ return { type: "object", additionalProperties: toJsonSchema(shape.value), propertyNames: { pattern: "^[^$]" } };
156
+ case "object": {
157
+ const properties = {};
158
+ const required = [];
159
+ for (const [k, f] of Object.entries(shape.fields)) {
160
+ properties[k] = toJsonSchema(f.shape);
161
+ if (!f.optional)
162
+ required.push(k);
163
+ }
164
+ return { type: "object", properties, required, additionalProperties: false };
165
+ }
166
+ case "union":
167
+ return { anyOf: shape.members.map(toJsonSchema) };
168
+ }
169
+ }
170
+ const int64Schema = {
171
+ type: "object",
172
+ properties: { $int64: { type: "string", pattern: "^-?[0-9]+$" } },
173
+ required: ["$int64"],
174
+ additionalProperties: false,
175
+ };
package/dist/key.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ export declare const TAG: {
2
+ readonly end: 0;
3
+ readonly undefined: 1;
4
+ readonly null: 2;
5
+ readonly int64: 3;
6
+ readonly number: 4;
7
+ readonly false: 5;
8
+ readonly true: 6;
9
+ readonly string: 7;
10
+ readonly bytes: 8;
11
+ readonly array: 9;
12
+ readonly object: 10;
13
+ };
14
+ export type KeyValue = unknown;
15
+ /** Encodes a tuple of values into an order-preserving byte string. */
16
+ export declare function encodeKey(values: readonly unknown[]): Uint8Array;
17
+ /** Encodes a single value (as a one-element tuple). */
18
+ export declare const encodeValue: (x: unknown) => Uint8Array;
19
+ /** Decodes a key produced by `encodeKey` back into its tuple. */
20
+ export declare function decodeKey(key: Uint8Array): unknown[];
21
+ /** memcmp: negative, zero or positive. */
22
+ export declare function compareBytes(a: Uint8Array, b: Uint8Array): number;
23
+ export declare function concatBytes(...parts: Uint8Array[]): Uint8Array;
24
+ /** Exclusive upper bound of every key that starts with the tuple `prefix` (the encoded prefix ++ 0xFF). */
25
+ export declare const prefixEnd: (prefix: Uint8Array) => Uint8Array;
26
+ /** The smallest key strictly greater than `key` (key ++ 0x00). */
27
+ export declare const keySuccessor: (key: Uint8Array) => Uint8Array;
28
+ /** A half-open key range `[lo, hi)`. */
29
+ export type KeyRange = {
30
+ lo: Uint8Array;
31
+ hi: Uint8Array;
32
+ };
33
+ export type LowerBound = {
34
+ op: "gt" | "gte";
35
+ value: unknown;
36
+ };
37
+ export type UpperBound = {
38
+ op: "lt" | "lte";
39
+ value: unknown;
40
+ };
41
+ /**
42
+ * The key range of an index read: equality on a prefix of the index fields, then optional lower/upper bounds on
43
+ * the next field. Bounds are on tuples, so `gt(x)` excludes every key whose field equals `x` regardless of the
44
+ * fields that follow.
45
+ */
46
+ export declare function rangeFor(eq: readonly unknown[], lower?: LowerBound, upper?: UpperBound): KeyRange;
47
+ /** Whether `key` lies in `[lo, hi)`. */
48
+ export declare const inKeyRange: (key: Uint8Array, lo: Uint8Array, hi: Uint8Array) => boolean;
49
+ /** Code-point order (which equals UTF-8 byte order); JS `<` compares UTF-16 units and differs above U+FFFF. */
50
+ export declare function compareStrings(a: string, b: string): number;
51
+ /**
52
+ * Logical comparison of two values in index order (the order `encodeKey` produces). Used for `.filter()`
53
+ * comparisons and anywhere values are ordered outside SQL.
54
+ */
55
+ export declare function compareValues(a: unknown, b: unknown): number;