@lushly-dev/violet-runtime 0.0.0-stage → 0.3.0-preview.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 Lushly
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,76 @@
1
- # Temporary Holding Version
1
+ # @lushly-dev/violet-runtime
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
+ Web SDK for Violet Design tokens: load a node's resolved tokens from the Violet API, cache them, apply them as CSS custom properties, and switch themes at runtime.
4
+
5
+ ```bash
6
+ npm install @lushly-dev/violet-runtime@preview
7
+ ```
8
+
9
+ ```ts
10
+ import { ThemeManager, VioletRuntime } from '@lushly-dev/violet-runtime';
11
+
12
+ const violet = new VioletRuntime({
13
+ nodeId: 'brand-light',
14
+ apiUrl: 'https://violet.example.com', // your Violet deployment
15
+ apiKey: 'your-api-key',
16
+ });
17
+ await violet.load();
18
+
19
+ const themes = new ThemeManager(violet, {
20
+ themes: [
21
+ { nodeId: 'brand-light', name: 'Light' },
22
+ { nodeId: 'brand-dark', name: 'Dark' },
23
+ ],
24
+ defaultTheme: 'brand-light',
25
+ });
26
+ await themes.switch('brand-dark');
27
+ ```
28
+
29
+ `apiUrl` is required whenever you pass `apiKey`: there is no default host, so the constructor throws rather than send your key somewhere you did not choose. Without a key, `apiUrl` defaults to the page's own origin.
30
+
31
+ ## Preloaded tokens
32
+
33
+ A static build can apply a theme with no token server: pass the resolved tokens as `source` in place of `apiUrl`. The two are either/or: the types refuse both, and so does the constructor.
34
+
35
+ ```ts
36
+ import themes from './theme.json'; // { nodes: { 'brand-dark': [{ id, value }, ...], ... } }
37
+
38
+ const violet = new VioletRuntime({
39
+ nodeId: 'brand-dark',
40
+ source: { tokens: themes.nodes['brand-dark'] },
41
+ });
42
+ await violet.load(); // no request; applies the tokens as custom properties
43
+
44
+ await violet.switchNode('brand-light', { tokens: themes.nodes['brand-light'] });
45
+ ```
46
+
47
+ - A token needs a non-empty `id` and a string, finite number or object `value`; `resolvedAt` defaults to the node the source was given for. The runtime copies the array and each token's top level, so adding, removing or replacing tokens in your array later does not reach it; nested values are shared.
48
+ - `load()` applies the current source. `switchNode(nodeId, source)` takes the new node's tokens; without a source it can only reapply the node the runtime already holds. An HTTP runtime refuses a source.
49
+ - Nothing is cached and `preload()` has nothing to do: `cacheEnabled` and `timeout` are ignored.
50
+ - Give each `ThemeManager` theme its `source`, and the manager passes it to `switchNode`:
51
+
52
+ ```ts
53
+ const manager = new ThemeManager(violet, {
54
+ themes: [
55
+ { nodeId: 'brand-light', name: 'Light', source: { tokens: themes.nodes['brand-light'] } },
56
+ { nodeId: 'brand-dark', name: 'Dark', source: { tokens: themes.nodes['brand-dark'] } },
57
+ ],
58
+ defaultTheme: 'brand-dark',
59
+ });
60
+ ```
61
+
62
+ ## System preference and high contrast
63
+
64
+ `useSystemPreference(light, dark)` follows `(prefers-color-scheme: dark)`. Pass a third theme to choose it whenever `(prefers-contrast: more)` or `(forced-colors: active)` matches, whatever the color scheme:
65
+
66
+ ```ts
67
+ const stop = manager.useSystemPreference('brand-light', 'brand-dark', 'brand-contrast');
68
+ // later
69
+ stop(); // removes the listeners on every query
70
+ ```
71
+
72
+ The manager follows changes to each query until you call the returned function. Without a third theme it reads only the color scheme.
73
+
74
+ ## License
75
+
76
+ MIT
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Token Cache
3
+ *
4
+ * IndexedDB-based caching for token data with TTL support.
5
+ * Falls back to in-memory cache when IndexedDB is unavailable.
6
+ */
7
+ import type { CacheEntry, Token } from './types.js';
8
+ /**
9
+ * TokenCache provides local caching for resolved tokens.
10
+ *
11
+ * Uses IndexedDB for persistent storage with in-memory fallback.
12
+ * Supports TTL-based expiration.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const cache = new TokenCache();
17
+ * await cache.init();
18
+ *
19
+ * // Store tokens
20
+ * await cache.set("xbox-web-dark", tokens, 3600);
21
+ *
22
+ * // Retrieve tokens
23
+ * const cached = await cache.get("xbox-web-dark");
24
+ * if (cached && !cache.isExpired(cached)) {
25
+ * // Use cached tokens
26
+ * }
27
+ * ```
28
+ */
29
+ export declare class TokenCache {
30
+ private db;
31
+ private memoryCache;
32
+ private useIndexedDB;
33
+ /**
34
+ * Initialize the cache.
35
+ * Attempts to open IndexedDB, falls back to memory if unavailable.
36
+ */
37
+ init(): Promise<void>;
38
+ /**
39
+ * Get cached tokens for a node.
40
+ */
41
+ get(nodeId: string): Promise<CacheEntry | null>;
42
+ /**
43
+ * Store tokens in cache.
44
+ */
45
+ set(nodeId: string, tokens: Token[], ttl: number): Promise<void>;
46
+ /**
47
+ * Check if a cache entry has expired.
48
+ */
49
+ isExpired(entry: CacheEntry): boolean;
50
+ /**
51
+ * Delete cached tokens for a node.
52
+ */
53
+ delete(nodeId: string): Promise<void>;
54
+ /**
55
+ * Clear all cached tokens.
56
+ */
57
+ clear(): Promise<void>;
58
+ /**
59
+ * Get all cached node IDs.
60
+ */
61
+ keys(): Promise<string[]>;
62
+ /**
63
+ * Close the database connection.
64
+ */
65
+ close(): void;
66
+ private openDatabase;
67
+ private getFromIndexedDB;
68
+ private setInIndexedDB;
69
+ private deleteFromIndexedDB;
70
+ private clearIndexedDB;
71
+ private getKeysFromIndexedDB;
72
+ }
73
+ //# sourceMappingURL=cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAMpD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBAAa,UAAU;IACtB,OAAO,CAAC,EAAE,CAA4B;IACtC,OAAO,CAAC,WAAW,CAAsC;IACzD,OAAO,CAAC,YAAY,CAAQ;IAE5B;;;OAGG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAY1B;IAED;;OAEG;IACG,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAKpD;IAED;;OAEG;IACG,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAarE;IAED;;OAEG;IACH,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAGpC;IAED;;OAEG;IACG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAM1C;IAED;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAM3B;IAED;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAK9B;IAED;;OAEG;IACH,KAAK,IAAI,IAAI,CAKZ;IAID,OAAO,CAAC,YAAY;IAgBpB,OAAO,CAAC,gBAAgB;IAgBxB,OAAO,CAAC,cAAc;IAgBtB,OAAO,CAAC,mBAAmB;IAgB3B,OAAO,CAAC,cAAc;IAgBtB,OAAO,CAAC,oBAAoB;CAe5B"}
package/dist/cache.js ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Token Cache
3
+ *
4
+ * IndexedDB-based caching for token data with TTL support.
5
+ * Falls back to in-memory cache when IndexedDB is unavailable.
6
+ */
7
+ const DB_NAME = 'violet-runtime';
8
+ const STORE_NAME = 'tokens';
9
+ const DB_VERSION = 1;
10
+ /**
11
+ * TokenCache provides local caching for resolved tokens.
12
+ *
13
+ * Uses IndexedDB for persistent storage with in-memory fallback.
14
+ * Supports TTL-based expiration.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const cache = new TokenCache();
19
+ * await cache.init();
20
+ *
21
+ * // Store tokens
22
+ * await cache.set("xbox-web-dark", tokens, 3600);
23
+ *
24
+ * // Retrieve tokens
25
+ * const cached = await cache.get("xbox-web-dark");
26
+ * if (cached && !cache.isExpired(cached)) {
27
+ * // Use cached tokens
28
+ * }
29
+ * ```
30
+ */
31
+ export class TokenCache {
32
+ db = null;
33
+ memoryCache = new Map();
34
+ useIndexedDB = true;
35
+ /**
36
+ * Initialize the cache.
37
+ * Attempts to open IndexedDB, falls back to memory if unavailable.
38
+ */
39
+ async init() {
40
+ if (typeof indexedDB === 'undefined') {
41
+ this.useIndexedDB = false;
42
+ return;
43
+ }
44
+ try {
45
+ this.db = await this.openDatabase();
46
+ }
47
+ catch {
48
+ // IndexedDB not available (e.g., private browsing)
49
+ this.useIndexedDB = false;
50
+ }
51
+ }
52
+ /**
53
+ * Get cached tokens for a node.
54
+ */
55
+ async get(nodeId) {
56
+ if (this.useIndexedDB && this.db) {
57
+ return this.getFromIndexedDB(nodeId);
58
+ }
59
+ return this.memoryCache.get(nodeId) ?? null;
60
+ }
61
+ /**
62
+ * Store tokens in cache.
63
+ */
64
+ async set(nodeId, tokens, ttl) {
65
+ const entry = {
66
+ tokens,
67
+ cachedAt: Date.now(),
68
+ ttl,
69
+ nodeId,
70
+ };
71
+ if (this.useIndexedDB && this.db) {
72
+ await this.setInIndexedDB(entry);
73
+ }
74
+ else {
75
+ this.memoryCache.set(nodeId, entry);
76
+ }
77
+ }
78
+ /**
79
+ * Check if a cache entry has expired.
80
+ */
81
+ isExpired(entry) {
82
+ const expiresAt = entry.cachedAt + entry.ttl * 1000;
83
+ return Date.now() > expiresAt;
84
+ }
85
+ /**
86
+ * Delete cached tokens for a node.
87
+ */
88
+ async delete(nodeId) {
89
+ if (this.useIndexedDB && this.db) {
90
+ await this.deleteFromIndexedDB(nodeId);
91
+ }
92
+ else {
93
+ this.memoryCache.delete(nodeId);
94
+ }
95
+ }
96
+ /**
97
+ * Clear all cached tokens.
98
+ */
99
+ async clear() {
100
+ if (this.useIndexedDB && this.db) {
101
+ await this.clearIndexedDB();
102
+ }
103
+ else {
104
+ this.memoryCache.clear();
105
+ }
106
+ }
107
+ /**
108
+ * Get all cached node IDs.
109
+ */
110
+ async keys() {
111
+ if (this.useIndexedDB && this.db) {
112
+ return this.getKeysFromIndexedDB();
113
+ }
114
+ return Array.from(this.memoryCache.keys());
115
+ }
116
+ /**
117
+ * Close the database connection.
118
+ */
119
+ close() {
120
+ if (this.db) {
121
+ this.db.close();
122
+ this.db = null;
123
+ }
124
+ }
125
+ // Private: IndexedDB operations
126
+ openDatabase() {
127
+ return new Promise((resolve, reject) => {
128
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
129
+ request.onerror = () => reject(request.error);
130
+ request.onsuccess = () => resolve(request.result);
131
+ request.onupgradeneeded = (event) => {
132
+ const db = event.target.result;
133
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
134
+ db.createObjectStore(STORE_NAME, { keyPath: 'nodeId' });
135
+ }
136
+ };
137
+ });
138
+ }
139
+ getFromIndexedDB(nodeId) {
140
+ return new Promise((resolve, reject) => {
141
+ if (!this.db) {
142
+ resolve(null);
143
+ return;
144
+ }
145
+ const transaction = this.db.transaction(STORE_NAME, 'readonly');
146
+ const store = transaction.objectStore(STORE_NAME);
147
+ const request = store.get(nodeId);
148
+ request.onerror = () => reject(request.error);
149
+ request.onsuccess = () => resolve(request.result ?? null);
150
+ });
151
+ }
152
+ setInIndexedDB(entry) {
153
+ return new Promise((resolve, reject) => {
154
+ if (!this.db) {
155
+ reject(new Error('Database not initialized'));
156
+ return;
157
+ }
158
+ const transaction = this.db.transaction(STORE_NAME, 'readwrite');
159
+ const store = transaction.objectStore(STORE_NAME);
160
+ const request = store.put(entry);
161
+ request.onerror = () => reject(request.error);
162
+ request.onsuccess = () => resolve();
163
+ });
164
+ }
165
+ deleteFromIndexedDB(nodeId) {
166
+ return new Promise((resolve, reject) => {
167
+ if (!this.db) {
168
+ resolve();
169
+ return;
170
+ }
171
+ const transaction = this.db.transaction(STORE_NAME, 'readwrite');
172
+ const store = transaction.objectStore(STORE_NAME);
173
+ const request = store.delete(nodeId);
174
+ request.onerror = () => reject(request.error);
175
+ request.onsuccess = () => resolve();
176
+ });
177
+ }
178
+ clearIndexedDB() {
179
+ return new Promise((resolve, reject) => {
180
+ if (!this.db) {
181
+ resolve();
182
+ return;
183
+ }
184
+ const transaction = this.db.transaction(STORE_NAME, 'readwrite');
185
+ const store = transaction.objectStore(STORE_NAME);
186
+ const request = store.clear();
187
+ request.onerror = () => reject(request.error);
188
+ request.onsuccess = () => resolve();
189
+ });
190
+ }
191
+ getKeysFromIndexedDB() {
192
+ return new Promise((resolve, reject) => {
193
+ if (!this.db) {
194
+ resolve([]);
195
+ return;
196
+ }
197
+ const transaction = this.db.transaction(STORE_NAME, 'readonly');
198
+ const store = transaction.objectStore(STORE_NAME);
199
+ const request = store.getAllKeys();
200
+ request.onerror = () => reject(request.error);
201
+ request.onsuccess = () => resolve(request.result);
202
+ });
203
+ }
204
+ }
205
+ //# sourceMappingUR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AAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC9C,OAAO,CAAC,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,MAAkB,CAAC,CAAC;QAC/D,CAAC,CAAC,CAAC;IACJ,CAAC;CACD"}
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Violet Runtime Client
3
+ *
4
+ * Main client for loading and managing design tokens.
5
+ */
6
+ import type { RuntimeEvent, RuntimeEventListener, Token, VioletConfig, VioletTokenSource } from './types.js';
7
+ /**
8
+ * VioletRuntime - Web SDK for dynamic token loading and application.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const violet = new VioletRuntime({
13
+ * nodeId: "xbox-web-dark",
14
+ * apiUrl: "https://violet.example.com",
15
+ * apiKey: "your-api-key",
16
+ * });
17
+ *
18
+ * // Load tokens from API
19
+ * await violet.load();
20
+ *
21
+ * // Get a specific token
22
+ * const primary = violet.get("color.brand.primary");
23
+ *
24
+ * // Apply to document as CSS variables
25
+ * violet.applyToDocument();
26
+ *
27
+ * // Switch to different theme
28
+ * await violet.switchNode("xbox-web-light");
29
+ *
30
+ * // Or apply preloaded tokens with no token server
31
+ * const local = new VioletRuntime({ nodeId: "brand-dark", source: { tokens } });
32
+ * await local.load();
33
+ * await local.switchNode("brand-light", { tokens: lightTokens });
34
+ * ```
35
+ */
36
+ export declare class VioletRuntime {
37
+ private config;
38
+ /** Tokens for currentNodeId when created with a preloaded source; null over HTTP. */
39
+ private source;
40
+ private cache;
41
+ private tokens;
42
+ private currentNodeId;
43
+ private listeners;
44
+ private initialized;
45
+ /**
46
+ * Incremented by every load()/switchNode(). A request only applies its
47
+ * result if no newer request has started since (latest request wins).
48
+ */
49
+ private generation;
50
+ constructor(config: VioletConfig);
51
+ /**
52
+ * Initialize the runtime (call once before using).
53
+ */
54
+ init(): Promise<void>;
55
+ /**
56
+ * Load tokens from the preloaded source, or from API or cache.
57
+ * Automatically applies tokens if autoApply is enabled.
58
+ */
59
+ load(): Promise<Token[]>;
60
+ /**
61
+ * Get a token by ID.
62
+ */
63
+ get(tokenId: string): Token | undefined;
64
+ /**
65
+ * Get token value directly.
66
+ */
67
+ getValue(tokenId: string): string | number | Record<string, unknown> | undefined;
68
+ /**
69
+ * Get all loaded tokens.
70
+ */
71
+ getAll(): Token[];
72
+ /**
73
+ * Get tokens whose ID matches a glob pattern. `*` matches any characters;
74
+ * everything else is literal and the whole ID must match
75
+ * (`color.*` matches `color.primary` but not `bgcolor.primary`).
76
+ */
77
+ getByPattern(pattern: string): Token[];
78
+ /**
79
+ * Apply tokens to document as CSS custom properties.
80
+ */
81
+ applyToDocument(): void;
82
+ /**
83
+ * Remove tokens from document.
84
+ */
85
+ removeFromDocument(): void;
86
+ /**
87
+ * Switch to a different node (e.g., theme switch).
88
+ *
89
+ * A runtime created with a `source` takes the new node's tokens as
90
+ * `source`; it may be omitted only to reapply the node it already holds.
91
+ * An HTTP runtime refuses a source.
92
+ */
93
+ switchNode(nodeId: string, source?: VioletTokenSource): Promise<Token[]>;
94
+ /**
95
+ * Get current node ID.
96
+ */
97
+ getCurrentNodeId(): string;
98
+ /**
99
+ * Preload tokens for a node without applying. Nothing to do with a
100
+ * preloaded source: its tokens are already in memory.
101
+ */
102
+ preload(nodeId: string): Promise<void>;
103
+ /**
104
+ * Invalidate cache for current or specified node.
105
+ */
106
+ invalidateCache(nodeId?: string): Promise<void>;
107
+ /**
108
+ * Clear all cached tokens.
109
+ */
110
+ clearCache(): Promise<void>;
111
+ /**
112
+ * Subscribe to runtime events.
113
+ */
114
+ on(event: RuntimeEvent, listener: RuntimeEventListener): () => void;
115
+ /**
116
+ * Emit an event to listeners.
117
+ */
118
+ private emit;
119
+ /**
120
+ * The validated tokens a switch to `nodeId` applies from memory, or null
121
+ * when this runtime loads over HTTP. Throws when the call does not fit the
122
+ * runtime's token origin.
123
+ */
124
+ private nextSource;
125
+ /**
126
+ * Set tokens in internal map.
127
+ */
128
+ private setTokens;
129
+ /**
130
+ * Convert token ID to CSS variable name.
131
+ */
132
+ private tokenToCssVar;
133
+ /**
134
+ * Cache key for a node. Includes the API URL so tokens from different
135
+ * backends (staging/production) never collide.
136
+ */
137
+ private cacheKey;
138
+ /**
139
+ * Read from the cache. Cache I/O is best-effort: failures count as a miss.
140
+ */
141
+ private readCache;
142
+ /**
143
+ * Write to the cache. Cache I/O is best-effort (e.g. storage quota errors
144
+ * must not break loading). Returns whether the write succeeded.
145
+ */
146
+ private writeCache;
147
+ /**
148
+ * Resolve tokens for a node from cache or API without touching runtime
149
+ * state (tokens, currentNodeId, document).
150
+ */
151
+ private resolveTokens;
152
+ /**
153
+ * Fetch tokens from API (with timeout). Emits `load:error` exactly once on failure.
154
+ */
155
+ private fetchTokens;
156
+ }
157
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAGX,YAAY,EAEZ,oBAAoB,EACpB,KAAK,EAEL,YAAY,EAEZ,iBAAiB,EACjB,MAAM,YAAY,CAAC;AA2DpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBAAa,aAAa;IACzB,OAAO,CAAC,MAAM,CAA6C;IAC3D,qFAAqF;IACrF,OAAO,CAAC,MAAM,CAAwB;IACtC,OAAO,CAAC,KAAK,CAAa;IAC1B,OAAO,CAAC,MAAM,CAAiC;IAC/C,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,SAAS,CAA2D;IAC5E,OAAO,CAAC,WAAW,CAAS;IAC5B;;;OAGG;IACH,OAAO,CAAC,UAAU,CAAK;IAEvB,YAAY,MAAM,EAAE,YAAY,EAuB/B;IAED;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAO1B;IAED;;;OAGG;IACG,IAAI,IAAI,OAAO,CAAC,KAAK,EAAE,C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