@farm.js/sync 0.1.0-beta.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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Farm.js Team
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.
22
+
@@ -0,0 +1,80 @@
1
+ import { SyncModelStore, type SyncRow, type SyncRuntimeConfig } from "./store.js";
2
+ export type SyncMutationState = "pending" | "paused" | "completed" | "failed";
3
+ /**
4
+ * The result of a mutation, usable three ways:
5
+ *
6
+ * ```ts
7
+ * tasks.update({ id, status: "done" }); // fire and forget
8
+ * await tasks.update({ id, status: "done" }); // awaited directly
9
+ * await tasks.update({ id, status: "done" }).persisted; // explicit
10
+ * ```
11
+ *
12
+ * It is a thenable rather than a promise so that ignoring it is safe: the
13
+ * rejection is only materialized when a caller actually asks for it, and a
14
+ * write the UI already rolled back does not surface as an unhandled rejection.
15
+ */
16
+ export type SyncMutationHandle<TRow = SyncRow> = PromiseLike<TRow> & {
17
+ readonly key: unknown;
18
+ readonly state: SyncMutationState;
19
+ /** Resolves once the server has stored the write; rejects if it never lands. */
20
+ readonly persisted: Promise<TRow>;
21
+ catch<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<TRow | TResult>;
22
+ finally(onFinally?: (() => void) | null): Promise<TRow>;
23
+ };
24
+ export type SyncClientOptions = {
25
+ /** Pause writes while offline and resume them on reconnect. Default true. */
26
+ networkMode?: "always" | "online";
27
+ /** Retry transient failures. Default 2 retries with linear backoff. */
28
+ retry?: {
29
+ count?: number;
30
+ delay?: number | ((attempt: number) => number);
31
+ };
32
+ };
33
+ /** @internal Called by the plugin's client hook once the descriptor is available. */
34
+ export declare function startSyncRuntime(config: SyncRuntimeConfig, options?: SyncClientOptions): void;
35
+ export declare function getSyncStore(model: string): SyncModelStore;
36
+ /** Fetch rows for a model, incrementally when the schema supports a cursor. */
37
+ export declare function loadModel(model: string): Promise<void>;
38
+ export type SyncModelClient = {
39
+ insert(input: SyncRow): SyncMutationHandle;
40
+ update(input: SyncRow): SyncMutationHandle;
41
+ delete(input: SyncRow): SyncMutationHandle;
42
+ get(key: unknown): SyncRow | undefined;
43
+ refresh(): Promise<void>;
44
+ readonly rows: SyncRow[];
45
+ readonly status: string;
46
+ readonly pending: number;
47
+ readonly paused: number;
48
+ /** @internal */
49
+ readonly __farmSyncModel: string;
50
+ };
51
+ /** Typed per-model client accessor, resolved lazily so imports stay cheap. */
52
+ export declare const db: Record<string, SyncModelClient>;
53
+ /**
54
+ * Rows are written to the browser directly rather than through the shared
55
+ * query cache: they are feature-owned data with their own lifetime, and this
56
+ * keeps the plugin working whether or not the app configures
57
+ * `cache.client.adapter`.
58
+ *
59
+ * `localStorage` is the default because it is synchronous on read, which is
60
+ * what makes a warm start paint before the first network round trip. Apps that
61
+ * outgrow it can pass their own store.
62
+ */
63
+ type SyncPersistence = {
64
+ read(model: string): {
65
+ rows: SyncRow[];
66
+ cursor: string | null;
67
+ } | null;
68
+ write(model: string, value: {
69
+ rows: SyncRow[];
70
+ cursor: string | null;
71
+ }): void;
72
+ clear(): void;
73
+ };
74
+ /** Replace the default browser store, for example with an IndexedDB one. */
75
+ export declare function setSyncPersistence(store: SyncPersistence | null): void;
76
+ /** Remove every persisted row. Call on logout so a shared device stays clean. */
77
+ export declare function clearSyncedRows(): void;
78
+ export declare function hydrateModel(model: string): void;
79
+ export {};
80
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EAEd,KAAK,OAAO,EACZ,KAAK,iBAAiB,EACvB,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,iBAAiB,GAAG,SAAS,GAAG,QAAQ,GAAG,WAAW,GAAG,QAAQ,CAAC;AAE9E;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,kBAAkB,CAAC,IAAI,GAAG,OAAO,IAAI,WAAW,CAAC,IAAI,CAAC,GAAG;IACnE,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC;IAClC,gFAAgF;IAChF,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAClC,KAAK,CAAC,OAAO,GAAG,KAAK,EACnB,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,OAAO,KAAK,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,GACxE,OAAO,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC;IAC3B,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACzD,CAAC;AAEF,MAAM,MAAM,iBAAiB,G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GAAG;IACrB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,GAAG,IAAI,CAAC;IACvE,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,GAAG,IAAI,CAAC;IAC9E,KAAK,IAAI,IAAI,CAAC;CACf,CAAC;AAwCF,4EAA4E;AAC5E,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI,GAAG,IAAI,CAEtE;AAED,iFAAiF;AACjF,wBAAgB,eAAe,IAAI,IAAI,CAEtC;AASD,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAMhD"}
package/dist/client.js ADDED
@@ -0,0 +1,326 @@
1
+ import { SyncModelStore, } from "./store.js";
2
+ let runtime;
3
+ /** @internal Called by the plugin's client hook once the descriptor is available. */
4
+ export function startSyncRuntime(config, options = {}) {
5
+ if (runtime)
6
+ return;
7
+ runtime = { config, stores: new Map(), options };
8
+ }
9
+ const isBrowser = () => typeof window !== "undefined";
10
+ /** Placeholder used while server rendering, before the browser runtime starts. */
11
+ const SSR_DESCRIPTOR = {
12
+ key: "id",
13
+ access: "read",
14
+ persist: false,
15
+ cursor: null,
16
+ };
17
+ function requireRuntime() {
18
+ if (runtime)
19
+ return runtime;
20
+ const pending = globalThis.__FARM_SYNC_CONFIG__;
21
+ if (pending) {
22
+ startSyncRuntime(pending);
23
+ return runtime;
24
+ }
25
+ // Server rendering runs before the plugin's client hook, and the rows live in
26
+ // the browser anyway. Render an empty store rather than failing the request;
27
+ // hydration starts the real runtime and fills it in.
28
+ if (!isBrowser()) {
29
+ return { config: { path: "", models: {} }, stores: new Map(), options: {} };
30
+ }
31
+ throw new Error("The sync runtime is not started. Add `sync({ ... })` to the plugins in farm.config.ts.");
32
+ }
33
+ export function getSyncStore(model) {
34
+ const state = requireRuntime();
35
+ let store = state.stores.get(model);
36
+ if (store)
37
+ return store;
38
+ const descriptor = state.config.models[model];
39
+ if (!descriptor) {
40
+ if (!isBrowser())
41
+ return new SyncModelStore(model, SSR_DESCRIPTOR);
42
+ throw new Error(`Model "${model}" is not exposed to the browser. Add it to \`models\` in sync().`);
43
+ }
44
+ store = new SyncModelStore(model, descriptor);
45
+ state.stores.set(model, store);
46
+ if (isBrowser())
47
+ void loadModel(model);
48
+ return store;
49
+ }
50
+ async function request(body) {
51
+ const state = requireRuntime();
52
+ const response = await fetch(state.config.path, {
53
+ method: "POST",
54
+ headers: { "content-type": "application/json" },
55
+ body: JSON.stringify(body),
56
+ credentials: "same-origin",
57
+ });
58
+ const payload = await response.json().catch(() => undefined);
59
+ if (!response.ok) {
60
+ const message = payload?.error?.message ?? `Sync request failed with ${response.status}`;
61
+ const error = new Error(message);
62
+ error.code = payload?.error?.code;
63
+ error.status = response.status;
64
+ throw error;
65
+ }
66
+ return payload;
67
+ }
68
+ /** Fetch rows for a model, incrementally when the schema supports a cursor. */
69
+ export async function loadModel(model) {
70
+ const store = getSyncStore(model);
71
+ if (store.status === "idle")
72
+ store.setStatus("loading");
73
+ try {
74
+ const result = await request({ model, operation: "list", since: store.cursor });
75
+ store.applyServerRows(result.rows ?? [], {
76
+ full: result.full !== false,
77
+ cursor: result.cursor ?? null,
78
+ });
79
+ // Keep the warm-start copy current even when the session performs no writes.
80
+ persistModel(model);
81
+ }
82
+ catch (cause) {
83
+ store.setStatus("error", cause instanceof Error ? cause : new Error(String(cause)));
84
+ }
85
+ }
86
+ function isOnline() {
87
+ return typeof navigator === "undefined" || typeof navigator.onLine !== "boolean"
88
+ ? true
89
+ : navigator.onLine;
90
+ }
91
+ function waitForOnline() {
92
+ if (typeof window === "undefined")
93
+ return Promise.resolve();
94
+ return new Promise((resolve) => {
95
+ const onOnline = () => {
96
+ window.removeEventListener("online", onOnline);
97
+ resolve();
98
+ };
99
+ window.addEventListener("online", onOnline);
100
+ });
101
+ }
102
+ /**
103
+ * Send a write, pausing while offline and retrying transient failures. The
104
+ * caller has already applied an optimistic layer, so the row stays on screen
105
+ * for the whole wait.
106
+ */
107
+ async function dispatchWrite(store, body, options) {
108
+ const mode = options.networkMode ?? "online";
109
+ const maxRetries = options.retry?.count ?? 2;
110
+ let attempt = 0;
111
+ while (true) {
112
+ if (mode === "online" && !isOnline()) {
113
+ store.trackPaused(1);
114
+ try {
115
+ await waitForOnline();
116
+ }
117
+ finally {
118
+ store.trackPaused(-1);
119
+ }
120
+ }
121
+ try {
122
+ return await request(body);
123
+ }
124
+ catch (error) {
125
+ const status = error.status ?? 0;
126
+ // A rejection the server reasoned about is final; only transport and
127
+ // server faults are worth retrying.
128
+ const retriable = status === 0 || status >= 500;
129
+ if (mode === "online" && !isOnline())
130
+ continue;
131
+ if (!retriable || attempt >= maxRetries)
132
+ throw error;
133
+ attempt += 1;
134
+ const delay = typeof options.retry?.delay === "function"
135
+ ? options.retry.delay(attempt)
136
+ : (options.retry?.delay ?? attempt * 300);
137
+ if (delay > 0)
138
+ await new Promise((resolve) => setTimeout(resolve, delay));
139
+ }
140
+ }
141
+ }
142
+ function runMutation(model, operation, input, optimistic) {
143
+ const state = requireRuntime();
144
+ const store = getSyncStore(model);
145
+ const layer = optimistic.row === null
146
+ ? { type: "delete", key: optimistic.key }
147
+ : { type: "upsert", key: optimistic.key, row: optimistic.row };
148
+ store.addLayer(layer);
149
+ store.trackPending(1);
150
+ let handleState = "pending";
151
+ const isPersisted = (async () => {
152
+ try {
153
+ const result = await dispatchWrite(store, { model, operation, input }, state.options);
154
+ store.commitLayer(layer, operation === "delete" ? null : result);
155
+ handleState = "completed";
156
+ persistModel(model);
157
+ return result;
158
+ }
159
+ catch (error) {
160
+ store.removeLayer(layer);
161
+ handleState = "failed";
162
+ throw error;
163
+ }
164
+ finally {
165
+ store.trackPending(-1);
166
+ }
167
+ })();
168
+ // Keep the promise owned so a fire-and-forget failure never becomes an
169
+ // unhandled rejection. Callers that await get a fresh chain below.
170
+ void isPersisted.catch(() => undefined);
171
+ return {
172
+ key: optimistic.key,
173
+ get state() {
174
+ return handleState;
175
+ },
176
+ get persisted() {
177
+ return isPersisted;
178
+ },
179
+ then: (onFulfilled, onRejected) => isPersisted.then(onFulfilled, onRejected),
180
+ catch: (onRejected) => isPersisted.catch(onRejected),
181
+ finally: (onFinally) => isPersisted.finally(onFinally),
182
+ };
183
+ }
184
+ const clientCache = new Map();
185
+ function createModelClient(model) {
186
+ const client = {
187
+ insert(input) {
188
+ const store = getSyncStore(model);
189
+ const key = input[store.descriptor.key] ?? generateKey();
190
+ const row = { ...input, [store.descriptor.key]: key };
191
+ return runMutation(model, "insert", row, { key, row });
192
+ },
193
+ update(input) {
194
+ const store = getSyncStore(model);
195
+ const key = input[store.descriptor.key];
196
+ if (key === undefined) {
197
+ throw new Error(`${model}.update() requires "${store.descriptor.key}" in its input.`);
198
+ }
199
+ return runMutation(model, "update", input, { key, row: store.mergeRow(key, input) });
200
+ },
201
+ delete(input) {
202
+ const store = getSyncStore(model);
203
+ const key = input[store.descriptor.key];
204
+ if (key === undefined) {
205
+ throw new Error(`${model}.delete() requires "${store.descriptor.key}" in its input.`);
206
+ }
207
+ return runMutation(model, "delete", { [store.descriptor.key]: key }, { key, row: null });
208
+ },
209
+ get(key) {
210
+ return getSyncStore(model).get(key);
211
+ },
212
+ refresh() {
213
+ return loadModel(model);
214
+ },
215
+ get rows() {
216
+ return getSyncStore(model).getRows();
217
+ },
218
+ get status() {
219
+ return getSyncStore(model).status;
220
+ },
221
+ get pending() {
222
+ return getSyncStore(model).pending;
223
+ },
224
+ get paused() {
225
+ return getSyncStore(model).paused;
226
+ },
227
+ __farmSyncModel: model,
228
+ };
229
+ // Bind so `useMutation(db.tasks.update)` keeps working when detached.
230
+ client.insert = client.insert.bind(client);
231
+ client.update = client.update.bind(client);
232
+ client.delete = client.delete.bind(client);
233
+ return client;
234
+ }
235
+ function generateKey() {
236
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
237
+ return crypto.randomUUID();
238
+ }
239
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
240
+ }
241
+ /** Typed per-model client accessor, resolved lazily so imports stay cheap. */
242
+ export const db = new Proxy({}, {
243
+ get(_target, property) {
244
+ if (typeof property !== "string")
245
+ return undefined;
246
+ let client = clientCache.get(property);
247
+ if (!client) {
248
+ client = createModelClient(property);
249
+ clientCache.set(property, client);
250
+ }
251
+ return client;
252
+ },
253
+ });
254
+ // ── persistence ────────────────────────────────────────────────────────────
255
+ // Rows ride the client cache adapter configured through cache.client.adapter,
256
+ // so warm starts render from disk before the first network round trip.
257
+ const PERSIST_PREFIX = "farm-sync:";
258
+ const PERSIST_VERSION = "1";
259
+ function createLocalStoragePersistence() {
260
+ if (typeof localStorage === "undefined")
261
+ return null;
262
+ const keyFor = (model) => `${PERSIST_PREFIX}${PERSIST_VERSION}:${model}`;
263
+ return {
264
+ read(model) {
265
+ try {
266
+ const raw = localStorage.getItem(keyFor(model));
267
+ return raw ? JSON.parse(raw) : null;
268
+ }
269
+ catch {
270
+ return null;
271
+ }
272
+ },
273
+ write(model, value) {
274
+ try {
275
+ localStorage.setItem(keyFor(model), JSON.stringify(value));
276
+ }
277
+ catch {
278
+ // Quota or private browsing: rows stay in memory for this session.
279
+ }
280
+ },
281
+ clear() {
282
+ try {
283
+ for (const key of Object.keys(localStorage)) {
284
+ if (key.startsWith(PERSIST_PREFIX))
285
+ localStorage.removeItem(key);
286
+ }
287
+ }
288
+ catch {
289
+ // Nothing to clean up if storage is unavailable.
290
+ }
291
+ },
292
+ };
293
+ }
294
+ let persistence;
295
+ function getPersistence() {
296
+ persistence ??= createLocalStoragePersistence();
297
+ return persistence;
298
+ }
299
+ /** Replace the default browser store, for example with an IndexedDB one. */
300
+ export function setSyncPersistence(store) {
301
+ persistence = store;
302
+ }
303
+ /** Remove every persisted row. Call on logout so a shared device stays clean. */
304
+ export function clearSyncedRows() {
305
+ getPersistence()?.clear();
306
+ }
307
+ function persistModel(model) {
308
+ const store = runtime?.stores.get(model);
309
+ if (!store?.descriptor.persist)
310
+ return;
311
+ getPersistence()?.write(model, { rows: store.confirmedRows(), cursor: store.cursor });
312
+ }
313
+ export function hydrateModel(model) {
314
+ const store = getSyncStore(model);
315
+ if (!store.descriptor.persist)
316
+ return;
317
+ const saved = getPersistence()?.read(model);
318
+ if (saved?.rows?.length)
319
+ store.hydrate(saved.rows, saved.cursor ?? null);
320
+ }
321
+ // Register for the plugin handshake: the client hook may run before or after
322
+ // this module is evaluated, so both directions are covered.
323
+ const scope = globalThis;
324
+ scope.__FARM_SYNC__ = { start: (config) => startSyncRuntime(config) };
325
+ if (scope.__FARM_SYNC_CONFIG__)
326
+ startSyncRuntime(scope.__FARM_SYNC_CONFIG__);
@@ -0,0 +1,57 @@
1
+ import type { FarmSchema, FarmSqlDialect } from "@farm.js/core";
2
+ import { executeSyncOperation, SyncOperationError } from "./server.js";
3
+ import { resolveSyncModels, type ResolvedSyncModel, type SyncModelSetting, type SyncWhere } from "./types.js";
4
+ export type SyncPluginOptions = {
5
+ /** Declarative data schema; see `defineSchema` from `@farm.js/core`. */
6
+ schema: FarmSchema;
7
+ /**
8
+ * Name of a mount from `storage.mounts` in `farm.config.ts`. Models are read
9
+ * and written through it, so an app with storage configured needs no
10
+ * separate data-layer module.
11
+ */
12
+ storage?: string;
13
+ /**
14
+ * Your database, instead of `storage`. Pass a raw connection — a `pg` Pool, a
15
+ * Drizzle or Prisma client, a D1 binding, a Mongo client, an unstorage
16
+ * instance — and the orm runtime detects the driver and builds the model
17
+ * client from the schema. An already-built orm client is used as-is.
18
+ */
19
+ client?: unknown | (() => unknown | Promise<unknown>);
20
+ /** Row filter applied to every read and write, server side. */
21
+ where?: SyncWhere | false;
22
+ /** Which models the browser may read or write. Unlisted models are not exposed. */
23
+ models: Record<string, SyncModelSetting>;
24
+ /** Request middleware producing the context passed to `where`. */
25
+ middleware?: readonly SyncMiddleware[];
26
+ /** Endpoint the browser calls. */
27
+ path?: string;
28
+ /** Persist rows through the configured client cache adapter. */
29
+ persist?: boolean;
30
+ /**
31
+ * Sql dialect for `farm sync migrate`. Only needed when the client's dialect
32
+ * cannot be detected from its shape.
33
+ */
34
+ dialect?: FarmSqlDialect;
35
+ };
36
+ export type SyncMiddlewareContext = {
37
+ request: Request;
38
+ context: Record<string, unknown>;
39
+ };
40
+ export type SyncMiddleware = (ctx: SyncMiddlewareContext) => Record<string, unknown> | void | Promise<Record<string, unknown> | void>;
41
+ export type { SyncOrmClient } from "./server.js";
42
+ export type { SyncAccess, SyncModelConfig, SyncModelSetting, SyncOperation, SyncWhere, SyncWhereContext, } from "./types.js";
43
+ export declare function sync(options: SyncPluginOptions): import("@farm.js/core").FarmPlugin<undefined, Record<string, never>, void, {
44
+ path: string;
45
+ models: {
46
+ [k: string]: {
47
+ key: string;
48
+ access: import("./types.js").SyncAccess;
49
+ persist: boolean;
50
+ cursor: string | null;
51
+ };
52
+ };
53
+ }, unknown, false, import("@farm.js/core").PluginRoutes>;
54
+ /** @internal Exposed for tests. */
55
+ export { resolveSyncModels, executeSyncOperation, SyncOperationError };
56
+ export type { ResolvedSyncModel };
57
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAsB,MAAM,aAAa,CAAC;AAC3F,OAAO,EACL,iBAAiB,EACjB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EAErB,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,iBAAiB,GAAG;IAC9B,wEAAwE;IACxE,MAAM,EAAE,UAAU,CAAC;IACnB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