@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,742 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/plus/index.ts
31
- var plus_exports = {};
32
- __export(plus_exports, {
33
- A1: () => A1,
34
- BatchOperations: () => BatchOperations,
35
- GoogleSheetsCore: () => GoogleSheetsCore,
36
- GoogleSheetsError: () => GoogleSheetsError,
37
- Parsers: () => Parsers,
38
- Serializers: () => Serializers,
39
- SimpleCache: () => SimpleCache,
40
- TypedSheets: () => TypedSheets,
41
- createAuth: () => createAuth,
42
- createOAuth2Client: () => createOAuth2Client,
43
- createServiceAccountAuth: () => createServiceAccountAuth,
44
- generateAuthUrl: () => generateAuthUrl,
45
- getTokenFromCode: () => getTokenFromCode,
46
- saveToken: () => saveToken,
47
- withCache: () => withCache
48
- });
49
- module.exports = __toCommonJS(plus_exports);
50
-
51
- // src/plus/batch.ts
52
- var BatchOperations = class {
53
- constructor(client) {
54
- this.client = client;
55
- // Google Sheets allows up to 100 operations per batch
56
- this.MAX_BATCH_SIZE = 100;
57
- }
58
- /**
59
- * Execute multiple write operations efficiently
60
- * Automatically splits into optimal batch sizes
61
- */
62
- async batchWrite(spreadsheetId, operations) {
63
- const batches = this.chunk(operations, this.MAX_BATCH_SIZE);
64
- const results = [];
65
- for (const batch of batches) {
66
- const result = await this.client.batchWrite(spreadsheetId, batch);
67
- results.push(result);
68
- }
69
- return results;
70
- }
71
- /**
72
- * Execute multiple clear operations efficiently
73
- */
74
- async batchClear(spreadsheetId, ranges) {
75
- const batches = this.chunk(ranges, this.MAX_BATCH_SIZE);
76
- const results = [];
77
- for (const batch of batches) {
78
- const result = await this.client.batchClear(spreadsheetId, batch);
79
- results.push(result);
80
- }
81
- return results;
82
- }
83
- /**
84
- * Execute multiple read operations efficiently
85
- */
86
- async batchRead(spreadsheetId, ranges) {
87
- const batches = this.chunk(ranges, this.MAX_BATCH_SIZE);
88
- const results = [];
89
- for (const batch of batches) {
90
- const batchResult = await this.client.batchRead(spreadsheetId, batch);
91
- results.push(...batchResult);
92
- }
93
- return results;
94
- }
95
- /**
96
- * Execute a mixed batch of operations
97
- */
98
- async executeBatch(spreadsheetId, operations) {
99
- const results = {};
100
- const promises = [];
101
- if (operations.writes) {
102
- promises.push(
103
- this.batchWrite(spreadsheetId, operations.writes).then((r) => {
104
- results.writeResults = r;
105
- })
106
- );
107
- }
108
- if (operations.clears) {
109
- promises.push(
110
- this.batchClear(spreadsheetId, operations.clears).then((r) => {
111
- results.clearResults = r;
112
- })
113
- );
114
- }
115
- if (operations.reads) {
116
- promises.push(
117
- this.batchRead(spreadsheetId, operations.reads).then((r) => {
118
- results.readResults = r;
119
- })
120
- );
121
- }
122
- await Promise.all(promises);
123
- return results;
124
- }
125
- /**
126
- * Helper to chunk arrays into smaller batches
127
- */
128
- chunk(array, size) {
129
- const chunks = [];
130
- for (let i = 0; i < array.length; i += size) {
131
- chunks.push(array.slice(i, i + size));
132
- }
133
- return chunks;
134
- }
135
- };
136
-
137
- // src/plus/cache.ts
138
- var SimpleCache = class {
139
- constructor(config) {
140
- this.cache = /* @__PURE__ */ new Map();
141
- this.config = {
142
- ttlSeconds: config?.ttlSeconds ?? 60,
143
- maxEntries: config?.maxEntries ?? 100
144
- };
145
- }
146
- get(key) {
147
- const entry = this.cache.get(key);
148
- if (!entry) return null;
149
- if (Date.now() > entry.expiry) {
150
- this.cache.delete(key);
151
- return null;
152
- }
153
- return entry.value;
154
- }
155
- set(key, value, ttlOverride) {
156
- if (this.cache.size >= this.config.maxEntries) {
157
- const firstKey = this.cache.keys().next().value;
158
- if (firstKey) {
159
- this.cache.delete(firstKey);
160
- }
161
- }
162
- const ttl = ttlOverride ?? this.config.ttlSeconds;
163
- this.cache.set(key, {
164
- value,
165
- expiry: Date.now() + ttl * 1e3
166
- });
167
- }
168
- invalidate(pattern) {
169
- if (!pattern) {
170
- this.cache.clear();
171
- return;
172
- }
173
- const regex = new RegExp(pattern.replace("*", ".*"));
174
- for (const key of this.cache.keys()) {
175
- if (regex.test(key)) {
176
- this.cache.delete(key);
177
- }
178
- }
179
- }
180
- size() {
181
- return this.cache.size;
182
- }
183
- clear() {
184
- this.cache.clear();
185
- }
186
- };
187
- function withCache(client, config) {
188
- const cache = new SimpleCache(config);
189
- const wrappedClient = Object.create(client);
190
- const originalRead = client.read.bind(client);
191
- wrappedClient.read = async function(spreadsheetId, range) {
192
- const cacheKey = `${spreadsheetId}:${range}`;
193
- const cached = cache.get(cacheKey);
194
- if (cached !== null) {
195
- return cached;
196
- }
197
- const result = await originalRead(spreadsheetId, range);
198
- cache.set(cacheKey, result);
199
- return result;
200
- };
201
- const originalBatchRead = client.batchRead.bind(client);
202
- wrappedClient.batchRead = async function(spreadsheetId, ranges) {
203
- const uncachedRanges = [];
204
- const cachedResults = /* @__PURE__ */ new Map();
205
- for (const range of ranges) {
206
- const cacheKey = `${spreadsheetId}:${range}`;
207
- const cached = cache.get(cacheKey);
208
- if (cached !== null) {
209
- cachedResults.set(range, {
210
- range,
211
- values: cached
212
- });
213
- } else {
214
- uncachedRanges.push(range);
215
- }
216
- }
217
- let freshResults = [];
218
- if (uncachedRanges.length > 0) {
219
- freshResults = await originalBatchRead(spreadsheetId, uncachedRanges);
220
- for (const result of freshResults) {
221
- if (result.range) {
222
- const cacheKey = `${spreadsheetId}:${result.range}`;
223
- cache.set(cacheKey, result.values || []);
224
- }
225
- }
226
- }
227
- const results = [];
228
- for (const range of ranges) {
229
- const cached = cachedResults.get(range);
230
- if (cached) {
231
- results.push(cached);
232
- } else {
233
- const fresh = freshResults.find((r) => r.range === range);
234
- if (fresh) {
235
- results.push(fresh);
236
- }
237
- }
238
- }
239
- return results;
240
- };
241
- const originalWrite = client.write.bind(client);
242
- wrappedClient.write = async function(spreadsheetId, range, values) {
243
- const result = await originalWrite(spreadsheetId, range, values);
244
- cache.invalidate(`${spreadsheetId}:${range}*`);
245
- return result;
246
- };
247
- const originalAppend = client.append.bind(client);
248
- wrappedClient.append = async function(spreadsheetId, range, values) {
249
- const result = await originalAppend(spreadsheetId, range, values);
250
- cache.invalidate(`${spreadsheetId}:*`);
251
- return result;
252
- };
253
- const originalClear = client.clear.bind(client);
254
- wrappedClient.clear = async function(spreadsheetId, range) {
255
- const result = await originalClear(spreadsheetId, range);
256
- cache.invalidate(`${spreadsheetId}:${range}*`);
257
- return result;
258
- };
259
- wrappedClient.cache = cache;
260
- return wrappedClient;
261
- }
262
-
263
- // src/plus/types.ts
264
- var A1 = class _A1 {
265
- /**
266
- * Convert column letter to index (A=0, B=1, etc)
267
- */
268
- static columnToIndex(column) {
269
- let index = 0;
270
- for (let i = 0; i < column.length; i++) {
271
- index = index * 26 + (column.charCodeAt(i) - 64);
272
- }
273
- return index - 1;
274
- }
275
- /**
276
- * Convert index to column letter (0=A, 1=B, etc)
277
- */
278
- static indexToColumn(index) {
279
- let column = "";
280
- index++;
281
- while (index > 0) {
282
- const remainder = (index - 1) % 26;
283
- column = String.fromCharCode(65 + remainder) + column;
284
- index = Math.floor((index - 1) / 26);
285
- }
286
- return column;
287
- }
288
- /**
289
- * Parse A1 notation to components
290
- */
291
- static parse(notation) {
292
- const match = notation.match(
293
- /^(?:(?:'([^']+)'|([^!]+))!)?([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?$/
294
- );
295
- if (!match) {
296
- throw new Error(`Invalid A1 notation: ${notation}`);
297
- }
298
- const [, quotedSheet, unquotedSheet, startCol, startRow, endCol, endRow] = match;
299
- return {
300
- sheet: quotedSheet || unquotedSheet || void 0,
301
- startCol,
302
- startRow: parseInt(startRow, 10),
303
- endCol: endCol || void 0,
304
- endRow: endRow ? parseInt(endRow, 10) : void 0
305
- };
306
- }
307
- /**
308
- * Build A1 notation from components
309
- */
310
- static build(sheet, startCol, startRow, endCol, endRow) {
311
- let sheetPrefix = "";
312
- if (sheet) {
313
- sheetPrefix = /[^a-zA-Z0-9]/.test(sheet) ? `'${sheet}'!` : `${sheet}!`;
314
- }
315
- const start = `${startCol}${startRow}`;
316
- if (endCol && endRow) {
317
- return `${sheetPrefix}${start}:${endCol}${endRow}`;
318
- }
319
- return `${sheetPrefix}${start}`;
320
- }
321
- /**
322
- * Get range dimensions
323
- */
324
- static getDimensions(notation) {
325
- const parsed = _A1.parse(notation);
326
- const rows = parsed.endRow ? parsed.endRow - parsed.startRow + 1 : 1;
327
- const columns = parsed.endCol ? _A1.columnToIndex(parsed.endCol) - _A1.columnToIndex(parsed.startCol) + 1 : 1;
328
- return { rows, columns };
329
- }
330
- /**
331
- * Offset a range by rows and columns
332
- */
333
- static offset(notation, rowOffset, colOffset) {
334
- const parsed = _A1.parse(notation);
335
- const newStartCol = _A1.indexToColumn(
336
- _A1.columnToIndex(parsed.startCol) + colOffset
337
- );
338
- const newStartRow = parsed.startRow + rowOffset;
339
- if (newStartRow < 1) {
340
- throw new Error("Row offset results in invalid range");
341
- }
342
- let newEndCol;
343
- let newEndRow;
344
- if (parsed.endCol && parsed.endRow) {
345
- newEndCol = _A1.indexToColumn(
346
- _A1.columnToIndex(parsed.endCol) + colOffset
347
- );
348
- newEndRow = parsed.endRow + rowOffset;
349
- if (newEndRow < 1) {
350
- throw new Error("Row offset results in invalid range");
351
- }
352
- }
353
- return _A1.build(parsed.sheet, newStartCol, newStartRow, newEndCol, newEndRow);
354
- }
355
- };
356
- var TypedSheets = class {
357
- constructor(client) {
358
- this.client = client;
359
- }
360
- async read(spreadsheetId, range, parser) {
361
- const data = await this.client.read(spreadsheetId, range);
362
- return parser ? parser(data) : data;
363
- }
364
- async write(spreadsheetId, range, data, serializer) {
365
- const values = serializer ? serializer(data) : data;
366
- await this.client.write(spreadsheetId, range, values);
367
- }
368
- async append(spreadsheetId, range, data, serializer) {
369
- const values = serializer ? serializer(data) : data;
370
- await this.client.append(spreadsheetId, range, values);
371
- }
372
- };
373
- var Parsers = {
374
- /**
375
- * Parse rows as objects using first row as headers
376
- */
377
- rowsToObjects(data) {
378
- if (data.length < 2) return [];
379
- const [headers, ...rows] = data;
380
- return rows.map((row) => {
381
- const obj = {};
382
- headers?.forEach((header, i) => {
383
- obj[header] = row[i];
384
- });
385
- return obj;
386
- });
387
- },
388
- /**
389
- * Parse as simple 2D array with type coercion to numbers
390
- */
391
- asNumbers(data) {
392
- return data.map((row) => row.map((cell) => parseFloat(cell) || 0));
393
- },
394
- /**
395
- * Parse as strings, handling empty cells
396
- */
397
- asStrings(data) {
398
- return data.map((row) => row.map((cell) => String(cell || "")));
399
- },
400
- /**
401
- * Parse as key-value pairs from two columns
402
- */
403
- asMap(data) {
404
- const map = /* @__PURE__ */ new Map();
405
- for (const row of data) {
406
- if (row.length >= 2) {
407
- map.set(String(row[0]), row[1]);
408
- }
409
- }
410
- return map;
411
- },
412
- /**
413
- * Parse single column as array
414
- */
415
- column(data, columnIndex = 0) {
416
- return data.map((row) => row[columnIndex]).filter((val) => val !== void 0);
417
- }
418
- };
419
- var Serializers = {
420
- /**
421
- * Convert objects to rows with headers
422
- */
423
- objectsToRows(objects, headers) {
424
- if (objects.length === 0) return [];
425
- const keys = headers || Object.keys(objects[0]);
426
- const headerRow = keys.map(String);
427
- const dataRows = objects.map((obj) => keys.map((key) => obj[key]));
428
- return [headerRow, ...dataRows];
429
- },
430
- /**
431
- * Convert Map to two-column format
432
- */
433
- mapToRows(map) {
434
- const rows = [];
435
- for (const [key, value] of map.entries()) {
436
- rows.push([key, value]);
437
- }
438
- return rows;
439
- },
440
- /**
441
- * Convert array to single column
442
- */
443
- arrayToColumn(array) {
444
- return array.map((item) => [item]);
445
- },
446
- /**
447
- * Transpose rows and columns
448
- */
449
- transpose(data) {
450
- if (data.length === 0) return [];
451
- const maxLength = Math.max(...data.map((row) => row.length));
452
- const result = [];
453
- for (let col = 0; col < maxLength; col++) {
454
- const newRow = [];
455
- for (let row = 0; row < data.length; row++) {
456
- newRow.push(data[row]?.[col] ?? "");
457
- }
458
- result.push(newRow);
459
- }
460
- return result;
461
- }
462
- };
463
-
464
- // src/core/client.ts
465
- var import_googleapis = require("googleapis");
466
-
467
- // src/core/errors.ts
468
- var GoogleSheetsError = class extends Error {
469
- constructor(originalError) {
470
- const message = originalError.response?.data?.error?.message || originalError.message || "Unknown error";
471
- super(message);
472
- this.name = "GoogleSheetsError";
473
- this.code = originalError.response?.status || originalError.code;
474
- this.originalError = originalError;
475
- const retryableCodes = [429, 500, 502, 503, 504, "ECONNRESET", "ETIMEDOUT", "ENOTFOUND"];
476
- this.isRetryable = retryableCodes.includes(this.code);
477
- if (originalError.stack) {
478
- this.stack = originalError.stack;
479
- }
480
- }
481
- /**
482
- * Check if error is a rate limit error
483
- */
484
- isRateLimitError() {
485
- return this.code === 429;
486
- }
487
- /**
488
- * Check if error is a permission error
489
- */
490
- isPermissionError() {
491
- return this.code === 403;
492
- }
493
- /**
494
- * Check if error is a not found error
495
- */
496
- isNotFoundError() {
497
- return this.code === 404;
498
- }
499
- /**
500
- * Get a user-friendly error message
501
- */
502
- getUserMessage() {
503
- if (this.isPermissionError()) {
504
- return "Permission denied. Please ensure the spreadsheet is shared with the service account or you have proper OAuth permissions.";
505
- }
506
- if (this.isRateLimitError()) {
507
- return "Rate limit exceeded. Please wait before making more requests.";
508
- }
509
- if (this.isNotFoundError()) {
510
- return "Spreadsheet or range not found. Please check the ID and range are correct.";
511
- }
512
- return this.message;
513
- }
514
- };
515
-
516
- // src/core/client.ts
517
- var GoogleSheetsCore = class {
518
- constructor(config) {
519
- this.sheets = import_googleapis.google.sheets({
520
- version: "v4",
521
- auth: config.auth
522
- });
523
- this.retryConfig = {
524
- maxAttempts: config.retryConfig?.maxAttempts ?? 3,
525
- maxDelay: config.retryConfig?.maxDelay ?? 1e4,
526
- initialDelay: config.retryConfig?.initialDelay ?? 1e3
527
- };
528
- }
529
- /**
530
- * Read values from a spreadsheet
531
- * @param spreadsheetId The spreadsheet ID
532
- * @param range A1 notation range (e.g., 'Sheet1!A1:B10')
533
- * @returns 2D array of values
534
- */
535
- async read(spreadsheetId, range) {
536
- return this.withRetry(async () => {
537
- const response = await this.sheets.spreadsheets.values.get({
538
- spreadsheetId,
539
- range
540
- });
541
- return response.data.values || [];
542
- });
543
- }
544
- /**
545
- * Write values to a spreadsheet
546
- * @param spreadsheetId The spreadsheet ID
547
- * @param range A1 notation range
548
- * @param values 2D array of values to write
549
- */
550
- async write(spreadsheetId, range, values) {
551
- return this.withRetry(async () => {
552
- const response = await this.sheets.spreadsheets.values.update({
553
- spreadsheetId,
554
- range,
555
- valueInputOption: "USER_ENTERED",
556
- requestBody: { values }
557
- });
558
- return response.data;
559
- });
560
- }
561
- /**
562
- * Append values to a spreadsheet
563
- */
564
- async append(spreadsheetId, range, values) {
565
- return this.withRetry(async () => {
566
- const response = await this.sheets.spreadsheets.values.append({
567
- spreadsheetId,
568
- range,
569
- valueInputOption: "USER_ENTERED",
570
- insertDataOption: "INSERT_ROWS",
571
- requestBody: { values }
572
- });
573
- return response.data;
574
- });
575
- }
576
- /**
577
- * Clear values in a range
578
- */
579
- async clear(spreadsheetId, range) {
580
- return this.withRetry(async () => {
581
- const response = await this.sheets.spreadsheets.values.clear({
582
- spreadsheetId,
583
- range
584
- });
585
- return response.data;
586
- });
587
- }
588
- /**
589
- * Batch read multiple ranges
590
- */
591
- async batchRead(spreadsheetId, ranges) {
592
- return this.withRetry(async () => {
593
- const response = await this.sheets.spreadsheets.values.batchGet({
594
- spreadsheetId,
595
- ranges
596
- });
597
- return response.data.valueRanges || [];
598
- });
599
- }
600
- /**
601
- * Batch update multiple ranges
602
- */
603
- async batchWrite(spreadsheetId, data) {
604
- return this.withRetry(async () => {
605
- const response = await this.sheets.spreadsheets.values.batchUpdate({
606
- spreadsheetId,
607
- requestBody: {
608
- data: data.map((item) => ({
609
- range: item.range,
610
- values: item.values
611
- })),
612
- valueInputOption: "USER_ENTERED"
613
- }
614
- });
615
- return response.data;
616
- });
617
- }
618
- /**
619
- * Batch clear multiple ranges
620
- */
621
- async batchClear(spreadsheetId, ranges) {
622
- return this.withRetry(async () => {
623
- const response = await this.sheets.spreadsheets.values.batchClear({
624
- spreadsheetId,
625
- requestBody: { ranges }
626
- });
627
- return response.data;
628
- });
629
- }
630
- /**
631
- * Get spreadsheet metadata
632
- */
633
- async getSpreadsheet(spreadsheetId) {
634
- return this.withRetry(async () => {
635
- const response = await this.sheets.spreadsheets.get({
636
- spreadsheetId
637
- });
638
- return response.data;
639
- });
640
- }
641
- /**
642
- * Get the underlying Sheets API instance for advanced usage
643
- */
644
- getApi() {
645
- return this.sheets;
646
- }
647
- /**
648
- * Simple exponential backoff retry logic
649
- */
650
- async withRetry(fn) {
651
- let lastError;
652
- for (let attempt = 0; attempt < this.retryConfig.maxAttempts; attempt++) {
653
- try {
654
- return await fn();
655
- } catch (error) {
656
- lastError = error;
657
- if (!this.isRetryable(error) || attempt === this.retryConfig.maxAttempts - 1) {
658
- throw new GoogleSheetsError(error);
659
- }
660
- const baseDelay = Math.min(
661
- this.retryConfig.initialDelay * Math.pow(2, attempt),
662
- this.retryConfig.maxDelay
663
- );
664
- const jitter = Math.random() * 1e3;
665
- const delay = baseDelay + jitter;
666
- await new Promise((resolve) => setTimeout(resolve, delay));
667
- }
668
- }
669
- throw new GoogleSheetsError(lastError);
670
- }
671
- isRetryable(error) {
672
- const retryableCodes = [429, 500, 502, 503, 504];
673
- const retryableErrors = ["ECONNRESET", "ETIMEDOUT", "ENOTFOUND"];
674
- return retryableCodes.includes(error.code) || retryableCodes.includes(error.response?.status) || retryableErrors.includes(error.code);
675
- }
676
- };
677
-
678
- // src/core/auth.ts
679
- var import_google_auth_library = require("google-auth-library");
680
- var fs = __toESM(require("fs/promises"));
681
- async function createServiceAccountAuth(keyFile) {
682
- const key = typeof keyFile === "string" ? JSON.parse(await fs.readFile(keyFile, "utf8")) : keyFile;
683
- const jwt = new import_google_auth_library.JWT({
684
- email: key.client_email,
685
- key: key.private_key,
686
- scopes: ["https://www.googleapis.com/auth/spreadsheets"]
687
- });
688
- return jwt;
689
- }
690
- async function createOAuth2Client(credentials, tokenPath) {
691
- const client = new import_google_auth_library.OAuth2Client(
692
- credentials.client_id,
693
- credentials.client_secret,
694
- credentials.redirect_uris[0]
695
- );
696
- if (tokenPath) {
697
- try {
698
- const token = JSON.parse(await fs.readFile(tokenPath, "utf8"));
699
- client.setCredentials(token);
700
- } catch {
701
- }
702
- }
703
- return client;
704
- }
705
- function generateAuthUrl(client, scopes = ["https://www.googleapis.com/auth/spreadsheets"]) {
706
- return client.generateAuthUrl({
707
- access_type: "offline",
708
- scope: scopes
709
- });
710
- }
711
- async function getTokenFromCode(client, code) {
712
- const { tokens } = await client.getToken(code);
713
- client.setCredentials(tokens);
714
- return tokens;
715
- }
716
- async function saveToken(tokens, path) {
717
- await fs.writeFile(path, JSON.stringify(tokens, null, 2));
718
- }
719
- function createAuth(auth) {
720
- if (auth instanceof import_google_auth_library.GoogleAuth || auth instanceof import_google_auth_library.OAuth2Client || auth instanceof import_google_auth_library.JWT) {
721
- return auth;
722
- }
723
- return createServiceAccountAuth(auth);
724
- }
725
- // Annotate the CommonJS export names for ESM import in node:
726
- 0 && (module.exports = {
727
- A1,
728
- BatchOperations,
729
- GoogleSheetsCore,
730
- GoogleSheetsError,
731
- Parsers,
732
- Serializers,
733
- SimpleCache,
734
- TypedSheets,
735
- createAuth,
736
- createOAuth2Client,
737
- createServiceAccountAuth,
738
- generateAuthUrl,
739
- getTokenFromCode,
740
- saveToken,
741
- withCache
742
- });