tersejson 0.1.1 → 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.
Files changed (38) hide show
  1. package/README.md +47 -4
  2. package/dist/{client-BQAZg7I8.d.mts → client-CFGvusCj.d.mts} +1 -1
  3. package/dist/{client-DOOGwp_p.d.ts → client-hUXNNGcN.d.ts} +1 -1
  4. package/dist/client.d.mts +2 -2
  5. package/dist/client.d.ts +2 -2
  6. package/dist/client.js.map +1 -1
  7. package/dist/client.mjs.map +1 -1
  8. package/dist/{express-LSVylWpN.d.ts → express-Da7WcJtt.d.ts} +1 -1
  9. package/dist/{express-BoL__Ao6.d.mts → express-O5w2NBTf.d.mts} +1 -1
  10. package/dist/express.d.mts +2 -2
  11. package/dist/express.d.ts +2 -2
  12. package/dist/graphql-C3PTnqnZ.d.mts +81 -0
  13. package/dist/graphql-DmtweJgh.d.ts +81 -0
  14. package/dist/graphql-client-2H4FjmRc.d.mts +123 -0
  15. package/dist/graphql-client-BXGtWqe9.d.ts +123 -0
  16. package/dist/graphql-client.d.mts +2 -0
  17. package/dist/graphql-client.d.ts +2 -0
  18. package/dist/graphql-client.js +215 -0
  19. package/dist/graphql-client.js.map +1 -0
  20. package/dist/graphql-client.mjs +207 -0
  21. package/dist/graphql-client.mjs.map +1 -0
  22. package/dist/graphql.d.mts +3 -0
  23. package/dist/graphql.d.ts +3 -0
  24. package/dist/graphql.js +304 -0
  25. package/dist/graphql.js.map +1 -0
  26. package/dist/graphql.mjs +296 -0
  27. package/dist/graphql.mjs.map +1 -0
  28. package/dist/index.d.mts +5 -3
  29. package/dist/index.d.ts +5 -3
  30. package/dist/index.js +400 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/index.mjs +398 -4
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/integrations.js.map +1 -1
  35. package/dist/integrations.mjs.map +1 -1
  36. package/dist/{types-CzaGQaV7.d.mts → types-BTonKlz8.d.mts} +56 -1
  37. package/dist/{types-CzaGQaV7.d.ts → types-BTonKlz8.d.ts} +56 -1
  38. package/package.json +16 -2
@@ -0,0 +1,207 @@
1
+ // src/types.ts
2
+ function isGraphQLTersePayload(value) {
3
+ return typeof value === "object" && value !== null && "data" in value && "__terse__" in value && typeof value.__terse__ === "object" && value.__terse__ !== null && "v" in value.__terse__ && "k" in value.__terse__ && "paths" in value.__terse__;
4
+ }
5
+
6
+ // src/core.ts
7
+ function createTerseProxy(compressed, keyMap) {
8
+ const originalToShort = new Map(
9
+ Object.entries(keyMap).map(([short, original]) => [original, short])
10
+ );
11
+ const handler = {
12
+ get(target, prop) {
13
+ if (typeof prop === "symbol") {
14
+ return Reflect.get(target, prop);
15
+ }
16
+ const shortKey = originalToShort.get(prop);
17
+ const actualKey = shortKey ?? prop;
18
+ const value = target[actualKey];
19
+ if (Array.isArray(value)) {
20
+ return value.map((item) => {
21
+ if (typeof item === "object" && item !== null && !Array.isArray(item)) {
22
+ return createTerseProxy(item, keyMap);
23
+ }
24
+ return item;
25
+ });
26
+ }
27
+ if (typeof value === "object" && value !== null) {
28
+ return createTerseProxy(value, keyMap);
29
+ }
30
+ return value;
31
+ },
32
+ has(target, prop) {
33
+ if (typeof prop === "symbol") {
34
+ return Reflect.has(target, prop);
35
+ }
36
+ const shortKey = originalToShort.get(prop);
37
+ return (shortKey ?? prop) in target;
38
+ },
39
+ ownKeys(target) {
40
+ return Object.keys(target).map((shortKey) => keyMap[shortKey] ?? shortKey);
41
+ },
42
+ getOwnPropertyDescriptor(target, prop) {
43
+ if (typeof prop === "symbol") {
44
+ return Reflect.getOwnPropertyDescriptor(target, prop);
45
+ }
46
+ const shortKey = originalToShort.get(prop);
47
+ const actualKey = shortKey ?? prop;
48
+ const descriptor = Object.getOwnPropertyDescriptor(target, actualKey);
49
+ if (descriptor) {
50
+ return { ...descriptor, enumerable: true, configurable: true };
51
+ }
52
+ return void 0;
53
+ }
54
+ };
55
+ return new Proxy(compressed, handler);
56
+ }
57
+
58
+ // src/graphql-client.ts
59
+ var DEFAULT_OPTIONS = {
60
+ useProxy: true,
61
+ debug: false
62
+ };
63
+ function getAtPath(obj, path) {
64
+ const parts = path.split(/\.|\[(\d+)\]/).filter(Boolean);
65
+ let current = obj;
66
+ for (const part of parts) {
67
+ if (current === null || current === void 0) return void 0;
68
+ const isIndex = /^\d+$/.test(part);
69
+ if (isIndex) {
70
+ current = current[parseInt(part, 10)];
71
+ } else {
72
+ current = current[part];
73
+ }
74
+ }
75
+ return current;
76
+ }
77
+ function setAtPath(obj, path, value) {
78
+ const parts = path.split(/\.|\[(\d+)\]/).filter(Boolean);
79
+ let current = obj;
80
+ for (let i = 0; i < parts.length - 1; i++) {
81
+ const part = parts[i];
82
+ const isIndex = /^\d+$/.test(part);
83
+ if (isIndex) {
84
+ current = current[parseInt(part, 10)];
85
+ } else {
86
+ current = current[part];
87
+ }
88
+ }
89
+ const lastPart = parts[parts.length - 1];
90
+ const isLastIndex = /^\d+$/.test(lastPart);
91
+ if (isLastIndex) {
92
+ current[parseInt(lastPart, 10)] = value;
93
+ } else {
94
+ current[lastPart] = value;
95
+ }
96
+ }
97
+ function expandObject(obj, keyMap, maxDepth = 10, currentDepth = 0) {
98
+ if (currentDepth >= maxDepth) return obj;
99
+ const shortToKey = new Map(
100
+ Object.entries(keyMap).map(([short, original]) => [short, original])
101
+ );
102
+ const expanded = {};
103
+ for (const [shortKey, value] of Object.entries(obj)) {
104
+ const originalKey = shortToKey.get(shortKey) ?? shortKey;
105
+ if (Array.isArray(value)) {
106
+ expanded[originalKey] = value.map((item) => {
107
+ if (typeof item === "object" && item !== null && !Array.isArray(item)) {
108
+ return expandObject(item, keyMap, maxDepth, currentDepth + 1);
109
+ }
110
+ return item;
111
+ });
112
+ } else if (typeof value === "object" && value !== null) {
113
+ expanded[originalKey] = expandObject(
114
+ value,
115
+ keyMap,
116
+ maxDepth,
117
+ currentDepth + 1
118
+ );
119
+ } else {
120
+ expanded[originalKey] = value;
121
+ }
122
+ }
123
+ return expanded;
124
+ }
125
+ function wrapArrayWithProxies(array, keyMap) {
126
+ return array.map((item) => createTerseProxy(item, keyMap));
127
+ }
128
+ function expandArray(array, keyMap) {
129
+ return array.map((item) => expandObject(item, keyMap));
130
+ }
131
+ function processGraphQLResponse(response, options = {}) {
132
+ const config = { ...DEFAULT_OPTIONS, ...options };
133
+ if (!isGraphQLTersePayload(response)) {
134
+ return response;
135
+ }
136
+ const terseResponse = response;
137
+ const { data, __terse__, ...rest } = terseResponse;
138
+ const { k: keyMap, paths } = __terse__;
139
+ if (config.debug) {
140
+ console.log("[tersejson/graphql-client] Processing terse response");
141
+ console.log("[tersejson/graphql-client] Paths:", paths);
142
+ console.log("[tersejson/graphql-client] Key map:", keyMap);
143
+ }
144
+ const clonedData = JSON.parse(JSON.stringify(data));
145
+ const result = { data: clonedData, ...rest };
146
+ for (const path of paths) {
147
+ const array = getAtPath(result, path);
148
+ if (!array || !Array.isArray(array)) {
149
+ if (config.debug) {
150
+ console.warn(`[tersejson/graphql-client] Path not found or not array: ${path}`);
151
+ }
152
+ continue;
153
+ }
154
+ if (config.useProxy) {
155
+ const proxied = wrapArrayWithProxies(array, keyMap);
156
+ setAtPath(result, path, proxied);
157
+ } else {
158
+ const expanded = expandArray(array, keyMap);
159
+ setAtPath(result, path, expanded);
160
+ }
161
+ }
162
+ return result;
163
+ }
164
+ function createTerseLink(options = {}) {
165
+ const config = { ...DEFAULT_OPTIONS, ...options };
166
+ return {
167
+ request(operation, forward) {
168
+ operation.setContext({
169
+ ...operation.getContext(),
170
+ headers: {
171
+ ...operation.getContext().headers || {},
172
+ "accept-terse": "true"
173
+ }
174
+ });
175
+ return forward(operation).map((result) => {
176
+ if (isGraphQLTersePayload(result)) {
177
+ if (config.debug) {
178
+ console.log("[tersejson/apollo] Processing terse response");
179
+ }
180
+ return processGraphQLResponse(result, config);
181
+ }
182
+ return result;
183
+ });
184
+ }
185
+ };
186
+ }
187
+ function createGraphQLFetch(options = {}) {
188
+ const config = { ...DEFAULT_OPTIONS, ...options };
189
+ return async function graphqlFetch(url, body, init = {}) {
190
+ const headers = new Headers(init.headers);
191
+ headers.set("Content-Type", "application/json");
192
+ headers.set("accept-terse", "true");
193
+ const response = await fetch(url, {
194
+ ...init,
195
+ method: "POST",
196
+ headers,
197
+ body: JSON.stringify(body)
198
+ });
199
+ const data = await response.json();
200
+ return processGraphQLResponse(data, config);
201
+ };
202
+ }
203
+ var graphql_client_default = processGraphQLResponse;
204
+
205
+ export { createGraphQLFetch, createTerseLink, graphql_client_default as default, isGraphQLTersePayload, processGraphQLResponse };
206
+ //# sourceMappingURL=graphql-client.mjs.map
207
+ //# sourceMappingURL=graphql-client.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/core.ts","../src/graphql-client.ts"],"names":[],"mappings":";AAsOO,SAAS,sBAAsB,KAAA,EAA+C;AACnF,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,MAAA,IAAU,KAAA,IACV,WAAA,IAAe,KAAA,IACf,OAAQ,KAAA,CAA+B,cAAc,QAAA,IACpD,KAAA,CAA+B,SAAA,KAAc,IAAA,IAC9C,GAAA,IAAQ,KAAA,CAA+B,aACvC,GAAA,IAAQ,KAAA,CAA+B,SAAA,IACvC,OAAA,IAAY,KAAA,CAA+B,SAAA;AAE/C;;;ACqKO,SAAS,gBAAA,CACd,YACA,MAAA,EACG;AAEH,EAAA,MAAM,kBAAkB,IAAI,GAAA;AAAA,IAC1B,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,CAAE,GAAA,CAAI,CAAC,CAAC,KAAA,EAAO,QAAQ,CAAA,KAAM,CAAC,QAAA,EAAU,KAAK,CAAC;AAAA,GACrE;AAEA,EAAA,MAAM,OAAA,GAAiD;AAAA,IACrD,GAAA,CAAI,QAAQ,IAAA,EAAuB;AACjC,MAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,QAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,MAA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eAAe,YAAA,CACpB,GAAA,EACA,IAAA,EACA,IAAA,GAAoB,EAAC,EACT;AACZ,IAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAQ,IAAA,CAAK,OAAO,CAAA;AACxC,IAAA,OAAA,CAAQ,GAAA,CAAI,gBAAgB,kBAAkB,CAAA;AAC9C,IAAA,OAAA,CAAQ,GAAA,CAAI,gBAAgB,MAAM,CAAA;AAElC,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAA,EAAK;AAAA,MAChC,GAAG,IAAA;AAAA,MACH,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA;AAAA,MACA,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,IAAI;AAAA,KAC1B,CAAA;AAED,IAAA,MAAM,IAAA,GAAO,MAAM,QAAA,CAAS,IAAA,EAAK;AAEjC,IAAA,OAAO,sBAAA,CAA0B,MAAM,MAAM,CAAA;AAAA,EAC/C,CAAA;AACF;AAMA,IAAO,sBAAA,GAAQ","file":"graphql-client.mjs","sourcesContent":["/**\n * TerseJSON Types\n *\n * Defines the wire format and configuration options for transparent\n * JSON key compression.\n */\n\n/**\n * The compressed format sent over the wire\n */\nexport interface TersePayload<T = unknown> {\n /** Marker to identify this as a TerseJSON payload */\n __terse__: true;\n /** Version for future compatibility */\n v: 1;\n /** Key mapping: short key -> original key */\n k: Record<string, string>;\n /** The compressed data with short keys */\n d: T;\n /** Pattern used for key generation (for debugging/info) */\n p?: string;\n}\n\n/**\n * Built-in key pattern presets\n */\nexport type KeyPatternPreset =\n | 'alpha' // a, b, c, ... z, aa, ab (default)\n | 'numeric' // 0, 1, 2, ... 9, 10, 11\n | 'alphanumeric' // a1, a2, ... a9, b1, b2\n | 'short' // _, __, ___, a, b (shortest possible)\n | 'prefixed'; // k0, k1, k2 (with 'k' prefix)\n\n/**\n * Custom key generator function\n */\nexport type KeyGenerator = (index: number) => string;\n\n/**\n * Key pattern configuration\n */\nexport type KeyPattern =\n | KeyPatternPreset\n | { prefix: string; style?: 'numeric' | 'alpha' }\n | KeyGenerator;\n\n/**\n * How to handle nested structures\n */\nexport type NestedHandling =\n | 'deep' // Compress all nested objects/arrays (default)\n | 'shallow' // Only compress top-level array\n | 'arrays' // Only compress nested arrays, not single objects\n | number; // Specific depth limit (1 = shallow, Infinity = deep)\n\n/**\n * Compression options\n */\nexport interface CompressOptions {\n /**\n * Minimum key length to consider for compression\n * Keys shorter than this won't be shortened\n * @default 3\n */\n minKeyLength?: number;\n\n /**\n * Maximum depth to traverse for nested objects\n * @default 10\n */\n maxDepth?: number;\n\n /**\n * Key pattern to use for generating short keys\n * @default 'alpha'\n */\n keyPattern?: KeyPattern;\n\n /**\n * How to handle nested objects and arrays\n * @default 'deep'\n */\n nestedHandling?: NestedHandling;\n\n /**\n * Only compress keys that appear in all objects (homogeneous)\n * @default false\n */\n homogeneousOnly?: boolean;\n\n /**\n * Keys to always exclude from compression\n */\n excludeKeys?: string[];\n\n /**\n * Keys to always include in compression (even if short)\n */\n includeKeys?: string[];\n}\n\n/**\n * Configuration options for the Express middleware\n */\nexport interface TerseMiddlewareOptions extends CompressOptions {\n /**\n * Minimum array length to trigger compression\n * @default 2\n */\n minArrayLength?: number;\n\n /**\n * Custom function to determine if a response should be compressed\n * Return false to skip compression for specific responses\n */\n shouldCompress?: (data: unknown, req: unknown) => boolean;\n\n /**\n * Custom header name for signaling terse responses\n * @default 'x-terse-json'\n */\n headerName?: string;\n\n /**\n * Enable debug logging\n * @default false\n */\n debug?: boolean;\n}\n\n/**\n * Configuration options for the client\n */\nexport interface TerseClientOptions {\n /**\n * Custom header name to check for terse responses\n * @default 'x-terse-json'\n */\n headerName?: string;\n\n /**\n * Enable debug logging\n * @default false\n */\n debug?: boolean;\n\n /**\n * Automatically expand terse responses\n * @default true\n */\n autoExpand?: boolean;\n}\n\n/**\n * Type helper to preserve original types through compression\n */\nexport type Tersed<T> = T;\n\n/**\n * Check if a value is a TersePayload\n */\nexport function isTersePayload(value: unknown): value is TersePayload {\n return (\n typeof value === 'object' &&\n value !== null &&\n '__terse__' in value &&\n (value as TersePayload).__terse__ === true &&\n 'v' in value &&\n 'k' in value &&\n 'd' in value\n );\n}\n\n/**\n * GraphQL terse metadata (attached to response)\n */\nexport interface GraphQLTerseMetadata {\n /** Version for compatibility */\n v: 1;\n /** Key mapping: short key -> original key */\n k: Record<string, string>;\n /** JSON paths to compressed arrays (e.g., [\"data.users\", \"data.products\"]) */\n paths: string[];\n}\n\n/**\n * GraphQL response with terse compression\n */\nexport interface GraphQLTerseResponse<T = unknown> {\n /** The compressed data with short keys in arrays */\n data: T;\n /** GraphQL errors (untouched) */\n errors?: Array<{ message: string; [key: string]: unknown }>;\n /** GraphQL extensions (untouched) */\n extensions?: Record<string, unknown>;\n /** Terse metadata */\n __terse__: GraphQLTerseMetadata;\n}\n\n/**\n * GraphQL middleware options\n */\nexport interface GraphQLTerseOptions extends CompressOptions {\n /**\n * Minimum array length to trigger compression\n * @default 2\n */\n minArrayLength?: number;\n\n /**\n * Custom function to determine if a path should be compressed\n * Return false to skip compression for specific paths\n */\n shouldCompress?: (data: unknown, path: string) => boolean;\n\n /**\n * Paths to exclude from compression (e.g., [\"data.config\"])\n */\n excludePaths?: string[];\n\n /**\n * Enable debug logging\n * @default false\n */\n debug?: boolean;\n}\n\n/**\n * Check if a value is a GraphQL terse response\n */\nexport function isGraphQLTersePayload(value: unknown): value is GraphQLTerseResponse {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'data' in value &&\n '__terse__' in value &&\n typeof (value as GraphQLTerseResponse).__terse__ === 'object' &&\n (value as GraphQLTerseResponse).__terse__ !== null &&\n 'v' in (value as GraphQLTerseResponse).__terse__ &&\n 'k' in (value as GraphQLTerseResponse).__terse__ &&\n 'paths' in (value as GraphQLTerseResponse).__terse__\n );\n}\n","/**\n * TerseJSON Core\n *\n * The core compression and expansion algorithms.\n */\n\nimport {\n TersePayload,\n isTersePayload,\n KeyPattern,\n KeyGenerator,\n NestedHandling,\n CompressOptions,\n} from './types';\n\n// ============================================================================\n// KEY PATTERN GENERATORS\n// ============================================================================\n\n/**\n * Alpha pattern: a, b, c, ... z, aa, ab, ...\n */\nfunction alphaGenerator(index: number): string {\n let key = '';\n let remaining = index;\n\n do {\n key = String.fromCharCode(97 + (remaining % 26)) + key;\n remaining = Math.floor(remaining / 26) - 1;\n } while (remaining >= 0);\n\n return key;\n}\n\n/**\n * Numeric pattern: 0, 1, 2, ... 9, 10, 11, ...\n */\nfunction numericGenerator(index: number): string {\n return String(index);\n}\n\n/**\n * Alphanumeric pattern: a1, a2, ... a9, b1, b2, ...\n */\nfunction alphanumericGenerator(index: number): string {\n const letterIndex = Math.floor(index / 9);\n const numIndex = (index % 9) + 1;\n return alphaGenerator(letterIndex) + numIndex;\n}\n\n/**\n * Short pattern: uses shortest possible keys\n * _, a, b, ..., z, aa, ab, ...\n */\nfunction shortGenerator(index: number): string {\n if (index === 0) return '_';\n return alphaGenerator(index - 1);\n}\n\n/**\n * Prefixed pattern: k0, k1, k2, ...\n */\nfunction prefixedGenerator(prefix: string, style: 'numeric' | 'alpha' = 'numeric'): KeyGenerator {\n return (index: number) => {\n if (style === 'alpha') {\n return prefix + alphaGenerator(index);\n }\n return prefix + index;\n };\n}\n\n/**\n * Creates a key generator from a pattern configuration\n */\nexport function createKeyGenerator(pattern: KeyPattern): { generator: KeyGenerator; name: string } {\n // If it's already a function, use it directly\n if (typeof pattern === 'function') {\n return { generator: pattern, name: 'custom' };\n }\n\n // If it's a preset string\n if (typeof pattern === 'string') {\n switch (pattern) {\n case 'alpha':\n return { generator: alphaGenerator, name: 'alpha' };\n case 'numeric':\n return { generator: numericGenerator, name: 'numeric' };\n case 'alphanumeric':\n return { generator: alphanumericGenerator, name: 'alphanumeric' };\n case 'short':\n return { generator: shortGenerator, name: 'short' };\n case 'prefixed':\n return { generator: prefixedGenerator('k'), name: 'prefixed:k' };\n default:\n return { generator: alphaGenerator, name: 'alpha' };\n }\n }\n\n // If it's a prefix config object\n if (typeof pattern === 'object' && 'prefix' in pattern) {\n return {\n generator: prefixedGenerator(pattern.prefix, pattern.style || 'numeric'),\n name: `prefixed:${pattern.prefix}`,\n };\n }\n\n return { generator: alphaGenerator, name: 'alpha' };\n}\n\n/**\n * Resolves nested handling to a numeric depth\n */\nfunction resolveNestedDepth(handling: NestedHandling | undefined, maxDepth: number): number {\n if (handling === undefined || handling === 'deep') {\n return maxDepth;\n }\n if (handling === 'shallow') {\n return 1;\n }\n if (handling === 'arrays') {\n return maxDepth; // Special handling in collect/compress functions\n }\n if (typeof handling === 'number') {\n return handling;\n }\n return maxDepth;\n}\n\n// Legacy generateShortKey removed - use createKeyGenerator instead\n\ninterface CollectKeysOptions {\n minKeyLength: number;\n maxDepth: number;\n nestedHandling: NestedHandling;\n excludeKeys?: string[];\n includeKeys?: string[];\n homogeneousOnly?: boolean;\n}\n\n/**\n * Collects all unique keys from an array of objects\n */\nfunction collectKeys(\n data: Record<string, unknown>[],\n options: CollectKeysOptions,\n currentDepth: number = 0\n): Set<string> {\n const keys = new Set<string>();\n const { minKeyLength, maxDepth, nestedHandling, excludeKeys, includeKeys } = options;\n\n if (currentDepth >= maxDepth) return keys;\n\n // For homogeneous mode, track key counts\n const keyCounts = new Map<string, number>();\n\n for (const item of data) {\n if (typeof item !== 'object' || item === null) continue;\n\n for (const key of Object.keys(item)) {\n // Skip excluded keys\n if (excludeKeys?.includes(key)) continue;\n\n // Include if in includeKeys, or if meets minKeyLength\n const shouldInclude = includeKeys?.includes(key) || key.length >= minKeyLength;\n\n if (shouldInclude) {\n keys.add(key);\n keyCounts.set(key, (keyCounts.get(key) || 0) + 1);\n }\n\n // Handle nested structures based on nestedHandling option\n const value = item[key];\n\n if (nestedHandling === 'shallow') {\n // Don't process nested structures\n continue;\n }\n\n if (Array.isArray(value) && value.length > 0 && isCompressibleArray(value)) {\n // Nested array of objects - always process\n const nestedKeys = collectKeys(\n value as Record<string, unknown>[],\n options,\n currentDepth + 1\n );\n nestedKeys.forEach(k => keys.add(k));\n } else if (\n nestedHandling !== 'arrays' &&\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value)\n ) {\n // Single nested object - skip if nestedHandling is 'arrays'\n const nestedKeys = collectKeys(\n [value as Record<string, unknown>],\n options,\n currentDepth + 1\n );\n nestedKeys.forEach(k => keys.add(k));\n }\n }\n }\n\n // If homogeneous mode, only keep keys that appear in ALL objects\n if (options.homogeneousOnly && data.length > 0) {\n for (const [key, count] of keyCounts) {\n if (count < data.length) {\n keys.delete(key);\n }\n }\n }\n\n return keys;\n}\n\n/**\n * Checks if an array is compressible (array of objects with consistent structure)\n */\nexport function isCompressibleArray(data: unknown): data is Record<string, unknown>[] {\n if (!Array.isArray(data) || data.length === 0) return false;\n\n // Check if all items are objects\n return data.every(\n item => typeof item === 'object' && item !== null && !Array.isArray(item)\n );\n}\n\n/**\n * Compresses an object using the key mapping\n */\nfunction compressObject(\n obj: Record<string, unknown>,\n keyToShort: Map<string, string>,\n maxDepth: number,\n currentDepth: number = 0\n): Record<string, unknown> {\n if (currentDepth >= maxDepth) return obj;\n\n const compressed: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const shortKey = keyToShort.get(key) ?? key;\n\n if (Array.isArray(value) && isCompressibleArray(value)) {\n // Recursively compress nested arrays\n compressed[shortKey] = value.map(item =>\n compressObject(\n item as Record<string, unknown>,\n keyToShort,\n maxDepth,\n currentDepth + 1\n )\n );\n } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n // Compress single nested objects too\n compressed[shortKey] = compressObject(\n value as Record<string, unknown>,\n keyToShort,\n maxDepth,\n currentDepth + 1\n );\n } else {\n compressed[shortKey] = value;\n }\n }\n\n return compressed;\n}\n\n/**\n * Expands an object using the key mapping\n */\nfunction expandObject(\n obj: Record<string, unknown>,\n shortToKey: Map<string, string>,\n maxDepth: number,\n currentDepth: number = 0\n): Record<string, unknown> {\n if (currentDepth >= maxDepth) return obj;\n\n const expanded: Record<string, unknown> = {};\n\n for (const [shortKey, value] of Object.entries(obj)) {\n const originalKey = shortToKey.get(shortKey) ?? shortKey;\n\n if (Array.isArray(value)) {\n expanded[originalKey] = value.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return expandObject(\n item as Record<string, unknown>,\n shortToKey,\n maxDepth,\n currentDepth + 1\n );\n }\n return item;\n });\n } else if (typeof value === 'object' && value !== null) {\n expanded[originalKey] = expandObject(\n value as Record<string, unknown>,\n shortToKey,\n maxDepth,\n currentDepth + 1\n );\n } else {\n expanded[originalKey] = value;\n }\n }\n\n return expanded;\n}\n\n// Re-export CompressOptions from types for backwards compatibility\nexport type { CompressOptions } from './types';\n\n/**\n * Compresses an array of objects by replacing keys with short aliases\n */\nexport function compress<T extends Record<string, unknown>[]>(\n data: T,\n options: CompressOptions = {}\n): TersePayload<unknown[]> {\n const {\n minKeyLength = 3,\n maxDepth = 10,\n keyPattern = 'alpha',\n nestedHandling = 'deep',\n homogeneousOnly = false,\n excludeKeys,\n includeKeys,\n } = options;\n\n // Create key generator\n const { generator, name: patternName } = createKeyGenerator(keyPattern);\n\n // Resolve nested depth\n const effectiveDepth = resolveNestedDepth(nestedHandling, maxDepth);\n\n // Collect all unique keys\n const allKeys = collectKeys(data, {\n minKeyLength,\n maxDepth: effectiveDepth,\n nestedHandling,\n excludeKeys,\n includeKeys,\n homogeneousOnly,\n });\n\n // Sort keys by frequency of use (most used first) for optimal compression\n // For now, just sort alphabetically for deterministic output\n const sortedKeys = Array.from(allKeys).sort();\n\n // Create bidirectional mapping\n const keyToShort = new Map<string, string>();\n const keyMap: Record<string, string> = {};\n\n sortedKeys.forEach((key, index) => {\n const shortKey = generator(index);\n // Only use short key if it's actually shorter\n if (shortKey.length < key.length) {\n keyToShort.set(key, shortKey);\n keyMap[shortKey] = key;\n }\n });\n\n // Compress the data\n const compressed = data.map(item =>\n compressObject(item, keyToShort, effectiveDepth)\n );\n\n return {\n __terse__: true,\n v: 1,\n k: keyMap,\n d: compressed,\n p: patternName,\n };\n}\n\n/**\n * Expands a TersePayload back to its original form\n */\nexport function expand<T = unknown>(payload: TersePayload): T {\n const shortToKey = new Map(\n Object.entries(payload.k).map(([short, original]) => [short, original])\n );\n\n if (Array.isArray(payload.d)) {\n return payload.d.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return expandObject(item as Record<string, unknown>, shortToKey, 10);\n }\n return item;\n }) as T;\n }\n\n if (typeof payload.d === 'object' && payload.d !== null) {\n return expandObject(payload.d as Record<string, unknown>, shortToKey, 10) as T;\n }\n\n return payload.d as T;\n}\n\n/**\n * Creates a Proxy that transparently maps original keys to short keys\n * This is the magic that makes client-side access seamless\n */\nexport function createTerseProxy<T extends Record<string, unknown>>(\n compressed: Record<string, unknown>,\n keyMap: Record<string, string> // short -> original\n): T {\n // Create reverse map: original -> short\n const originalToShort = new Map(\n Object.entries(keyMap).map(([short, original]) => [original, short])\n );\n\n const handler: ProxyHandler<Record<string, unknown>> = {\n get(target, prop: string | symbol) {\n if (typeof prop === 'symbol') {\n return Reflect.get(target, prop);\n }\n\n // Check if accessing by original key name\n const shortKey = originalToShort.get(prop);\n const actualKey = shortKey ?? prop;\n const value = target[actualKey];\n\n // Recursively proxy nested objects/arrays\n if (Array.isArray(value)) {\n return value.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return createTerseProxy(item as Record<string, unknown>, keyMap);\n }\n return item;\n });\n }\n\n if (typeof value === 'object' && value !== null) {\n return createTerseProxy(value as Record<string, unknown>, keyMap);\n }\n\n return value;\n },\n\n has(target, prop: string | symbol) {\n if (typeof prop === 'symbol') {\n return Reflect.has(target, prop);\n }\n const shortKey = originalToShort.get(prop);\n return (shortKey ?? prop) in target;\n },\n\n ownKeys(target) {\n // Return original key names\n return Object.keys(target).map(shortKey => keyMap[shortKey] ?? shortKey);\n },\n\n getOwnPropertyDescriptor(target, prop: string | symbol) {\n if (typeof prop === 'symbol') {\n return Reflect.getOwnPropertyDescriptor(target, prop);\n }\n const shortKey = originalToShort.get(prop);\n const actualKey = shortKey ?? prop;\n const descriptor = Object.getOwnPropertyDescriptor(target, actualKey);\n if (descriptor) {\n return { ...descriptor, enumerable: true, configurable: true };\n }\n return undefined;\n },\n };\n\n return new Proxy(compressed, handler) as T;\n}\n\n/**\n * Wraps TersePayload data with Proxies for transparent access\n */\nexport function wrapWithProxy<T>(payload: TersePayload): T {\n if (Array.isArray(payload.d)) {\n return payload.d.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return createTerseProxy(item as Record<string, unknown>, payload.k);\n }\n return item;\n }) as T;\n }\n\n if (typeof payload.d === 'object' && payload.d !== null) {\n return createTerseProxy(payload.d as Record<string, unknown>, payload.k) as T;\n }\n\n return payload.d as T;\n}\n\n// Re-export for convenience\nexport { isTersePayload };\n","/**\n * TerseJSON GraphQL Client\n *\n * Apollo Client Link and utilities for expanding GraphQL responses.\n */\n\nimport { GraphQLTerseResponse, isGraphQLTersePayload } from './types';\nimport { createTerseProxy } from './core';\n\n/**\n * Options for GraphQL client processing\n */\nexport interface GraphQLTerseClientOptions {\n /**\n * Use Proxy for lazy expansion (more memory efficient)\n * @default true\n */\n useProxy?: boolean;\n\n /**\n * Enable debug logging\n * @default false\n */\n debug?: boolean;\n}\n\nconst DEFAULT_OPTIONS: Required<GraphQLTerseClientOptions> = {\n useProxy: true,\n debug: false,\n};\n\n/**\n * Gets a value at a path in an object\n */\nfunction getAtPath(obj: unknown, path: string): unknown {\n const parts = path.split(/\\.|\\[(\\d+)\\]/).filter(Boolean);\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current === null || current === undefined) return undefined;\n const isIndex = /^\\d+$/.test(part);\n if (isIndex) {\n current = (current as unknown[])[parseInt(part, 10)];\n } else {\n current = (current as Record<string, unknown>)[part];\n }\n }\n\n return current;\n}\n\n/**\n * Sets a value at a path in an object (mutates the object)\n */\nfunction setAtPath(obj: Record<string, unknown>, path: string, value: unknown): void {\n const parts = path.split(/\\.|\\[(\\d+)\\]/).filter(Boolean);\n let current: unknown = obj;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n const isIndex = /^\\d+$/.test(part);\n if (isIndex) {\n current = (current as unknown[])[parseInt(part, 10)];\n } else {\n current = (current as Record<string, unknown>)[part];\n }\n }\n\n const lastPart = parts[parts.length - 1];\n const isLastIndex = /^\\d+$/.test(lastPart);\n if (isLastIndex) {\n (current as unknown[])[parseInt(lastPart, 10)] = value;\n } else {\n (current as Record<string, unknown>)[lastPart] = value;\n }\n}\n\n/**\n * Expands an object using the key mapping\n */\nfunction expandObject(\n obj: Record<string, unknown>,\n keyMap: Record<string, string>,\n maxDepth: number = 10,\n currentDepth: number = 0\n): Record<string, unknown> {\n if (currentDepth >= maxDepth) return obj;\n\n const shortToKey = new Map(\n Object.entries(keyMap).map(([short, original]) => [short, original])\n );\n\n const expanded: Record<string, unknown> = {};\n\n for (const [shortKey, value] of Object.entries(obj)) {\n const originalKey = shortToKey.get(shortKey) ?? shortKey;\n\n if (Array.isArray(value)) {\n expanded[originalKey] = value.map(item => {\n if (typeof item === 'object' && item !== null && !Array.isArray(item)) {\n return expandObject(item as Record<string, unknown>, keyMap, maxDepth, currentDepth + 1);\n }\n return item;\n });\n } else if (typeof value === 'object' && value !== null) {\n expanded[originalKey] = expandObject(\n value as Record<string, unknown>,\n keyMap,\n maxDepth,\n currentDepth + 1\n );\n } else {\n expanded[originalKey] = value;\n }\n }\n\n return expanded;\n}\n\n/**\n * Wraps an array with Proxies for transparent key access\n */\nfunction wrapArrayWithProxies<T extends Record<string, unknown>>(\n array: Record<string, unknown>[],\n keyMap: Record<string, string>\n): T[] {\n return array.map(item => createTerseProxy<T>(item, keyMap));\n}\n\n/**\n * Expands an array to its original form\n */\nfunction expandArray(\n array: Record<string, unknown>[],\n keyMap: Record<string, string>\n): Record<string, unknown>[] {\n return array.map(item => expandObject(item, keyMap));\n}\n\n/**\n * Processes a GraphQL terse response, expanding compressed arrays\n *\n * @example\n * ```typescript\n * import { processGraphQLResponse } from 'tersejson/graphql-client';\n *\n * const response = await fetch('/graphql', {\n * method: 'POST',\n * headers: {\n * 'Content-Type': 'application/json',\n * 'accept-terse': 'true',\n * },\n * body: JSON.stringify({ query: '{ users { firstName lastName } }' }),\n * }).then(r => r.json());\n *\n * const expanded = processGraphQLResponse(response);\n * console.log(expanded.data.users[0].firstName); // Works transparently\n * ```\n */\nexport function processGraphQLResponse<T = unknown>(\n response: unknown,\n options: GraphQLTerseClientOptions = {}\n): T {\n const config = { ...DEFAULT_OPTIONS, ...options };\n\n // If not a terse response, return as-is\n if (!isGraphQLTersePayload(response)) {\n return response as T;\n }\n\n const terseResponse = response as GraphQLTerseResponse;\n const { data, __terse__, ...rest } = terseResponse;\n const { k: keyMap, paths } = __terse__;\n\n if (config.debug) {\n console.log('[tersejson/graphql-client] Processing terse response');\n console.log('[tersejson/graphql-client] Paths:', paths);\n console.log('[tersejson/graphql-client] Key map:', keyMap);\n }\n\n // Clone the data to avoid mutating\n const clonedData = JSON.parse(JSON.stringify(data));\n const result: Record<string, unknown> = { data: clonedData, ...rest };\n\n // Process each compressed path\n for (const path of paths) {\n const array = getAtPath(result, path) as Record<string, unknown>[] | undefined;\n\n if (!array || !Array.isArray(array)) {\n if (config.debug) {\n console.warn(`[tersejson/graphql-client] Path not found or not array: ${path}`);\n }\n continue;\n }\n\n if (config.useProxy) {\n // Wrap with proxies for lazy expansion\n const proxied = wrapArrayWithProxies(array, keyMap);\n setAtPath(result, path, proxied);\n } else {\n // Fully expand the array\n const expanded = expandArray(array, keyMap);\n setAtPath(result, path, expanded);\n }\n }\n\n return result as T;\n}\n\n/**\n * Type for Apollo Link (avoiding direct dependency)\n */\ninterface ApolloLinkLike {\n request(\n operation: { getContext: () => Record<string, unknown>; setContext: (ctx: Record<string, unknown>) => void },\n forward: (operation: unknown) => { map: (fn: (result: unknown) => unknown) => unknown }\n ): unknown;\n}\n\n/**\n * Creates an Apollo Client Link for TerseJSON\n *\n * This link automatically adds the accept-terse header and processes\n * terse responses transparently.\n *\n * @example\n * ```typescript\n * import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client';\n * import { createTerseLink } from 'tersejson/graphql-client';\n *\n * const terseLink = createTerseLink({ debug: true });\n *\n * const httpLink = new HttpLink({\n * uri: '/graphql',\n * });\n *\n * const client = new ApolloClient({\n * link: from([terseLink, httpLink]),\n * cache: new InMemoryCache(),\n * });\n *\n * // Usage is completely transparent\n * const { data } = await client.query({\n * query: gql`\n * query GetUsers {\n * users { firstName lastName email }\n * }\n * `,\n * });\n *\n * console.log(data.users[0].firstName); // Just works!\n * ```\n */\nexport function createTerseLink(options: GraphQLTerseClientOptions = {}): ApolloLinkLike {\n const config = { ...DEFAULT_OPTIONS, ...options };\n\n return {\n request(operation, forward) {\n // Add accept-terse header to the request\n operation.setContext({\n ...operation.getContext(),\n headers: {\n ...((operation.getContext().headers as Record<string, string>) || {}),\n 'accept-terse': 'true',\n },\n });\n\n // Forward the operation and process the response\n return forward(operation).map((result: unknown) => {\n if (isGraphQLTersePayload(result)) {\n if (config.debug) {\n console.log('[tersejson/apollo] Processing terse response');\n }\n return processGraphQLResponse(result, config);\n }\n return result;\n });\n },\n };\n}\n\n/**\n * Creates a fetch wrapper for GraphQL requests\n *\n * Useful for non-Apollo GraphQL clients or direct fetch usage.\n *\n * @example\n * ```typescript\n * import { createGraphQLFetch } from 'tersejson/graphql-client';\n *\n * const gqlFetch = createGraphQLFetch({ debug: true });\n *\n * const result = await gqlFetch('/graphql', {\n * query: `{ users { firstName lastName } }`,\n * });\n *\n * console.log(result.data.users[0].firstName);\n * ```\n */\nexport function createGraphQLFetch(options: GraphQLTerseClientOptions = {}) {\n const config = { ...DEFAULT_OPTIONS, ...options };\n\n return async function graphqlFetch<T = unknown>(\n url: string,\n body: { query: string; variables?: Record<string, unknown>; operationName?: string },\n init: RequestInit = {}\n ): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/json');\n headers.set('accept-terse', 'true');\n\n const response = await fetch(url, {\n ...init,\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n const data = await response.json();\n\n return processGraphQLResponse<T>(data, config);\n };\n}\n\n// Re-export type guard for convenience\nexport { isGraphQLTersePayload } from './types';\n\n// Default export\nexport default processGraphQLResponse;\n"]}
@@ -0,0 +1,3 @@
1
+ import 'express';
2
+ import './types-BTonKlz8.mjs';
3
+ export { c as compressGraphQLResponse, a as createTerseFormatFn, t as default, f as findCompressibleArrays, t as terseGraphQL } from './graphql-C3PTnqnZ.mjs';
@@ -0,0 +1,3 @@
1
+ import 'express';
2
+ import './types-BTonKlz8.js';
3
+ export { c as compressGraphQLResponse, a as createTerseFormatFn, t as default, f as findCompressibleArrays, t as terseGraphQL } from './graphql-DmtweJgh.js';
@@ -0,0 +1,304 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ // src/core.ts
6
+ function alphaGenerator(index) {
7
+ let key = "";
8
+ let remaining = index;
9
+ do {
10
+ key = String.fromCharCode(97 + remaining % 26) + key;
11
+ remaining = Math.floor(remaining / 26) - 1;
12
+ } while (remaining >= 0);
13
+ return key;
14
+ }
15
+ function numericGenerator(index) {
16
+ return String(index);
17
+ }
18
+ function alphanumericGenerator(index) {
19
+ const letterIndex = Math.floor(index / 9);
20
+ const numIndex = index % 9 + 1;
21
+ return alphaGenerator(letterIndex) + numIndex;
22
+ }
23
+ function shortGenerator(index) {
24
+ if (index === 0) return "_";
25
+ return alphaGenerator(index - 1);
26
+ }
27
+ function prefixedGenerator(prefix, style = "numeric") {
28
+ return (index) => {
29
+ if (style === "alpha") {
30
+ return prefix + alphaGenerator(index);
31
+ }
32
+ return prefix + index;
33
+ };
34
+ }
35
+ function createKeyGenerator(pattern) {
36
+ if (typeof pattern === "function") {
37
+ return { generator: pattern, name: "custom" };
38
+ }
39
+ if (typeof pattern === "string") {
40
+ switch (pattern) {
41
+ case "alpha":
42
+ return { generator: alphaGenerator, name: "alpha" };
43
+ case "numeric":
44
+ return { generator: numericGenerator, name: "numeric" };
45
+ case "alphanumeric":
46
+ return { generator: alphanumericGenerator, name: "alphanumeric" };
47
+ case "short":
48
+ return { generator: shortGenerator, name: "short" };
49
+ case "prefixed":
50
+ return { generator: prefixedGenerator("k"), name: "prefixed:k" };
51
+ default:
52
+ return { generator: alphaGenerator, name: "alpha" };
53
+ }
54
+ }
55
+ if (typeof pattern === "object" && "prefix" in pattern) {
56
+ return {
57
+ generator: prefixedGenerator(pattern.prefix, pattern.style || "numeric"),
58
+ name: `prefixed:${pattern.prefix}`
59
+ };
60
+ }
61
+ return { generator: alphaGenerator, name: "alpha" };
62
+ }
63
+ function isCompressibleArray(data) {
64
+ if (!Array.isArray(data) || data.length === 0) return false;
65
+ return data.every(
66
+ (item) => typeof item === "object" && item !== null && !Array.isArray(item)
67
+ );
68
+ }
69
+
70
+ // src/graphql.ts
71
+ var DEFAULT_OPTIONS = {
72
+ minArrayLength: 2,
73
+ debug: false,
74
+ minKeyLength: 3,
75
+ maxDepth: 10,
76
+ keyPattern: "alpha",
77
+ nestedHandling: "deep",
78
+ homogeneousOnly: false,
79
+ excludeKeys: [],
80
+ includeKeys: [],
81
+ excludePaths: []
82
+ };
83
+ function findCompressibleArrays(data, basePath = "data", options, currentDepth = 0) {
84
+ const results = [];
85
+ if (currentDepth >= options.maxDepth) return results;
86
+ if (Array.isArray(data)) {
87
+ if (isCompressibleArray(data) && data.length >= options.minArrayLength && !options.excludePaths.includes(basePath)) {
88
+ results.push({ path: basePath, data });
89
+ }
90
+ data.forEach((item, index) => {
91
+ if (typeof item === "object" && item !== null) {
92
+ const nestedResults = findCompressibleArrays(
93
+ item,
94
+ `${basePath}[${index}]`,
95
+ options,
96
+ currentDepth + 1
97
+ );
98
+ results.push(...nestedResults);
99
+ }
100
+ });
101
+ } else if (typeof data === "object" && data !== null) {
102
+ for (const [key, value] of Object.entries(data)) {
103
+ const path = `${basePath}.${key}`;
104
+ const nestedResults = findCompressibleArrays(value, path, options, currentDepth + 1);
105
+ results.push(...nestedResults);
106
+ }
107
+ }
108
+ return results;
109
+ }
110
+ function collectKeysFromArrays(arrays, options) {
111
+ const allKeys = /* @__PURE__ */ new Set();
112
+ const { minKeyLength = 3, excludeKeys = [], includeKeys = [] } = options;
113
+ function collectFromObject(obj, depth = 0) {
114
+ if (depth >= (options.maxDepth ?? 10)) return;
115
+ for (const key of Object.keys(obj)) {
116
+ if (excludeKeys.includes(key)) continue;
117
+ const shouldInclude = includeKeys.includes(key) || key.length >= minKeyLength;
118
+ if (shouldInclude) {
119
+ allKeys.add(key);
120
+ }
121
+ const value = obj[key];
122
+ if (Array.isArray(value)) {
123
+ for (const item of value) {
124
+ if (typeof item === "object" && item !== null && !Array.isArray(item)) {
125
+ collectFromObject(item, depth + 1);
126
+ }
127
+ }
128
+ } else if (typeof value === "object" && value !== null) {
129
+ collectFromObject(value, depth + 1);
130
+ }
131
+ }
132
+ }
133
+ for (const { data } of arrays) {
134
+ for (const item of data) {
135
+ collectFromObject(item);
136
+ }
137
+ }
138
+ return allKeys;
139
+ }
140
+ function compressObjectWithMap(obj, keyToShort, maxDepth, currentDepth = 0) {
141
+ if (currentDepth >= maxDepth) return obj;
142
+ const compressed = {};
143
+ for (const [key, value] of Object.entries(obj)) {
144
+ const shortKey = keyToShort.get(key) ?? key;
145
+ if (Array.isArray(value)) {
146
+ compressed[shortKey] = value.map((item) => {
147
+ if (typeof item === "object" && item !== null && !Array.isArray(item)) {
148
+ return compressObjectWithMap(
149
+ item,
150
+ keyToShort,
151
+ maxDepth,
152
+ currentDepth + 1
153
+ );
154
+ }
155
+ return item;
156
+ });
157
+ } else if (typeof value === "object" && value !== null) {
158
+ compressed[shortKey] = compressObjectWithMap(
159
+ value,
160
+ keyToShort,
161
+ maxDepth,
162
+ currentDepth + 1
163
+ );
164
+ } else {
165
+ compressed[shortKey] = value;
166
+ }
167
+ }
168
+ return compressed;
169
+ }
170
+ function setAtPath(obj, path, value) {
171
+ const parts = path.split(/\.|\[(\d+)\]/).filter(Boolean);
172
+ let current = obj;
173
+ for (let i = 0; i < parts.length - 1; i++) {
174
+ const part = parts[i];
175
+ const isIndex = /^\d+$/.test(part);
176
+ if (isIndex) {
177
+ current = current[parseInt(part, 10)];
178
+ } else {
179
+ current = current[part];
180
+ }
181
+ }
182
+ const lastPart = parts[parts.length - 1];
183
+ const isLastIndex = /^\d+$/.test(lastPart);
184
+ if (isLastIndex) {
185
+ current[parseInt(lastPart, 10)] = value;
186
+ } else {
187
+ current[lastPart] = value;
188
+ }
189
+ }
190
+ function compressGraphQLResponse(response, options = {}) {
191
+ const config = { ...DEFAULT_OPTIONS, ...options };
192
+ if (!response.data) {
193
+ return response;
194
+ }
195
+ const arrays = findCompressibleArrays(response.data, "data", {
196
+ minArrayLength: config.minArrayLength,
197
+ excludePaths: config.excludePaths,
198
+ maxDepth: config.maxDepth
199
+ });
200
+ const filteredArrays = config.shouldCompress ? arrays.filter(({ path, data }) => config.shouldCompress(data, path)) : arrays;
201
+ if (filteredArrays.length === 0) {
202
+ return response;
203
+ }
204
+ const allKeys = collectKeysFromArrays(filteredArrays, config);
205
+ const sortedKeys = Array.from(allKeys).sort();
206
+ const { generator } = createKeyGenerator(config.keyPattern);
207
+ const keyToShort = /* @__PURE__ */ new Map();
208
+ const keyMap = {};
209
+ sortedKeys.forEach((key, index) => {
210
+ const shortKey = generator(index);
211
+ if (shortKey.length < key.length) {
212
+ keyToShort.set(key, shortKey);
213
+ keyMap[shortKey] = key;
214
+ }
215
+ });
216
+ if (Object.keys(keyMap).length === 0) {
217
+ return response;
218
+ }
219
+ const clonedData = JSON.parse(JSON.stringify(response.data));
220
+ const sortedArrays = [...filteredArrays].sort((a, b) => {
221
+ const depthA = (a.path.match(/\./g) || []).length + (a.path.match(/\[/g) || []).length;
222
+ const depthB = (b.path.match(/\./g) || []).length + (b.path.match(/\[/g) || []).length;
223
+ return depthB - depthA;
224
+ });
225
+ const paths = [];
226
+ for (const { path, data } of sortedArrays) {
227
+ const compressedArray = data.map(
228
+ (item) => compressObjectWithMap(item, keyToShort, config.maxDepth)
229
+ );
230
+ setAtPath({ data: clonedData }, path, compressedArray);
231
+ paths.push(path);
232
+ }
233
+ const terseMeta = {
234
+ v: 1,
235
+ k: keyMap,
236
+ paths
237
+ };
238
+ const terseResponse = {
239
+ data: clonedData,
240
+ __terse__: terseMeta
241
+ };
242
+ if ("errors" in response && response.errors) {
243
+ terseResponse.errors = response.errors;
244
+ }
245
+ if ("extensions" in response && response.extensions) {
246
+ terseResponse.extensions = response.extensions;
247
+ }
248
+ if (config.debug) {
249
+ const originalSize = JSON.stringify(response).length;
250
+ const compressedSize = JSON.stringify(terseResponse).length;
251
+ const savings = ((1 - compressedSize / originalSize) * 100).toFixed(1);
252
+ console.log(
253
+ `[tersejson/graphql] Compressed ${originalSize} -> ${compressedSize} bytes (${savings}% savings)`
254
+ );
255
+ console.log(`[tersejson/graphql] Compressed paths: ${paths.join(", ")}`);
256
+ }
257
+ return terseResponse;
258
+ }
259
+ function createTerseFormatFn(options = {}) {
260
+ return function formatResult(result, _context, _info) {
261
+ return compressGraphQLResponse(result, options);
262
+ };
263
+ }
264
+ function terseGraphQL(graphqlMiddleware, options = {}) {
265
+ const config = { ...DEFAULT_OPTIONS, ...options };
266
+ return function terseGraphQLMiddleware(req, res, next) {
267
+ const acceptsTerse = req.headers["accept-terse"] === "true" || req.headers["x-accept-terse"] === "true";
268
+ if (!acceptsTerse) {
269
+ graphqlMiddleware(req, res, next);
270
+ return;
271
+ }
272
+ const originalJson = res.json.bind(res);
273
+ res.json = function terseGraphQLJson(data) {
274
+ if (typeof data === "object" && data !== null && "data" in data) {
275
+ try {
276
+ const compressed = compressGraphQLResponse(
277
+ data,
278
+ config
279
+ );
280
+ if ("__terse__" in compressed) {
281
+ res.setHeader("x-terse-json", "graphql");
282
+ }
283
+ return originalJson(compressed);
284
+ } catch (error) {
285
+ if (config.debug) {
286
+ console.error("[tersejson/graphql] Compression failed:", error);
287
+ }
288
+ return originalJson(data);
289
+ }
290
+ }
291
+ return originalJson(data);
292
+ };
293
+ graphqlMiddleware(req, res, next);
294
+ };
295
+ }
296
+ var graphql_default = terseGraphQL;
297
+
298
+ exports.compressGraphQLResponse = compressGraphQLResponse;
299
+ exports.createTerseFormatFn = createTerseFormatFn;
300
+ exports.default = graphql_default;
301
+ exports.findCompressibleArrays = findCompressibleArrays;
302
+ exports.terseGraphQL = terseGraphQL;
303
+ //# sourceMappingURL=graphql.js.map
304
+ //# sourceMappingURL=graphql.js.map