@ariadng/sheets 0.1.1 → 0.3.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 (72) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +453 -299
  3. package/bin/sheets.js +3 -0
  4. package/dist/api/index.d.ts +31 -0
  5. package/dist/api/index.d.ts.map +1 -0
  6. package/dist/api/index.js +87 -0
  7. package/dist/api/index.js.map +1 -0
  8. package/dist/auth/constants.d.ts +13 -0
  9. package/dist/auth/constants.d.ts.map +1 -0
  10. package/dist/auth/constants.js +21 -0
  11. package/dist/auth/constants.js.map +1 -0
  12. package/dist/auth/index.d.ts +13 -0
  13. package/dist/auth/index.d.ts.map +1 -0
  14. package/dist/auth/index.js +22 -0
  15. package/dist/auth/index.js.map +1 -0
  16. package/dist/auth/oauth.d.ts +11 -0
  17. package/dist/auth/oauth.d.ts.map +1 -0
  18. package/dist/auth/oauth.js +14 -0
  19. package/dist/auth/oauth.js.map +1 -0
  20. package/dist/auth/service-account.d.ts +18 -0
  21. package/dist/auth/service-account.d.ts.map +1 -0
  22. package/dist/auth/service-account.js +92 -0
  23. package/dist/auth/service-account.js.map +1 -0
  24. package/dist/auth/user-auth.d.ts +24 -0
  25. package/dist/auth/user-auth.d.ts.map +1 -0
  26. package/dist/auth/user-auth.js +230 -0
  27. package/dist/auth/user-auth.js.map +1 -0
  28. package/dist/cli.d.ts +7 -0
  29. package/dist/cli.d.ts.map +1 -0
  30. package/dist/cli.js +412 -0
  31. package/dist/cli.js.map +1 -0
  32. package/dist/http/index.d.ts +19 -0
  33. package/dist/http/index.d.ts.map +1 -0
  34. package/dist/http/index.js +68 -0
  35. package/dist/http/index.js.map +1 -0
  36. package/dist/index.d.ts +11 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +12 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/types/index.d.ts +133 -0
  41. package/dist/types/index.d.ts.map +1 -0
  42. package/dist/types/index.js +16 -0
  43. package/dist/types/index.js.map +1 -0
  44. package/package.json +58 -79
  45. package/dist/advanced/index.d.ts +0 -5
  46. package/dist/advanced/index.d.ts.map +0 -1
  47. package/dist/advanced/index.js +0 -1063
  48. package/dist/advanced/index.mjs +0 -1005
  49. package/dist/advanced/metrics.d.ts +0 -50
  50. package/dist/advanced/metrics.d.ts.map +0 -1
  51. package/dist/advanced/rate-limit.d.ts +0 -27
  52. package/dist/advanced/rate-limit.d.ts.map +0 -1
  53. package/dist/core/auth.d.ts +0 -33
  54. package/dist/core/auth.d.ts.map +0 -1
  55. package/dist/core/client.d.ts +0 -35
  56. package/dist/core/client.d.ts.map +0 -1
  57. package/dist/core/errors.d.ts +0 -11
  58. package/dist/core/errors.d.ts.map +0 -1
  59. package/dist/core/index.d.ts +0 -6
  60. package/dist/core/index.d.ts.map +0 -1
  61. package/dist/core/index.js +0 -315
  62. package/dist/core/index.mjs +0 -271
  63. package/dist/plus/batch.d.ts +0 -25
  64. package/dist/plus/batch.d.ts.map +0 -1
  65. package/dist/plus/cache.d.ts +0 -19
  66. package/dist/plus/cache.d.ts.map +0 -1
  67. package/dist/plus/index.d.ts +0 -7
  68. package/dist/plus/index.d.ts.map +0 -1
  69. package/dist/plus/index.js +0 -742
  70. package/dist/plus/index.mjs +0 -691
  71. package/dist/plus/types.d.ts +0 -39
  72. package/dist/plus/types.d.ts.map +0 -1
@@ -1,1005 +0,0 @@
1
- // src/core/errors.ts
2
- var GoogleSheetsError = class extends Error {
3
- constructor(originalError) {
4
- const message = originalError.response?.data?.error?.message || originalError.message || "Unknown error";
5
- super(message);
6
- this.name = "GoogleSheetsError";
7
- this.code = originalError.response?.status || originalError.code;
8
- this.originalError = originalError;
9
- const retryableCodes = [429, 500, 502, 503, 504, "ECONNRESET", "ETIMEDOUT", "ENOTFOUND"];
10
- this.isRetryable = retryableCodes.includes(this.code);
11
- if (originalError.stack) {
12
- this.stack = originalError.stack;
13
- }
14
- }
15
- /**
16
- * Check if error is a rate limit error
17
- */
18
- isRateLimitError() {
19
- return this.code === 429;
20
- }
21
- /**
22
- * Check if error is a permission error
23
- */
24
- isPermissionError() {
25
- return this.code === 403;
26
- }
27
- /**
28
- * Check if error is a not found error
29
- */
30
- isNotFoundError() {
31
- return this.code === 404;
32
- }
33
- /**
34
- * Get a user-friendly error message
35
- */
36
- getUserMessage() {
37
- if (this.isPermissionError()) {
38
- return "Permission denied. Please ensure the spreadsheet is shared with the service account or you have proper OAuth permissions.";
39
- }
40
- if (this.isRateLimitError()) {
41
- return "Rate limit exceeded. Please wait before making more requests.";
42
- }
43
- if (this.isNotFoundError()) {
44
- return "Spreadsheet or range not found. Please check the ID and range are correct.";
45
- }
46
- return this.message;
47
- }
48
- };
49
-
50
- // src/advanced/rate-limit.ts
51
- var AdaptiveRateLimiter = class {
52
- constructor() {
53
- this.successRate = 1;
54
- this.baseDelay = 0;
55
- this.requestTimes = [];
56
- this.windowMs = 1e5;
57
- // 100 seconds (Google's quota window)
58
- this.maxRequestsPerWindow = 90;
59
- }
60
- // Leave buffer below 100 limit
61
- async execute(fn) {
62
- const now = Date.now();
63
- this.requestTimes = this.requestTimes.filter(
64
- (time) => time > now - this.windowMs
65
- );
66
- if (this.requestTimes.length >= this.maxRequestsPerWindow) {
67
- const oldestRequest = this.requestTimes[0];
68
- if (oldestRequest) {
69
- const waitTime = oldestRequest + this.windowMs - now;
70
- if (waitTime > 0) {
71
- await new Promise((r) => setTimeout(r, waitTime + 100));
72
- }
73
- }
74
- }
75
- if (this.baseDelay > 0) {
76
- await new Promise((r) => setTimeout(r, this.baseDelay));
77
- }
78
- try {
79
- const result = await fn();
80
- this.requestTimes.push(Date.now());
81
- this.successRate = Math.min(1, this.successRate * 1.05);
82
- this.baseDelay = Math.max(0, this.baseDelay - 10);
83
- return result;
84
- } catch (error) {
85
- const isRateLimit = error.code === 429 || error.response?.status === 429 || error instanceof GoogleSheetsError && error.isRateLimitError();
86
- if (isRateLimit) {
87
- this.successRate *= 0.5;
88
- this.baseDelay = Math.min(1e3, this.baseDelay + 200);
89
- }
90
- throw error;
91
- }
92
- }
93
- /**
94
- * Get current rate limiter stats
95
- */
96
- getStats() {
97
- const now = Date.now();
98
- this.requestTimes = this.requestTimes.filter(
99
- (time) => time > now - this.windowMs
100
- );
101
- return {
102
- requestsInWindow: this.requestTimes.length,
103
- successRate: this.successRate,
104
- baseDelay: this.baseDelay
105
- };
106
- }
107
- /**
108
- * Reset rate limiter state
109
- */
110
- reset() {
111
- this.successRate = 1;
112
- this.baseDelay = 0;
113
- this.requestTimes = [];
114
- }
115
- };
116
- function withAdaptiveRateLimit(client) {
117
- const limiter = new AdaptiveRateLimiter();
118
- const wrappedClient = Object.create(client);
119
- const methodsToWrap = [
120
- "read",
121
- "write",
122
- "append",
123
- "clear",
124
- "batchRead",
125
- "batchWrite",
126
- "batchClear",
127
- "getSpreadsheet"
128
- ];
129
- for (const method of methodsToWrap) {
130
- const original = client[method];
131
- if (typeof original === "function") {
132
- wrappedClient[method] = function(...args) {
133
- return limiter.execute(() => original.apply(client, args));
134
- };
135
- }
136
- }
137
- return wrappedClient;
138
- }
139
- var TokenBucketRateLimiter = class {
140
- // tokens per second
141
- constructor(maxTokens = 100, refillRate = 1) {
142
- this.maxTokens = maxTokens;
143
- this.tokens = maxTokens;
144
- this.refillRate = refillRate;
145
- this.lastRefill = Date.now();
146
- }
147
- async acquire(tokens = 1) {
148
- const now = Date.now();
149
- const timePassed = (now - this.lastRefill) / 1e3;
150
- const tokensToAdd = timePassed * this.refillRate;
151
- this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
152
- this.lastRefill = now;
153
- if (this.tokens < tokens) {
154
- const waitTime = (tokens - this.tokens) / this.refillRate * 1e3;
155
- await new Promise((r) => setTimeout(r, waitTime));
156
- return this.acquire(tokens);
157
- }
158
- this.tokens -= tokens;
159
- }
160
- getAvailableTokens() {
161
- const now = Date.now();
162
- const timePassed = (now - this.lastRefill) / 1e3;
163
- const tokensToAdd = timePassed * this.refillRate;
164
- return Math.min(this.maxTokens, this.tokens + tokensToAdd);
165
- }
166
- };
167
- function withTokenBucketRateLimit(client, maxTokens = 100, refillRate = 1) {
168
- const limiter = new TokenBucketRateLimiter(maxTokens, refillRate);
169
- const wrappedClient = Object.create(client);
170
- const methodsToWrap = [
171
- "read",
172
- "write",
173
- "append",
174
- "clear",
175
- "batchRead",
176
- "batchWrite",
177
- "batchClear",
178
- "getSpreadsheet"
179
- ];
180
- for (const method of methodsToWrap) {
181
- const original = client[method];
182
- if (typeof original === "function") {
183
- wrappedClient[method] = async function(...args) {
184
- await limiter.acquire(1);
185
- return original.apply(client, args);
186
- };
187
- }
188
- }
189
- return wrappedClient;
190
- }
191
-
192
- // src/advanced/metrics.ts
193
- var MetricsCollector = class {
194
- constructor() {
195
- this.metrics = {
196
- totalRequests: 0,
197
- successfulRequests: 0,
198
- failedRequests: 0,
199
- retryCount: 0,
200
- averageLatency: 0,
201
- rateLimitHits: 0,
202
- errorsByCode: /* @__PURE__ */ new Map(),
203
- requestsByMethod: /* @__PURE__ */ new Map()
204
- };
205
- this.latencies = [];
206
- this.maxLatencySamples = 100;
207
- this.startTime = Date.now();
208
- }
209
- recordRequest(method, duration, success, retries = 0, error) {
210
- this.metrics.totalRequests++;
211
- const currentCount = this.metrics.requestsByMethod.get(method) || 0;
212
- this.metrics.requestsByMethod.set(method, currentCount + 1);
213
- if (success) {
214
- this.metrics.successfulRequests++;
215
- } else {
216
- this.metrics.failedRequests++;
217
- if (error) {
218
- const code = error.code || error.response?.status || (error instanceof GoogleSheetsError ? error.code : "unknown");
219
- const errorCount = this.metrics.errorsByCode.get(code) || 0;
220
- this.metrics.errorsByCode.set(code, errorCount + 1);
221
- if (code === 429) {
222
- this.metrics.rateLimitHits++;
223
- }
224
- }
225
- }
226
- this.metrics.retryCount += retries;
227
- this.latencies.push(duration);
228
- if (this.latencies.length > this.maxLatencySamples) {
229
- this.latencies.shift();
230
- }
231
- this.metrics.averageLatency = this.latencies.reduce((a, b) => a + b, 0) / this.latencies.length;
232
- }
233
- recordRateLimitHit() {
234
- this.metrics.rateLimitHits++;
235
- }
236
- getMetrics() {
237
- return {
238
- ...this.metrics,
239
- errorsByCode: new Map(this.metrics.errorsByCode),
240
- requestsByMethod: new Map(this.metrics.requestsByMethod)
241
- };
242
- }
243
- getSummary() {
244
- const uptimeSeconds = (Date.now() - this.startTime) / 1e3;
245
- const successRate = this.metrics.totalRequests > 0 ? this.metrics.successfulRequests / this.metrics.totalRequests : 0;
246
- return {
247
- totalRequests: this.metrics.totalRequests,
248
- successRate,
249
- averageLatency: this.metrics.averageLatency,
250
- rateLimitHits: this.metrics.rateLimitHits,
251
- uptimeSeconds,
252
- requestsPerSecond: this.metrics.totalRequests / uptimeSeconds
253
- };
254
- }
255
- reset() {
256
- this.metrics = {
257
- totalRequests: 0,
258
- successfulRequests: 0,
259
- failedRequests: 0,
260
- retryCount: 0,
261
- averageLatency: 0,
262
- rateLimitHits: 0,
263
- errorsByCode: /* @__PURE__ */ new Map(),
264
- requestsByMethod: /* @__PURE__ */ new Map()
265
- };
266
- this.latencies = [];
267
- this.startTime = Date.now();
268
- }
269
- };
270
- function withMetrics(client) {
271
- const metrics = new MetricsCollector();
272
- const wrappedClient = Object.create(client);
273
- const methodsToWrap = [
274
- "read",
275
- "write",
276
- "append",
277
- "clear",
278
- "batchRead",
279
- "batchWrite",
280
- "batchClear",
281
- "getSpreadsheet"
282
- ];
283
- for (const method of methodsToWrap) {
284
- const original = client[method];
285
- if (typeof original === "function") {
286
- wrappedClient[method] = async function(...args) {
287
- const startTime = Date.now();
288
- let retries = 0;
289
- let lastError;
290
- while (retries < 3) {
291
- try {
292
- const result = await original.apply(client, args);
293
- const duration = Date.now() - startTime;
294
- metrics.recordRequest(method, duration, true, retries);
295
- return result;
296
- } catch (error) {
297
- lastError = error;
298
- retries++;
299
- const isRetryable = error instanceof GoogleSheetsError && error.isRetryable;
300
- if (!isRetryable || retries >= 3) {
301
- const duration = Date.now() - startTime;
302
- metrics.recordRequest(method, duration, false, retries - 1, error);
303
- throw error;
304
- }
305
- await new Promise((r) => setTimeout(r, 1e3 * retries));
306
- }
307
- }
308
- throw lastError;
309
- };
310
- }
311
- }
312
- wrappedClient.metrics = metrics;
313
- return wrappedClient;
314
- }
315
- var PerformanceMonitor = class {
316
- constructor() {
317
- this.operations = /* @__PURE__ */ new Map();
318
- }
319
- record(operation, duration) {
320
- const current = this.operations.get(operation) || {
321
- count: 0,
322
- totalDuration: 0,
323
- minDuration: Infinity,
324
- maxDuration: 0
325
- };
326
- current.count++;
327
- current.totalDuration += duration;
328
- current.minDuration = Math.min(current.minDuration, duration);
329
- current.maxDuration = Math.max(current.maxDuration, duration);
330
- this.operations.set(operation, current);
331
- }
332
- getStats(operation) {
333
- const stats = this.operations.get(operation);
334
- if (!stats) return null;
335
- return {
336
- count: stats.count,
337
- average: stats.totalDuration / stats.count,
338
- min: stats.minDuration,
339
- max: stats.maxDuration
340
- };
341
- }
342
- getAllStats() {
343
- const result = /* @__PURE__ */ new Map();
344
- for (const [operation, stats] of this.operations) {
345
- result.set(operation, {
346
- count: stats.count,
347
- average: stats.totalDuration / stats.count,
348
- min: stats.minDuration,
349
- max: stats.maxDuration
350
- });
351
- }
352
- return result;
353
- }
354
- reset() {
355
- this.operations.clear();
356
- }
357
- };
358
-
359
- // src/plus/batch.ts
360
- var BatchOperations = class {
361
- constructor(client) {
362
- this.client = client;
363
- // Google Sheets allows up to 100 operations per batch
364
- this.MAX_BATCH_SIZE = 100;
365
- }
366
- /**
367
- * Execute multiple write operations efficiently
368
- * Automatically splits into optimal batch sizes
369
- */
370
- async batchWrite(spreadsheetId, operations) {
371
- const batches = this.chunk(operations, this.MAX_BATCH_SIZE);
372
- const results = [];
373
- for (const batch of batches) {
374
- const result = await this.client.batchWrite(spreadsheetId, batch);
375
- results.push(result);
376
- }
377
- return results;
378
- }
379
- /**
380
- * Execute multiple clear operations efficiently
381
- */
382
- async batchClear(spreadsheetId, ranges) {
383
- const batches = this.chunk(ranges, this.MAX_BATCH_SIZE);
384
- const results = [];
385
- for (const batch of batches) {
386
- const result = await this.client.batchClear(spreadsheetId, batch);
387
- results.push(result);
388
- }
389
- return results;
390
- }
391
- /**
392
- * Execute multiple read operations efficiently
393
- */
394
- async batchRead(spreadsheetId, ranges) {
395
- const batches = this.chunk(ranges, this.MAX_BATCH_SIZE);
396
- const results = [];
397
- for (const batch of batches) {
398
- const batchResult = await this.client.batchRead(spreadsheetId, batch);
399
- results.push(...batchResult);
400
- }
401
- return results;
402
- }
403
- /**
404
- * Execute a mixed batch of operations
405
- */
406
- async executeBatch(spreadsheetId, operations) {
407
- const results = {};
408
- const promises = [];
409
- if (operations.writes) {
410
- promises.push(
411
- this.batchWrite(spreadsheetId, operations.writes).then((r) => {
412
- results.writeResults = r;
413
- })
414
- );
415
- }
416
- if (operations.clears) {
417
- promises.push(
418
- this.batchClear(spreadsheetId, operations.clears).then((r) => {
419
- results.clearResults = r;
420
- })
421
- );
422
- }
423
- if (operations.reads) {
424
- promises.push(
425
- this.batchRead(spreadsheetId, operations.reads).then((r) => {
426
- results.readResults = r;
427
- })
428
- );
429
- }
430
- await Promise.all(promises);
431
- return results;
432
- }
433
- /**
434
- * Helper to chunk arrays into smaller batches
435
- */
436
- chunk(array, size) {
437
- const chunks = [];
438
- for (let i = 0; i < array.length; i += size) {
439
- chunks.push(array.slice(i, i + size));
440
- }
441
- return chunks;
442
- }
443
- };
444
-
445
- // src/plus/cache.ts
446
- var SimpleCache = class {
447
- constructor(config) {
448
- this.cache = /* @__PURE__ */ new Map();
449
- this.config = {
450
- ttlSeconds: config?.ttlSeconds ?? 60,
451
- maxEntries: config?.maxEntries ?? 100
452
- };
453
- }
454
- get(key) {
455
- const entry = this.cache.get(key);
456
- if (!entry) return null;
457
- if (Date.now() > entry.expiry) {
458
- this.cache.delete(key);
459
- return null;
460
- }
461
- return entry.value;
462
- }
463
- set(key, value, ttlOverride) {
464
- if (this.cache.size >= this.config.maxEntries) {
465
- const firstKey = this.cache.keys().next().value;
466
- if (firstKey) {
467
- this.cache.delete(firstKey);
468
- }
469
- }
470
- const ttl = ttlOverride ?? this.config.ttlSeconds;
471
- this.cache.set(key, {
472
- value,
473
- expiry: Date.now() + ttl * 1e3
474
- });
475
- }
476
- invalidate(pattern) {
477
- if (!pattern) {
478
- this.cache.clear();
479
- return;
480
- }
481
- const regex = new RegExp(pattern.replace("*", ".*"));
482
- for (const key of this.cache.keys()) {
483
- if (regex.test(key)) {
484
- this.cache.delete(key);
485
- }
486
- }
487
- }
488
- size() {
489
- return this.cache.size;
490
- }
491
- clear() {
492
- this.cache.clear();
493
- }
494
- };
495
- function withCache(client, config) {
496
- const cache = new SimpleCache(config);
497
- const wrappedClient = Object.create(client);
498
- const originalRead = client.read.bind(client);
499
- wrappedClient.read = async function(spreadsheetId, range) {
500
- const cacheKey = `${spreadsheetId}:${range}`;
501
- const cached = cache.get(cacheKey);
502
- if (cached !== null) {
503
- return cached;
504
- }
505
- const result = await originalRead(spreadsheetId, range);
506
- cache.set(cacheKey, result);
507
- return result;
508
- };
509
- const originalBatchRead = client.batchRead.bind(client);
510
- wrappedClient.batchRead = async function(spreadsheetId, ranges) {
511
- const uncachedRanges = [];
512
- const cachedResults = /* @__PURE__ */ new Map();
513
- for (const range of ranges) {
514
- const cacheKey = `${spreadsheetId}:${range}`;
515
- const cached = cache.get(cacheKey);
516
- if (cached !== null) {
517
- cachedResults.set(range, {
518
- range,
519
- values: cached
520
- });
521
- } else {
522
- uncachedRanges.push(range);
523
- }
524
- }
525
- let freshResults = [];
526
- if (uncachedRanges.length > 0) {
527
- freshResults = await originalBatchRead(spreadsheetId, uncachedRanges);
528
- for (const result of freshResults) {
529
- if (result.range) {
530
- const cacheKey = `${spreadsheetId}:${result.range}`;
531
- cache.set(cacheKey, result.values || []);
532
- }
533
- }
534
- }
535
- const results = [];
536
- for (const range of ranges) {
537
- const cached = cachedResults.get(range);
538
- if (cached) {
539
- results.push(cached);
540
- } else {
541
- const fresh = freshResults.find((r) => r.range === range);
542
- if (fresh) {
543
- results.push(fresh);
544
- }
545
- }
546
- }
547
- return results;
548
- };
549
- const originalWrite = client.write.bind(client);
550
- wrappedClient.write = async function(spreadsheetId, range, values) {
551
- const result = await originalWrite(spreadsheetId, range, values);
552
- cache.invalidate(`${spreadsheetId}:${range}*`);
553
- return result;
554
- };
555
- const originalAppend = client.append.bind(client);
556
- wrappedClient.append = async function(spreadsheetId, range, values) {
557
- const result = await originalAppend(spreadsheetId, range, values);
558
- cache.invalidate(`${spreadsheetId}:*`);
559
- return result;
560
- };
561
- const originalClear = client.clear.bind(client);
562
- wrappedClient.clear = async function(spreadsheetId, range) {
563
- const result = await originalClear(spreadsheetId, range);
564
- cache.invalidate(`${spreadsheetId}:${range}*`);
565
- return result;
566
- };
567
- wrappedClient.cache = cache;
568
- return wrappedClient;
569
- }
570
-
571
- // src/plus/types.ts
572
- var A1 = class _A1 {
573
- /**
574
- * Convert column letter to index (A=0, B=1, etc)
575
- */
576
- static columnToIndex(column) {
577
- let index = 0;
578
- for (let i = 0; i < column.length; i++) {
579
- index = index * 26 + (column.charCodeAt(i) - 64);
580
- }
581
- return index - 1;
582
- }
583
- /**
584
- * Convert index to column letter (0=A, 1=B, etc)
585
- */
586
- static indexToColumn(index) {
587
- let column = "";
588
- index++;
589
- while (index > 0) {
590
- const remainder = (index - 1) % 26;
591
- column = String.fromCharCode(65 + remainder) + column;
592
- index = Math.floor((index - 1) / 26);
593
- }
594
- return column;
595
- }
596
- /**
597
- * Parse A1 notation to components
598
- */
599
- static parse(notation) {
600
- const match = notation.match(
601
- /^(?:(?:'([^']+)'|([^!]+))!)?([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?$/
602
- );
603
- if (!match) {
604
- throw new Error(`Invalid A1 notation: ${notation}`);
605
- }
606
- const [, quotedSheet, unquotedSheet, startCol, startRow, endCol, endRow] = match;
607
- return {
608
- sheet: quotedSheet || unquotedSheet || void 0,
609
- startCol,
610
- startRow: parseInt(startRow, 10),
611
- endCol: endCol || void 0,
612
- endRow: endRow ? parseInt(endRow, 10) : void 0
613
- };
614
- }
615
- /**
616
- * Build A1 notation from components
617
- */
618
- static build(sheet, startCol, startRow, endCol, endRow) {
619
- let sheetPrefix = "";
620
- if (sheet) {
621
- sheetPrefix = /[^a-zA-Z0-9]/.test(sheet) ? `'${sheet}'!` : `${sheet}!`;
622
- }
623
- const start = `${startCol}${startRow}`;
624
- if (endCol && endRow) {
625
- return `${sheetPrefix}${start}:${endCol}${endRow}`;
626
- }
627
- return `${sheetPrefix}${start}`;
628
- }
629
- /**
630
- * Get range dimensions
631
- */
632
- static getDimensions(notation) {
633
- const parsed = _A1.parse(notation);
634
- const rows = parsed.endRow ? parsed.endRow - parsed.startRow + 1 : 1;
635
- const columns = parsed.endCol ? _A1.columnToIndex(parsed.endCol) - _A1.columnToIndex(parsed.startCol) + 1 : 1;
636
- return { rows, columns };
637
- }
638
- /**
639
- * Offset a range by rows and columns
640
- */
641
- static offset(notation, rowOffset, colOffset) {
642
- const parsed = _A1.parse(notation);
643
- const newStartCol = _A1.indexToColumn(
644
- _A1.columnToIndex(parsed.startCol) + colOffset
645
- );
646
- const newStartRow = parsed.startRow + rowOffset;
647
- if (newStartRow < 1) {
648
- throw new Error("Row offset results in invalid range");
649
- }
650
- let newEndCol;
651
- let newEndRow;
652
- if (parsed.endCol && parsed.endRow) {
653
- newEndCol = _A1.indexToColumn(
654
- _A1.columnToIndex(parsed.endCol) + colOffset
655
- );
656
- newEndRow = parsed.endRow + rowOffset;
657
- if (newEndRow < 1) {
658
- throw new Error("Row offset results in invalid range");
659
- }
660
- }
661
- return _A1.build(parsed.sheet, newStartCol, newStartRow, newEndCol, newEndRow);
662
- }
663
- };
664
- var TypedSheets = class {
665
- constructor(client) {
666
- this.client = client;
667
- }
668
- async read(spreadsheetId, range, parser) {
669
- const data = await this.client.read(spreadsheetId, range);
670
- return parser ? parser(data) : data;
671
- }
672
- async write(spreadsheetId, range, data, serializer) {
673
- const values = serializer ? serializer(data) : data;
674
- await this.client.write(spreadsheetId, range, values);
675
- }
676
- async append(spreadsheetId, range, data, serializer) {
677
- const values = serializer ? serializer(data) : data;
678
- await this.client.append(spreadsheetId, range, values);
679
- }
680
- };
681
- var Parsers = {
682
- /**
683
- * Parse rows as objects using first row as headers
684
- */
685
- rowsToObjects(data) {
686
- if (data.length < 2) return [];
687
- const [headers, ...rows] = data;
688
- return rows.map((row) => {
689
- const obj = {};
690
- headers?.forEach((header, i) => {
691
- obj[header] = row[i];
692
- });
693
- return obj;
694
- });
695
- },
696
- /**
697
- * Parse as simple 2D array with type coercion to numbers
698
- */
699
- asNumbers(data) {
700
- return data.map((row) => row.map((cell) => parseFloat(cell) || 0));
701
- },
702
- /**
703
- * Parse as strings, handling empty cells
704
- */
705
- asStrings(data) {
706
- return data.map((row) => row.map((cell) => String(cell || "")));
707
- },
708
- /**
709
- * Parse as key-value pairs from two columns
710
- */
711
- asMap(data) {
712
- const map = /* @__PURE__ */ new Map();
713
- for (const row of data) {
714
- if (row.length >= 2) {
715
- map.set(String(row[0]), row[1]);
716
- }
717
- }
718
- return map;
719
- },
720
- /**
721
- * Parse single column as array
722
- */
723
- column(data, columnIndex = 0) {
724
- return data.map((row) => row[columnIndex]).filter((val) => val !== void 0);
725
- }
726
- };
727
- var Serializers = {
728
- /**
729
- * Convert objects to rows with headers
730
- */
731
- objectsToRows(objects, headers) {
732
- if (objects.length === 0) return [];
733
- const keys = headers || Object.keys(objects[0]);
734
- const headerRow = keys.map(String);
735
- const dataRows = objects.map((obj) => keys.map((key) => obj[key]));
736
- return [headerRow, ...dataRows];
737
- },
738
- /**
739
- * Convert Map to two-column format
740
- */
741
- mapToRows(map) {
742
- const rows = [];
743
- for (const [key, value] of map.entries()) {
744
- rows.push([key, value]);
745
- }
746
- return rows;
747
- },
748
- /**
749
- * Convert array to single column
750
- */
751
- arrayToColumn(array) {
752
- return array.map((item) => [item]);
753
- },
754
- /**
755
- * Transpose rows and columns
756
- */
757
- transpose(data) {
758
- if (data.length === 0) return [];
759
- const maxLength = Math.max(...data.map((row) => row.length));
760
- const result = [];
761
- for (let col = 0; col < maxLength; col++) {
762
- const newRow = [];
763
- for (let row = 0; row < data.length; row++) {
764
- newRow.push(data[row]?.[col] ?? "");
765
- }
766
- result.push(newRow);
767
- }
768
- return result;
769
- }
770
- };
771
-
772
- // src/core/client.ts
773
- import { google } from "googleapis";
774
- var GoogleSheetsCore = class {
775
- constructor(config) {
776
- this.sheets = google.sheets({
777
- version: "v4",
778
- auth: config.auth
779
- });
780
- this.retryConfig = {
781
- maxAttempts: config.retryConfig?.maxAttempts ?? 3,
782
- maxDelay: config.retryConfig?.maxDelay ?? 1e4,
783
- initialDelay: config.retryConfig?.initialDelay ?? 1e3
784
- };
785
- }
786
- /**
787
- * Read values from a spreadsheet
788
- * @param spreadsheetId The spreadsheet ID
789
- * @param range A1 notation range (e.g., 'Sheet1!A1:B10')
790
- * @returns 2D array of values
791
- */
792
- async read(spreadsheetId, range) {
793
- return this.withRetry(async () => {
794
- const response = await this.sheets.spreadsheets.values.get({
795
- spreadsheetId,
796
- range
797
- });
798
- return response.data.values || [];
799
- });
800
- }
801
- /**
802
- * Write values to a spreadsheet
803
- * @param spreadsheetId The spreadsheet ID
804
- * @param range A1 notation range
805
- * @param values 2D array of values to write
806
- */
807
- async write(spreadsheetId, range, values) {
808
- return this.withRetry(async () => {
809
- const response = await this.sheets.spreadsheets.values.update({
810
- spreadsheetId,
811
- range,
812
- valueInputOption: "USER_ENTERED",
813
- requestBody: { values }
814
- });
815
- return response.data;
816
- });
817
- }
818
- /**
819
- * Append values to a spreadsheet
820
- */
821
- async append(spreadsheetId, range, values) {
822
- return this.withRetry(async () => {
823
- const response = await this.sheets.spreadsheets.values.append({
824
- spreadsheetId,
825
- range,
826
- valueInputOption: "USER_ENTERED",
827
- insertDataOption: "INSERT_ROWS",
828
- requestBody: { values }
829
- });
830
- return response.data;
831
- });
832
- }
833
- /**
834
- * Clear values in a range
835
- */
836
- async clear(spreadsheetId, range) {
837
- return this.withRetry(async () => {
838
- const response = await this.sheets.spreadsheets.values.clear({
839
- spreadsheetId,
840
- range
841
- });
842
- return response.data;
843
- });
844
- }
845
- /**
846
- * Batch read multiple ranges
847
- */
848
- async batchRead(spreadsheetId, ranges) {
849
- return this.withRetry(async () => {
850
- const response = await this.sheets.spreadsheets.values.batchGet({
851
- spreadsheetId,
852
- ranges
853
- });
854
- return response.data.valueRanges || [];
855
- });
856
- }
857
- /**
858
- * Batch update multiple ranges
859
- */
860
- async batchWrite(spreadsheetId, data) {
861
- return this.withRetry(async () => {
862
- const response = await this.sheets.spreadsheets.values.batchUpdate({
863
- spreadsheetId,
864
- requestBody: {
865
- data: data.map((item) => ({
866
- range: item.range,
867
- values: item.values
868
- })),
869
- valueInputOption: "USER_ENTERED"
870
- }
871
- });
872
- return response.data;
873
- });
874
- }
875
- /**
876
- * Batch clear multiple ranges
877
- */
878
- async batchClear(spreadsheetId, ranges) {
879
- return this.withRetry(async () => {
880
- const response = await this.sheets.spreadsheets.values.batchClear({
881
- spreadsheetId,
882
- requestBody: { ranges }
883
- });
884
- return response.data;
885
- });
886
- }
887
- /**
888
- * Get spreadsheet metadata
889
- */
890
- async getSpreadsheet(spreadsheetId) {
891
- return this.withRetry(async () => {
892
- const response = await this.sheets.spreadsheets.get({
893
- spreadsheetId
894
- });
895
- return response.data;
896
- });
897
- }
898
- /**
899
- * Get the underlying Sheets API instance for advanced usage
900
- */
901
- getApi() {
902
- return this.sheets;
903
- }
904
- /**
905
- * Simple exponential backoff retry logic
906
- */
907
- async withRetry(fn) {
908
- let lastError;
909
- for (let attempt = 0; attempt < this.retryConfig.maxAttempts; attempt++) {
910
- try {
911
- return await fn();
912
- } catch (error) {
913
- lastError = error;
914
- if (!this.isRetryable(error) || attempt === this.retryConfig.maxAttempts - 1) {
915
- throw new GoogleSheetsError(error);
916
- }
917
- const baseDelay = Math.min(
918
- this.retryConfig.initialDelay * Math.pow(2, attempt),
919
- this.retryConfig.maxDelay
920
- );
921
- const jitter = Math.random() * 1e3;
922
- const delay = baseDelay + jitter;
923
- await new Promise((resolve) => setTimeout(resolve, delay));
924
- }
925
- }
926
- throw new GoogleSheetsError(lastError);
927
- }
928
- isRetryable(error) {
929
- const retryableCodes = [429, 500, 502, 503, 504];
930
- const retryableErrors = ["ECONNRESET", "ETIMEDOUT", "ENOTFOUND"];
931
- return retryableCodes.includes(error.code) || retryableCodes.includes(error.response?.status) || retryableErrors.includes(error.code);
932
- }
933
- };
934
-
935
- // src/core/auth.ts
936
- import { GoogleAuth, OAuth2Client, JWT } from "google-auth-library";
937
- import * as fs from "fs/promises";
938
- async function createServiceAccountAuth(keyFile) {
939
- const key = typeof keyFile === "string" ? JSON.parse(await fs.readFile(keyFile, "utf8")) : keyFile;
940
- const jwt = new JWT({
941
- email: key.client_email,
942
- key: key.private_key,
943
- scopes: ["https://www.googleapis.com/auth/spreadsheets"]
944
- });
945
- return jwt;
946
- }
947
- async function createOAuth2Client(credentials, tokenPath) {
948
- const client = new OAuth2Client(
949
- credentials.client_id,
950
- credentials.client_secret,
951
- credentials.redirect_uris[0]
952
- );
953
- if (tokenPath) {
954
- try {
955
- const token = JSON.parse(await fs.readFile(tokenPath, "utf8"));
956
- client.setCredentials(token);
957
- } catch {
958
- }
959
- }
960
- return client;
961
- }
962
- function generateAuthUrl(client, scopes = ["https://www.googleapis.com/auth/spreadsheets"]) {
963
- return client.generateAuthUrl({
964
- access_type: "offline",
965
- scope: scopes
966
- });
967
- }
968
- async function getTokenFromCode(client, code) {
969
- const { tokens } = await client.getToken(code);
970
- client.setCredentials(tokens);
971
- return tokens;
972
- }
973
- async function saveToken(tokens, path) {
974
- await fs.writeFile(path, JSON.stringify(tokens, null, 2));
975
- }
976
- function createAuth(auth) {
977
- if (auth instanceof GoogleAuth || auth instanceof OAuth2Client || auth instanceof JWT) {
978
- return auth;
979
- }
980
- return createServiceAccountAuth(auth);
981
- }
982
- export {
983
- A1,
984
- AdaptiveRateLimiter,
985
- BatchOperations,
986
- GoogleSheetsCore,
987
- GoogleSheetsError,
988
- MetricsCollector,
989
- Parsers,
990
- PerformanceMonitor,
991
- Serializers,
992
- SimpleCache,
993
- TokenBucketRateLimiter,
994
- TypedSheets,
995
- createAuth,
996
- createOAuth2Client,
997
- createServiceAccountAuth,
998
- generateAuthUrl,
999
- getTokenFromCode,
1000
- saveToken,
1001
- withAdaptiveRateLimit,
1002
- withCache,
1003
- withMetrics,
1004
- withTokenBucketRateLimit
1005
- };