@opengeni/documents 0.2.64 → 0.2.69

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.
@@ -0,0 +1,588 @@
1
+ // src/google-drive.ts
2
+ var GOOGLE_DRIVE_PROVIDER_KEY = "google-drive";
3
+ var GOOGLE_DRIVE_FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
4
+ var GOOGLE_DRIVE_SHORTCUT_MIME_TYPE = "application/vnd.google-apps.shortcut";
5
+ var GOOGLE_DRIVE_NATIVE_MIME_PREFIX = "application/vnd.google-apps.";
6
+ var GOOGLE_DRIVE_MAX_ID_CHARS = 256;
7
+ var GOOGLE_DRIVE_MAX_NAME_CHARS = 1024;
8
+ var GOOGLE_DRIVE_MAX_MIME_CHARS = 256;
9
+ var GOOGLE_DRIVE_MAX_PAGE_TOKEN_CHARS = 4096;
10
+ var GOOGLE_DRIVE_MAX_PAGE_ITEMS = 100;
11
+ var GOOGLE_DRIVE_MAX_CHECKPOINT_FOLDERS = 2e3;
12
+ var GOOGLE_DRIVE_MAX_CHECKPOINT_BYTES = 2 * 1024 * 1024;
13
+ var GOOGLE_DRIVE_NATIVE_EXPORTS = /* @__PURE__ */ new Map([
14
+ [
15
+ "application/vnd.google-apps.document",
16
+ {
17
+ contentType: "application/pdf",
18
+ extension: ".pdf"
19
+ }
20
+ ],
21
+ [
22
+ "application/vnd.google-apps.spreadsheet",
23
+ {
24
+ contentType: "application/pdf",
25
+ extension: ".pdf"
26
+ }
27
+ ],
28
+ [
29
+ "application/vnd.google-apps.presentation",
30
+ {
31
+ contentType: "application/pdf",
32
+ extension: ".pdf"
33
+ }
34
+ ],
35
+ ["application/vnd.google-apps.drawing", { contentType: "application/pdf", extension: ".pdf" }]
36
+ ]);
37
+ var DEPENDENCY_FREE_ORDINARY_CONTENT_TYPES = /* @__PURE__ */ new Set([
38
+ "application/json",
39
+ "application/pdf",
40
+ "application/xml",
41
+ "application/x-yaml",
42
+ "application/yaml"
43
+ ]);
44
+ var GENERIC_BINARY_CONTENT_TYPES = /* @__PURE__ */ new Set(["application/octet-stream", "binary/octet-stream"]);
45
+ var DEPENDENCY_FREE_EXTENSION_CONTENT_TYPES = /* @__PURE__ */ new Map([
46
+ [".csv", "text/csv"],
47
+ [".htm", "text/html"],
48
+ [".html", "text/html"],
49
+ [".json", "application/json"],
50
+ [".markdown", "text/markdown"],
51
+ [".md", "text/markdown"],
52
+ [".pdf", "application/pdf"],
53
+ [".text", "text/plain"],
54
+ [".tsv", "text/tab-separated-values"],
55
+ [".txt", "text/plain"],
56
+ [".xml", "application/xml"],
57
+ [".yaml", "application/x-yaml"],
58
+ [".yml", "application/x-yaml"]
59
+ ]);
60
+ var GoogleDriveInventoryProviderError = class extends Error {
61
+ constructor(providerCode) {
62
+ super(providerCode);
63
+ this.providerCode = providerCode;
64
+ this.name = "GoogleDriveInventoryProviderError";
65
+ }
66
+ };
67
+ function googleDriveKnowledgeScope(targetScope, workspaceId, initiatingSubjectId) {
68
+ const boundedWorkspaceId = boundedText(workspaceId, "workspaceId", 256);
69
+ const boundedSubjectId = boundedText(initiatingSubjectId, "initiatingSubjectId", 1024);
70
+ if (targetScope === "organization") {
71
+ return { kind: "organization", workspaceId: null, subjectId: null };
72
+ }
73
+ if (targetScope === "workspace") {
74
+ return { kind: "workspace", workspaceId: boundedWorkspaceId, subjectId: null };
75
+ }
76
+ return {
77
+ kind: "personal",
78
+ workspaceId: boundedWorkspaceId,
79
+ subjectId: boundedSubjectId
80
+ };
81
+ }
82
+ function googleDriveKnowledgeSourceIdentity(input) {
83
+ const sourceId = driveId(input.source.id, "source.id");
84
+ const externalTenantId = normalizedGooglePermissionId(input.googlePermissionId);
85
+ const sourceDriveId = nullableDriveId(input.source.driveId, "source.driveId");
86
+ return {
87
+ providerKey: GOOGLE_DRIVE_PROVIDER_KEY,
88
+ externalTenantId,
89
+ externalSourceId: sourceId,
90
+ sourceKind: sourceId === "root" ? "google-drive-my-drive" : sourceDriveId === sourceId ? "google-drive-shared-drive" : "google-drive-folder",
91
+ sourceUri: googleDriveSourceUri(sourceId),
92
+ scope: googleDriveKnowledgeScope(
93
+ input.source.targetScope,
94
+ input.workspaceId,
95
+ input.initiatingSubjectId
96
+ )
97
+ };
98
+ }
99
+ function planGoogleDriveTransfer(item, maxFileBytes) {
100
+ const normalized = validatedProviderItem(item);
101
+ const byteLimit = safePositiveInteger(maxFileBytes, "maxFileBytes");
102
+ if (normalized.trashed) {
103
+ return { action: "skip", reason: "trashed" };
104
+ }
105
+ if (normalized.mimeType === GOOGLE_DRIVE_FOLDER_MIME_TYPE) {
106
+ return { action: "traverse" };
107
+ }
108
+ if (normalized.mimeType === GOOGLE_DRIVE_SHORTCUT_MIME_TYPE) {
109
+ return { action: "skip", reason: "shortcut_unsupported" };
110
+ }
111
+ const nativeExport = GOOGLE_DRIVE_NATIVE_EXPORTS.get(normalized.mimeType);
112
+ if (nativeExport) {
113
+ return {
114
+ action: "export",
115
+ contentType: nativeExport.contentType,
116
+ filename: exportedFilename(normalized.name, nativeExport.extension),
117
+ declaredBytes: null
118
+ };
119
+ }
120
+ if (normalized.mimeType.startsWith(GOOGLE_DRIVE_NATIVE_MIME_PREFIX)) {
121
+ return { action: "skip", reason: "unsupported_native_type" };
122
+ }
123
+ const declaredBytes = fileSize(normalized.size);
124
+ if (declaredBytes !== null && declaredBytes > BigInt(byteLimit)) {
125
+ return { action: "skip", reason: "file_too_large" };
126
+ }
127
+ const contentType = dependencyFreeOrdinaryContentType(normalized.name, normalized.mimeType);
128
+ if (!contentType) {
129
+ return { action: "skip", reason: "unsupported_file_type" };
130
+ }
131
+ return {
132
+ action: "download",
133
+ contentType,
134
+ filename: safeFilename(normalized.name),
135
+ declaredBytes: declaredBytes?.toString() ?? null
136
+ };
137
+ }
138
+ async function inventoryGoogleDriveSource(input) {
139
+ const limits = validatedLimits(input.limits);
140
+ const googlePermissionId = normalizedGooglePermissionId(input.googlePermissionId);
141
+ const source = googleDriveKnowledgeSourceIdentity({
142
+ googlePermissionId,
143
+ source: input.source,
144
+ workspaceId: input.workspaceId,
145
+ initiatingSubjectId: input.initiatingSubjectId
146
+ });
147
+ const checkpointIdentity = {
148
+ googlePermissionId,
149
+ externalTenantId: source.externalTenantId,
150
+ sourceId: source.externalSourceId,
151
+ sourceDriveId: nullableDriveId(input.source.driveId, "source.driveId"),
152
+ scope: source.scope
153
+ };
154
+ const now = input.now ?? Date.now;
155
+ const startedAt = now();
156
+ const checkpoint = input.checkpoint ? validatedCheckpoint(input.checkpoint, checkpointIdentity, limits) : initialCheckpoint(checkpointIdentity);
157
+ const initialTotals = cloneTotals(checkpoint.totals);
158
+ const entries = [];
159
+ const issues = [];
160
+ let stopReason = null;
161
+ while (checkpoint.pendingFolders.length > 0) {
162
+ if (now() - startedAt >= limits.maxElapsedMs) {
163
+ stopReason = "elapsed_time_limit";
164
+ break;
165
+ }
166
+ const frame = checkpoint.pendingFolders[0];
167
+ if (frame.loaded && frame.bufferedItems.length === 0) {
168
+ if (frame.nextPageToken) {
169
+ frame.pageToken = frame.nextPageToken;
170
+ frame.nextPageToken = null;
171
+ frame.loaded = false;
172
+ } else {
173
+ checkpoint.pendingFolders.shift();
174
+ }
175
+ continue;
176
+ }
177
+ if (checkpoint.totals.itemCount >= limits.maxItems) {
178
+ stopReason = "item_limit";
179
+ break;
180
+ }
181
+ if (!frame.loaded) {
182
+ if (checkpoint.totals.apiRequestCount >= limits.maxApiRequests) {
183
+ stopReason = "api_request_limit";
184
+ break;
185
+ }
186
+ const remainingItems = limits.maxItems - checkpoint.totals.itemCount;
187
+ const requestedPageSize = Math.min(limits.pageSize, remainingItems);
188
+ let page;
189
+ try {
190
+ page = await input.listChildren({
191
+ folderId: frame.folderId,
192
+ driveId: frame.driveId,
193
+ pageToken: frame.pageToken,
194
+ pageSize: requestedPageSize
195
+ });
196
+ } catch (error) {
197
+ checkpoint.totals.apiRequestCount += 1;
198
+ issues.push({
199
+ code: "provider_error",
200
+ folderId: frame.folderId,
201
+ providerCode: providerErrorCode(error)
202
+ });
203
+ stopReason = "provider_error";
204
+ break;
205
+ }
206
+ checkpoint.totals.apiRequestCount += 1;
207
+ if (!validPage(page, requestedPageSize)) {
208
+ issues.push({ code: "invalid_page", folderId: frame.folderId, providerCode: null });
209
+ stopReason = "provider_error";
210
+ break;
211
+ }
212
+ if (page.incompleteSearch) {
213
+ issues.push({ code: "incomplete_search", folderId: frame.folderId, providerCode: null });
214
+ stopReason = "incomplete_search";
215
+ break;
216
+ }
217
+ frame.loaded = true;
218
+ frame.bufferedItems = page.items.map(validatedProviderItem);
219
+ frame.nextPageToken = page.nextPageToken;
220
+ if (now() - startedAt >= limits.maxElapsedMs) {
221
+ stopReason = "elapsed_time_limit";
222
+ break;
223
+ }
224
+ }
225
+ if (frame.bufferedItems.length === 0) {
226
+ if (frame.nextPageToken) {
227
+ frame.pageToken = frame.nextPageToken;
228
+ frame.nextPageToken = null;
229
+ frame.loaded = false;
230
+ } else {
231
+ checkpoint.pendingFolders.shift();
232
+ }
233
+ continue;
234
+ }
235
+ const item = validatedProviderItem(frame.bufferedItems[0]);
236
+ let transfer = planGoogleDriveTransfer(item, limits.maxFileBytes);
237
+ if (transfer.action === "download" && transfer.declaredBytes !== null) {
238
+ const nextKnownBytes = BigInt(checkpoint.totals.knownBytes) + BigInt(transfer.declaredBytes);
239
+ if (nextKnownBytes > BigInt(limits.maxKnownBytes)) {
240
+ stopReason = "known_byte_limit";
241
+ break;
242
+ }
243
+ }
244
+ frame.bufferedItems.shift();
245
+ checkpoint.totals.itemCount += 1;
246
+ const effectiveDriveId = item.driveId ?? frame.driveId;
247
+ if (transfer.action === "traverse") {
248
+ if (checkpoint.seenFolderIds.includes(item.id)) {
249
+ transfer = { action: "skip", reason: "folder_loop" };
250
+ } else if (checkpoint.seenFolderIds.length >= limits.maxFolders) {
251
+ transfer = { action: "skip", reason: "folder_limit" };
252
+ } else {
253
+ checkpoint.seenFolderIds.push(item.id);
254
+ checkpoint.totals.folderCount += 1;
255
+ checkpoint.pendingFolders.push({
256
+ folderId: item.id,
257
+ driveId: effectiveDriveId,
258
+ pageToken: null,
259
+ loaded: false,
260
+ bufferedItems: [],
261
+ nextPageToken: null
262
+ });
263
+ }
264
+ }
265
+ if (transfer.action === "skip") {
266
+ checkpoint.totals.skippedItemCount += 1;
267
+ } else if (transfer.action === "download") {
268
+ checkpoint.totals.plannedFileCount += 1;
269
+ checkpoint.totals.downloadFileCount += 1;
270
+ if (transfer.declaredBytes === null) {
271
+ checkpoint.totals.unknownSizeFileCount += 1;
272
+ } else {
273
+ checkpoint.totals.knownBytes = (BigInt(checkpoint.totals.knownBytes) + BigInt(transfer.declaredBytes)).toString();
274
+ }
275
+ } else if (transfer.action === "export") {
276
+ checkpoint.totals.plannedFileCount += 1;
277
+ checkpoint.totals.exportFileCount += 1;
278
+ checkpoint.totals.unknownSizeFileCount += 1;
279
+ }
280
+ entries.push({
281
+ externalObjectId: item.id,
282
+ externalVersionId: item.version ?? item.md5Checksum ?? item.modifiedTime,
283
+ sourceId: source.externalSourceId,
284
+ parentFolderId: frame.folderId,
285
+ driveId: effectiveDriveId,
286
+ title: item.name,
287
+ mimeType: item.mimeType,
288
+ modifiedTime: item.modifiedTime,
289
+ createdTime: item.createdTime,
290
+ sourceUri: item.webViewLink ?? googleDriveFileUri(item.id),
291
+ transfer
292
+ });
293
+ }
294
+ const elapsedMs = Math.max(0, now() - startedAt);
295
+ const complete = checkpoint.pendingFolders.length === 0;
296
+ const outputCheckpoint = complete ? null : cloneCheckpoint(checkpoint);
297
+ if (outputCheckpoint) assertCheckpointBytes(outputCheckpoint);
298
+ return {
299
+ status: complete ? "complete" : "paused",
300
+ stopReason: complete ? null : stopReason,
301
+ source,
302
+ entries,
303
+ issues,
304
+ totals: cloneTotals(checkpoint.totals),
305
+ run: {
306
+ ...subtractTotals(checkpoint.totals, initialTotals),
307
+ elapsedMs
308
+ },
309
+ checkpoint: outputCheckpoint
310
+ };
311
+ }
312
+ function initialCheckpoint(identity) {
313
+ return {
314
+ version: 2,
315
+ googlePermissionId: identity.googlePermissionId,
316
+ externalTenantId: identity.externalTenantId,
317
+ sourceId: identity.sourceId,
318
+ sourceDriveId: identity.sourceDriveId,
319
+ scope: cloneScope(identity.scope),
320
+ pendingFolders: [
321
+ {
322
+ folderId: identity.sourceId,
323
+ driveId: identity.sourceDriveId,
324
+ pageToken: null,
325
+ loaded: false,
326
+ bufferedItems: [],
327
+ nextPageToken: null
328
+ }
329
+ ],
330
+ seenFolderIds: [identity.sourceId],
331
+ totals: emptyTotals()
332
+ };
333
+ }
334
+ function validatedCheckpoint(value, identity, limits) {
335
+ if (!value || typeof value !== "object" || value.version !== 2) {
336
+ throw new Error("unsupported Google Drive inventory checkpoint");
337
+ }
338
+ if (value.googlePermissionId !== identity.googlePermissionId || value.externalTenantId !== identity.externalTenantId || value.sourceId !== identity.sourceId || value.sourceDriveId !== identity.sourceDriveId || !sameScope(value.scope, identity.scope)) {
339
+ throw new Error("Google Drive inventory checkpoint does not match the selected source");
340
+ }
341
+ const checkpoint = cloneCheckpoint(value);
342
+ if (checkpoint.pendingFolders.length === 0) {
343
+ throw new Error("Google Drive inventory checkpoint is already complete");
344
+ }
345
+ if (checkpoint.pendingFolders.length > GOOGLE_DRIVE_MAX_CHECKPOINT_FOLDERS || checkpoint.seenFolderIds.length > GOOGLE_DRIVE_MAX_CHECKPOINT_FOLDERS || checkpoint.seenFolderIds.length > limits.maxFolders) {
346
+ throw new Error("Google Drive inventory checkpoint exceeds the folder limit");
347
+ }
348
+ if (!checkpoint.seenFolderIds.includes(identity.sourceId)) {
349
+ throw new Error("Google Drive inventory checkpoint lost its source boundary");
350
+ }
351
+ if (new Set(checkpoint.seenFolderIds).size !== checkpoint.seenFolderIds.length) {
352
+ throw new Error("Google Drive inventory checkpoint contains duplicate folder identity");
353
+ }
354
+ for (const folderId of checkpoint.seenFolderIds) driveId(folderId, "checkpoint.folderId");
355
+ const pendingFolderIds = /* @__PURE__ */ new Set();
356
+ for (const frame of checkpoint.pendingFolders) {
357
+ driveId(frame.folderId, "checkpoint.pending.folderId");
358
+ if (!checkpoint.seenFolderIds.includes(frame.folderId) || pendingFolderIds.has(frame.folderId)) {
359
+ throw new Error("Google Drive inventory checkpoint contains an invalid pending folder");
360
+ }
361
+ pendingFolderIds.add(frame.folderId);
362
+ nullableDriveId(frame.driveId, "checkpoint.pending.driveId");
363
+ pageToken(frame.pageToken, "checkpoint.pending.pageToken");
364
+ pageToken(frame.nextPageToken, "checkpoint.pending.nextPageToken");
365
+ if (typeof frame.loaded !== "boolean" || frame.bufferedItems.length > GOOGLE_DRIVE_MAX_PAGE_ITEMS) {
366
+ throw new Error("Google Drive inventory checkpoint contains an invalid page frame");
367
+ }
368
+ if (!frame.loaded && (frame.bufferedItems.length > 0 || frame.nextPageToken !== null)) {
369
+ throw new Error("Google Drive inventory checkpoint contains an uncommitted page frame");
370
+ }
371
+ frame.bufferedItems = frame.bufferedItems.map(validatedProviderItem);
372
+ }
373
+ validatedTotals(checkpoint.totals);
374
+ if (checkpoint.totals.folderCount !== checkpoint.seenFolderIds.length || checkpoint.totals.plannedFileCount !== checkpoint.totals.exportFileCount + checkpoint.totals.downloadFileCount || checkpoint.totals.unknownSizeFileCount > checkpoint.totals.plannedFileCount || checkpoint.totals.itemCount !== checkpoint.totals.skippedItemCount + checkpoint.totals.plannedFileCount + checkpoint.totals.folderCount - 1) {
375
+ throw new Error("Google Drive inventory checkpoint totals are inconsistent");
376
+ }
377
+ if (checkpoint.totals.itemCount > limits.maxItems || checkpoint.totals.apiRequestCount > limits.maxApiRequests || BigInt(checkpoint.totals.knownBytes) > BigInt(limits.maxKnownBytes)) {
378
+ throw new Error("Google Drive inventory checkpoint exceeds the supplied limits");
379
+ }
380
+ assertCheckpointBytes(checkpoint);
381
+ return checkpoint;
382
+ }
383
+ function validatedLimits(value) {
384
+ const limits = {
385
+ maxItems: safePositiveInteger(value.maxItems, "limits.maxItems"),
386
+ maxKnownBytes: safePositiveInteger(value.maxKnownBytes, "limits.maxKnownBytes"),
387
+ maxApiRequests: safePositiveInteger(value.maxApiRequests, "limits.maxApiRequests"),
388
+ maxElapsedMs: safePositiveInteger(value.maxElapsedMs, "limits.maxElapsedMs"),
389
+ maxFileBytes: safePositiveInteger(value.maxFileBytes, "limits.maxFileBytes"),
390
+ maxFolders: safePositiveInteger(value.maxFolders, "limits.maxFolders"),
391
+ pageSize: safePositiveInteger(value.pageSize, "limits.pageSize")
392
+ };
393
+ if (limits.pageSize > GOOGLE_DRIVE_MAX_PAGE_ITEMS) {
394
+ throw new Error(`limits.pageSize must be <= ${GOOGLE_DRIVE_MAX_PAGE_ITEMS}`);
395
+ }
396
+ if (limits.maxFolders > GOOGLE_DRIVE_MAX_CHECKPOINT_FOLDERS) {
397
+ throw new Error(`limits.maxFolders must be <= ${GOOGLE_DRIVE_MAX_CHECKPOINT_FOLDERS}`);
398
+ }
399
+ return limits;
400
+ }
401
+ function validPage(value, expectedMaxItems) {
402
+ if (!value || !Array.isArray(value.items) || value.items.length > expectedMaxItems || value.items.length > GOOGLE_DRIVE_MAX_PAGE_ITEMS) {
403
+ return false;
404
+ }
405
+ try {
406
+ pageToken(value.nextPageToken, "page.nextPageToken");
407
+ value.items.forEach(validatedProviderItem);
408
+ return typeof value.incompleteSearch === "boolean";
409
+ } catch {
410
+ return false;
411
+ }
412
+ }
413
+ function validatedProviderItem(item) {
414
+ const id = driveId(item.id, "item.id");
415
+ const name = boundedText(item.name, "item.name", GOOGLE_DRIVE_MAX_NAME_CHARS);
416
+ const mimeType = boundedText(item.mimeType, "item.mimeType", GOOGLE_DRIVE_MAX_MIME_CHARS);
417
+ const parents = Array.isArray(item.parents) ? item.parents.map((parent) => driveId(parent, "item.parent")) : [];
418
+ if (parents.length > 100) throw new Error("item.parents exceeds the supported bound");
419
+ return {
420
+ id,
421
+ name,
422
+ mimeType,
423
+ driveId: nullableDriveId(item.driveId, "item.driveId"),
424
+ parents,
425
+ modifiedTime: nullableBoundedText(item.modifiedTime, "item.modifiedTime", 128),
426
+ createdTime: nullableBoundedText(item.createdTime, "item.createdTime", 128),
427
+ version: nullableBoundedText(item.version, "item.version", 256),
428
+ md5Checksum: nullableBoundedText(item.md5Checksum, "item.md5Checksum", 128),
429
+ size: fileSize(item.size)?.toString() ?? null,
430
+ webViewLink: nullableHttpsUrl(item.webViewLink, "item.webViewLink"),
431
+ trashed: item.trashed === true
432
+ };
433
+ }
434
+ function dependencyFreeOrdinaryContentType(name, mimeType) {
435
+ const normalizedMime = mimeType.trim().toLowerCase();
436
+ if (normalizedMime.startsWith("text/")) return normalizedMime;
437
+ if (DEPENDENCY_FREE_ORDINARY_CONTENT_TYPES.has(normalizedMime)) return normalizedMime;
438
+ if (!GENERIC_BINARY_CONTENT_TYPES.has(normalizedMime)) return null;
439
+ const lowerName = name.toLowerCase();
440
+ for (const [extension, contentType] of DEPENDENCY_FREE_EXTENSION_CONTENT_TYPES) {
441
+ if (lowerName.endsWith(extension)) return contentType;
442
+ }
443
+ return null;
444
+ }
445
+ function exportedFilename(name, extension) {
446
+ const filename = safeFilename(name);
447
+ return filename.toLowerCase().endsWith(extension) ? filename : `${filename}${extension}`;
448
+ }
449
+ function safeFilename(value) {
450
+ const cleaned = value.normalize("NFKC").replace(/[\u0000-\u001f\u007f/\\]/gu, " ").replace(/\s+/gu, " ").trim().slice(0, 512);
451
+ return cleaned || "untitled";
452
+ }
453
+ function googleDriveSourceUri(id) {
454
+ return id === "root" ? "https://drive.google.com/drive/my-drive" : `https://drive.google.com/drive/folders/${encodeURIComponent(id)}`;
455
+ }
456
+ function googleDriveFileUri(id) {
457
+ return `https://drive.google.com/open?id=${encodeURIComponent(id)}`;
458
+ }
459
+ function fileSize(value) {
460
+ if (value === null) return null;
461
+ if (!/^\d{1,40}$/u.test(value)) throw new Error("item.size is invalid");
462
+ return BigInt(value);
463
+ }
464
+ function providerErrorCode(error) {
465
+ if (!(error instanceof GoogleDriveInventoryProviderError)) return null;
466
+ const normalized = error.providerCode.trim().toLowerCase();
467
+ return /^[a-z0-9](?:[a-z0-9._-]{0,126}[a-z0-9])?$/u.test(normalized) ? normalized : null;
468
+ }
469
+ function driveId(value, label) {
470
+ const candidate = boundedText(value, label, GOOGLE_DRIVE_MAX_ID_CHARS);
471
+ if (candidate === "root" || /^[A-Za-z0-9_-]+$/u.test(candidate)) return candidate;
472
+ throw new Error(`${label} is invalid`);
473
+ }
474
+ function normalizedGooglePermissionId(value) {
475
+ return boundedText(value, "googlePermissionId", GOOGLE_DRIVE_MAX_ID_CHARS);
476
+ }
477
+ function nullableDriveId(value, label) {
478
+ return value === null ? null : driveId(value, label);
479
+ }
480
+ function pageToken(value, label) {
481
+ if (value === null) return null;
482
+ return boundedText(value, label, GOOGLE_DRIVE_MAX_PAGE_TOKEN_CHARS);
483
+ }
484
+ function boundedText(value, label, maxChars) {
485
+ if (typeof value !== "string") throw new Error(`${label} must be a string`);
486
+ const trimmed = value.trim();
487
+ if (!trimmed || trimmed.length > maxChars || /[\u0000-\u001f\u007f]/u.test(trimmed)) {
488
+ throw new Error(`${label} is invalid`);
489
+ }
490
+ return trimmed;
491
+ }
492
+ function nullableBoundedText(value, label, maxChars) {
493
+ return value === null ? null : boundedText(value, label, maxChars);
494
+ }
495
+ function nullableHttpsUrl(value, label) {
496
+ if (value === null) return null;
497
+ const bounded = boundedText(value, label, 4096);
498
+ const parsed = new URL(bounded);
499
+ if (parsed.protocol !== "https:") throw new Error(`${label} must use https`);
500
+ return parsed.toString();
501
+ }
502
+ function safePositiveInteger(value, label) {
503
+ if (!Number.isSafeInteger(value) || value <= 0) {
504
+ throw new Error(`${label} must be a positive safe integer`);
505
+ }
506
+ return value;
507
+ }
508
+ function validatedTotals(totals) {
509
+ for (const [key, value] of Object.entries(totals)) {
510
+ if (key === "knownBytes") continue;
511
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
512
+ throw new Error(`checkpoint.totals.${key} is invalid`);
513
+ }
514
+ }
515
+ if (!/^\d+$/u.test(totals.knownBytes)) {
516
+ throw new Error("checkpoint.totals.knownBytes is invalid");
517
+ }
518
+ }
519
+ function emptyTotals() {
520
+ return {
521
+ itemCount: 0,
522
+ folderCount: 1,
523
+ plannedFileCount: 0,
524
+ skippedItemCount: 0,
525
+ exportFileCount: 0,
526
+ downloadFileCount: 0,
527
+ unknownSizeFileCount: 0,
528
+ apiRequestCount: 0,
529
+ knownBytes: "0"
530
+ };
531
+ }
532
+ function cloneTotals(value) {
533
+ return { ...value };
534
+ }
535
+ function subtractTotals(value, initial) {
536
+ return {
537
+ itemCount: value.itemCount - initial.itemCount,
538
+ folderCount: value.folderCount - initial.folderCount,
539
+ plannedFileCount: value.plannedFileCount - initial.plannedFileCount,
540
+ skippedItemCount: value.skippedItemCount - initial.skippedItemCount,
541
+ exportFileCount: value.exportFileCount - initial.exportFileCount,
542
+ downloadFileCount: value.downloadFileCount - initial.downloadFileCount,
543
+ unknownSizeFileCount: value.unknownSizeFileCount - initial.unknownSizeFileCount,
544
+ apiRequestCount: value.apiRequestCount - initial.apiRequestCount,
545
+ knownBytes: (BigInt(value.knownBytes) - BigInt(initial.knownBytes)).toString()
546
+ };
547
+ }
548
+ function cloneProviderItem(value) {
549
+ return { ...value, parents: [...value.parents] };
550
+ }
551
+ function cloneScope(scope) {
552
+ return { ...scope };
553
+ }
554
+ function cloneCheckpoint(value) {
555
+ return {
556
+ version: 2,
557
+ googlePermissionId: value.googlePermissionId,
558
+ externalTenantId: value.externalTenantId,
559
+ sourceId: value.sourceId,
560
+ sourceDriveId: value.sourceDriveId,
561
+ scope: cloneScope(value.scope),
562
+ pendingFolders: value.pendingFolders.map((frame) => ({
563
+ ...frame,
564
+ bufferedItems: frame.bufferedItems.map(cloneProviderItem)
565
+ })),
566
+ seenFolderIds: [...value.seenFolderIds],
567
+ totals: cloneTotals(value.totals)
568
+ };
569
+ }
570
+ function sameScope(left, right) {
571
+ return !!left && typeof left === "object" && left.kind === right.kind && left.workspaceId === right.workspaceId && left.subjectId === right.subjectId;
572
+ }
573
+ function assertCheckpointBytes(checkpoint) {
574
+ if (Buffer.byteLength(JSON.stringify(checkpoint), "utf8") > GOOGLE_DRIVE_MAX_CHECKPOINT_BYTES) {
575
+ throw new Error("Google Drive inventory checkpoint exceeds the serialized byte limit");
576
+ }
577
+ }
578
+ export {
579
+ GOOGLE_DRIVE_FOLDER_MIME_TYPE,
580
+ GOOGLE_DRIVE_PROVIDER_KEY,
581
+ GOOGLE_DRIVE_SHORTCUT_MIME_TYPE,
582
+ GoogleDriveInventoryProviderError,
583
+ googleDriveKnowledgeScope,
584
+ googleDriveKnowledgeSourceIdentity,
585
+ inventoryGoogleDriveSource,
586
+ planGoogleDriveTransfer
587
+ };
588
+ //# sourceMappingURL=google-drive.js.map