@cyc-seattle/gsuite-sdk 0.3.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @cyc-seattle/gsuite-sdk
2
2
 
3
- Typed wrappers around Google Workspace APIs: Calendar, Sheets, the Admin SDK Directory, and Group Settings.
3
+ Typed wrappers around Google Workspace APIs: the Admin SDK Directory and Group Settings.
4
4
 
5
5
  ```sh
6
6
  pnpm add @cyc-seattle/gsuite-sdk
@@ -8,36 +8,11 @@ pnpm add @cyc-seattle/gsuite-sdk
8
8
 
9
9
  Every client takes a `GoogleAuth` instance from `googleapis`. It uses Application Default Credentials (ADC) unless you pass a key. Set `scopes` for the APIs you call.
10
10
 
11
- ## Spreadsheets
12
-
13
- ```ts
14
- import { SpreadsheetClient, type Row } from "@cyc-seattle/gsuite-sdk";
15
- import { google } from "googleapis";
16
-
17
- interface Camp extends Row {
18
- name: string;
19
- start: string;
20
- }
21
-
22
- const auth = new google.auth.GoogleAuth({ scopes: ["https://www.googleapis.com/auth/spreadsheets"] });
23
- const spreadsheet = await new SpreadsheetClient(auth).loadSpreadsheet("<spreadsheet URL or ID>");
24
- const worksheet = await spreadsheet.getOrCreateWorksheet<Camp>("Camps", ["name", "start"]);
25
- const table = await worksheet.getTable();
26
- ```
27
-
28
- ## Calendar
29
-
30
- ```ts
31
- import { CalendarClient } from "@cyc-seattle/gsuite-sdk";
32
-
33
- const calendar = new CalendarClient(auth).loadCalendar("<calendar ID>");
34
- const events = await calendar.listEvents();
35
- ```
36
-
37
11
  ## Directory and Group Settings
38
12
 
39
13
  ```ts
40
14
  import { DirectoryClient, GroupSettingsClient } from "@cyc-seattle/gsuite-sdk";
15
+ import { google } from "googleapis";
41
16
 
42
17
  const auth = new google.auth.GoogleAuth({
43
18
  scopes: [
@@ -49,6 +24,8 @@ const members = await new DirectoryClient(auth).listMembers("team@example.org");
49
24
  const settings = await new GroupSettingsClient(auth).getSettings("team@example.org");
50
25
  ```
51
26
 
27
+ `addMember` and `removeMember` are idempotent: adding someone already in a group answers `"already-member"`, raising their role if it's lower, and taking out someone who isn't there answers `"not-member"`. Taking someone out of a group that doesn't exist throws.
28
+
52
29
  ### Client options
53
30
 
54
31
  `DirectoryClient` and `GroupSettingsClient` take an optional second argument:
@@ -134,4 +111,4 @@ docker run -p 8080:8080 -e NEW_GROUP_DELAY_MS=0 ghcr.io/cyc-seattle/workspace-fa
134
111
 
135
112
  ## Release
136
113
 
137
- Every merge to `main` releases from the PR title. The title must be a conventional commit. `fix:` makes a patch release, `feat:` a minor release, and a `!` after the type a major release. Types such as `docs:`, `build:`, and `test:` release nothing. semantic-release publishes to npm and creates the GitHub release.
114
+ Every merge to `main` releases from the PR title, once CI passes. The title must be a conventional commit. `fix:` makes a patch release, `feat:` a minor release, and a `!` after the type a major release. Types such as `docs:`, `build:`, and `test:` release nothing. semantic-release publishes to npm and creates the GitHub release.
package/dist/common.d.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  /**
2
2
  * Extracts the HTTP status code from an error thrown by a Google API client.
3
3
  *
4
- * The two client libraries in use report the status differently:
5
- * - `google-spreadsheet` uses axios, which exposes it as `error.response.status`.
6
- * - `googleapis` uses gaxios, which additionally sets a numeric `error.code`
7
- * (and `error.status` on newer versions).
4
+ * Clients report the status differently: axios exposes it as `error.response.status`, and
5
+ * `googleapis`' gaxios also sets a numeric `error.code` (and `error.status` on newer versions).
8
6
  *
9
7
  * Returns `undefined` when no HTTP status can be determined (e.g. a plain
10
8
  * programming error or a network failure without a response).
package/dist/common.js CHANGED
@@ -1,17 +1,13 @@
1
1
  import winston from "winston";
2
2
  import { backOff } from "exponential-backoff";
3
- // The default quota on Google Spreadsheet API is 60 requests/minute/user.
4
- // However, there's a separate read and write quota, so we can safely double
5
- // this to get a little bit more throughput.
3
+ // The default pace: two requests a second, well under the Directory and Groups Settings quotas.
6
4
  const requestPerMinute = 60 * 2;
7
5
  const millisPerRequest = (60 * 1000) / requestPerMinute;
8
6
  /**
9
7
  * Extracts the HTTP status code from an error thrown by a Google API client.
10
8
  *
11
- * The two client libraries in use report the status differently:
12
- * - `google-spreadsheet` uses axios, which exposes it as `error.response.status`.
13
- * - `googleapis` uses gaxios, which additionally sets a numeric `error.code`
14
- * (and `error.status` on newer versions).
9
+ * Clients report the status differently: axios exposes it as `error.response.status`, and
10
+ * `googleapis`' gaxios also sets a numeric `error.code` (and `error.status` on newer versions).
15
11
  *
16
12
  * Returns `undefined` when no HTTP status can be determined (e.g. a plain
17
13
  * programming error or a network failure without a response).
@@ -24,11 +24,12 @@ export interface GroupMember {
24
24
  type?: GroupMemberType;
25
25
  }
26
26
  /**
27
- * Result of adding a member to a group. The sync that drives this client is
28
- * add-only and idempotent, so a member who's already there is an expected
29
- * outcome, not a failure — Google reports it as an HTTP 409.
27
+ * Result of adding a member to a group. Adding is idempotent, so a member who's
28
+ * already there is an expected outcome, not a failure — Google reports it as an HTTP 409.
30
29
  */
31
30
  export type AddMemberResult = "added" | "already-member";
31
+ /** Result of taking a member out of a group. Someone who isn't there (HTTP 404) is already out. */
32
+ export type RemoveMemberResult = "removed" | "not-member";
32
33
  /**
33
34
  * Admin SDK Directory API client for groups and their members.
34
35
  *
@@ -67,6 +68,11 @@ export declare class DirectoryClient {
67
68
  * than planned is left alone.
68
69
  */
69
70
  addMember(groupKey: string, email: string, role: GroupRole): Promise<AddMemberResult>;
71
+ /**
72
+ * Takes a member out of a group. Returns "not-member" instead of throwing when they aren't in it
73
+ * (HTTP 404), since the caller wants them out either way. A missing group throws.
74
+ */
75
+ removeMember(groupKey: string, email: string): Promise<RemoveMemberResult>;
70
76
  /** The 409 path of `addMember`: promotes an existing member up to `role` if they're currently
71
77
  * below it, and does nothing otherwise - including when they already outrank it. */
72
78
  private promoteIfBelow;
package/dist/directory.js CHANGED
@@ -15,8 +15,8 @@ export class DirectoryClient {
15
15
  constructor(auth, options = {}) {
16
16
  this.pacing = options.pacing ?? {};
17
17
  // The `directory_v1` cast is needed because `google.admin` also has overloads for
18
- // two other API versions, which the `auth` cast below (needed for its own reasons —
19
- // see CalendarClient) leaves TypeScript unable to discriminate between.
18
+ // two other API versions, which the `auth` cast below leaves TypeScript unable to discriminate
19
+ // between.
20
20
  this.client = google.admin({
21
21
  version: "directory_v1",
22
22
  auth,
@@ -140,6 +140,27 @@ export class DirectoryClient {
140
140
  throw error;
141
141
  }
142
142
  }
143
+ /**
144
+ * Takes a member out of a group. Returns "not-member" instead of throwing when they aren't in it
145
+ * (HTTP 404), since the caller wants them out either way. A missing group throws.
146
+ */
147
+ async removeMember(groupKey, email) {
148
+ winston.debug("Removing group member", { groupKey, email });
149
+ try {
150
+ await safeCall(async () => {
151
+ await this.client.members.delete({ groupKey, memberKey: email });
152
+ }, this.pacing);
153
+ winston.info("Removed group member", { groupKey, email });
154
+ return "removed";
155
+ }
156
+ catch (error) {
157
+ if (getHttpStatus(error) === 404 && (await this.getGroup(groupKey)) !== null) {
158
+ winston.debug("Member not in group", { groupKey, email });
159
+ return "not-member";
160
+ }
161
+ throw error;
162
+ }
163
+ }
143
164
  /** The 409 path of `addMember`: promotes an existing member up to `role` if they're currently
144
165
  * below it, and does nothing otherwise - including when they already outrank it. */
145
166
  async promoteIfBelow(groupKey, email, role) {
@@ -77,6 +77,7 @@ export declare class WorkspaceModel {
77
77
  updateMember(groupKey: string, memberKey: string, body: {
78
78
  role?: string | null;
79
79
  }): FakeMember;
80
+ deleteMember(groupKey: string, memberKey: string): void;
80
81
  getSettings(groupUniqueId: string): GroupSettings;
81
82
  patchSettings(groupUniqueId: string, patch: GroupSettings): GroupSettings;
82
83
  private requireGroup;
@@ -174,6 +174,14 @@ export class WorkspaceModel {
174
174
  }
175
175
  return this.toMember(member);
176
176
  }
177
+ deleteMember(groupKey, memberKey) {
178
+ const group = this.requireGroup(groupKey);
179
+ const member = this.requireMember(group, memberKey);
180
+ for (const [key, stored] of group.members) {
181
+ if (stored === member)
182
+ group.members.delete(key);
183
+ }
184
+ }
177
185
  getSettings(groupUniqueId) {
178
186
  return this.toSettings(this.requireSettingsGroup(groupUniqueId));
179
187
  }
@@ -47,6 +47,11 @@ const ROUTES = [
47
47
  path: new RegExp(`^/admin/directory/v1/groups/${SEGMENT}/members/${SEGMENT}$`),
48
48
  handle: (model, [groupKey, memberKey], _, body) => model.updateMember(groupKey, memberKey, asObject(body)),
49
49
  },
50
+ {
51
+ method: "DELETE",
52
+ path: new RegExp(`^/admin/directory/v1/groups/${SEGMENT}/members/${SEGMENT}$`),
53
+ handle: (model, [groupKey, memberKey]) => model.deleteMember(groupKey, memberKey),
54
+ },
50
55
  {
51
56
  method: "GET",
52
57
  path: new RegExp(`^/groups/v1/groups/${SEGMENT}$`),
@@ -116,7 +121,11 @@ async function handle(model, request, response) {
116
121
  }
117
122
  try {
118
123
  const result = route.handle(model, match, url, body);
119
- if (url.pathname.startsWith("/groups/v1/") && url.searchParams.get("alt") !== "json") {
124
+ if (result === undefined) {
125
+ // A delete answers with no body, as Google's does.
126
+ response.writeHead(204).end();
127
+ }
128
+ else if (url.pathname.startsWith("/groups/v1/") && url.searchParams.get("alt") !== "json") {
120
129
  sendAtom(response, result);
121
130
  }
122
131
  else {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,3 @@
1
1
  export * from "./common.js";
2
- export * from "./calendar.js";
3
- export * from "./spreadsheet.js";
4
2
  export * from "./directory.js";
5
3
  export * from "./group-settings-templates.js";
package/dist/index.js CHANGED
@@ -1,5 +1,3 @@
1
1
  export * from "./common.js";
2
- export * from "./calendar.js";
3
- export * from "./spreadsheet.js";
4
2
  export * from "./directory.js";
5
3
  export * from "./group-settings-templates.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cyc-seattle/gsuite-sdk",
3
- "version": "0.3.0",
3
+ "version": "1.1.0",
4
4
  "description": "Domain-agnostic wrappers around Google Workspace APIs",
5
5
  "author": "CYC Community Sailing Center",
6
6
  "license": "Apache-2.0",
@@ -19,7 +19,7 @@
19
19
  "engines": {
20
20
  "node": ">=22"
21
21
  },
22
- "packageManager": "pnpm@10.34.7",
22
+ "packageManager": "pnpm@10.34.9",
23
23
  "prettier": "@cyc-seattle/ts-config/prettier",
24
24
  "exports": {
25
25
  ".": {
@@ -42,15 +42,12 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "exponential-backoff": "^3.1.3",
45
- "google-spreadsheet": "^5.0.0",
46
45
  "googleapis": "^144.0.0",
47
- "luxon": "^3.7.2",
48
46
  "winston": "^3.18.3"
49
47
  },
50
48
  "devDependencies": {
51
49
  "@amiceli/vitest-cucumber": "^8.0.0",
52
50
  "@cyc-seattle/ts-config": "^0.1.2",
53
- "@types/luxon": "^3.7.1",
54
51
  "@types/node": "^22.20.5",
55
52
  "eslint": "^9.39.5",
56
53
  "prettier": "^3.9.10",
@@ -1,48 +0,0 @@
1
- import { calendar_v3 } from "googleapis";
2
- import { Auth } from "googleapis";
3
- import { DateTime } from "luxon";
4
- /**
5
- * Represents a calendar event
6
- */
7
- export interface CalendarEvent {
8
- /** Unique identifier for the event */
9
- id: string;
10
- title: string;
11
- startTime: DateTime;
12
- endTime: DateTime;
13
- allDay: boolean;
14
- description?: string;
15
- location?: string;
16
- /** Additional metadata */
17
- metadata?: Record<string, string> | undefined;
18
- }
19
- /**
20
- * Google Calendar API client
21
- */
22
- export declare class CalendarClient {
23
- private client;
24
- constructor(auth: Auth.GoogleAuth);
25
- loadCalendar(calendarId: string): Calendar;
26
- }
27
- export declare class Calendar {
28
- private client;
29
- readonly calendarId: string;
30
- constructor(client: calendar_v3.Calendar, calendarId: string);
31
- /**
32
- * Gets a single event by ID
33
- * Returns null if the event doesn't exist
34
- */
35
- getEvent(eventId: string): Promise<CalendarEvent | null>;
36
- /**
37
- * Lists all events in a calendar within a date range
38
- */
39
- listEvents(timeMin?: DateTime, timeMax?: DateTime): Promise<CalendarEvent[]>;
40
- /**
41
- * Creates a new event in the calendar
42
- */
43
- createEvent(calendarId: string, event: Omit<CalendarEvent, "id">): Promise<CalendarEvent>;
44
- /**
45
- * Updates an existing event in the calendar
46
- */
47
- updateEvent(calendarId: string, event: CalendarEvent): Promise<CalendarEvent>;
48
- }
package/dist/calendar.js DELETED
@@ -1,157 +0,0 @@
1
- import { google } from "googleapis";
2
- import { safeCall } from "./common.js";
3
- import { DateTime } from "luxon";
4
- import winston from "winston";
5
- /**
6
- * Google Calendar API client
7
- */
8
- export class CalendarClient {
9
- client;
10
- constructor(auth) {
11
- this.client = google.calendar({ version: "v3", auth });
12
- }
13
- loadCalendar(calendarId) {
14
- return new Calendar(this.client, calendarId);
15
- }
16
- }
17
- export class Calendar {
18
- client;
19
- calendarId;
20
- constructor(client, calendarId) {
21
- this.client = client;
22
- this.calendarId = calendarId;
23
- }
24
- /**
25
- * Gets a single event by ID
26
- * Returns null if the event doesn't exist
27
- */
28
- async getEvent(eventId) {
29
- winston.debug("Getting calendar event", { calendar: this.calendarId, eventId });
30
- try {
31
- const response = await safeCall(async () => this.client.events.get({
32
- calendarId: this.calendarId,
33
- eventId,
34
- }));
35
- if (!response.data.id || response.data.status === "cancelled") {
36
- return null;
37
- }
38
- winston.debug("Found calendar event", { eventId: response.data.id });
39
- return convertToCalendarEvent(response.data);
40
- }
41
- catch (error) {
42
- // If event doesn't exist, return null instead of throwing
43
- if (error.code === 404) {
44
- winston.debug("Event not found", { eventId });
45
- return null;
46
- }
47
- throw error;
48
- }
49
- }
50
- /**
51
- * Lists all events in a calendar within a date range
52
- */
53
- async listEvents(timeMin, timeMax) {
54
- winston.debug("Listing calendar events", { calendar: this.calendarId, timeMin, timeMax });
55
- // Typed explicitly, and the optional bounds assigned only when present: given a bare object
56
- // literal TypeScript resolves `events.list` to its callback-style overload and infers `void`,
57
- // and under exactOptionalPropertyTypes an explicit `undefined` is not assignable to `timeMin?`.
58
- const params = {
59
- calendarId: this.calendarId,
60
- singleEvents: true,
61
- orderBy: "startTime",
62
- };
63
- const min = timeMin?.toISO();
64
- if (min) {
65
- params.timeMin = min;
66
- }
67
- const max = timeMax?.toISO();
68
- if (max) {
69
- params.timeMax = max;
70
- }
71
- const data = await safeCall(async () => {
72
- const res = await this.client.events.list(params);
73
- return res.data;
74
- });
75
- const events = data.items ?? [];
76
- winston.info(`Found ${events.length} events in calendar`);
77
- return events
78
- .filter((event) => Boolean(event.start && event.id))
79
- .map((event) => convertToCalendarEvent(event));
80
- }
81
- /**
82
- * Creates a new event in the calendar
83
- */
84
- async createEvent(calendarId, event) {
85
- winston.debug("Creating calendar event", { calendar: this.calendarId, event });
86
- const response = await safeCall(async () => this.client.events.insert({
87
- calendarId,
88
- requestBody: convertToGoogleEvent(event),
89
- }));
90
- if (!response.data.id) {
91
- throw new Error("Failed to create event: no ID returned");
92
- }
93
- winston.info("Created calendar event", { eventId: response.data.id });
94
- return convertToCalendarEvent(response.data);
95
- }
96
- /**
97
- * Updates an existing event in the calendar
98
- */
99
- async updateEvent(calendarId, event) {
100
- winston.debug("Updating calendar event", { calendar: calendarId, eventId: event.id });
101
- const response = await safeCall(async () => this.client.events.update({
102
- calendarId,
103
- eventId: event.id,
104
- requestBody: convertToGoogleEvent(event),
105
- }));
106
- if (!response.data.id) {
107
- throw new Error("Failed to update event: no ID returned");
108
- }
109
- winston.info("Updated calendar event", { eventId: response.data.id });
110
- return convertToCalendarEvent(response.data);
111
- }
112
- }
113
- function convertToCalendarEvent(event) {
114
- const allDay = !event.start?.dateTime;
115
- const startTime = allDay ? DateTime.fromISO(event.start?.date ?? "") : DateTime.fromISO(event.start?.dateTime ?? "");
116
- const endTime = allDay ? DateTime.fromISO(event.end?.date ?? "") : DateTime.fromISO(event.end?.dateTime ?? "");
117
- const calEvent = {
118
- id: event.id,
119
- title: event.summary ?? "Untitled Event",
120
- startTime,
121
- endTime,
122
- allDay,
123
- };
124
- if (event.description) {
125
- calEvent.description = event.description;
126
- }
127
- if (event.location) {
128
- calEvent.location = event.location;
129
- }
130
- if (event.extendedProperties?.private) {
131
- calEvent.metadata = event.extendedProperties.private;
132
- }
133
- return calEvent;
134
- }
135
- function convertToGoogleEvent(event) {
136
- const googleEvent = {
137
- summary: event.title ?? null,
138
- description: event.description ?? null,
139
- location: event.location ?? null,
140
- };
141
- if (event.startTime && event.endTime) {
142
- if (event.allDay) {
143
- googleEvent.start = { date: event.startTime.toISODate() ?? null };
144
- googleEvent.end = { date: event.endTime.toISODate() ?? null };
145
- }
146
- else {
147
- googleEvent.start = { dateTime: event.startTime.toISO() ?? null };
148
- googleEvent.end = { dateTime: event.endTime.toISO() ?? null };
149
- }
150
- }
151
- if (event.metadata) {
152
- googleEvent.extendedProperties = {
153
- private: event.metadata,
154
- };
155
- }
156
- return googleEvent;
157
- }
@@ -1,111 +0,0 @@
1
- import { GoogleSpreadsheet, GoogleSpreadsheetCellErrorValue, GoogleSpreadsheetWorksheet } from "google-spreadsheet";
2
- import { Auth, sheets_v4 } from "googleapis";
3
- type RowValueType = number | boolean | string | Date | undefined;
4
- type CachedValue = number | boolean | string | Date | null | GoogleSpreadsheetCellErrorValue;
5
- export type Row = Record<string, RowValueType>;
6
- export type RowKeys<T extends Row> = Extract<keyof T, string>;
7
- export type HeaderValues<T extends Row> = RowKeys<T>[];
8
- interface AddOrUpdateResult {
9
- readonly existing: boolean;
10
- }
11
- /**
12
- * Represents a table in a Google Spreadsheet with cached cell access
13
- */
14
- export declare class Table<T extends Row> {
15
- private readonly worksheet;
16
- private readonly headerColumns;
17
- private readonly addedRows;
18
- private readonly valueCache;
19
- constructor(worksheet: GoogleSpreadsheetWorksheet, headerColumns: Map<string, number>);
20
- private cacheKey;
21
- getCellValue(header: RowKeys<T>, rowIndex: number): CachedValue | undefined;
22
- /**
23
- * Finds all rows (by index) containing the values in "needle". This object may be a partial record to only
24
- * match on key fields.
25
- */
26
- findRows(needle: Partial<T>): number[];
27
- updateRow(rowIndex: number, values: Partial<T>): void;
28
- addRow(values: Partial<T>): void;
29
- updateRows(keys: HeaderValues<T>, values: Partial<T>): void;
30
- /**
31
- * Updates ALL rows where the key columns matched the supplied values, or if
32
- * no such rows exist, adds a new one.
33
- */
34
- addOrUpdate(keys: HeaderValues<T>, values: Partial<T>): AddOrUpdateResult;
35
- save(reload?: boolean): Promise<void>;
36
- }
37
- /**
38
- * Represents a worksheet in a Google Spreadsheet
39
- */
40
- export declare class Worksheet<T extends Row> {
41
- private readonly worksheet;
42
- constructor(worksheet: GoogleSpreadsheetWorksheet);
43
- /** The numeric sheet id, needed to target this worksheet in raw Sheets API requests. */
44
- get sheetId(): number;
45
- getRows(): Promise<import("google-spreadsheet").GoogleSpreadsheetRow<T>[]>;
46
- getTable(): Promise<Table<T>>;
47
- }
48
- /**
49
- * Extended GoogleSpreadsheet with helper methods
50
- */
51
- export declare class Spreadsheet extends GoogleSpreadsheet {
52
- private createWorksheet;
53
- getOrCreateWorksheet<T extends Row>(title: string, headerValues: HeaderValues<T>): Promise<Worksheet<T>>;
54
- /**
55
- * Adds a worksheet with the given headers, returning the typed wrapper. Unlike
56
- * {@link getOrCreateWorksheet}, this always creates a new sheet (used when building a
57
- * fresh spreadsheet where each tab is written once).
58
- */
59
- addWorksheet<T extends Row>(title: string, headerValues: HeaderValues<T>): Promise<Worksheet<T>>;
60
- /** Deletes the worksheet with the given title, if it exists. */
61
- deleteWorksheet(title: string): Promise<void>;
62
- /**
63
- * Clears every existing worksheet so the spreadsheet can be rebuilt from scratch,
64
- * leaving a single empty placeholder sheet (a spreadsheet must always have ≥1 sheet).
65
- * The placeholder is created first so it survives while the originals are deleted, and
66
- * its title is returned so the caller can remove it after adding the real sheets.
67
- */
68
- resetSheets(): Promise<string>;
69
- }
70
- /**
71
- * Client for loading Google Spreadsheets
72
- */
73
- export declare class SpreadsheetClient {
74
- private readonly auth;
75
- constructor(auth: Auth.GoogleAuth);
76
- /**
77
- * Creates a new, empty Google Spreadsheet inside the given Drive folder and returns it
78
- * loaded and ready to write.
79
- *
80
- * The Drive API is used (rather than google-spreadsheet's createNewSpreadsheetDocument,
81
- * which only lands the file in "My Drive") so the file can be parented directly in a
82
- * folder. `supportsAllDrives` is required because our target folders live in shared
83
- * drives. Requires the `drive` OAuth scope.
84
- */
85
- createSpreadsheet(title: string, folderId: string): Promise<Spreadsheet>;
86
- /**
87
- * Finds the id of a non-trashed spreadsheet with the exact given name inside the folder,
88
- * or undefined if none exists. `supportsAllDrives` / `includeItemsFromAllDrives` are set
89
- * because our folders live in shared drives.
90
- */
91
- findSpreadsheetInFolder(title: string, folderId: string): Promise<string | undefined>;
92
- /**
93
- * Returns a spreadsheet named `title` in the folder, ready to be rebuilt: if one already
94
- * exists it is reused (and its sheets cleared) so the file id / URL stays stable across
95
- * runs; otherwise a new one is created. The returned `placeholderTitle` is a throwaway
96
- * sheet the caller should delete after adding the real worksheets.
97
- */
98
- getOrCreateSpreadsheet(title: string, folderId: string): Promise<{
99
- spreadsheet: Spreadsheet;
100
- placeholderTitle: string;
101
- reused: boolean;
102
- }>;
103
- /**
104
- * Applies raw Sheets API requests (formatting, banding, borders, etc.) that the
105
- * google-spreadsheet abstraction doesn't expose. Requests are sent as a single atomic
106
- * batchUpdate.
107
- */
108
- batchUpdate(spreadsheetId: string, requests: sheets_v4.Schema$Request[]): Promise<void>;
109
- loadSpreadsheet(spreadsheetUrlOrId: string): Promise<Spreadsheet>;
110
- }
111
- export {};
@@ -1,330 +0,0 @@
1
- import { GoogleSpreadsheet } from "google-spreadsheet";
2
- import { google } from "googleapis";
3
- import winston from "winston";
4
- import { safeCall } from "./common.js";
5
- /**
6
- * Represents a table in a Google Spreadsheet with cached cell access
7
- */
8
- export class Table {
9
- worksheet;
10
- headerColumns;
11
- addedRows = [];
12
- // Cell values keyed by "row,col", populated lazily on read and kept in sync on
13
- // write. google-spreadsheet's `cell.value` getter throws "Value has been changed"
14
- // once a cell has been assigned but not yet saved, so findRows must never re-read
15
- // a cell that an earlier updateRow modified. Caching the value we read (or wrote)
16
- // avoids touching the live getter a second time.
17
- valueCache = new Map();
18
- constructor(worksheet, headerColumns) {
19
- this.worksheet = worksheet;
20
- this.headerColumns = headerColumns;
21
- }
22
- cacheKey(rowIndex, columnIndex) {
23
- return `${rowIndex},${columnIndex}`;
24
- }
25
- getCellValue(header, rowIndex) {
26
- const columnIndex = this.headerColumns.get(header);
27
- if (columnIndex === undefined) {
28
- return undefined;
29
- }
30
- const key = this.cacheKey(rowIndex, columnIndex);
31
- if (this.valueCache.has(key)) {
32
- return this.valueCache.get(key);
33
- }
34
- // Safe to read the live cell here: it has not been modified this session.
35
- const value = this.worksheet.getCell(rowIndex, columnIndex).value;
36
- this.valueCache.set(key, value);
37
- return value;
38
- }
39
- /**
40
- * Finds all rows (by index) containing the values in "needle". This object may be a partial record to only
41
- * match on key fields.
42
- */
43
- findRows(needle) {
44
- const rows = [];
45
- const needleKeys = Object.keys(needle);
46
- for (let row = 1; row < this.worksheet.rowCount; row++) {
47
- const found = needleKeys.every((header) => {
48
- const rowValue = this.getCellValue(header, row);
49
- const needleValue = needle[header];
50
- return rowValue === needleValue;
51
- });
52
- if (found) {
53
- rows.push(row);
54
- }
55
- }
56
- return rows;
57
- }
58
- updateRow(rowIndex, values) {
59
- winston.info("Updating existing row", { rowIndex, values });
60
- const headers = Object.keys(values);
61
- for (const header of headers) {
62
- const columnIndex = this.headerColumns.get(header);
63
- if (columnIndex !== undefined) {
64
- const cell = this.worksheet.getCell(rowIndex, columnIndex);
65
- const value = values[header];
66
- cell.value = value;
67
- // Keep the cache consistent with the write so later reads don't hit the
68
- // now-dirty cell's throwing getter and so findRows reflects the update.
69
- this.valueCache.set(this.cacheKey(rowIndex, columnIndex), value ?? null);
70
- }
71
- }
72
- }
73
- addRow(values) {
74
- winston.info("Adding new row", { values });
75
- const newRow = [];
76
- const headers = Object.keys(values);
77
- for (const header of headers) {
78
- const columnIndex = this.headerColumns.get(header);
79
- if (columnIndex !== undefined) {
80
- newRow[columnIndex] = values[header] ?? "";
81
- }
82
- }
83
- this.addedRows.push(newRow);
84
- }
85
- updateRows(keys, values) {
86
- const needle = {};
87
- for (const key of keys) {
88
- needle[key] = values[key];
89
- }
90
- const rows = this.findRows(needle);
91
- for (const rowIndex of rows) {
92
- this.updateRow(rowIndex, values);
93
- }
94
- }
95
- /**
96
- * Updates ALL rows where the key columns matched the supplied values, or if
97
- * no such rows exist, adds a new one.
98
- */
99
- addOrUpdate(keys, values) {
100
- const needle = {};
101
- for (const key of keys) {
102
- needle[key] = values[key];
103
- }
104
- const rows = this.findRows(needle);
105
- if (rows.length == 0) {
106
- this.addRow(values);
107
- return { existing: false };
108
- }
109
- else {
110
- for (const rowIndex of rows) {
111
- this.updateRow(rowIndex, values);
112
- }
113
- return { existing: true };
114
- }
115
- }
116
- async save(reload) {
117
- winston.debug("Saving updated cells");
118
- await safeCall(() => this.worksheet.saveUpdatedCells());
119
- if (this.addedRows.length > 0) {
120
- winston.debug("Adding new rows", { count: this.addedRows.length });
121
- await safeCall(() => this.worksheet.addRows(this.addedRows));
122
- }
123
- if (reload) {
124
- await safeCall(() => this.worksheet.loadCells());
125
- }
126
- }
127
- }
128
- /**
129
- * Represents a worksheet in a Google Spreadsheet
130
- */
131
- export class Worksheet {
132
- worksheet;
133
- constructor(worksheet) {
134
- this.worksheet = worksheet;
135
- }
136
- /** The numeric sheet id, needed to target this worksheet in raw Sheets API requests. */
137
- get sheetId() {
138
- return this.worksheet.sheetId;
139
- }
140
- async getRows() {
141
- return safeCall(() => this.worksheet.getRows());
142
- }
143
- async getTable() {
144
- winston.debug("Loading worksheet cells", { title: this.worksheet.title });
145
- await safeCall(() => this.worksheet.loadCells());
146
- winston.debug("Loaded worksheet cells", this.worksheet.cellStats);
147
- const headerColumns = new Map();
148
- for (let col = 0; col < this.worksheet.columnCount; col++) {
149
- const cellValue = this.worksheet.getCell(0, col).stringValue;
150
- if (cellValue !== undefined) {
151
- headerColumns.set(cellValue, col);
152
- }
153
- }
154
- return new Table(this.worksheet, headerColumns);
155
- }
156
- }
157
- /**
158
- * Extended GoogleSpreadsheet with helper methods
159
- */
160
- export class Spreadsheet extends GoogleSpreadsheet {
161
- async createWorksheet(title, headerValues) {
162
- winston.debug("Creating worksheet", { title, headerValues: headerValues });
163
- return safeCall(() => this.addSheet({
164
- title: title,
165
- headerValues: headerValues,
166
- gridProperties: {
167
- rowCount: 1,
168
- columnCount: headerValues.length,
169
- },
170
- }));
171
- }
172
- async getOrCreateWorksheet(title, headerValues) {
173
- const worksheet = this.sheetsByTitle[title] ?? (await this.createWorksheet(title, headerValues));
174
- return new Worksheet(worksheet);
175
- }
176
- /**
177
- * Adds a worksheet with the given headers, returning the typed wrapper. Unlike
178
- * {@link getOrCreateWorksheet}, this always creates a new sheet (used when building a
179
- * fresh spreadsheet where each tab is written once).
180
- */
181
- async addWorksheet(title, headerValues) {
182
- const worksheet = await this.createWorksheet(title, headerValues);
183
- return new Worksheet(worksheet);
184
- }
185
- /** Deletes the worksheet with the given title, if it exists. */
186
- async deleteWorksheet(title) {
187
- const worksheet = this.sheetsByTitle[title];
188
- if (worksheet !== undefined) {
189
- await safeCall(() => worksheet.delete());
190
- }
191
- }
192
- /**
193
- * Clears every existing worksheet so the spreadsheet can be rebuilt from scratch,
194
- * leaving a single empty placeholder sheet (a spreadsheet must always have ≥1 sheet).
195
- * The placeholder is created first so it survives while the originals are deleted, and
196
- * its title is returned so the caller can remove it after adding the real sheets.
197
- */
198
- async resetSheets() {
199
- const placeholderTitle = `_rebuild_${Date.now()}`;
200
- const existing = [...this.sheetsByIndex];
201
- await safeCall(() => this.addSheet({ title: placeholderTitle, gridProperties: { rowCount: 1, columnCount: 1 } }));
202
- for (const worksheet of existing) {
203
- await safeCall(() => worksheet.delete());
204
- }
205
- return placeholderTitle;
206
- }
207
- }
208
- /**
209
- * Extracts spreadsheet ID from a URL or returns the ID as-is
210
- */
211
- function extractSpreadsheetId(urlOrId) {
212
- try {
213
- const url = new URL(urlOrId);
214
- const pathSegments = url.pathname.split("/");
215
- if (pathSegments.length < 4) {
216
- throw new Error(`Cannot extract spreadsheet ID from ${urlOrId}`);
217
- }
218
- return pathSegments[3];
219
- }
220
- catch {
221
- // If it's not a valid URL, assume it's already an ID
222
- return urlOrId;
223
- }
224
- }
225
- /**
226
- * Client for loading Google Spreadsheets
227
- */
228
- export class SpreadsheetClient {
229
- auth;
230
- constructor(auth) {
231
- this.auth = auth;
232
- }
233
- /**
234
- * Creates a new, empty Google Spreadsheet inside the given Drive folder and returns it
235
- * loaded and ready to write.
236
- *
237
- * The Drive API is used (rather than google-spreadsheet's createNewSpreadsheetDocument,
238
- * which only lands the file in "My Drive") so the file can be parented directly in a
239
- * folder. `supportsAllDrives` is required because our target folders live in shared
240
- * drives. Requires the `drive` OAuth scope.
241
- */
242
- async createSpreadsheet(title, folderId) {
243
- const drive = google.drive("v3");
244
- const file = await safeCall(async () => {
245
- const response = await drive.files.create({
246
- auth: this.auth,
247
- requestBody: {
248
- name: title,
249
- mimeType: "application/vnd.google-apps.spreadsheet",
250
- parents: [folderId],
251
- },
252
- fields: "id",
253
- supportsAllDrives: true,
254
- });
255
- return response.data;
256
- });
257
- const spreadsheetId = file.id;
258
- if (!spreadsheetId) {
259
- throw new Error(`Drive did not return an id for the new spreadsheet "${title}"`);
260
- }
261
- winston.info("Created spreadsheet", { title, spreadsheetId, folderId });
262
- return this.loadSpreadsheet(spreadsheetId);
263
- }
264
- /**
265
- * Finds the id of a non-trashed spreadsheet with the exact given name inside the folder,
266
- * or undefined if none exists. `supportsAllDrives` / `includeItemsFromAllDrives` are set
267
- * because our folders live in shared drives.
268
- */
269
- async findSpreadsheetInFolder(title, folderId) {
270
- const drive = google.drive("v3");
271
- const escapedTitle = title.replace(/'/g, "\\'");
272
- const fileList = await safeCall(async () => {
273
- const response = await drive.files.list({
274
- auth: this.auth,
275
- q: `name = '${escapedTitle}' and '${folderId}' in parents and mimeType = 'application/vnd.google-apps.spreadsheet' and trashed = false`,
276
- fields: "files(id,name)",
277
- supportsAllDrives: true,
278
- includeItemsFromAllDrives: true,
279
- pageSize: 1,
280
- });
281
- return response.data;
282
- });
283
- return fileList.files?.[0]?.id ?? undefined;
284
- }
285
- /**
286
- * Returns a spreadsheet named `title` in the folder, ready to be rebuilt: if one already
287
- * exists it is reused (and its sheets cleared) so the file id / URL stays stable across
288
- * runs; otherwise a new one is created. The returned `placeholderTitle` is a throwaway
289
- * sheet the caller should delete after adding the real worksheets.
290
- */
291
- async getOrCreateSpreadsheet(title, folderId) {
292
- const existingId = await this.findSpreadsheetInFolder(title, folderId);
293
- if (existingId !== undefined) {
294
- winston.info("Reusing existing spreadsheet", { title, spreadsheetId: existingId });
295
- const spreadsheet = await this.loadSpreadsheet(existingId);
296
- const placeholderTitle = await spreadsheet.resetSheets();
297
- return { spreadsheet, placeholderTitle, reused: true };
298
- }
299
- const spreadsheet = await this.createSpreadsheet(title, folderId);
300
- return { spreadsheet, placeholderTitle: "Sheet1", reused: false };
301
- }
302
- /**
303
- * Applies raw Sheets API requests (formatting, banding, borders, etc.) that the
304
- * google-spreadsheet abstraction doesn't expose. Requests are sent as a single atomic
305
- * batchUpdate.
306
- */
307
- async batchUpdate(spreadsheetId, requests) {
308
- if (requests.length === 0) {
309
- return;
310
- }
311
- const sheets = google.sheets("v4");
312
- await safeCall(() => sheets.spreadsheets.batchUpdate({
313
- auth: this.auth,
314
- spreadsheetId,
315
- requestBody: { requests },
316
- }));
317
- }
318
- async loadSpreadsheet(spreadsheetUrlOrId) {
319
- const spreadsheetId = extractSpreadsheetId(spreadsheetUrlOrId);
320
- const spreadsheet = new Spreadsheet(spreadsheetId, this.auth);
321
- await safeCall(() => spreadsheet.loadInfo());
322
- winston.debug("Loaded spreadsheet", {
323
- spreadsheetId,
324
- title: spreadsheet.title,
325
- locale: spreadsheet.locale,
326
- timeZone: spreadsheet.timeZone,
327
- });
328
- return spreadsheet;
329
- }
330
- }