@tearleads/client-sdk 0.1.23 → 0.1.25
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/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -0
- package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
- package/data/persistence/container-contents/containerDeletionPersistence.js +3 -0
- package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
- package/data/persistence/container-contents/documentPurgePlacement.js +15 -0
- package/data/persistence/container-contents/documentPurgePlacement.js.map +1 -0
- package/data/persistence/documents/documentsPersistence.js +7 -0
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +7 -0
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/orphanBlobPersistence.d.ts +13 -0
- package/data/persistence/documents/orphanBlobPersistence.js +2 -0
- package/data/persistence/documents/orphanBlobPersistence.js.map +1 -0
- package/data/persistence/documents/types.d.ts +4 -1
- package/data/persistence/documents/types.js.map +1 -1
- package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +13 -2
- package/data/persistence/principalCurrentAcknowledgementPersistence.js +36 -20
- package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
- package/index.d.ts +2 -2
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +6 -2
- package/internal/api-client/ApiClient.js +4 -5
- package/internal/api-client/ApiClient.js.map +1 -1
- package/internal/api-client/apiRequestRuntime.d.ts +1 -2
- package/internal/api-client/apiRequestRuntime.js +12 -15
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/routes/containers/mutations.js +2 -2
- package/internal/api-client/routes/containers/mutations.js.map +1 -1
- package/internal/api-client/sessionRefresh.js +14 -6
- package/internal/api-client/sessionRefresh.js.map +1 -1
- package/internal/api-client/sessionRenewal.js +54 -0
- package/internal/api-client/sessionRenewal.js.map +1 -0
- package/internal/validators/operation/containerMutations.d.ts +3 -0
- package/internal/validators/operation/containerMutations.js +1 -0
- package/internal/validators/operation/containerMutations.js.map +1 -1
- package/package.json +1 -1
- package/stores/documents/documentStore/attachmentHydration.js +2 -2
- package/stores/documents/documentStore/attachmentHydration.js.map +1 -1
- package/stores/documents/documentStore/attachments.js +7 -5
- package/stores/documents/documentStore/attachments.js.map +1 -1
- package/stores/documents/documentStore/discard.js +3 -2
- package/stores/documents/documentStore/discard.js.map +1 -1
- package/stores/documents/documentStore/orphanMaintenance.js +3 -5
- package/stores/documents/documentStore/orphanMaintenance.js.map +1 -1
- package/stores/documents/documentStore/persistence.js +3 -4
- package/stores/documents/documentStore/persistence.js.map +1 -1
- package/stores/documents/documentStore/syncDetachedAttachments.js +3 -2
- package/stores/documents/documentStore/syncDetachedAttachments.js.map +1 -1
- package/stores/documents/documentStore/syncRequest.js +3 -4
- package/stores/documents/documentStore/syncRequest.js.map +1 -1
- package/workflows/container-contents/container-state/delete.js +2 -0
- package/workflows/container-contents/container-state/delete.js.map +1 -1
- package/workflows/container-contents/container-state/localPurgeScope.js +49 -0
- package/workflows/container-contents/container-state/localPurgeScope.js.map +1 -0
- package/workflows/container-contents/container-state/purgeTree.js +42 -7
- package/workflows/container-contents/container-state/purgeTree.js.map +1 -1
- package/workflows/container-contents/container-state/purgeTreeCollection.js +11 -0
- package/workflows/container-contents/container-state/purgeTreeCollection.js.map +1 -1
- package/workflows/container-contents/container-state/purgeTreeContainerDeletion.js +4 -1
- package/workflows/container-contents/container-state/purgeTreeContainerDeletion.js.map +1 -1
- package/workflows/container-contents/container-state/purgeTreeScope.js +158 -0
- package/workflows/container-contents/container-state/purgeTreeScope.js.map +1 -0
- package/workflows/container-contents/container-state/readLocalPurgeScope.js +18 -0
- package/workflows/container-contents/container-state/readLocalPurgeScope.js.map +1 -0
- package/workflows/container-contents/container-state/remote.js +1 -0
- package/workflows/container-contents/container-state/remote.js.map +1 -1
- package/workflows/container-contents/container-state/types.js.map +1 -1
- package/workflows/container-contents/documentLinks.d.ts +4 -0
- package/workflows/container-contents/documentLinks.js +2 -0
- package/workflows/container-contents/documentLinks.js.map +1 -1
- package/workflows/container-contents/documentPurge.d.ts +6 -1
- package/workflows/container-contents/documentPurge.js +12 -5
- package/workflows/container-contents/documentPurge.js.map +1 -1
- package/workflows/documents/linkSet.d.ts +1 -0
- package/workflows/documents/linkSet.js +2 -0
- package/workflows/documents/linkSet.js.map +1 -1
- package/workflows/documents/linkSetRemote.d.ts +2 -0
- package/workflows/documents/linkSetRemote.js +3 -0
- package/workflows/documents/linkSetRemote.js.map +1 -1
- package/workflows/documents/orphanBlobReclaimState.js +20 -0
- package/workflows/documents/orphanBlobReclaimState.js.map +1 -0
- package/workflows/documents/orphanBlobReclaims.d.ts +3 -2
- package/workflows/documents/orphanBlobReclaims.js +49 -47
- package/workflows/documents/orphanBlobReclaims.js.map +1 -1
- package/workflows/documents/purge.d.ts +3 -0
- package/workflows/documents/purge.js +7 -0
- package/workflows/documents/purge.js.map +1 -1
- package/workflows/documents/subtreePurgeScope.js +11 -0
- package/workflows/documents/subtreePurgeScope.js.map +1 -0
- package/workflows/organizations/acknowledgedPrincipalPredecessor.d.ts +39 -0
- package/workflows/organizations/acknowledgedPrincipalPredecessor.js +87 -0
- package/workflows/organizations/acknowledgedPrincipalPredecessor.js.map +1 -0
- package/workflows/organizations/currentOrganizationMutationRetention.js +13 -2
- package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -1
- package/workflows/organizations/index.d.ts +1 -0
- package/workflows/organizations/index.js +1 -0
- package/workflows/organizations/index.js.map +1 -1
- package/workflows/organizations/initialPrincipalCurrentPublication.js +3 -2
- package/workflows/organizations/initialPrincipalCurrentPublication.js.map +1 -1
- package/workflows/organizations/reconcileAcknowledgedPrincipalCurrent.js +63 -0
- package/workflows/organizations/reconcileAcknowledgedPrincipalCurrent.js.map +1 -0
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +3 -0
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +33 -55
- package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
- package/workflows/organizations/runtimeCurrentGroupMutation.js +13 -2
- package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -1
- package/workflows/organizations/runtimeCurrentOrganizationMutation.js +2 -2
- package/workflows/organizations/runtimeCurrentOrganizationMutation.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apiRequestRuntime.js","sourceRoot":"","sources":["apiRequestRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAiBlE,MAAM,OAAO,iBAAiB;IACpB,SAAS,GAAkB,IAAI,CAAC;IAChC,cAAc,GAAwC,IAAI,CAAC;IAClD,OAAO,CAAS;IACzB,OAAO,GAAuC,IAAI,CAAC;IACnD,cAAc,GAAwB,IAAI,CAAC;IAC3C,gBAAgB,GAAwB,IAAI,CAAC;IAC7C,YAAY,GAAuC,IAAI,CAAC;IACxD,gBAAgB,GAA0B,IAAI,CAAC;IAC/C,iBAAiB,GAAkC,IAAI,CAAC;IAC/C,oBAAoB,GAAG,IAAI,GAAG,EAA0B,CAAC;IACjE,OAAO,CAAqB;IAC5B,aAAa,CAA2B;IACxC,eAAe,CAA6B;IAErD,YAAY,OAAuB;QACjC,IAAI,CAAC,OAAO,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;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QAAQ,CAAC,MAAM;YAC7B,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU;SACtC,CAAC,CAAC;IACL,CAAC;IAEO,4BAA4B,CAClC,KAA4C;QAE5C,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC7B,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;QAC1B,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;YACzB,GAAG,KAAK;YACR,YAAY,EAAE,KAAK,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI;YACjD,mBAAmB,EAAE,SAAS;SAC/B,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n authChallengeSigningBytes,\n canonicalAuthOrigin,\n} from \"@tearleads/crypto\";\nimport {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n errorMessage,\n hasHeader,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport type {\n HttpMethod,\n OperationRequestFn,\n OperationRequestResultFn,\n OperationResponseRequestFn,\n RequestBody,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n ResponseRequestValidationFailureInput,\n} from \"./types\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\nexport class ApiRequestRuntime {\n private authToken: string | null = null;\n private sessionRenewal: { from: string; to: string } | null = null;\n private readonly baseUrl: string;\n private onError: ((message: string) => void) | null = null;\n private onNetworkError: (() => void) | null = null;\n private onNetworkSuccess: (() => void) | null = null;\n private onApiVersion: ((version: number) => void) | null = null;\n private onSessionExpired: ExpiredHandler | null = null;\n private onPaymentRequired: PaymentRequiredHandler | null = null;\n private readonly requestFailuresByKey = new Map<string, RequestFailure>();\n readonly request: OperationRequestFn;\n readonly requestResult: OperationRequestResultFn;\n readonly responseRequest: OperationResponseRequestFn;\n\n constructor(baseUrl?: string | null) {\n this.baseUrl = normalizeApiBaseUrl(baseUrl);\n bindPrototypeMethods(this, ApiRequestRuntime.prototype);\n this.request = this.makeRequest;\n this.requestResult = this.makeRequestResult;\n this.responseRequest = Object.assign(this.makeResponseRequest, {\n reportFailure: this.reportResponseRequestFailure,\n });\n }\n\n /**\n * The bytes a login challenge is signed as, bound to the API this client\n * addresses. A relative base URL resolves against the page, as its requests\n * do; with neither, there is no API origin to sign for.\n */\n authChallengeBytes(challengeHex: string, fingerprint: string): Uint8Array {\n let apiOrigin: string;\n try {\n apiOrigin = canonicalAuthOrigin(\n new URL(this.baseUrl || \"/\", globalThis.location?.href).href,\n );\n } catch {\n throw new Error(\"The API origin is unavailable for authentication\");\n }\n return authChallengeSigningBytes({ apiOrigin, challengeHex, fingerprint });\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.onNetworkError = handler;\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.onNetworkSuccess = handler;\n }\n\n /** Receives the build named by each response that carries one. */\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.onApiVersion = handler;\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.onSessionExpired = handler;\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.onPaymentRequired = handler;\n }\n\n setAuthToken(token: string | null): boolean {\n const changed = this.authToken !== token;\n if (changed) this.sessionRenewal = null;\n this.authToken = token;\n return changed;\n }\n\n getAuthToken(): string | null {\n return this.authToken;\n }\n\n private async renewSession(): Promise<boolean> {\n const from = this.authToken;\n const renewed = await (this.onSessionExpired?.() ?? false);\n const to = this.authToken;\n if (renewed && from && to && from !== to)\n this.sessionRenewal = { from, to };\n return renewed;\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;\n }\n\n private buildHeaders(\n body: RequestBody | undefined,\n headers: Record<string, string> | undefined,\n authToken: string | null,\n ): Record<string, string> {\n return {\n ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),\n ...(typeof body === \"string\" && !hasHeader(headers, \"Content-Type\")\n ? { \"Content-Type\": \"application/json\" }\n : {}),\n ...headers,\n };\n }\n\n private async makeRequest<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<T | null> {\n const result = await this.makeRequestResult(\n path,\n validator,\n method,\n body,\n options,\n failureOperation,\n );\n return result.ok ? result.data : null;\n }\n\n private requestFailure(input: {\n code?: string | undefined;\n kind: RequestFailureKind;\n message: string;\n method: HttpMethod;\n path: string;\n reportErrors: boolean;\n requiredContainerIds?: RequestFailure[\"requiredContainerIds\"];\n stalePrincipalHeads: RequestFailure[\"stalePrincipalHeads\"];\n status: number | null;\n statusText: string;\n }): RequestFailure {\n const failure: RequestFailure = {\n ...(input.code === undefined ? {} : { code: input.code }),\n kind: input.kind,\n message: input.message,\n method: input.method,\n ok: false,\n path: input.path,\n report: () => {\n if (input.kind !== \"cancelled\") this.onError?.(input.message);\n },\n status: input.status,\n statusText: input.statusText,\n ...(input.stalePrincipalHeads\n ? { stalePrincipalHeads: input.stalePrincipalHeads }\n : {}),\n ...(input.requiredContainerIds\n ? { requiredContainerIds: input.requiredContainerIds }\n : {}),\n };\n this.requestFailuresByKey.set(\n requestFailureKey({ method: input.method, path: input.path }),\n failure,\n );\n\n if (input.reportErrors) {\n failure.report();\n }\n\n return failure;\n }\n\n private async makeRequestResult<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions = {},\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\n const responseResult = await this.makeResponseRequest(\n path,\n method,\n body,\n options,\n [],\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n\n const response = responseResult.data;\n const reportErrors = options.reportErrors ?? true;\n let data: unknown;\n try {\n data = await response.json();\n } catch (error) {\n const failure = responseBodyFailure(error, errorMessage(error));\n if (failure.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n kind: failure.kind,\n message: `${method} ${path}: ${failure.message}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n if (!validator(data)) {\n return this.requestFailure({\n kind: \"shape\",\n message: `Invalid response shape for ${path}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return { data, ok: true };\n }\n\n private async makeResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions = {},\n additionalSuccessStatuses: readonly number[],\n failureOperation: Parameters<OperationResponseRequestFn>[5],\n ): Promise<RequestResult<Response>> {\n const authToken = this.authToken;\n const responseResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n const response = responseResult.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: response, ok: true };\n }\n\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\n if (\n await shouldRetryAfterSessionExpired({\n authToken,\n body,\n code: errorDescription.code,\n getCurrentAuthToken: () => this.authToken,\n isKnownSessionRenewal: (from, to) =>\n this.sessionRenewal?.from === from && this.sessionRenewal.to === to,\n options,\n refreshSession: () => this.renewSession(),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n })\n ) {\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n path,\n response,\n });\n const retryResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n this.authToken,\n );\n if (!retryResult.ok) {\n return retryResult;\n }\n const retryResponse = retryResult.data;\n if (isSuccessfulResponse(retryResponse, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: retryResponse, ok: true };\n }\n\n return this.httpFailure({\n errorDescription: await describeErrorResponse(\n retryResponse,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n ),\n failureOperation,\n method,\n options,\n path,\n response: retryResponse,\n });\n }\n\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\n });\n }\n\n private async fetchResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n ): Promise<RequestResult<Response>> {\n const reportErrors = options.reportErrors ?? true;\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: this.buildHeaders(body, options.headers, authToken),\n ...(options.signal ? { signal: options.signal } : {}),\n };\n if (body !== undefined) {\n init.body = body;\n if (body instanceof ReadableStream) {\n init.duplex = \"half\";\n }\n }\n\n let response: Response;\n try {\n response = await fetch(`${this.baseUrl}${path}`, init);\n } catch (error) {\n const cancelled = options.signal?.aborted === true;\n if (!cancelled) this.onNetworkError?.();\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${errorMessage(error)}`,\n method,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\n this.onNetworkSuccess?.();\n const apiVersion = parseApiVersion(\n response.headers.get(apiVersionHeaderName),\n );\n if (apiVersion !== null) this.onApiVersion?.(apiVersion);\n return { data: response, ok: true };\n }\n\n private httpFailure(input: {\n readonly errorDescription: ErrorResponseDescription;\n readonly failureOperation: Parameters<OperationResponseRequestFn>[5];\n readonly method: HttpMethod;\n readonly options: RequestResultOptions;\n readonly path: string;\n readonly response: Response;\n }): RequestFailure {\n const cancelled = input.options.signal?.aborted === true;\n const reportErrors = input.options.reportErrors ?? true;\n if (\n !cancelled &&\n input.response.status === 402 &&\n input.failureOperation.failureResponses?.[402] &&\n input.errorDescription.paymentRequiredOrganizationId !== undefined &&\n input.errorDescription.paymentRequiredOrganizationId ===\n input.options.expectedPaymentRequiredOrganizationId\n ) {\n this.onPaymentRequired?.(\n input.errorDescription.paymentRequiredOrganizationId,\n );\n }\n return this.requestFailure({\n ...(cancelled\n ? { code: \"request_aborted\" }\n : input.errorDescription.code === null\n ? {}\n : { code: input.errorDescription.code }),\n kind: cancelled ? \"cancelled\" : \"http\",\n message: `${input.method} ${input.path}: ${input.response.status} ${input.response.statusText}${input.errorDescription.detail}`,\n method: input.method,\n path: input.path,\n reportErrors: !cancelled && reportErrors,\n requiredContainerIds: input.errorDescription.requiredContainerIds,\n stalePrincipalHeads: input.errorDescription.stalePrincipalHeads,\n status: input.response.status,\n statusText: input.response.statusText,\n });\n }\n\n private reportResponseRequestFailure(\n input: ResponseRequestValidationFailureInput,\n ): RequestFailure {\n if (input.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n ...input,\n reportErrors: input.options?.reportErrors ?? true,\n stalePrincipalHeads: undefined,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"apiRequestRuntime.js","sourceRoot":"","sources":["apiRequestRuntime.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,GAChB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,oBAAoB,EACpB,qBAAqB,EAErB,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,mBAAmB,EACnB,iBAAiB,GAClB,MAA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AC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;YAC5C,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM;YACtC,OAAO,EAAE,GAAG,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,UAAU,GAAG,KAAK,CAAC,gBAAgB,CAAC,MAAM,EAAE;YAC/H,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,YAAY,EAAE,CAAC,SAAS,IAAI,YAAY;YACxC,oBAAoB,EAAE,KAAK,CAAC,gBAAgB,CAAC,oBAAoB;YACjE,mBAAmB,EAAE,KAAK,CAAC,gBAAgB,CAAC,mBAAmB;YAC/D,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,MAAM;YAC7B,UAAU,EAAE,KAAK,CAAC,QAAQ,CAAC,UAAU;SACtC,CAAC,CAAC;IACL,CAAC;IAEO,4BAA4B,CAClC,KAA4C;QAE5C,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC7B,IAAI,CAAC,cAAc,EAAE,EAAE,CAAC;QAC1B,CAAC;QACD,OAAO,IAAI,CAAC,cAAc,CAAC;YACzB,GAAG,KAAK;YACR,YAAY,EAAE,KAAK,CAAC,OAAO,EAAE,YAAY,IAAI,IAAI;YACjD,mBAAmB,EAAE,SAAS;SAC/B,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n authChallengeSigningBytes,\n canonicalAuthOrigin,\n} from \"@tearleads/crypto\";\nimport {\n apiVersionHeaderName,\n parseApiVersion,\n} from \"@tearleads/validators/operation\";\nimport {\n bindPrototypeMethods,\n describeErrorResponse,\n type ErrorResponseDescription,\n errorMessage,\n hasHeader,\n isSuccessfulResponse,\n normalizeApiBaseUrl,\n requestFailureKey,\n} from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport { shouldRetryAfterSessionExpired } from \"./sessionRefresh\";\nimport { SessionRenewalTracker } from \"./sessionRenewal\";\nimport type {\n HttpMethod,\n OperationRequestFn,\n OperationRequestResultFn,\n OperationResponseRequestFn,\n RequestBody,\n RequestFailure,\n RequestFailureKind,\n RequestResult,\n RequestResultOptions,\n ResponseRequestValidationFailureInput,\n} from \"./types\";\n\ntype ExpiredHandler = () => boolean | Promise<boolean>;\ntype PaymentRequiredHandler = (organizationId: string | null) => void;\n\nexport class ApiRequestRuntime {\n private authToken: string | null = null;\n private readonly sessionRenewals = new SessionRenewalTracker(\n () => this.authToken,\n );\n private readonly baseUrl: string;\n private onError: ((message: string) => void) | null = null;\n private onNetworkError: (() => void) | null = null;\n private onNetworkSuccess: (() => void) | null = null;\n private onApiVersion: ((version: number) => void) | null = null;\n private onSessionExpired: ExpiredHandler | null = null;\n private onPaymentRequired: PaymentRequiredHandler | null = null;\n private readonly requestFailuresByKey = new Map<string, RequestFailure>();\n readonly request: OperationRequestFn;\n readonly requestResult: OperationRequestResultFn;\n readonly responseRequest: OperationResponseRequestFn;\n\n constructor(baseUrl?: string | null) {\n this.baseUrl = normalizeApiBaseUrl(baseUrl);\n bindPrototypeMethods(this, ApiRequestRuntime.prototype);\n this.request = this.makeRequest;\n this.requestResult = this.makeRequestResult;\n this.responseRequest = Object.assign(this.makeResponseRequest, {\n reportFailure: this.reportResponseRequestFailure,\n });\n }\n\n /**\n * The bytes a login challenge is signed as, bound to the API this client\n * addresses. A relative base URL resolves against the page, as its requests\n * do; with neither, there is no API origin to sign for.\n */\n authChallengeBytes(challengeHex: string, fingerprint: string): Uint8Array {\n let apiOrigin: string;\n try {\n apiOrigin = canonicalAuthOrigin(\n new URL(this.baseUrl || \"/\", globalThis.location?.href).href,\n );\n } catch {\n throw new Error(\"The API origin is unavailable for authentication\");\n }\n return authChallengeSigningBytes({ apiOrigin, challengeHex, fingerprint });\n }\n\n setOnError(handler: ((message: string) => void) | null): void {\n this.onError = handler;\n }\n\n setOnNetworkError(handler: (() => void) | null): void {\n this.onNetworkError = handler;\n }\n\n setOnNetworkSuccess(handler: (() => void) | null): void {\n this.onNetworkSuccess = handler;\n }\n\n /** Receives the build named by each response that carries one. */\n setOnApiVersion(handler: ((version: number) => void) | null): void {\n this.onApiVersion = handler;\n }\n\n setOnSessionExpired(handler: ExpiredHandler | null): void {\n this.onSessionExpired = handler;\n }\n\n setOnPaymentRequired(handler: PaymentRequiredHandler | null): void {\n this.onPaymentRequired = handler;\n }\n\n setAuthToken(token: string | null): boolean {\n const changed = this.authToken !== token;\n if (changed) this.sessionRenewals.tokenChanged();\n this.authToken = token;\n return changed;\n }\n\n getAuthToken(): string | null {\n return this.authToken;\n }\n\n getRequestFailure(input: { method: HttpMethod; path: string }) {\n return this.requestFailuresByKey.get(requestFailureKey(input)) ?? null;\n }\n\n private buildHeaders(\n body: RequestBody | undefined,\n headers: Record<string, string> | undefined,\n authToken: string | null,\n ): Record<string, string> {\n return {\n ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),\n ...(typeof body === \"string\" && !hasHeader(headers, \"Content-Type\")\n ? { \"Content-Type\": \"application/json\" }\n : {}),\n ...headers,\n };\n }\n\n private async makeRequest<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<T | null> {\n const result = await this.makeRequestResult(\n path,\n validator,\n method,\n body,\n options,\n failureOperation,\n );\n return result.ok ? result.data : null;\n }\n\n private requestFailure(input: {\n code?: string | undefined;\n kind: RequestFailureKind;\n message: string;\n method: HttpMethod;\n path: string;\n reportErrors: boolean;\n requiredContainerIds?: RequestFailure[\"requiredContainerIds\"];\n stalePrincipalHeads: RequestFailure[\"stalePrincipalHeads\"];\n status: number | null;\n statusText: string;\n }): RequestFailure {\n const failure: RequestFailure = {\n ...(input.code === undefined ? {} : { code: input.code }),\n kind: input.kind,\n message: input.message,\n method: input.method,\n ok: false,\n path: input.path,\n report: () => {\n if (input.kind !== \"cancelled\") this.onError?.(input.message);\n },\n status: input.status,\n statusText: input.statusText,\n ...(input.stalePrincipalHeads\n ? { stalePrincipalHeads: input.stalePrincipalHeads }\n : {}),\n ...(input.requiredContainerIds\n ? { requiredContainerIds: input.requiredContainerIds }\n : {}),\n };\n this.requestFailuresByKey.set(\n requestFailureKey({ method: input.method, path: input.path }),\n failure,\n );\n\n if (input.reportErrors) {\n failure.report();\n }\n\n return failure;\n }\n\n private async makeRequestResult<T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions = {},\n failureOperation: Parameters<OperationRequestFn>[5],\n ): Promise<RequestResult<T>> {\n const responseResult = await this.makeResponseRequest(\n path,\n method,\n body,\n options,\n [],\n failureOperation,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n\n const response = responseResult.data;\n const reportErrors = options.reportErrors ?? true;\n let data: unknown;\n try {\n data = await response.json();\n } catch (error) {\n const failure = responseBodyFailure(error, errorMessage(error));\n if (failure.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n kind: failure.kind,\n message: `${method} ${path}: ${failure.message}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n if (!validator(data)) {\n return this.requestFailure({\n kind: \"shape\",\n message: `Invalid response shape for ${path}`,\n method,\n path,\n reportErrors,\n stalePrincipalHeads: undefined,\n status: response.status,\n statusText: response.statusText,\n });\n }\n\n return { data, ok: true };\n }\n\n private async makeResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions = {},\n additionalSuccessStatuses: readonly number[],\n failureOperation: Parameters<OperationResponseRequestFn>[5],\n ): Promise<RequestResult<Response>> {\n const authToken = this.authToken;\n const responseResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n authToken,\n );\n if (!responseResult.ok) {\n return responseResult;\n }\n const response = responseResult.data;\n if (isSuccessfulResponse(response, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: response, ok: true };\n }\n\n const errorDescription = await describeErrorResponse(\n response,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n );\n const shouldRetry = await shouldRetryAfterSessionExpired({\n authToken,\n body,\n code: errorDescription.code,\n getCurrentAuthToken: () => this.authToken,\n isKnownSessionRenewal: (from, to) =>\n this.sessionRenewals.isKnown(from, to),\n pendingSessionRenewal: (from) => this.sessionRenewals.pending(from),\n options,\n refreshSession: () => this.sessionRenewals.renew(this.onSessionExpired),\n reportError: (message) => this.onError?.(message),\n responseStatus: response.status,\n });\n const retryAuthToken = this.sessionRenewals.currentToken(authToken);\n // Recheck after the awaited helper and the host's renewal notification.\n if (shouldRetry && retryAuthToken) {\n if (options.retryOnSessionExpired === \"renew-only\")\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options: {\n ...options,\n reportErrors: method === \"GET\" ? false : options.reportErrors,\n },\n path,\n response,\n });\n const retryResult = await this.fetchResponseRequest(\n path,\n method,\n body,\n options,\n retryAuthToken,\n );\n if (!retryResult.ok) {\n return retryResult;\n }\n const retryResponse = retryResult.data;\n if (isSuccessfulResponse(retryResponse, additionalSuccessStatuses)) {\n this.requestFailuresByKey.delete(requestFailureKey({ method, path }));\n return { data: retryResponse, ok: true };\n }\n\n return this.httpFailure({\n errorDescription: await describeErrorResponse(\n retryResponse,\n failureOperation,\n options.expectedPaymentRequiredOrganizationId,\n ),\n failureOperation,\n method,\n options,\n path,\n response: retryResponse,\n });\n }\n\n return this.httpFailure({\n errorDescription,\n failureOperation,\n method,\n options,\n path,\n response,\n });\n }\n\n private async fetchResponseRequest(\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n authToken: string | null,\n ): Promise<RequestResult<Response>> {\n const reportErrors = options.reportErrors ?? true;\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: this.buildHeaders(body, options.headers, authToken),\n ...(options.signal ? { signal: options.signal } : {}),\n };\n if (body !== undefined) {\n init.body = body;\n if (body instanceof ReadableStream) {\n init.duplex = \"half\";\n }\n }\n\n let response: Response;\n try {\n response = await fetch(`${this.baseUrl}${path}`, init);\n } catch (error) {\n const cancelled = options.signal?.aborted === true;\n if (!cancelled) this.onNetworkError?.();\n return this.requestFailure({\n ...(cancelled ? { code: \"request_aborted\" } : {}),\n kind: cancelled ? \"cancelled\" : \"network\",\n message: `${method} ${path}: ${errorMessage(error)}`,\n method,\n path,\n reportErrors: cancelled ? false : reportErrors,\n stalePrincipalHeads: undefined,\n status: null,\n statusText: \"\",\n });\n }\n\n this.onNetworkSuccess?.();\n const apiVersion = parseApiVersion(\n response.headers.get(apiVersionHeaderName),\n );\n if (apiVersion !== null) this.onApiVersion?.(apiVersion);\n return { data: response, ok: true };\n }\n\n private httpFailure(input: {\n readonly errorDescription: ErrorResponseDescription;\n readonly failureOperation: Parameters<OperationResponseRequestFn>[5];\n readonly method: HttpMethod;\n readonly options: RequestResultOptions;\n readonly path: string;\n readonly response: Response;\n }): RequestFailure {\n const cancelled = input.options.signal?.aborted === true;\n const reportErrors = input.options.reportErrors ?? true;\n if (\n !cancelled &&\n input.response.status === 402 &&\n input.failureOperation.failureResponses?.[402] &&\n input.errorDescription.paymentRequiredOrganizationId !== undefined &&\n input.errorDescription.paymentRequiredOrganizationId ===\n input.options.expectedPaymentRequiredOrganizationId\n ) {\n this.onPaymentRequired?.(\n input.errorDescription.paymentRequiredOrganizationId,\n );\n }\n return this.requestFailure({\n ...(cancelled\n ? { code: \"request_aborted\" }\n : input.errorDescription.code === null\n ? {}\n : { code: input.errorDescription.code }),\n kind: cancelled ? \"cancelled\" : \"http\",\n message: `${input.method} ${input.path}: ${input.response.status} ${input.response.statusText}${input.errorDescription.detail}`,\n method: input.method,\n path: input.path,\n reportErrors: !cancelled && reportErrors,\n requiredContainerIds: input.errorDescription.requiredContainerIds,\n stalePrincipalHeads: input.errorDescription.stalePrincipalHeads,\n status: input.response.status,\n statusText: input.response.statusText,\n });\n }\n\n private reportResponseRequestFailure(\n input: ResponseRequestValidationFailureInput,\n ): RequestFailure {\n if (input.kind === \"network\") {\n this.onNetworkError?.();\n }\n return this.requestFailure({\n ...input,\n reportErrors: input.options?.reportErrors ?? true,\n stalePrincipalHeads: undefined,\n });\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createContainerOperation, createContainerWithMetadataDocumentOperation, deleteContainerOperation, isContainerMutationOperationRequest, isContainerMutationOperationResponse, isContainerRotationOperationRequest, isContainerRotationOperationResponse, isCreateContainerWithMetadataDocumentOperationRequest, isCreateContainerWithMetadataDocumentOperationResponse, isDeleteContainerOperationResponse, moveContainerOperation, operationRequestPath, reciteContainerOperation, rekeyContainerOperation, revokeContainerOperation, shareContainerOperation, } from "../../../validators/operation/index.js";
|
|
1
|
+
import { createContainerOperation, createContainerWithMetadataDocumentOperation, deleteContainerOperation, isContainerMutationOperationRequest, isContainerMutationOperationResponse, isContainerRotationOperationRequest, isContainerRotationOperationResponse, isCreateContainerWithMetadataDocumentOperationRequest, isCreateContainerWithMetadataDocumentOperationResponse, isDeleteContainerOperationResponse, moveContainerOperation, operationRequestPath, operationRequestPathWithQuery, reciteContainerOperation, rekeyContainerOperation, revokeContainerOperation, shareContainerOperation, } from "../../../validators/operation/index.js";
|
|
2
2
|
import { isContainerReciteRequest } from "../../../validators/request/index.js";
|
|
3
3
|
import { isContainerReciteResponse } from "../../../validators/response/index.js";
|
|
4
4
|
export const containerRecite = {
|
|
@@ -49,6 +49,6 @@ export const containerMove = {
|
|
|
49
49
|
export const containerDelete = {
|
|
50
50
|
isResponse: isDeleteContainerOperationResponse,
|
|
51
51
|
method: deleteContainerOperation.method,
|
|
52
|
-
path: (containerId) =>
|
|
52
|
+
path: (containerId, requiredAncestorId) => operationRequestPathWithQuery(deleteContainerOperation, { containerId }, { requiredAncestorId }),
|
|
53
53
|
};
|
|
54
54
|
//# sourceMappingURL=mutations.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutations.js","sourceRoot":"","sources":["mutations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,4CAA4C,EAC5C,wBAAwB,EACxB,mCAAmC,EACnC,oCAAoC,EACpC,mCAAmC,EACnC,oCAAoC,EACpC,qDAAqD,EACrD,sDAAsD,EACtD,kCAAkC,EAClC,sBAAsB,EACtB,oBAAoB,EACpB,wBAAwB,EACxB,uBAAuB,EACvB,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAE3E,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,SAAS,EAAE,wBAAwB;IACnC,UAAU,EAAE,yBAAyB;IACrC,MAAM,EAAE,wBAAwB,CAAC,MAAM;IACvC,IAAI,EAAE,CAAC,WAAmB,EAAE,EAAE,CAC5B,oBAAoB,CAAC,wBAAwB,EAAE,EAAE,WAAW,EAAE,CAAC;CACzD,CAAC;AAEX,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,SAAS,EAAE,mCAAmC;IAC9C,UAAU,EAAE,oCAAoC;IAChD,MAAM,EAAE,wBAAwB,CAAC,MAAM;IACvC,IAAI,EAAE,oBAAoB,CAAC,wBAAwB,EAAE,EAAE,CAAC;CAChD,CAAC;AAEX,MAAM,CAAC,MAAM,mCAAmC,GAAG;IACjD,SAAS,EAAE,qDAAqD;IAChE,UAAU,EAAE,sDAAsD;IAClE,MAAM,EAAE,4CAA4C,CAAC,MAAM;IAC3D,IAAI,EAAE,oBAAoB,CAAC,4CAA4C,EAAE,EAAE,CAAC;CACpE,CAAC;AAEX,SAAS,q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Ac,GAAG;IAC5B,SAAS,EAAE,mCAAmC;IAC9C,UAAU,EAAE,oCAAoC;IAChD,MAAM,EAAE,uBAAuB,CAAC,MAAM;IACtC,IAAI,EAAE,CAAC,WAAmB,EAAE,EAAE,CAC5B,qBAAqB,CAAC,uBAAuB,EAAE,WAAW,CAAC;CACrD,CAAC;AAEX,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,SAAS,EAAE,mCAAmC;IAC9C,UAAU,EAAE,oCAAoC;IAChD,MAAM,EAAE,wBAAwB,CAAC,MAAM;IACvC,IAAI,EAAE,CAAC,WAAmB,EAAE,EAAE,CAC5B,qBAAqB,CAAC,wBAAwB,EAAE,WAAW,CAAC;CACtD,CAAC;AAEX,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,SAAS,EAAE,mCAAmC;IAC9C,UAAU,EAAE,oCAAoC;IAChD,MAAM,EAAE,uBAAuB,CAAC,MAAM;IACtC,IAAI,EAAE,CAAC,WAAmB,EAAE,EAAE,CAC5B,qBAAqB,CAAC,uBAAuB,EAAE,WAAW,CAAC;CACrD,CAAC;AAEX,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,SAAS,EAAE,mCAAmC;IAC9C,UAAU,EAAE,oCAAoC;IAChD,MAAM,EAAE,sBAAsB,CAAC,MAAM;IACrC,IAAI,EAAE,CAAC,WAAmB,EAAE,EAAE,CAC5B,qBAAqB,CAAC,sBAAsB,EAAE,WAAW,CAAC;CACpD,CAAC;AAEX,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,UAAU,EAAE,kCAAkC;IAC9C,MAAM,EAAE,wBAAwB,CAAC,MAAM;IACvC,IAAI,EAAE,CAAC,WAAmB,EAAE,kBAA2B,EAAE,EAAE,CACzD,6BAA6B,CAC3B,wBAAwB,EACxB,EAAE,WAAW,EAAE,EACf,EAAE,kBAAkB,EAAE,CACvB;CACK,CAAC","sourcesContent":["import {\n createContainerOperation,\n createContainerWithMetadataDocumentOperation,\n deleteContainerOperation,\n isContainerMutationOperationRequest,\n isContainerMutationOperationResponse,\n isContainerRotationOperationRequest,\n isContainerRotationOperationResponse,\n isCreateContainerWithMetadataDocumentOperationRequest,\n isCreateContainerWithMetadataDocumentOperationResponse,\n isDeleteContainerOperationResponse,\n moveContainerOperation,\n operationRequestPath,\n operationRequestPathWithQuery,\n reciteContainerOperation,\n rekeyContainerOperation,\n revokeContainerOperation,\n shareContainerOperation,\n} from \"@tearleads/validators/operation\";\nimport { isContainerReciteRequest } from \"@tearleads/validators/request\";\nimport { isContainerReciteResponse } from \"@tearleads/validators/response\";\n\nexport const containerRecite = {\n isRequest: isContainerReciteRequest,\n isResponse: isContainerReciteResponse,\n method: reciteContainerOperation.method,\n path: (containerId: string) =>\n operationRequestPath(reciteContainerOperation, { containerId }),\n} as const;\n\nexport const containerCreate = {\n isRequest: isContainerMutationOperationRequest,\n isResponse: isContainerMutationOperationResponse,\n method: createContainerOperation.method,\n path: operationRequestPath(createContainerOperation, {}),\n} as const;\n\nexport const containerCreateWithMetadataDocument = {\n isRequest: isCreateContainerWithMetadataDocumentOperationRequest,\n isResponse: isCreateContainerWithMetadataDocumentOperationResponse,\n method: createContainerWithMetadataDocumentOperation.method,\n path: operationRequestPath(createContainerWithMetadataDocumentOperation, {}),\n} as const;\n\nfunction containerMutationPath(\n operation:\n | typeof moveContainerOperation\n | typeof rekeyContainerOperation\n | typeof revokeContainerOperation\n | typeof shareContainerOperation,\n containerId: string,\n) {\n return operationRequestPath(operation, { containerId });\n}\n\nexport const containerShare = {\n isRequest: isContainerMutationOperationRequest,\n isResponse: isContainerMutationOperationResponse,\n method: shareContainerOperation.method,\n path: (containerId: string) =>\n containerMutationPath(shareContainerOperation, containerId),\n} as const;\n\nexport const containerRevoke = {\n isRequest: isContainerRotationOperationRequest,\n isResponse: isContainerRotationOperationResponse,\n method: revokeContainerOperation.method,\n path: (containerId: string) =>\n containerMutationPath(revokeContainerOperation, containerId),\n} as const;\n\nexport const containerRekey = {\n isRequest: isContainerRotationOperationRequest,\n isResponse: isContainerRotationOperationResponse,\n method: rekeyContainerOperation.method,\n path: (containerId: string) =>\n containerMutationPath(rekeyContainerOperation, containerId),\n} as const;\n\nexport const containerMove = {\n isRequest: isContainerRotationOperationRequest,\n isResponse: isContainerRotationOperationResponse,\n method: moveContainerOperation.method,\n path: (containerId: string) =>\n containerMutationPath(moveContainerOperation, containerId),\n} as const;\n\nexport const containerDelete = {\n isResponse: isDeleteContainerOperationResponse,\n method: deleteContainerOperation.method,\n path: (containerId: string, requiredAncestorId?: string) =>\n operationRequestPathWithQuery(\n deleteContainerOperation,\n { containerId },\n { requiredAncestorId },\n ),\n} as const;\n"]}
|
|
@@ -12,14 +12,21 @@ export async function shouldRetryAfterSessionExpired(input) {
|
|
|
12
12
|
return false;
|
|
13
13
|
}
|
|
14
14
|
const currentAuthToken = input.getCurrentAuthToken();
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
let pending = null;
|
|
16
|
+
if (currentAuthToken !== input.authToken) {
|
|
17
|
+
const renewed = currentAuthToken !== null &&
|
|
18
|
+
input.isKnownSessionRenewal(input.authToken, currentAuthToken);
|
|
19
|
+
if (renewed) {
|
|
17
20
|
input.options.onSessionRenewed?.();
|
|
18
|
-
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
pending = input.pendingSessionRenewal(input.authToken);
|
|
24
|
+
if (!currentAuthToken || !pending)
|
|
25
|
+
return false;
|
|
19
26
|
}
|
|
20
27
|
let refreshed = false;
|
|
21
28
|
try {
|
|
22
|
-
refreshed = await input.refreshSession();
|
|
29
|
+
refreshed = await (pending ?? input.refreshSession());
|
|
23
30
|
}
|
|
24
31
|
catch (error) {
|
|
25
32
|
if (error instanceof KeyingVerificationError) {
|
|
@@ -29,9 +36,10 @@ export async function shouldRetryAfterSessionExpired(input) {
|
|
|
29
36
|
input.reportError(`Session refresh failed: ${errorMessage(error)}`);
|
|
30
37
|
}
|
|
31
38
|
}
|
|
39
|
+
const refreshedToken = input.getCurrentAuthToken();
|
|
32
40
|
const renewed = Boolean(refreshed &&
|
|
33
|
-
|
|
34
|
-
input.
|
|
41
|
+
refreshedToken &&
|
|
42
|
+
input.isKnownSessionRenewal(input.authToken, refreshedToken));
|
|
35
43
|
if (renewed)
|
|
36
44
|
input.options.onSessionRenewed?.();
|
|
37
45
|
return renewed;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionRefresh.js","sourceRoot":"","sources":["sessionRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"sessionRefresh.js","sourceRoot":"","sources":["sessionRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAgB5B;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,KAA0B;IAE1B,IACE,KAAK,CAAC,OAAO,CAAC,qBAAqB,KAAK,KAAK;QAC7C,CAAC,KAAK,CAAC,SAAS;QAChB,CAAC,uBAAuB,CAAC,KAAK,CAAC,IAAI,CAAC;QACpC,CAAC,yBAAyB,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,IAAI,CAAC,EAC5D,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,gBAAgB,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACrD,IAAI,OAAO,GAA4B,IAAI,CAAC;IAC5C,IAAI,gBAAgB,KAAK,KAAK,CAAC,SAAS,EAAE,CAAC;QACzC,MAAM,OAAO,GACX,gBAAgB,KAAK,IAAI;YACzB,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;QACjE,IAAI,OAAO,EAAE,CAAC;YACZ,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;YACnC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,GAAG,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACvD,IAAI,CAAC,gBAAgB,IAAI,CAAC,OAAO;YAAE,OAAO,KAAK,CAAC;IAClD,CAAC;IAED,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,CAAC;QACH,SAAS,GAAG,MAAM,CAAC,OAAO,IAAI,KAAK,CAAC,cAAc,EAAE,CAAC,CAAC;IACxD,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,IAAI,IAAI,EAAE,CAAC;YACvC,KAAK,CAAC,WAAW,CAAC,2BAA2B,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACtE,CAAC;IACH,CAAC;IAED,MAAM,cAAc,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACnD,MAAM,OAAO,GAAG,OAAO,CACrB,SAAS;QACP,cAAc;QACd,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,SAAS,EAAE,cAAc,CAAC,CAC/D,CAAC;IACF,IAAI,OAAO;QAAE,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;IAChD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n errorMessage,\n isRefreshableSessionError,\n isReplayableRequestBody,\n} from \"./requestInternals\";\nimport type { RequestBody, RequestResultOptions } from \"./types\";\n\ninterface SessionRefreshInput {\n readonly authToken: string | null;\n readonly body: RequestBody | undefined;\n readonly code: string | null;\n readonly getCurrentAuthToken: () => string | null;\n readonly isKnownSessionRenewal: (from: string, to: string) => boolean;\n readonly options: RequestResultOptions;\n readonly pendingSessionRenewal: (from: string) => Promise<boolean> | null;\n readonly refreshSession: () => boolean | Promise<boolean>;\n readonly reportError: (message: string) => void;\n readonly responseStatus: number;\n}\n\n/**\n * Decides whether a failed request can be replayed after session renewal.\n * Identity-integrity failures are terminal and must retain their typed error.\n */\nexport async function shouldRetryAfterSessionExpired(\n input: SessionRefreshInput,\n): Promise<boolean> {\n if (\n input.options.retryOnSessionExpired === false ||\n !input.authToken ||\n !isReplayableRequestBody(input.body) ||\n !isRefreshableSessionError(input.responseStatus, input.code)\n ) {\n return false;\n }\n\n const currentAuthToken = input.getCurrentAuthToken();\n let pending: Promise<boolean> | null = null;\n if (currentAuthToken !== input.authToken) {\n const renewed =\n currentAuthToken !== null &&\n input.isKnownSessionRenewal(input.authToken, currentAuthToken);\n if (renewed) {\n input.options.onSessionRenewed?.();\n return true;\n }\n pending = input.pendingSessionRenewal(input.authToken);\n if (!currentAuthToken || !pending) return false;\n }\n\n let refreshed = false;\n try {\n refreshed = await (pending ?? input.refreshSession());\n } catch (error: unknown) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n if (input.options.reportErrors ?? true) {\n input.reportError(`Session refresh failed: ${errorMessage(error)}`);\n }\n }\n\n const refreshedToken = input.getCurrentAuthToken();\n const renewed = Boolean(\n refreshed &&\n refreshedToken &&\n input.isKnownSessionRenewal(input.authToken, refreshedToken),\n );\n if (renewed) input.options.onSessionRenewed?.();\n return renewed;\n}\n"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** An identity change invalidates renewal evidence, including an awaited callback. */
|
|
2
|
+
export class SessionRenewalTracker {
|
|
3
|
+
readToken;
|
|
4
|
+
revision = 0;
|
|
5
|
+
known = null;
|
|
6
|
+
inFlight = null;
|
|
7
|
+
constructor(readToken) {
|
|
8
|
+
this.readToken = readToken;
|
|
9
|
+
}
|
|
10
|
+
tokenChanged() {
|
|
11
|
+
this.revision += 1;
|
|
12
|
+
this.known = null;
|
|
13
|
+
}
|
|
14
|
+
isKnown(from, to) {
|
|
15
|
+
return this.known?.from === from && this.known.to === to;
|
|
16
|
+
}
|
|
17
|
+
currentToken(from) {
|
|
18
|
+
const token = this.readToken();
|
|
19
|
+
return from && token && this.isKnown(from, token) ? token : null;
|
|
20
|
+
}
|
|
21
|
+
pending(from) {
|
|
22
|
+
return this.inFlight?.from === from ? this.inFlight.promise : null;
|
|
23
|
+
}
|
|
24
|
+
async renew(handler) {
|
|
25
|
+
const from = this.readToken();
|
|
26
|
+
if (!from)
|
|
27
|
+
return false;
|
|
28
|
+
const existing = this.pending(from);
|
|
29
|
+
if (existing)
|
|
30
|
+
return existing;
|
|
31
|
+
const pending = {
|
|
32
|
+
from,
|
|
33
|
+
promise: this.complete(from, this.revision, handler),
|
|
34
|
+
};
|
|
35
|
+
this.inFlight = pending;
|
|
36
|
+
try {
|
|
37
|
+
return await pending.promise;
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
if (this.inFlight === pending)
|
|
41
|
+
this.inFlight = null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async complete(from, revision, handler) {
|
|
45
|
+
const renewed = await (handler?.() ?? false);
|
|
46
|
+
const to = this.readToken();
|
|
47
|
+
// The trusted callback authenticates the same identity and installs one
|
|
48
|
+
// replacement token. A second transition cannot borrow that renewal.
|
|
49
|
+
if (renewed && to && from !== to && this.revision === revision + 1)
|
|
50
|
+
this.known = { from, to };
|
|
51
|
+
return renewed;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=sessionRenewal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessionRenewal.js","sourceRoot":"","sources":["sessionRenewal.ts"],"names":[],"mappings":"AAEA,sFAAsF;AACtF,MAAM,OAAO,qBAAqB;IAKH;IAJrB,QAAQ,GAAG,CAAC,CAAC;IACb,KAAK,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,CAAC;YACH,OAAO,MAAM,OAAO,CAAC,OAAO,CAAC;QAC/B,CAAC;gBAAS,CAAC;YACT,IAAI,IAAI,CAAC,QAAQ,KAAK,OAAO;gBAAE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACtD,CAAC;IACH,CAAC;IAEO,KAAK,CAAC,QAAQ,CACpB,IAAY,EACZ,QAAgB,EAChB,OAAqB;QAErB,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,EAAE,EAAE,IAAI,KAAK,CAAC,CAAC;QAC7C,MAAM,EAAE,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;QAC5B,wEAAwE;QACxE,qEAAqE;QACrE,IAAI,OAAO,IAAI,EAAE,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,CAAC,QAAQ,KAAK,QAAQ,GAAG,CAAC;YAChE,IAAI,CAAC,KAAK,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;QAC5B,OAAO,OAAO,CAAC;IACjB,CAAC;CACF","sourcesContent":["type RenewSession = (() => boolean | Promise<boolean>) | null;\n\n/** An identity change invalidates renewal evidence, including an awaited callback. */\nexport class SessionRenewalTracker {\n private revision = 0;\n private known: { from: string; to: string } | null = null;\n private inFlight: { from: string; promise: Promise<boolean> } | null = null;\n\n constructor(private readonly readToken: () => string | null) {}\n\n tokenChanged(): void {\n this.revision += 1;\n this.known = null;\n }\n\n isKnown(from: string, to: string): boolean {\n return this.known?.from === from && this.known.to === to;\n }\n\n currentToken(from: string | null): string | null {\n const token = this.readToken();\n return from && token && this.isKnown(from, token) ? token : null;\n }\n\n pending(from: string): Promise<boolean> | null {\n return this.inFlight?.from === from ? this.inFlight.promise : null;\n }\n\n async renew(handler: RenewSession): Promise<boolean> {\n const from = this.readToken();\n if (!from) return false;\n const existing = this.pending(from);\n if (existing) return existing;\n const pending = {\n from,\n promise: this.complete(from, this.revision, handler),\n };\n this.inFlight = pending;\n try {\n return await pending.promise;\n } finally {\n if (this.inFlight === pending) this.inFlight = null;\n }\n }\n\n private async complete(\n from: string,\n revision: number,\n handler: RenewSession,\n ): Promise<boolean> {\n const renewed = await (handler?.() ?? false);\n const to = this.readToken();\n // The trusted callback authenticates the same identity and installs one\n // replacement token. A second transition cannot borrow that renewal.\n if (renewed && to && from !== to && this.revision === revision + 1)\n this.known = { from, to };\n return renewed;\n }\n}\n"]}
|
|
@@ -6244,6 +6244,9 @@ export declare const deleteContainerOperation: Omit<{
|
|
|
6244
6244
|
containerId: z.ZodString;
|
|
6245
6245
|
}, z.core.$strict>;
|
|
6246
6246
|
readonly path: "/containers/{containerId}";
|
|
6247
|
+
readonly query: z.ZodObject<{
|
|
6248
|
+
requiredAncestorId: z.ZodOptional<z.ZodString>;
|
|
6249
|
+
}, z.core.$strict>;
|
|
6247
6250
|
readonly responses: {
|
|
6248
6251
|
readonly 200: z.ZodType<{
|
|
6249
6252
|
containerId: string;
|
|
@@ -119,6 +119,7 @@ export const deleteContainerOperation = defineJsonOperation({
|
|
|
119
119
|
method: "DELETE",
|
|
120
120
|
params: ContainerMutationPathParamsSchema,
|
|
121
121
|
path: "/containers/{containerId}",
|
|
122
|
+
query: z.strictObject({ requiredAncestorId: z.string().min(1).optional() }),
|
|
122
123
|
responses: { 200: ContainerDeleteResponseSchema },
|
|
123
124
|
});
|
|
124
125
|
export const isContainerMutationOperationRequest = isContainerMutationRequest;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"containerMutations.js","sourceRoot":"","sources":["containerMutations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,kDAAkD,EAAE,MAAM,wCAAwC,CAAC;AAC5G,OAAO,EACL,gDAAgD,EAChD,8BAA8B,EAC9B,4BAA4B,EAC5B,8BAA8B,EAC9B,4CAA4C,EAC5C,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,iDAAiD,EACjD,6BAA6B,EAC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AAM,oCAAoC,GAAG,2BAA2B,CAAC;AAChF,MAAM,CAAC,MAAM,mCAAmC,GAAG,0BAA0B,CAAC;AAC9E,MAAM,CAAC,MAAM,oCAAoC,GAAG,2BAA2B,CAAC;AAChF,MAAM,CAAC,MAAM,qDAAqD,GAChE,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,sDAAsD,GACjE,6CAA6C,CAAC;AAChD,MAAM,CAAC,MAAM,kCAAkC,GAAG,yBAAyB,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { organizationProvisioningContainerKeyringRefinement } from \"../organizationProvisioningRefinements\";\nimport {\n ContainerCreateWithMetadataDocumentRequestSchema,\n ContainerMutationRequestSchema,\n ContainerReciteRequestSchema,\n ContainerRotationRequestSchema,\n isContainerCreateWithMetadataDocumentRequest,\n isContainerMutationRequest,\n isContainerRotationRequest,\n} from \"../request\";\nimport {\n ContainerCreateWithMetadataDocumentResponseSchema,\n ContainerDeleteResponseSchema,\n ContainerMutationFailureResponseSchema,\n ContainerMutationResponseSchema,\n ContainerNotFoundErrorResponseSchema,\n ContainerReciteResponseSchema,\n ContainerRotationResponseSchema,\n ErrorResponseSchema,\n isContainerCreateWithMetadataDocumentResponse,\n isContainerDeleteResponse,\n isContainerMutationResponse,\n isContainerRotationResponse,\n PaymentRequiredErrorResponseSchema,\n SessionFailureResponseSchema,\n} from \"../response\";\nimport { defineJsonOperation } from \"./definition\";\n\nconst EmptyContainerMutationPathParamsSchema = z.strictObject({});\n\nexport const ContainerMutationPathParamsSchema = z.strictObject({\n containerId: z.string(),\n});\n\nexport type ContainerMutationPathParams = z.infer<\n typeof ContainerMutationPathParamsSchema\n>;\n\nconst containerMutationFailureResponses = {\n 400: ErrorResponseSchema,\n 401: SessionFailureResponseSchema,\n 402: PaymentRequiredErrorResponseSchema,\n 403: ErrorResponseSchema,\n 404: ErrorResponseSchema,\n 409: ContainerMutationFailureResponseSchema,\n 500: ErrorResponseSchema,\n} as const;\n\nconst containerMutationFailureStatuses = [\n 400, 401, 402, 403, 404, 409, 500,\n] as const;\n\nconst containerMutationRuntimeRefinements = [\n organizationProvisioningContainerKeyringRefinement,\n] as const;\n\nexport const createContainerOperation = defineJsonOperation({\n auth: \"session\",\n body: ContainerMutationRequestSchema,\n failureResponses: containerMutationFailureResponses,\n failureStatuses: containerMutationFailureStatuses,\n id: \"containers.create\",\n method: \"POST\",\n params: EmptyContainerMutationPathParamsSchema,\n path: \"/containers\",\n responses: { 200: ContainerMutationResponseSchema },\n runtimeRefinements: containerMutationRuntimeRefinements,\n});\n\nexport const createContainerWithMetadataDocumentOperation = defineJsonOperation(\n {\n auth: \"session\",\n body: ContainerCreateWithMetadataDocumentRequestSchema,\n failureResponses: {\n ...containerMutationFailureResponses,\n 503: ErrorResponseSchema,\n },\n failureStatuses: [...containerMutationFailureStatuses, 503],\n id: \"containers.withMetadataDocument.create\",\n method: \"POST\",\n params: EmptyContainerMutationPathParamsSchema,\n path: \"/containers/with-metadata-document\",\n responses: { 200: ContainerCreateWithMetadataDocumentResponseSchema },\n runtimeRefinements: containerMutationRuntimeRefinements,\n },\n);\n\nfunction defineContainerMutationOperation<\n const Id extends string,\n const Path extends `/${string}`,\n>(input: { readonly id: Id; readonly path: Path }) {\n return defineJsonOperation({\n auth: \"session\",\n body: ContainerMutationRequestSchema,\n failureResponses: containerMutationFailureResponses,\n failureStatuses: containerMutationFailureStatuses,\n id: input.id,\n method: \"POST\",\n params: ContainerMutationPathParamsSchema,\n path: input.path,\n responses: { 200: ContainerMutationResponseSchema },\n runtimeRefinements: containerMutationRuntimeRefinements,\n });\n}\n\n/**\n * Rekey, revoke, and move mint a new key epoch, so they alone may carry the\n * descendant rekeys that must commit with them.\n */\nfunction defineContainerRotationOperation<\n const Id extends string,\n const Path extends `/${string}`,\n>(input: { readonly id: Id; readonly path: Path }) {\n return defineJsonOperation({\n auth: \"session\",\n body: ContainerRotationRequestSchema,\n failureResponses: containerMutationFailureResponses,\n failureStatuses: containerMutationFailureStatuses,\n id: input.id,\n method: \"POST\",\n params: ContainerMutationPathParamsSchema,\n path: input.path,\n responses: { 200: ContainerRotationResponseSchema },\n runtimeRefinements: containerMutationRuntimeRefinements,\n });\n}\n\nexport const shareContainerOperation = defineContainerMutationOperation({\n id: \"containers.share\",\n path: \"/containers/{containerId}/share\",\n});\n\nexport const reciteContainerOperation = defineJsonOperation({\n auth: \"session\",\n body: ContainerReciteRequestSchema,\n failureResponses: containerMutationFailureResponses,\n failureStatuses: containerMutationFailureStatuses,\n id: \"containers.recite\",\n method: \"POST\",\n params: ContainerMutationPathParamsSchema,\n path: \"/containers/{containerId}/recite\",\n responses: { 200: ContainerReciteResponseSchema },\n});\n\nexport const revokeContainerOperation = defineContainerRotationOperation({\n id: \"containers.revoke\",\n path: \"/containers/{containerId}/revoke\",\n});\n\nexport const rekeyContainerOperation = defineContainerRotationOperation({\n id: \"containers.rekey\",\n path: \"/containers/{containerId}/rekey\",\n});\n\nexport const moveContainerOperation = defineContainerRotationOperation({\n id: \"containers.move\",\n path: \"/containers/{containerId}/move\",\n});\n\nexport const deleteContainerOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n ...containerMutationFailureResponses,\n 404: ContainerNotFoundErrorResponseSchema,\n },\n failureStatuses: containerMutationFailureStatuses,\n id: \"containers.delete\",\n method: \"DELETE\",\n params: ContainerMutationPathParamsSchema,\n path: \"/containers/{containerId}\",\n responses: { 200: ContainerDeleteResponseSchema },\n});\n\nexport const isContainerMutationOperationRequest = isContainerMutationRequest;\nexport const isContainerMutationOperationResponse = isContainerMutationResponse;\nexport const isContainerRotationOperationRequest = isContainerRotationRequest;\nexport const isContainerRotationOperationResponse = isContainerRotationResponse;\nexport const isCreateContainerWithMetadataDocumentOperationRequest =\n isContainerCreateWithMetadataDocumentRequest;\nexport const isCreateContainerWithMetadataDocumentOperationResponse =\n isContainerCreateWithMetadataDocumentResponse;\nexport const isDeleteContainerOperationResponse = isContainerDeleteResponse;\n"]}
|
|
1
|
+
{"version":3,"file":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gBAAgB,EAAE;QAChB,GAAG,iCAAiC;QACpC,GAAG,EAAE,oCAAoC;KAC1C;IACD,eAAe,EAAE,gCAAgC;IACjD,EAAE,EAAE,mBAAmB;IACvB,MAAM,EAAE,QAAQ;IAChB,MAAM,EAAE,iCAAiC;IACzC,IAAI,EAAE,2BAA2B;IACjC,KAAK,EAAE,CAAC,CAAC,YAAY,CAAC,EAAE,kBAAkB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC;IAC3E,SAAS,EAAE,EAAE,GAAG,EAAE,6BAA6B,EAAE;CAClD,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,mCAAmC,GAAG,0BAA0B,CAAC;AAC9E,MAAM,CAAC,MAAM,oCAAoC,GAAG,2BAA2B,CAAC;AAChF,MAAM,CAAC,MAAM,mCAAmC,GAAG,0BAA0B,CAAC;AAC9E,MAAM,CAAC,MAAM,oCAAoC,GAAG,2BAA2B,CAAC;AAChF,MAAM,CAAC,MAAM,qDAAqD,GAChE,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,sDAAsD,GACjE,6CAA6C,CAAC;AAChD,MAAM,CAAC,MAAM,kCAAkC,GAAG,yBAAyB,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { organizationProvisioningContainerKeyringRefinement } from \"../organizationProvisioningRefinements\";\nimport {\n ContainerCreateWithMetadataDocumentRequestSchema,\n ContainerMutationRequestSchema,\n ContainerReciteRequestSchema,\n ContainerRotationRequestSchema,\n isContainerCreateWithMetadataDocumentRequest,\n isContainerMutationRequest,\n isContainerRotationRequest,\n} from \"../request\";\nimport {\n ContainerCreateWithMetadataDocumentResponseSchema,\n ContainerDeleteResponseSchema,\n ContainerMutationFailureResponseSchema,\n ContainerMutationResponseSchema,\n ContainerNotFoundErrorResponseSchema,\n ContainerReciteResponseSchema,\n ContainerRotationResponseSchema,\n ErrorResponseSchema,\n isContainerCreateWithMetadataDocumentResponse,\n isContainerDeleteResponse,\n isContainerMutationResponse,\n isContainerRotationResponse,\n PaymentRequiredErrorResponseSchema,\n SessionFailureResponseSchema,\n} from \"../response\";\nimport { defineJsonOperation } from \"./definition\";\n\nconst EmptyContainerMutationPathParamsSchema = z.strictObject({});\n\nexport const ContainerMutationPathParamsSchema = z.strictObject({\n containerId: z.string(),\n});\n\nexport type ContainerMutationPathParams = z.infer<\n typeof ContainerMutationPathParamsSchema\n>;\n\nconst containerMutationFailureResponses = {\n 400: ErrorResponseSchema,\n 401: SessionFailureResponseSchema,\n 402: PaymentRequiredErrorResponseSchema,\n 403: ErrorResponseSchema,\n 404: ErrorResponseSchema,\n 409: ContainerMutationFailureResponseSchema,\n 500: ErrorResponseSchema,\n} as const;\n\nconst containerMutationFailureStatuses = [\n 400, 401, 402, 403, 404, 409, 500,\n] as const;\n\nconst containerMutationRuntimeRefinements = [\n organizationProvisioningContainerKeyringRefinement,\n] as const;\n\nexport const createContainerOperation = defineJsonOperation({\n auth: \"session\",\n body: ContainerMutationRequestSchema,\n failureResponses: containerMutationFailureResponses,\n failureStatuses: containerMutationFailureStatuses,\n id: \"containers.create\",\n method: \"POST\",\n params: EmptyContainerMutationPathParamsSchema,\n path: \"/containers\",\n responses: { 200: ContainerMutationResponseSchema },\n runtimeRefinements: containerMutationRuntimeRefinements,\n});\n\nexport const createContainerWithMetadataDocumentOperation = defineJsonOperation(\n {\n auth: \"session\",\n body: ContainerCreateWithMetadataDocumentRequestSchema,\n failureResponses: {\n ...containerMutationFailureResponses,\n 503: ErrorResponseSchema,\n },\n failureStatuses: [...containerMutationFailureStatuses, 503],\n id: \"containers.withMetadataDocument.create\",\n method: \"POST\",\n params: EmptyContainerMutationPathParamsSchema,\n path: \"/containers/with-metadata-document\",\n responses: { 200: ContainerCreateWithMetadataDocumentResponseSchema },\n runtimeRefinements: containerMutationRuntimeRefinements,\n },\n);\n\nfunction defineContainerMutationOperation<\n const Id extends string,\n const Path extends `/${string}`,\n>(input: { readonly id: Id; readonly path: Path }) {\n return defineJsonOperation({\n auth: \"session\",\n body: ContainerMutationRequestSchema,\n failureResponses: containerMutationFailureResponses,\n failureStatuses: containerMutationFailureStatuses,\n id: input.id,\n method: \"POST\",\n params: ContainerMutationPathParamsSchema,\n path: input.path,\n responses: { 200: ContainerMutationResponseSchema },\n runtimeRefinements: containerMutationRuntimeRefinements,\n });\n}\n\n/**\n * Rekey, revoke, and move mint a new key epoch, so they alone may carry the\n * descendant rekeys that must commit with them.\n */\nfunction defineContainerRotationOperation<\n const Id extends string,\n const Path extends `/${string}`,\n>(input: { readonly id: Id; readonly path: Path }) {\n return defineJsonOperation({\n auth: \"session\",\n body: ContainerRotationRequestSchema,\n failureResponses: containerMutationFailureResponses,\n failureStatuses: containerMutationFailureStatuses,\n id: input.id,\n method: \"POST\",\n params: ContainerMutationPathParamsSchema,\n path: input.path,\n responses: { 200: ContainerRotationResponseSchema },\n runtimeRefinements: containerMutationRuntimeRefinements,\n });\n}\n\nexport const shareContainerOperation = defineContainerMutationOperation({\n id: \"containers.share\",\n path: \"/containers/{containerId}/share\",\n});\n\nexport const reciteContainerOperation = defineJsonOperation({\n auth: \"session\",\n body: ContainerReciteRequestSchema,\n failureResponses: containerMutationFailureResponses,\n failureStatuses: containerMutationFailureStatuses,\n id: \"containers.recite\",\n method: \"POST\",\n params: ContainerMutationPathParamsSchema,\n path: \"/containers/{containerId}/recite\",\n responses: { 200: ContainerReciteResponseSchema },\n});\n\nexport const revokeContainerOperation = defineContainerRotationOperation({\n id: \"containers.revoke\",\n path: \"/containers/{containerId}/revoke\",\n});\n\nexport const rekeyContainerOperation = defineContainerRotationOperation({\n id: \"containers.rekey\",\n path: \"/containers/{containerId}/rekey\",\n});\n\nexport const moveContainerOperation = defineContainerRotationOperation({\n id: \"containers.move\",\n path: \"/containers/{containerId}/move\",\n});\n\nexport const deleteContainerOperation = defineJsonOperation({\n auth: \"session\",\n failureResponses: {\n ...containerMutationFailureResponses,\n 404: ContainerNotFoundErrorResponseSchema,\n },\n failureStatuses: containerMutationFailureStatuses,\n id: \"containers.delete\",\n method: \"DELETE\",\n params: ContainerMutationPathParamsSchema,\n path: \"/containers/{containerId}\",\n query: z.strictObject({ requiredAncestorId: z.string().min(1).optional() }),\n responses: { 200: ContainerDeleteResponseSchema },\n});\n\nexport const isContainerMutationOperationRequest = isContainerMutationRequest;\nexport const isContainerMutationOperationResponse = isContainerMutationResponse;\nexport const isContainerRotationOperationRequest = isContainerRotationRequest;\nexport const isContainerRotationOperationResponse = isContainerRotationResponse;\nexport const isCreateContainerWithMetadataDocumentOperationRequest =\n isContainerCreateWithMetadataDocumentRequest;\nexport const isCreateContainerWithMetadataDocumentOperationResponse =\n isContainerCreateWithMetadataDocumentResponse;\nexport const isDeleteContainerOperationResponse = isContainerDeleteResponse;\n"]}
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/** Hydrate only bytes matching the current document's authenticated attachment intent. */
|
|
2
2
|
import { getDocumentAttachments } from "../../../data/documents/documentContent.js";
|
|
3
3
|
import { hydrateDocumentAttachmentBlobs } from "../../../workflows/blobs/index.js";
|
|
4
|
-
import { reclaimDocumentOrphanBlobs, } from "../../../workflows/documents/index.js";
|
|
5
4
|
import { createRuntimePrincipalPolicyWarmer } from "../../../workflows/principals/runtimePolicyWarmer.js";
|
|
6
5
|
import { commitHydratedAttachment } from "./attachmentHydrationCommit.js";
|
|
6
|
+
import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
|
|
7
7
|
import { isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent, } from "./syncGeneration.js";
|
|
8
8
|
export async function hydrateAttachmentBlobs(state, currentDoc, currentRecord, expectedGeneration) {
|
|
9
9
|
const generationIsCurrent = () => !expectedGeneration || isSyncGenerationCurrent(state, expectedGeneration);
|
|
@@ -52,6 +52,6 @@ export async function hydrateAttachmentBlobs(state, currentDoc, currentRecord, e
|
|
|
52
52
|
expectedStorageKey: expectedStorageKeys[hydratedBlob.attachment.slotId] ?? null,
|
|
53
53
|
});
|
|
54
54
|
}
|
|
55
|
-
|
|
55
|
+
void runDocumentOrphanMaintenance(state);
|
|
56
56
|
}
|
|
57
57
|
//# sourceMappingURL=attachmentHydration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentHydration.js","sourceRoot":"","sources":["attachmentHydration.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAE1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"attachmentHydration.js","sourceRoot":"","sources":["attachmentHydration.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAE1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,0BAA0B,CAAC;AAE1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AAEnE,OAAO,EAEL,oCAAoC,IAAI,uBAAuB,GAChE,MAAM,kBAAkB,CAAC;AAE1B,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAyB,EACzB,UAAyB,EACzB,aAAoC,EACpC,kBAAgD;IAEhD,MAAM,mBAAmB,GAAG,GAAG,EAAE,CAC/B,CAAC,kBAAkB,IAAI,uBAAuB,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;IAC5E,IAAI,CAAC,mBAAmB,EAAE;QAAE,OAAO;IAEnC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC9B,MAAM,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,CAAC;IACjE,IACE,CAAC,oBAAoB;QACrB,CAAC,OAAO,CAAC,IAAI,C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I,IAAI;SAC9D,CAAC,CAAC;IACL,CAAC;IACD,KAAK,4BAA4B,CAAC,KAAK,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/** Hydrate only bytes matching the current document's authenticated attachment intent. */\n\nimport { getDocumentAttachments } from \"../../../data/documents/documentContent\";\nimport { hydrateDocumentAttachmentBlobs } from \"../../../workflows/blobs\";\nimport type { DocumentRecord } from \"../../../workflows/documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../workflows/principals/runtimePolicyWarmer\";\nimport { commitHydratedAttachment } from \"./attachmentHydrationCommit\";\nimport { runDocumentOrphanMaintenance } from \"./orphanMaintenance\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport async function hydrateAttachmentBlobs(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n currentRecord: DocumentRecord | null,\n expectedGeneration?: DocumentStoreSyncGeneration,\n) {\n const generationIsCurrent = () =>\n !expectedGeneration || isSyncGenerationCurrent(state, expectedGeneration);\n if (!generationIsCurrent()) return;\n\n const runtime = state.runtime;\n const encapsulationKeyPair = runtime.crypto.encapsulationKeyPair;\n if (\n !encapsulationKeyPair ||\n !runtime.auth.isAuthenticated ||\n !runtime.state.online ||\n !currentRecord?.documentId\n ) {\n return;\n }\n\n const attachments = getDocumentAttachments(currentDoc);\n if (attachments.length === 0) {\n return;\n }\n\n const expectedStorageKeys = { ...state.attachmentStorageKeyBySlotId };\n const hydratedBlobs = await hydrateDocumentAttachmentBlobs({\n apiClient: runtime.apiClient,\n attachments,\n documentId: currentRecord.documentId,\n execSql: runtime.infra.execSql,\n localBlobIdBySlotId: state.attachmentBlobIdBySlotId,\n localStorageKeyBySlotId: state.attachmentStorageKeyBySlotId,\n log: runtime.util.log,\n rejectedServedBindings: state.rejectedServedAttachmentBindings,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveProjectionUserKey:\n expectedGeneration?.resolveProjectionUserKey ??\n state.resolveProjectionUserKey,\n targetSecretKey: encapsulationKeyPair.secretKey,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n });\n if (!generationIsCurrent()) return;\n if (!hydratedBlobs) {\n return;\n }\n\n for (const hydratedBlob of hydratedBlobs) {\n await commitHydratedAttachment({\n state,\n currentDoc,\n hydratedBlob,\n generationIsCurrent,\n expectedStorageKey:\n expectedStorageKeys[hydratedBlob.attachment.slotId] ?? null,\n });\n }\n void runDocumentOrphanMaintenance(state);\n}\n"]}
|
|
@@ -8,6 +8,7 @@ import { removeLocalAttachmentSlot } from "./attachmentPersistence.js";
|
|
|
8
8
|
import { deleteUnreferencedStagedAttachmentBytes, installPendingAttachmentRows, stagePendingAttachments, } from "./attachmentStaging.js";
|
|
9
9
|
import { captureAttachmentWriteGeneration, isAttachmentWriteGenerationCurrent, shouldAbortAttachmentPersistFollowup, } from "./attachmentWriteGeneration.js";
|
|
10
10
|
import { ensureDocumentStoreReady } from "./initialization.js";
|
|
11
|
+
import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
|
|
11
12
|
import { advancePendingBaseVersion, pendingDeltaSinceBase, persistDocument, } from "./persistence.js";
|
|
12
13
|
import { reportDocumentStoreWriteFailure } from "./reportWriteFailure.js";
|
|
13
14
|
import { canAttachFiles, canWriteDocument, setReadySnapshot, } from "./state.js";
|
|
@@ -171,19 +172,20 @@ async function persistSlotAttachmentFile(state, slotId, file, writeGeneration) {
|
|
|
171
172
|
state.runtime.util.log(`Queued attachment ${file.name} for slot ${slotId}.`);
|
|
172
173
|
requestDocumentStoreSync(state);
|
|
173
174
|
}
|
|
174
|
-
|
|
175
|
+
function installCommittedAttachmentRemoval(input) {
|
|
175
176
|
const { slotId, state, storageKey } = input;
|
|
176
177
|
if (!storageKey)
|
|
177
178
|
return;
|
|
178
179
|
state.pendingAttachments = state.pendingAttachments.filter((attachment) => attachment.slotId !== slotId || attachment.storageKey !== storageKey);
|
|
180
|
+
// The committed removal queued this key. A reset can leave another document
|
|
181
|
+
// uploading from the same copy, even though this document is local-only.
|
|
182
|
+
if (!input.syncedAttachment)
|
|
183
|
+
void runDocumentOrphanMaintenance(state);
|
|
179
184
|
if (input.syncedAttachment ||
|
|
180
185
|
state.attachmentStorageKeyBySlotId[slotId] !== storageKey) {
|
|
181
186
|
return;
|
|
182
187
|
}
|
|
183
188
|
removeLocalAttachmentSlot(state, slotId);
|
|
184
|
-
await state.runtime.infra.blobStore
|
|
185
|
-
.deleteBytes(storageKey)
|
|
186
|
-
.catch(() => state.runtime.util.log(`Documents: failed to delete detached attachment bytes for ${slotId}.`));
|
|
187
189
|
setReadySnapshot(state, input.currentDoc, state.snapshot.syncing, state.snapshot.text, state.snapshot.structuredFields);
|
|
188
190
|
}
|
|
189
191
|
async function persistRemovedAttachment(state, slotId, writeGeneration) {
|
|
@@ -244,7 +246,7 @@ async function persistRemovedAttachment(state, slotId, writeGeneration) {
|
|
|
244
246
|
// See persistAttachedFiles: only durable same-identity work re-arms sync.
|
|
245
247
|
return;
|
|
246
248
|
}
|
|
247
|
-
|
|
249
|
+
installCommittedAttachmentRemoval({
|
|
248
250
|
currentDoc,
|
|
249
251
|
slotId,
|
|
250
252
|
state,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachments.js","sourceRoot":"","sources":["attachments.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAEjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAEvD,OAAO,EACL,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AA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IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QACrD,OAAO;IACT,CAAC;IAED,MAAM,eAAe,GAAG,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAChE,IAAI,CAAC,eAAe;QAAE,OAAO;IAC7B,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU;SAChC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;SACtB,IAAI,CAAC,KAAK,IAAI,EAAE,CACf,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe,CAAC,CAChE;SACA,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,+BAA+B,CAAC,KAAK,EAAE,0BAA0B,EAAE,KAAK,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;IACL,OAAO,KAAK,CAAC,UAAU,CAAC;AAC1B,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport {\n addDocumentAttachments,\n getDocumentAttachments,\n removeDocumentAttachment,\n} from \"../../../data/documents/documentContent\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport type { PendingAttachmentRecord } from \"../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport type { DocumentAttachmentUpload } from \"../types\";\nimport {\n buildAttachmentIntent,\n buildPendingAttachments,\n} from \"./attachmentIntents\";\nimport {\n persistStagedAttachmentMutation,\n restoreFailedAttachmentMutation,\n} from \"./attachmentMutationPersistence\";\nimport { removeLocalAttachmentSlot } from \"./attachmentPersistence\";\nimport {\n deleteUnreferencedStagedAttachmentBytes,\n installPendingAttachmentRows,\n stagePendingAttachments,\n} from \"./attachmentStaging\";\nimport {\n type AttachmentWriteGeneration,\n captureAttachmentWriteGeneration,\n isAttachmentWriteGenerationCurrent,\n shouldAbortAttachmentPersistFollowup,\n} from \"./attachmentWriteGeneration\";\nimport { ensureDocumentStoreReady } from \"./initialization\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"./persistence\";\nimport { reportDocumentStoreWriteFailure } from \"./reportWriteFailure\";\nimport {\n canAttachFiles,\n canWriteDocument,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./syncGeneration\";\n\n// Fixed literal: a reported message must never carry file names or slot ids.\nconst ATTACHMENT_FAILURE_MESSAGE = \"Documents: attachment mutation failed\";\n\nfunction logAttachedFiles(state: DocumentStoreState, count: number) {\n state.runtime.util.log(\n state.runtime.state.online && state.runtime.auth.isAuthenticated\n ? `Attached ${count} file${count === 1 ? \"\" : \"s\"} to document ${state.localId}.`\n : `Stored ${count} attachment${count === 1 ? \"\" : \"s\"} locally for document ${state.localId}.`,\n );\n}\n\nasync function persistAttachedFiles(\n state: DocumentStoreState,\n files: ReadonlyArray<DocumentAttachmentUpload>,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n\n if (!currentDoc || !canAttachFiles(state)) {\n state.runtime.util.log(\n \"Documents: attachments require a local key package.\",\n );\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const { nextAttachments, nextPendingAttachments } =\n await buildPendingAttachments(state.localId, files);\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n addDocumentAttachments(currentDoc, nextAttachments);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n // Captured at delta time: the enqueued row proves coverage up to exactly\n // this version, so it is the frontier the persist below may publish.\n const coveredVersion = encodeVersionVector(currentDoc);\n\n let staged: Awaited<ReturnType<typeof stagePendingAttachments>>;\n try {\n staged = await stagePendingAttachments({\n files,\n generation,\n pendingAttachments: nextPendingAttachments,\n state,\n });\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (!staged) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n return;\n }\n // This persist changes attachments, not prose. setReadySnapshot always\n // re-derives attachments from the doc, but preserve the text/structured\n // fields so an attach that overlaps an in-flight keystroke does not republish\n // a stale doc read over the live optimistic editor value.\n const persisted = await persistStagedAttachmentMutation({\n attachmentUpdate,\n coveredVersion,\n currentDoc,\n generation,\n rollbackSnapshot,\n staged,\n state,\n });\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n await deleteUnreferencedStagedAttachmentBytes({\n generation,\n pendingAttachments: staged.pendingAttachments,\n state,\n });\n return;\n }\n installPendingAttachmentRows({ ...staged, state });\n advancePendingBaseVersion(state, currentDoc);\n logAttachedFiles(state, files.length);\n requestDocumentStoreSync(state);\n}\n\nasync function persistSlotAttachmentFile(\n state: DocumentStoreState,\n slotId: string,\n file: DocumentAttachmentUpload,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n\n if (!currentDoc || !canAttachFiles(state)) {\n state.runtime.util.log(\n \"Documents: slot attachments require a local key package.\",\n );\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const replacementAttachment = await buildAttachmentIntent(slotId, file);\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n addDocumentAttachments(currentDoc, [replacementAttachment]);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n const coveredVersion = encodeVersionVector(currentDoc);\n\n const storageKey = `${state.localId}-${slotId}-${crypto.randomUUID()}`;\n const pendingAttachment: PendingAttachmentRecord = {\n byteLength: replacementAttachment.byteLength,\n contentSha256: replacementAttachment.contentSha256,\n localId: state.localId,\n mimeType: replacementAttachment.mimeType,\n name: replacementAttachment.name,\n slotId,\n storageKey,\n };\n let staged: Awaited<ReturnType<typeof stagePendingAttachments>>;\n try {\n staged = await stagePendingAttachments({\n files: [file],\n generation,\n pendingAttachments: [pendingAttachment],\n state,\n });\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (!staged) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n return;\n }\n // Preserve the optimistic text/structured fields (see persistAttachedFiles):\n // a slot replacement overlapping a keystroke must not regress the editor.\n const persisted = await persistStagedAttachmentMutation({\n attachmentUpdate,\n coveredVersion,\n currentDoc,\n generation,\n rollbackSnapshot,\n staged,\n state,\n });\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n await deleteUnreferencedStagedAttachmentBytes({\n generation,\n pendingAttachments: staged.pendingAttachments,\n state,\n });\n return;\n }\n installPendingAttachmentRows({ ...staged, state });\n advancePendingBaseVersion(state, currentDoc);\n state.runtime.util.log(`Queued attachment ${file.name} for slot ${slotId}.`);\n requestDocumentStoreSync(state);\n}\n\nasync function installCommittedAttachmentRemoval(input: {\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>;\n slotId: string;\n state: DocumentStoreState;\n storageKey: string | undefined;\n syncedAttachment: boolean;\n}): Promise<void> {\n const { slotId, state, storageKey } = input;\n if (!storageKey) return;\n state.pendingAttachments = state.pendingAttachments.filter(\n (attachment) =>\n attachment.slotId !== slotId || attachment.storageKey !== storageKey,\n );\n if (\n input.syncedAttachment ||\n state.attachmentStorageKeyBySlotId[slotId] !== storageKey\n ) {\n return;\n }\n removeLocalAttachmentSlot(state, slotId);\n await state.runtime.infra.blobStore\n .deleteBytes(storageKey)\n .catch(() =>\n state.runtime.util.log(\n `Documents: failed to delete detached attachment bytes for ${slotId}.`,\n ),\n );\n setReadySnapshot(\n state,\n input.currentDoc,\n state.snapshot.syncing,\n state.snapshot.text,\n state.snapshot.structuredFields,\n );\n}\n\nasync function persistRemovedAttachment(\n state: DocumentStoreState,\n slotId: string,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n if (!currentDoc) {\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const existingAttachment = getDocumentAttachments(currentDoc).find(\n (attachment) => attachment.slotId === slotId,\n );\n if (!existingAttachment) {\n return;\n }\n\n const storageKey = state.attachmentStorageKeyBySlotId[slotId];\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n removeDocumentAttachment(currentDoc, slotId);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n const coveredVersion = encodeVersionVector(currentDoc);\n const pendingUpdate = createPendingUpdateFields(attachmentUpdate);\n const syncedAttachment = Boolean(state.record?.documentId);\n\n // Preserve the optimistic text/structured fields (see persistAttachedFiles):\n // removing an attachment while typing must not regress the editor.\n let persisted: Awaited<ReturnType<typeof persistDocument>>;\n try {\n persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n {\n ...(storageKey\n ? {\n attachmentRemoval: {\n mode: syncedAttachment\n ? (\"detach\" as const)\n : (\"delete\" as const),\n slotId,\n storageKey,\n },\n }\n : {}),\n ...(pendingUpdate ? { pendingUpdate } : {}),\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n generation,\n );\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n // See persistAttachedFiles: only durable same-identity work re-arms sync.\n return;\n }\n await installCommittedAttachmentRemoval({\n currentDoc,\n slotId,\n state,\n storageKey,\n syncedAttachment,\n });\n advancePendingBaseVersion(state, currentDoc);\n state.runtime.util.log(\n `Removed attachment ${existingAttachment.name} from document ${state.localId}.`,\n );\n requestDocumentStoreSync(state);\n}\n\nexport async function attachFilesToDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n files: ReadonlyArray<DocumentAttachmentUpload>,\n) {\n if (files.length === 0) {\n return;\n }\n\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => persistAttachedFiles(state, files, writeGeneration))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n\nexport async function removeAttachmentFromDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n slotId: string,\n) {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => persistRemovedAttachment(state, slotId, writeGeneration))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n\nexport async function replaceAttachmentInDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n slotId: string,\n file: DocumentAttachmentUpload,\n) {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () =>\n persistSlotAttachmentFile(state, slotId, file, writeGeneration),\n )\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"attachments.js","sourceRoot":"","sources":["attachments.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,GACzB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAEjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAEvD,OAAO,EACL,qBAAqB,EACrB,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,+BAA+B,EAC/B,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EACL,uCAAuC,EACvC,4BAA4B,EAC5B,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,gCAAgC,EAChC,kCAAkC,EAClC,oCAAoC,GACrC,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACnE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c,EAAE,EAAE;QACxB,+BAA+B,CAAC,KAAK,EAAE,0BAA0B,EAAE,KAAK,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;IACL,OAAO,KAAK,CAAC,UAAU,CAAC;AAC1B,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport {\n addDocumentAttachments,\n getDocumentAttachments,\n removeDocumentAttachment,\n} from \"../../../data/documents/documentContent\";\nimport { createPendingUpdateFields } from \"../../../data/documents/documentSync\";\nimport type { PendingAttachmentRecord } from \"../../../workflows/documents\";\nimport { requestDocumentStoreSync } from \"../registry\";\nimport type { DocumentAttachmentUpload } from \"../types\";\nimport {\n buildAttachmentIntent,\n buildPendingAttachments,\n} from \"./attachmentIntents\";\nimport {\n persistStagedAttachmentMutation,\n restoreFailedAttachmentMutation,\n} from \"./attachmentMutationPersistence\";\nimport { removeLocalAttachmentSlot } from \"./attachmentPersistence\";\nimport {\n deleteUnreferencedStagedAttachmentBytes,\n installPendingAttachmentRows,\n stagePendingAttachments,\n} from \"./attachmentStaging\";\nimport {\n type AttachmentWriteGeneration,\n captureAttachmentWriteGeneration,\n isAttachmentWriteGenerationCurrent,\n shouldAbortAttachmentPersistFollowup,\n} from \"./attachmentWriteGeneration\";\nimport { ensureDocumentStoreReady } from \"./initialization\";\nimport { runDocumentOrphanMaintenance } from \"./orphanMaintenance\";\nimport {\n advancePendingBaseVersion,\n pendingDeltaSinceBase,\n persistDocument,\n} from \"./persistence\";\nimport { reportDocumentStoreWriteFailure } from \"./reportWriteFailure\";\nimport {\n canAttachFiles,\n canWriteDocument,\n type DocumentStoreState,\n setReadySnapshot,\n} from \"./state\";\nimport { captureDocumentStoreSyncGeneration } from \"./syncGeneration\";\n\n// Fixed literal: a reported message must never carry file names or slot ids.\nconst ATTACHMENT_FAILURE_MESSAGE = \"Documents: attachment mutation failed\";\n\nfunction logAttachedFiles(state: DocumentStoreState, count: number) {\n state.runtime.util.log(\n state.runtime.state.online && state.runtime.auth.isAuthenticated\n ? `Attached ${count} file${count === 1 ? \"\" : \"s\"} to document ${state.localId}.`\n : `Stored ${count} attachment${count === 1 ? \"\" : \"s\"} locally for document ${state.localId}.`,\n );\n}\n\nasync function persistAttachedFiles(\n state: DocumentStoreState,\n files: ReadonlyArray<DocumentAttachmentUpload>,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n\n if (!currentDoc || !canAttachFiles(state)) {\n state.runtime.util.log(\n \"Documents: attachments require a local key package.\",\n );\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const { nextAttachments, nextPendingAttachments } =\n await buildPendingAttachments(state.localId, files);\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n addDocumentAttachments(currentDoc, nextAttachments);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n // Captured at delta time: the enqueued row proves coverage up to exactly\n // this version, so it is the frontier the persist below may publish.\n const coveredVersion = encodeVersionVector(currentDoc);\n\n let staged: Awaited<ReturnType<typeof stagePendingAttachments>>;\n try {\n staged = await stagePendingAttachments({\n files,\n generation,\n pendingAttachments: nextPendingAttachments,\n state,\n });\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (!staged) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n return;\n }\n // This persist changes attachments, not prose. setReadySnapshot always\n // re-derives attachments from the doc, but preserve the text/structured\n // fields so an attach that overlaps an in-flight keystroke does not republish\n // a stale doc read over the live optimistic editor value.\n const persisted = await persistStagedAttachmentMutation({\n attachmentUpdate,\n coveredVersion,\n currentDoc,\n generation,\n rollbackSnapshot,\n staged,\n state,\n });\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n await deleteUnreferencedStagedAttachmentBytes({\n generation,\n pendingAttachments: staged.pendingAttachments,\n state,\n });\n return;\n }\n installPendingAttachmentRows({ ...staged, state });\n advancePendingBaseVersion(state, currentDoc);\n logAttachedFiles(state, files.length);\n requestDocumentStoreSync(state);\n}\n\nasync function persistSlotAttachmentFile(\n state: DocumentStoreState,\n slotId: string,\n file: DocumentAttachmentUpload,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n\n if (!currentDoc || !canAttachFiles(state)) {\n state.runtime.util.log(\n \"Documents: slot attachments require a local key package.\",\n );\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const replacementAttachment = await buildAttachmentIntent(slotId, file);\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n addDocumentAttachments(currentDoc, [replacementAttachment]);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n const coveredVersion = encodeVersionVector(currentDoc);\n\n const storageKey = `${state.localId}-${slotId}-${crypto.randomUUID()}`;\n const pendingAttachment: PendingAttachmentRecord = {\n byteLength: replacementAttachment.byteLength,\n contentSha256: replacementAttachment.contentSha256,\n localId: state.localId,\n mimeType: replacementAttachment.mimeType,\n name: replacementAttachment.name,\n slotId,\n storageKey,\n };\n let staged: Awaited<ReturnType<typeof stagePendingAttachments>>;\n try {\n staged = await stagePendingAttachments({\n files: [file],\n generation,\n pendingAttachments: [pendingAttachment],\n state,\n });\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (!staged) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n return;\n }\n // Preserve the optimistic text/structured fields (see persistAttachedFiles):\n // a slot replacement overlapping a keystroke must not regress the editor.\n const persisted = await persistStagedAttachmentMutation({\n attachmentUpdate,\n coveredVersion,\n currentDoc,\n generation,\n rollbackSnapshot,\n staged,\n state,\n });\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n await deleteUnreferencedStagedAttachmentBytes({\n generation,\n pendingAttachments: staged.pendingAttachments,\n state,\n });\n return;\n }\n installPendingAttachmentRows({ ...staged, state });\n advancePendingBaseVersion(state, currentDoc);\n state.runtime.util.log(`Queued attachment ${file.name} for slot ${slotId}.`);\n requestDocumentStoreSync(state);\n}\n\nfunction installCommittedAttachmentRemoval(input: {\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>;\n slotId: string;\n state: DocumentStoreState;\n storageKey: string | undefined;\n syncedAttachment: boolean;\n}): void {\n const { slotId, state, storageKey } = input;\n if (!storageKey) return;\n state.pendingAttachments = state.pendingAttachments.filter(\n (attachment) =>\n attachment.slotId !== slotId || attachment.storageKey !== storageKey,\n );\n // The committed removal queued this key. A reset can leave another document\n // uploading from the same copy, even though this document is local-only.\n if (!input.syncedAttachment) void runDocumentOrphanMaintenance(state);\n if (\n input.syncedAttachment ||\n state.attachmentStorageKeyBySlotId[slotId] !== storageKey\n ) {\n return;\n }\n removeLocalAttachmentSlot(state, slotId);\n setReadySnapshot(\n state,\n input.currentDoc,\n state.snapshot.syncing,\n state.snapshot.text,\n state.snapshot.structuredFields,\n );\n}\n\nasync function persistRemovedAttachment(\n state: DocumentStoreState,\n slotId: string,\n writeGeneration: AttachmentWriteGeneration,\n) {\n if (!isAttachmentWriteGenerationCurrent(state, writeGeneration)) return;\n const currentDoc = state.doc;\n if (!currentDoc) {\n return;\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n return;\n }\n\n const existingAttachment = getDocumentAttachments(currentDoc).find(\n (attachment) => attachment.slotId === slotId,\n );\n if (!existingAttachment) {\n return;\n }\n\n const storageKey = state.attachmentStorageKeyBySlotId[slotId];\n if (\n !isAttachmentWriteGenerationCurrent(state, writeGeneration) ||\n state.doc !== currentDoc\n )\n return;\n const rollbackSnapshot = exportFullHistorySnapshot(currentDoc).slice();\n removeDocumentAttachment(currentDoc, slotId);\n const attachmentUpdate = pendingDeltaSinceBase(state, currentDoc);\n const coveredVersion = encodeVersionVector(currentDoc);\n const pendingUpdate = createPendingUpdateFields(attachmentUpdate);\n const syncedAttachment = Boolean(state.record?.documentId);\n\n // Preserve the optimistic text/structured fields (see persistAttachedFiles):\n // removing an attachment while typing must not regress the editor.\n let persisted: Awaited<ReturnType<typeof persistDocument>>;\n try {\n persisted = await persistDocument(\n state,\n currentDoc,\n { snapshotEndVersion: coveredVersion },\n {\n ...(storageKey\n ? {\n attachmentRemoval: {\n mode: syncedAttachment\n ? (\"detach\" as const)\n : (\"delete\" as const),\n slotId,\n storageKey,\n },\n }\n : {}),\n ...(pendingUpdate ? { pendingUpdate } : {}),\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n generation,\n );\n } catch (error) {\n await restoreFailedAttachmentMutation({\n generation,\n rollbackSnapshot,\n state,\n });\n throw error;\n }\n if (\n shouldAbortAttachmentPersistFollowup(\n state,\n writeGeneration,\n generation,\n persisted,\n )\n ) {\n // See persistAttachedFiles: only durable same-identity work re-arms sync.\n return;\n }\n installCommittedAttachmentRemoval({\n currentDoc,\n slotId,\n state,\n storageKey,\n syncedAttachment,\n });\n advancePendingBaseVersion(state, currentDoc);\n state.runtime.util.log(\n `Removed attachment ${existingAttachment.name} from document ${state.localId}.`,\n );\n requestDocumentStoreSync(state);\n}\n\nexport async function attachFilesToDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n files: ReadonlyArray<DocumentAttachmentUpload>,\n) {\n if (files.length === 0) {\n return;\n }\n\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => persistAttachedFiles(state, files, writeGeneration))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n\nexport async function removeAttachmentFromDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n slotId: string,\n) {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () => persistRemovedAttachment(state, slotId, writeGeneration))\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n\nexport async function replaceAttachmentInDocumentStore(\n state: DocumentStoreState,\n scheduleSync: () => void,\n slotId: string,\n file: DocumentAttachmentUpload,\n) {\n let ready: boolean;\n try {\n ready = await ensureDocumentStoreReady(state, scheduleSync);\n } catch (error) {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n return;\n }\n\n if (!ready || !state.doc || !canWriteDocument(state)) {\n return;\n }\n\n const writeGeneration = captureAttachmentWriteGeneration(state);\n if (!writeGeneration) return;\n state.writeChain = state.writeChain\n .catch(() => undefined)\n .then(async () =>\n persistSlotAttachmentFile(state, slotId, file, writeGeneration),\n )\n .catch((error: unknown) => {\n reportDocumentStoreWriteFailure(state, ATTACHMENT_FAILURE_MESSAGE, error);\n });\n return state.writeChain;\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { discardPersistedDocumentToShell
|
|
1
|
+
import { discardPersistedDocumentToShell } from "../../../workflows/documents/index.js";
|
|
2
2
|
import { chainIdentityWrite } from "./identityWriteChain.js";
|
|
3
|
+
import { runDocumentOrphanMaintenance } from "./orphanMaintenance.js";
|
|
3
4
|
import { resetDocumentStore } from "./state.js";
|
|
4
5
|
/**
|
|
5
6
|
* User-initiated escape hatch for a document whose queued local writes can no
|
|
@@ -79,7 +80,7 @@ export async function discardDocumentStoreLocalState(state, expectedDocumentId)
|
|
|
79
80
|
}
|
|
80
81
|
// The conversion queued the bytes its dropped rows pointed to; the
|
|
81
82
|
// reclaim deletes each only once no other row references it.
|
|
82
|
-
|
|
83
|
+
void runDocumentOrphanMaintenance(state);
|
|
83
84
|
resetDocumentStore(state);
|
|
84
85
|
runtime.util.log(`Documents: discarded local edits for document ${state.localId}; re-pulling the server copy`);
|
|
85
86
|
return true;
|