@lunora/client 1.0.0-alpha.23 → 1.0.0-alpha.230

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 (97) hide show
  1. package/README.md +16 -3
  2. package/dist/auth/index.d.mts +43 -12
  3. package/dist/auth/index.d.ts +43 -12
  4. package/dist/auth/index.mjs +1 -60
  5. package/dist/index.d.mts +869 -438
  6. package/dist/index.d.ts +869 -438
  7. package/dist/index.mjs +1 -21
  8. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs +1 -0
  10. package/dist/packem_shared/LunoraClient-QytMj9EU.mjs +1 -0
  11. package/dist/packem_shared/OfflineQueue-BWamzR6p.mjs +1 -0
  12. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  13. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  14. package/dist/packem_shared/SubscriptionRegistry-DKIXE7M7.mjs +1 -0
  15. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  16. package/dist/packem_shared/applyDelta-CWpwS3Bb.mjs +1 -0
  17. package/dist/packem_shared/client-urls-BHLUjjcG.mjs +1 -0
  18. package/dist/packem_shared/connectLiveStream-DCgklEjI.mjs +1 -0
  19. package/dist/packem_shared/createAsyncStoragePersistence-6FCvqc6C.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStorageQueryCache-f5023fdB.mjs +1 -0
  21. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  22. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs +1 -0
  25. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  26. package/dist/packem_shared/createLocalStore-BT0QPKdf.mjs +1 -0
  27. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  28. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  29. package/dist/packem_shared/createServerClient-Cf_Z8KM-.mjs +1 -0
  30. package/dist/packem_shared/createSnapshotPrecondition-CLkxVeN1.mjs +1 -0
  31. package/dist/packem_shared/delta-merge-Ls3DED4g.mjs +1 -0
  32. package/dist/packem_shared/deserializePreloaded-CyFK_cv6.mjs +1 -0
  33. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  34. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  35. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  36. package/dist/packem_shared/httpStream-BhSpxRWB.mjs +9 -0
  37. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  38. package/dist/packem_shared/live-stream-ct8j7T75.mjs +10 -0
  39. package/dist/packem_shared/liveTopicSubscription-Bs-ULKfs.mjs +1 -0
  40. package/dist/packem_shared/local-store-fqWV2n_Z.mjs +1 -0
  41. package/dist/packem_shared/lunora-client.d-B9efyT52.d.ts +4913 -0
  42. package/dist/packem_shared/lunora-client.d-CRPqJc1_.d.mts +4913 -0
  43. package/dist/packem_shared/offline-queue-D_fr-uQ3.mjs +1 -0
  44. package/dist/packem_shared/preload.d-BSwDmNsZ.d.mts +21 -0
  45. package/dist/packem_shared/preload.d-CYzGQBaA.d.ts +21 -0
  46. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  47. package/dist/packem_shared/single-blob-store-DpqSxsgi.mjs +1 -0
  48. package/dist/packem_shared/wire-errors-WYlbE1Nh.mjs +1 -0
  49. package/dist/pagination/index.d.mts +42 -42
  50. package/dist/pagination/index.d.ts +42 -42
  51. package/dist/pagination/index.mjs +1 -61
  52. package/dist/query/index.d.mts +111 -43
  53. package/dist/query/index.d.ts +111 -43
  54. package/dist/query/index.mjs +1 -1
  55. package/dist/service.d.mts +49 -0
  56. package/dist/service.d.ts +49 -0
  57. package/dist/service.mjs +1 -0
  58. package/dist/ssr/index.d.mts +109 -79
  59. package/dist/ssr/index.d.ts +109 -79
  60. package/dist/ssr/index.mjs +1 -4
  61. package/dist/upload.d.mts +35 -0
  62. package/dist/upload.d.ts +35 -0
  63. package/dist/upload.mjs +1 -0
  64. package/package.json +15 -2
  65. package/dist/packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs +0 -33
  66. package/dist/packem_shared/ClientServiceWorker-C3PAFwy0.mjs +0 -100
  67. package/dist/packem_shared/DEFAULT_MAX_BUFFER-7hFnzNk9.mjs +0 -110
  68. package/dist/packem_shared/LunoraClient-BBCQjjbl.mjs +0 -3599
  69. package/dist/packem_shared/OfflineQueue-B4HUF7rt.mjs +0 -1
  70. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  71. package/dist/packem_shared/SubscriptionRegistry-CxS_Inha.mjs +0 -31
  72. package/dist/packem_shared/TabCoordinator-BwRR8H06.mjs +0 -222
  73. package/dist/packem_shared/applyDelta-CRKZ1PBt.mjs +0 -81
  74. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  75. package/dist/packem_shared/createClientQuery-CQ51bWAE.mjs +0 -71
  76. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  77. package/dist/packem_shared/createInMemoryPersistence-DZ2VHWgm.mjs +0 -79
  78. package/dist/packem_shared/createInMemoryQueryCache-DiaGZkA2.mjs +0 -112
  79. package/dist/packem_shared/createLocalStore-BtqUmOQA.mjs +0 -2
  80. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  81. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  82. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  83. package/dist/packem_shared/createReply-lI4tVS2w.mjs +0 -36
  84. package/dist/packem_shared/createServerClient-CTTAmvMx.mjs +0 -11
  85. package/dist/packem_shared/createSnapshotPrecondition-CxQ1T4ZP.mjs +0 -18
  86. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  87. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  88. package/dist/packem_shared/httpStream-BJU-aflc.mjs +0 -159
  89. package/dist/packem_shared/idb-utility-DrSVX43Q.mjs +0 -48
  90. package/dist/packem_shared/local-store-DIq-UWfD.mjs +0 -106
  91. package/dist/packem_shared/lunora-client.d-JvtVpf8A.d.mts +0 -2824
  92. package/dist/packem_shared/lunora-client.d-JvtVpf8A.d.ts +0 -2824
  93. package/dist/packem_shared/offline-queue-CF4_Co5k.mjs +0 -199
  94. package/dist/packem_shared/preload.d-C4_d_l5v.d.ts +0 -20
  95. package/dist/packem_shared/preload.d-DKbjGN5O.d.mts +0 -20
  96. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  97. package/dist/packem_shared/wire-key-Djie6aaR.mjs +0 -266
@@ -1,199 +0,0 @@
1
- const isStaleVersion = (current, stamped) => current !== void 0 && stamped !== current;
2
-
3
- let idCounter = 0;
4
- const nextId = () => {
5
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
6
- return crypto.randomUUID();
7
- }
8
- idCounter += 1;
9
- const entropy = typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function" ? [...crypto.getRandomValues(new Uint8Array(8))].map((byte) => byte.toString(16).padStart(2, "0")).join("") : (
10
- // eslint-disable-next-line sonarjs/pseudo-random -- non-cryptographic uniqueness entropy, not a security token; only reached when neither crypto.randomUUID nor crypto.getRandomValues exists
11
- Math.random().toString(16).slice(2, 12)
12
- );
13
- return `m_${Date.now().toString(36)}_${idCounter.toString(36)}_${entropy}`;
14
- };
15
- const reportPersistenceError = (handler, operation, error, mutationId) => {
16
- if (handler) {
17
- handler({ error, mutationId, operation });
18
- return;
19
- }
20
- console.warn(`[lunora] offline-queue persistence ${operation} failed`, error);
21
- };
22
- class OfflineQueue {
23
- /** Opt-in to queueing mutations before the targeted shard's first connect. */
24
- queueBeforeFirstConnect;
25
- maxItems;
26
- onPersistenceError;
27
- persistence;
28
- onEvict;
29
- onSizeChange;
30
- /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
31
- version;
32
- items = [];
33
- constructor(options = {}, deps = {}) {
34
- this.maxItems = options.maxItems ?? 1e3;
35
- this.queueBeforeFirstConnect = options.queueBeforeFirstConnect ?? false;
36
- this.onPersistenceError = options.onPersistenceError;
37
- this.persistence = deps.persistence;
38
- this.onEvict = deps.onEvict;
39
- this.onSizeChange = deps.onSizeChange;
40
- this.version = deps.version;
41
- }
42
- get size() {
43
- return this.items.length;
44
- }
45
- enqueue(entry) {
46
- const item = entry;
47
- item.id ??= nextId();
48
- this.items.push(item);
49
- this.persistence?.append({
50
- args: item.args,
51
- functionPath: item.functionPath,
52
- id: item.id,
53
- identity: item.identity,
54
- shardKey: item.shardKey,
55
- ...this.version === void 0 ? {} : { version: this.version }
56
- }).catch((error) => {
57
- reportPersistenceError(this.onPersistenceError, "append", error, item.id);
58
- });
59
- while (this.items.length > this.maxItems) {
60
- const dropped = this.items.shift();
61
- if (dropped) {
62
- if (dropped.id) {
63
- this.persistence?.remove(dropped.id).catch((error2) => {
64
- reportPersistenceError(this.onPersistenceError, "remove", error2, dropped.id);
65
- });
66
- }
67
- const error = new Error("offline queue overflow");
68
- error.code = "OFFLINE_QUEUE_OVERFLOW";
69
- dropped.reject(error);
70
- this.onEvict?.(dropped, error);
71
- }
72
- }
73
- this.notifySize();
74
- }
75
- /**
76
- * Restore mutations persisted in a prior session and re-queue them in FIFO
77
- * order. Restored entries already live in durable storage, so they are not
78
- * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
79
- * gone after a reload). No-op when no persistence adapter is configured.
80
- * Returns the distinct shard keys of the restored writes so the caller can
81
- * open their sockets to trigger a flush.
82
- */
83
- async hydrate() {
84
- if (!this.persistence) {
85
- return [];
86
- }
87
- let persisted;
88
- try {
89
- persisted = await this.persistence.load();
90
- } catch (error) {
91
- reportPersistenceError(this.onPersistenceError, "load", error);
92
- throw error;
93
- }
94
- const shardKeys = /* @__PURE__ */ new Set();
95
- for (const mutation of persisted) {
96
- if (this.items.some((item) => item.id === mutation.id)) {
97
- continue;
98
- }
99
- if (isStaleVersion(this.version, mutation.version)) {
100
- this.persistence.remove(mutation.id).catch((error) => {
101
- reportPersistenceError(this.onPersistenceError, "remove", error, mutation.id);
102
- });
103
- continue;
104
- }
105
- this.items.push({
106
- args: mutation.args,
107
- functionPath: mutation.functionPath,
108
- id: mutation.id,
109
- identity: mutation.identity,
110
- reject: () => void 0,
111
- resolve: () => void 0,
112
- shardKey: mutation.shardKey
113
- });
114
- shardKeys.add(mutation.shardKey);
115
- }
116
- this.notifySize();
117
- return [...shardKeys];
118
- }
119
- /**
120
- * Remove and return queued mutations. With no `predicate`, drains the whole
121
- * queue. With one, drains only matching entries (preserving FIFO order) and
122
- * leaves the rest queued — used to flush a single shard's writes when its
123
- * socket reconnects while other shards are still down.
124
- */
125
- drain(predicate) {
126
- if (!predicate) {
127
- const drained2 = [...this.items];
128
- this.items.length = 0;
129
- this.notifySize();
130
- return drained2;
131
- }
132
- const drained = [];
133
- const kept = [];
134
- for (const item of this.items) {
135
- (predicate(item) ? drained : kept).push(item);
136
- }
137
- this.items.length = 0;
138
- this.items.push(...kept);
139
- this.notifySize();
140
- return drained;
141
- }
142
- /**
143
- * Return previously-drained mutations to the front of the queue, preserving
144
- * their FIFO order, without re-persisting them — they were never unpersisted,
145
- * so durable storage still holds them. Used when a flush aborts on a transient
146
- * transport failure: the unreplayed writes stay queued for the next reconnect.
147
- */
148
- requeue(items) {
149
- if (items.length === 0) {
150
- return;
151
- }
152
- this.items.unshift(...items);
153
- this.notifySize();
154
- }
155
- /**
156
- * Remove mutations whose precondition evaluates to `false` (stale/dirty
157
- * writes that should not replay) and reject each with an
158
- * `OFFLINE_PRECONDITION_FAILED` error. The valid (admitted) mutations stay
159
- * queued in FIFO order. Returns the drained stale entries.
160
- *
161
- * Called during reconnect before the flush cycle to weed out writes whose
162
- * assumptions no longer hold (e.g. a document was deleted by another client).
163
- */
164
- drainConflict() {
165
- const conflicted = [];
166
- const kept = [];
167
- for (const item of this.items) {
168
- if (item.precondition !== void 0 && !item.precondition()) {
169
- const error = new Error("offline mutation skipped: precondition failed before replay");
170
- error.code = "OFFLINE_PRECONDITION_FAILED";
171
- item.reject(error);
172
- conflicted.push(item);
173
- } else {
174
- kept.push(item);
175
- }
176
- }
177
- if (conflicted.length > 0) {
178
- this.items.length = 0;
179
- this.items.push(...kept);
180
- this.notifySize();
181
- }
182
- return conflicted;
183
- }
184
- clear() {
185
- for (const item of this.items) {
186
- const error = new Error("CLIENT_CLOSED");
187
- error.code = "CLIENT_CLOSED";
188
- item.reject(error);
189
- }
190
- this.items.length = 0;
191
- this.notifySize();
192
- }
193
- /** Notify the size observer (the client's pending-sync count) after any change. */
194
- notifySize() {
195
- this.onSizeChange?.(this.items.length);
196
- }
197
- }
198
-
199
- export { OfflineQueue as O, isStaleVersion as i, nextId as n, reportPersistenceError as r };
@@ -1,20 +0,0 @@
1
- import { F as FunctionReference, L as LunoraClient, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./lunora-client.d-JvtVpf8A.js";
2
- /**
3
- * Run a query once on the server (during SSR) and capture its result in a
4
- * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
5
- * pass it to `usePreloadedQuery` on the client: the first client render shows
6
- * the server value with no loading flash, then a live subscription takes over.
7
- *
8
- * The query is executed through the supplied {@link LunoraClient} over the same
9
- * HTTP RPC path the browser uses, so the SSR client only needs a `fetch`
10
- * implementation that can reach the worker — no in-process Durable Object access.
11
- */
12
- declare const preloadQuery: <F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: {
13
- shardKey?: string;
14
- }) => Promise<Preloaded<ReturnOf<F>>>;
15
- /**
16
- * Read the captured value out of a {@link Preloaded} token without subscribing.
17
- * Useful on the server (or in tests) when you only need the data, not a live feed.
18
- */
19
- declare const preloadedQueryResult: <T>(preloaded: Preloaded<T>) => T;
20
- export { preloadedQueryResult as a, preloadQuery as p };
@@ -1,20 +0,0 @@
1
- import { F as FunctionReference, L as LunoraClient, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./lunora-client.d-JvtVpf8A.mjs";
2
- /**
3
- * Run a query once on the server (during SSR) and capture its result in a
4
- * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
5
- * pass it to `usePreloadedQuery` on the client: the first client render shows
6
- * the server value with no loading flash, then a live subscription takes over.
7
- *
8
- * The query is executed through the supplied {@link LunoraClient} over the same
9
- * HTTP RPC path the browser uses, so the SSR client only needs a `fetch`
10
- * implementation that can reach the worker — no in-process Durable Object access.
11
- */
12
- declare const preloadQuery: <F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: {
13
- shardKey?: string;
14
- }) => Promise<Preloaded<ReturnOf<F>>>;
15
- /**
16
- * Read the captured value out of a {@link Preloaded} token without subscribing.
17
- * Useful on the server (or in tests) when you only need the data, not a live feed.
18
- */
19
- declare const preloadedQueryResult: <T>(preloaded: Preloaded<T>) => T;
20
- export { preloadedQueryResult as a, preloadQuery as p };
@@ -1,13 +0,0 @@
1
- const preloadQuery = async (client, function_, args, options = {}) => {
2
- const value = await client.query(function_, args, options);
3
- return {
4
- __lunoraPreloaded: true,
5
- args: args ?? {},
6
- functionPath: function_.__lunoraRef,
7
- shardKey: options.shardKey,
8
- value
9
- };
10
- };
11
- const preloadedQueryResult = (preloaded) => preloaded.value;
12
-
13
- export { preloadQuery, preloadedQueryResult };
@@ -1,266 +0,0 @@
1
- const compareKeys = (a, b) => {
2
- if (a < b) {
3
- return -1;
4
- }
5
- return a > b ? 1 : 0;
6
- };
7
- const stableStringify = (value) => {
8
- if (value === void 0) {
9
- return "null";
10
- }
11
- if (typeof value === "bigint") {
12
- throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");
13
- }
14
- if (value === null || typeof value !== "object") {
15
- return JSON.stringify(value);
16
- }
17
- if (Array.isArray(value)) {
18
- return `[${value.map((item) => stableStringify(item)).join(",")}]`;
19
- }
20
- const proto = Object.getPrototypeOf(value);
21
- if (proto !== null && proto !== Object.prototype) {
22
- const name = value.constructor?.name ?? "value";
23
- throw new TypeError(
24
- `stableStringify: cannot use a ${name} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`
25
- );
26
- }
27
- const record = value;
28
- const keys = Object.keys(record).toSorted(compareKeys);
29
- const parts = [];
30
- for (const key of keys) {
31
- const raw = record[key];
32
- if (raw === void 0) {
33
- continue;
34
- }
35
- parts.push(`${JSON.stringify(key)}:${stableStringify(raw)}`);
36
- }
37
- return `{${parts.join(",")}}`;
38
- };
39
-
40
- const toBase64 = (bytes) => {
41
- let binary = "";
42
- const chunk = 32768;
43
- for (let index = 0; index < bytes.length; index += chunk) {
44
- binary += String.fromCharCode(...bytes.subarray(index, index + chunk));
45
- }
46
- return btoa(binary);
47
- };
48
- const fromBase64 = (base64) => {
49
- const binary = atob(base64);
50
- const bytes = new Uint8Array(binary.length);
51
- for (let index = 0; index < binary.length; index += 1) {
52
- bytes[index] = binary.codePointAt(index) ?? 0;
53
- }
54
- return bytes;
55
- };
56
-
57
- const TAG = "$lunora.wire$";
58
- const MAX_DEPTH = 64;
59
- const MAX_BIGINT_DIGITS = 1024;
60
- const UNSAFE_KEY = "__proto__";
61
- const TYPED_ARRAY_CTORS = {
62
- BigInt64Array,
63
- BigUint64Array,
64
- Float32Array,
65
- Float64Array,
66
- Int8Array,
67
- Int16Array,
68
- Int32Array,
69
- Uint8Array,
70
- Uint8ClampedArray,
71
- Uint16Array,
72
- Uint32Array
73
- };
74
- const ERROR_CTORS = {
75
- Error,
76
- EvalError,
77
- RangeError,
78
- ReferenceError,
79
- SyntaxError,
80
- TypeError,
81
- URIError
82
- };
83
- const encodeWire = (value, depth = 0) => {
84
- if (depth > MAX_DEPTH) {
85
- throw new RangeError(`wire-codec: value nesting exceeds the ${MAX_DEPTH}-level limit`);
86
- }
87
- if (value === void 0) {
88
- return [TAG, "undefined"];
89
- }
90
- if (value === null) {
91
- return null;
92
- }
93
- const kind = typeof value;
94
- if (kind === "bigint") {
95
- return [TAG, "bigint", value.toString()];
96
- }
97
- if (kind === "number") {
98
- const numeric = value;
99
- if (Number.isNaN(numeric)) {
100
- return [TAG, "nan"];
101
- }
102
- if (numeric === Infinity) {
103
- return [TAG, "inf"];
104
- }
105
- if (numeric === -Infinity) {
106
- return [TAG, "-inf"];
107
- }
108
- return numeric;
109
- }
110
- if (kind !== "object") {
111
- return value;
112
- }
113
- if (value instanceof Date) {
114
- return [TAG, "date", encodeWire(value.getTime(), depth + 1)];
115
- }
116
- if (value instanceof Error) {
117
- const error = value;
118
- const properties = {};
119
- for (const key of Object.keys(error)) {
120
- if (error[key] !== void 0) {
121
- properties[key] = encodeWire(error[key], depth + 1);
122
- }
123
- }
124
- const encodedError = [TAG, "error", error.name, error.message, properties];
125
- if (error.cause !== void 0) {
126
- encodedError.push(encodeWire(error.cause, depth + 1));
127
- }
128
- return encodedError;
129
- }
130
- if (value instanceof URL) {
131
- return [TAG, "url", value.href];
132
- }
133
- if (value instanceof Map) {
134
- return [TAG, "map", [...value.entries()].map(([k, v]) => [encodeWire(k, depth + 1), encodeWire(v, depth + 1)])];
135
- }
136
- if (value instanceof Set) {
137
- return [TAG, "set", [...value].map((item) => encodeWire(item, depth + 1))];
138
- }
139
- if (value instanceof ArrayBuffer) {
140
- return [TAG, "bytes", toBase64(new Uint8Array(value)), "ArrayBuffer"];
141
- }
142
- if (ArrayBuffer.isView(value)) {
143
- const view = value;
144
- const ctorName = view.constructor.name;
145
- const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
146
- return ctorName === "Uint8Array" ? [TAG, "bytes", toBase64(bytes)] : [TAG, "bytes", toBase64(bytes), ctorName];
147
- }
148
- if (Array.isArray(value)) {
149
- const encoded = value.map((item) => encodeWire(item, depth + 1));
150
- return encoded.length > 0 && encoded[0] === TAG ? [TAG, "arr", encoded] : encoded;
151
- }
152
- const proto = Object.getPrototypeOf(value);
153
- if (proto !== null && proto !== Object.prototype) {
154
- const name = value.constructor?.name ?? "value";
155
- throw new TypeError(
156
- `wire-codec: cannot encode a ${name} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`
157
- );
158
- }
159
- const source = value;
160
- const result = {};
161
- for (const key of Object.keys(source)) {
162
- const field = source[key];
163
- if (field !== void 0) {
164
- result[key] = encodeWire(field, depth + 1);
165
- }
166
- }
167
- return result;
168
- };
169
- const decodeWire = (value, depth = 0) => {
170
- if (depth > MAX_DEPTH) {
171
- throw new RangeError(`wire-codec: value nesting exceeds the ${MAX_DEPTH}-level limit`);
172
- }
173
- if (value === null || typeof value !== "object") {
174
- return value;
175
- }
176
- if (Array.isArray(value)) {
177
- if (value[0] === TAG) {
178
- const tag = value[1];
179
- switch (tag) {
180
- case "-inf": {
181
- return -Infinity;
182
- }
183
- case "arr": {
184
- return value[2].map((item) => decodeWire(item, depth + 1));
185
- }
186
- case "bigint": {
187
- const raw = value[2];
188
- if (typeof raw !== "string" || raw.length > MAX_BIGINT_DIGITS || !/^-?\d+$/.test(raw)) {
189
- throw new RangeError(`wire-codec: invalid or over-long bigint (max ${MAX_BIGINT_DIGITS} digits)`);
190
- }
191
- return BigInt(raw);
192
- }
193
- case "date": {
194
- return new Date(decodeWire(value[2], depth + 1));
195
- }
196
- case "map": {
197
- return new Map(value[2].map(([k, v]) => [decodeWire(k, depth + 1), decodeWire(v, depth + 1)]));
198
- }
199
- case "set": {
200
- return new Set(value[2].map((item) => decodeWire(item, depth + 1)));
201
- }
202
- case "url": {
203
- return new URL(value[2]);
204
- }
205
- case "error": {
206
- const name = value[2];
207
- const message = value[3];
208
- const Ctor = (Object.hasOwn(ERROR_CTORS, name) ? ERROR_CTORS[name] : void 0) ?? Error;
209
- const error = new Ctor(message);
210
- if (error.name !== name) {
211
- Object.defineProperty(error, "name", { configurable: true, value: name, writable: true });
212
- }
213
- const props = decodeWire(value[4], depth + 1);
214
- for (const key of Object.keys(props)) {
215
- if (key === UNSAFE_KEY) {
216
- Object.defineProperty(error, key, { configurable: true, enumerable: true, value: props[key], writable: true });
217
- } else {
218
- error[key] = props[key];
219
- }
220
- }
221
- if (value.length > 5) {
222
- Object.defineProperty(error, "cause", { configurable: true, value: decodeWire(value[5], depth + 1), writable: true });
223
- }
224
- return error;
225
- }
226
- case "bytes": {
227
- const bytes = fromBase64(value[2]);
228
- const ctorName = value[3] ?? "Uint8Array";
229
- if (ctorName === "ArrayBuffer") {
230
- return bytes.buffer.byteLength === bytes.byteLength ? bytes.buffer : bytes.slice().buffer;
231
- }
232
- const Ctor = Object.hasOwn(TYPED_ARRAY_CTORS, ctorName) ? TYPED_ARRAY_CTORS[ctorName] : void 0;
233
- return Ctor ? new Ctor(bytes.slice().buffer) : bytes;
234
- }
235
- case "inf": {
236
- return Infinity;
237
- }
238
- case "nan": {
239
- return Number.NaN;
240
- }
241
- case "undefined": {
242
- return void 0;
243
- }
244
- default: {
245
- return value.map((item) => decodeWire(item, depth + 1));
246
- }
247
- }
248
- }
249
- return value.map((item) => decodeWire(item, depth + 1));
250
- }
251
- const source = value;
252
- const result = {};
253
- for (const key of Object.keys(source)) {
254
- const decoded = decodeWire(source[key], depth + 1);
255
- if (key === UNSAFE_KEY) {
256
- Object.defineProperty(result, key, { configurable: true, enumerable: true, value: decoded, writable: true });
257
- } else {
258
- result[key] = decoded;
259
- }
260
- }
261
- return result;
262
- };
263
-
264
- const stableWireKey = (value) => stableStringify(encodeWire(value));
265
-
266
- export { decodeWire as d, encodeWire as e, stableWireKey as s };