@fgv/ts-extras 5.1.0-47 → 5.1.0-49
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/LICENSE +1 -1
- package/dist/packlets/ai-assist/completionClient.js +435 -0
- package/dist/packlets/ai-assist/completionClient.js.map +1 -0
- package/dist/packlets/ai-assist/embeddingClient.js +2 -2
- package/dist/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/dist/packlets/ai-assist/endpoint.js +29 -0
- package/dist/packlets/ai-assist/endpoint.js.map +1 -1
- package/dist/packlets/ai-assist/http.js +48 -19
- package/dist/packlets/ai-assist/http.js.map +1 -1
- package/dist/packlets/ai-assist/imageGenerationClient.js +454 -0
- package/dist/packlets/ai-assist/imageGenerationClient.js.map +1 -0
- package/dist/packlets/ai-assist/index.js +3 -1
- package/dist/packlets/ai-assist/index.js.map +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/dist/packlets/ai-assist/listModelsClient.js +294 -0
- package/dist/packlets/ai-assist/listModelsClient.js.map +1 -0
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +2 -5
- package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js +2 -1
- package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
- package/dist/packlets/crypto-utils/encryptedFile.js +37 -0
- package/dist/packlets/crypto-utils/encryptedFile.js.map +1 -1
- package/dist/packlets/crypto-utils/index.js +1 -1
- package/dist/packlets/crypto-utils/index.js.map +1 -1
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +32 -0
- package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -1
- package/dist/ts-extras.d.ts +59 -4
- package/lib/packlets/ai-assist/completionClient.d.ts +74 -0
- package/lib/packlets/ai-assist/completionClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/completionClient.js +439 -0
- package/lib/packlets/ai-assist/completionClient.js.map +1 -0
- package/lib/packlets/ai-assist/embeddingClient.js +1 -1
- package/lib/packlets/ai-assist/embeddingClient.js.map +1 -1
- package/lib/packlets/ai-assist/endpoint.d.ts +21 -0
- package/lib/packlets/ai-assist/endpoint.d.ts.map +1 -1
- package/lib/packlets/ai-assist/endpoint.js +31 -0
- package/lib/packlets/ai-assist/endpoint.js.map +1 -1
- package/lib/packlets/ai-assist/http.d.ts +12 -2
- package/lib/packlets/ai-assist/http.d.ts.map +1 -1
- package/lib/packlets/ai-assist/http.js +49 -18
- package/lib/packlets/ai-assist/http.js.map +1 -1
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts +46 -0
- package/lib/packlets/ai-assist/imageGenerationClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/imageGenerationClient.js +458 -0
- package/lib/packlets/ai-assist/imageGenerationClient.js.map +1 -0
- package/lib/packlets/ai-assist/index.d.ts +3 -1
- package/lib/packlets/ai-assist/index.d.ts.map +1 -1
- package/lib/packlets/ai-assist/index.js +9 -7
- package/lib/packlets/ai-assist/index.js.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.js +2 -2
- package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/lib/packlets/ai-assist/listModelsClient.d.ts +46 -0
- package/lib/packlets/ai-assist/listModelsClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/listModelsClient.js +298 -0
- package/lib/packlets/ai-assist/listModelsClient.js.map +1 -0
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +2 -5
- package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js +2 -1
- package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -1
- package/lib/packlets/crypto-utils/encryptedFile.d.ts +25 -0
- package/lib/packlets/crypto-utils/encryptedFile.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/encryptedFile.js +38 -0
- package/lib/packlets/crypto-utils/encryptedFile.js.map +1 -1
- package/lib/packlets/crypto-utils/index.d.ts +1 -1
- package/lib/packlets/crypto-utils/index.d.ts.map +1 -1
- package/lib/packlets/crypto-utils/index.js +2 -1
- package/lib/packlets/crypto-utils/index.js.map +1 -1
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +30 -2
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +32 -0
- package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -1
- package/package.json +7 -7
- package/dist/packlets/ai-assist/apiClient.js +0 -1236
- package/dist/packlets/ai-assist/apiClient.js.map +0 -1
- package/lib/packlets/ai-assist/apiClient.d.ts +0 -152
- package/lib/packlets/ai-assist/apiClient.d.ts.map +0 -1
- package/lib/packlets/ai-assist/apiClient.js +0 -1244
- package/lib/packlets/ai-assist/apiClient.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gemini.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/gemini.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;;;;;;;;;;;;;;;;;;;;;AAEZ;;;;;;;;;;GAUG;AAEH,OA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D,MAAM,KAAK,GAAG,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,EAAE,CAAC;IAClC,MAAM,IAAI,GAAG,MAAM,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AACvF,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming adapter for Gemini's `streamGenerateContent` endpoint. Gemini\n * emits no explicit tool-progress events even when `google_search` is\n * enabled — grounding metadata arrives attached to text chunks — so this\n * adapter never yields `tool-event`s.\n *\n * Client-defined tools (`functionCall` parts) are emitted as\n * `client-tool-call-done` immediately (no delta accumulation needed for Gemini).\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { isJsonObject, type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildGeminiContents } from '../chatRequestBuilders';\nimport { AiPrompt, type AiToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toGeminiTools } from '../toolFormats';\nimport { type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport { IStreamApiConfig, openSseConnection, validateEventPayload } from './common';\n\n// ============================================================================\n// Accumulated call state (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated function call from a Gemini stream. Gemini does not assign\n * call IDs; correlation is by tool name. Arguments arrive complete in the\n * `functionCall` part (no delta accumulation).\n * @internal\n */\nexport interface IAccumulatedGeminiFunctionCall {\n readonly name: string;\n readonly args: JsonObject;\n /**\n * The opaque thought signature Gemini stamps on a `functionCall` part when\n * thinking is enabled. It must be echoed back, verbatim, on the continuation's\n * model turn alongside the `functionCall`, or Gemini rejects the follow-up with\n * \"Function call is missing a thought_signature in functionCall parts\".\n * Absent when thinking is disabled. See\n * https://ai.google.dev/gemini-api/docs/thought-signatures.\n */\n readonly thoughtSignature?: string;\n}\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * One `parts[]` element in a Gemini streaming chunk. Text parts and\n * functionCall parts are both surfaced.\n * @internal\n */\ninterface IGeminiStreamPart {\n readonly text?: string;\n readonly functionCall?: { readonly name?: string; readonly args?: JsonObject };\n /**\n * The opaque thought signature attached to a `functionCall` part when thinking\n * is enabled. A sibling of `functionCall`/`text` at the part level (base64\n * string). Captured for replay on the continuation's model turn.\n */\n readonly thoughtSignature?: string;\n}\n\n/**\n * One `candidates[]` element in a Gemini streaming chunk.\n * @internal\n */\ninterface IGeminiStreamCandidate {\n readonly content?: { readonly parts?: ReadonlyArray<IGeminiStreamPart> };\n readonly finishReason?: string;\n}\n\n/**\n * One streaming chunk from `streamGenerateContent?alt=sse`.\n * @internal\n */\ninterface IGeminiStreamChunk {\n readonly candidates: ReadonlyArray<IGeminiStreamCandidate>;\n}\n\nconst jsonObjectValidator: Validator<JsonObject> = Validators.isA<JsonObject>(\n 'JsonObject',\n (v): v is JsonObject => isJsonObject(v)\n);\n\nconst geminiFunctionCallInner: Validator<{ name?: string; args?: JsonObject }> = Validators.object<{\n name?: string;\n args?: JsonObject;\n}>(\n {\n name: Validators.string.optional(),\n args: jsonObjectValidator.optional()\n },\n { options: { optionalFields: ['name', 'args'] } }\n);\n\nconst geminiStreamPart: Validator<IGeminiStreamPart> = Validators.object<IGeminiStreamPart>(\n {\n text: Validators.string.optional(),\n functionCall: geminiFunctionCallInner.optional(),\n thoughtSignature: Validators.string.optional()\n },\n { options: { optionalFields: ['text', 'functionCall', 'thoughtSignature'] } }\n);\n\nconst geminiStreamContent: Validator<{ parts?: ReadonlyArray<IGeminiStreamPart> }> = Validators.object<{\n parts?: ReadonlyArray<IGeminiStreamPart>;\n}>({ parts: Validators.arrayOf(geminiStreamPart).optional() }, { options: { optionalFields: ['parts'] } });\n\nconst geminiStreamCandidate: Validator<IGeminiStreamCandidate> = Validators.object<IGeminiStreamCandidate>(\n {\n content: geminiStreamContent.optional(),\n finishReason: Validators.string.optional()\n },\n { options: { optionalFields: ['content', 'finishReason'] } }\n);\n\nconst geminiStreamChunk: Validator<IGeminiStreamChunk> = Validators.object<IGeminiStreamChunk>({\n candidates: Validators.arrayOf(geminiStreamCandidate)\n});\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Translates a Gemini streamGenerateContent SSE stream into unified events.\n *\n * @internal\n */\nasync function* translateGeminiStream(\n response: Response,\n functionCalls: IAccumulatedGeminiFunctionCall[]\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let receivedFinishReason = false;\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const json = parseSseEventJson(message.data);\n /* c8 ignore next 3 - defensive: malformed SSE events skipped */\n if (json === undefined) {\n continue;\n }\n const chunk = validateEventPayload(json, geminiStreamChunk);\n /* c8 ignore next 1 - defensive: chunk?.candidates optional chain unreachable after validation */\n const candidate = chunk?.candidates[0];\n /* c8 ignore next 3 - defensive: SSE events without candidates skipped */\n if (!candidate) {\n continue;\n }\n /* c8 ignore next 1 - defensive: candidate.content?.parts null branch unreachable after validation */\n const parts = candidate.content?.parts;\n if (parts) {\n for (const part of parts) {\n if (typeof part.text === 'string' && part.text.length > 0) {\n fullText += part.text;\n yield { type: 'text-delta', delta: part.text };\n /* c8 ignore next 1 - defensive: functionCall parts without a `name` are silently dropped (cannot construct a continuation builder entry without one) */\n } else if (part.functionCall?.name) {\n const { name, args } = part.functionCall;\n /* c8 ignore next 1 - defensive: Gemini always sends args; {} fallback unreachable in practice */\n const callArgs = args ?? {};\n // Capture the part-level thoughtSignature (sibling of functionCall) so the\n // continuation builder can replay it on the model turn. Reads as undefined\n // when thinking is disabled; the builder omits the key in that case.\n functionCalls.push({ name, args: callArgs, thoughtSignature: part.thoughtSignature });\n yield { type: 'client-tool-call-done', toolName: name, args: callArgs };\n }\n }\n }\n const finishReason = candidate.finishReason;\n if (typeof finishReason === 'string' && finishReason.length > 0) {\n truncated = finishReason === 'MAX_TOKENS';\n receivedFinishReason = true;\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (receivedFinishReason) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Gemini stream ended without a finishReason' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Gemini request and returns the unified-event iterable\n * on success.\n *\n * @internal\n */\nexport async function callGeminiStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n functionCalls?: IAccumulatedGeminiFunctionCall[],\n continuationMessages?: ReadonlyArray<JsonObject>,\n maxTokens?: number\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/models/${config.model}:streamGenerateContent?alt=sse`;\n const contents = buildGeminiContents(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n // Temperature is sent only when explicitly provided; otherwise Gemini's default applies.\n const generationConfig: Record<string, unknown> = {};\n if (temperature !== undefined) {\n generationConfig.temperature = temperature;\n }\n if (maxTokens !== undefined) {\n generationConfig.maxOutputTokens = maxTokens;\n }\n if (resolvedThinking?.geminiThinkingBudget !== undefined) {\n generationConfig.thinkingConfig = { thinkingBudget: resolvedThinking.geminiThinkingBudget };\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(generationConfig, resolvedThinking.otherParams);\n }\n const body: Record<string, unknown> = {\n systemInstruction: { parts: [{ text: prompt.system }] },\n contents,\n generationConfig\n };\n /* c8 ignore next 3 - tools branch not exercised in streaming tests */\n if (tools && tools.length > 0) {\n body.tools = toGeminiTools(tools);\n }\n const headers: Record<string, string> = { 'x-goog-api-key': config.apiKey };\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Gemini streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const calls = functionCalls ?? [];\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateGeminiStream(response, calls)));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gemini.js","sourceRoot":"","sources":["../../../../src/packlets/ai-assist/streamingAdapters/gemini.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AA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AAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAC1F,MAAM,CAAC,IAAI,CAAC,2BAA2B,MAAM,CAAC,KAAK,WAAW,SAAS,EAAE,CAAC,CAAC;IAC7E,CAAC;IACD,MAAM,KAAK,GAAG,aAAa,aAAb,aAAa,cAAb,aAAa,GAAI,EAAE,CAAC;IAClC,MAAM,IAAI,GAAG,MAAM,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AACvF,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Streaming adapter for Gemini's `streamGenerateContent` endpoint. Gemini\n * emits no explicit tool-progress events even when `google_search` is\n * enabled — grounding metadata arrives attached to text chunks — so this\n * adapter never yields `tool-event`s.\n *\n * Client-defined tools (`functionCall` parts) are emitted as\n * `client-tool-call-done` immediately (no delta accumulation needed for Gemini).\n *\n * @packageDocumentation\n */\n\nimport { type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\nimport { isJsonObject, type JsonObject } from '@fgv/ts-json-base';\n\nimport { buildGeminiContents } from '../chatRequestBuilders';\nimport { geminiAuthHeader } from '../endpoint';\nimport { AiPrompt, type AiToolConfig, type IAiStreamEvent, type IChatMessage } from '../model';\nimport { parseSseEventJson, readSseEvents } from '../sseParser';\nimport { toGeminiTools } from '../toolFormats';\nimport { type IResolvedThinkingConfig } from '../thinkingOptionsResolver';\nimport { IStreamApiConfig, openSseConnection, validateEventPayload } from './common';\n\n// ============================================================================\n// Accumulated call state (internal — used by C3 continuation builder)\n// ============================================================================\n\n/**\n * An accumulated function call from a Gemini stream. Gemini does not assign\n * call IDs; correlation is by tool name. Arguments arrive complete in the\n * `functionCall` part (no delta accumulation).\n * @internal\n */\nexport interface IAccumulatedGeminiFunctionCall {\n readonly name: string;\n readonly args: JsonObject;\n /**\n * The opaque thought signature Gemini stamps on a `functionCall` part when\n * thinking is enabled. It must be echoed back, verbatim, on the continuation's\n * model turn alongside the `functionCall`, or Gemini rejects the follow-up with\n * \"Function call is missing a thought_signature in functionCall parts\".\n * Absent when thinking is disabled. See\n * https://ai.google.dev/gemini-api/docs/thought-signatures.\n */\n readonly thoughtSignature?: string;\n}\n\n// ============================================================================\n// Event payload shapes\n// ============================================================================\n\n/**\n * One `parts[]` element in a Gemini streaming chunk. Text parts and\n * functionCall parts are both surfaced.\n * @internal\n */\ninterface IGeminiStreamPart {\n readonly text?: string;\n readonly functionCall?: { readonly name?: string; readonly args?: JsonObject };\n /**\n * The opaque thought signature attached to a `functionCall` part when thinking\n * is enabled. A sibling of `functionCall`/`text` at the part level (base64\n * string). Captured for replay on the continuation's model turn.\n */\n readonly thoughtSignature?: string;\n}\n\n/**\n * One `candidates[]` element in a Gemini streaming chunk.\n * @internal\n */\ninterface IGeminiStreamCandidate {\n readonly content?: { readonly parts?: ReadonlyArray<IGeminiStreamPart> };\n readonly finishReason?: string;\n}\n\n/**\n * One streaming chunk from `streamGenerateContent?alt=sse`.\n * @internal\n */\ninterface IGeminiStreamChunk {\n readonly candidates: ReadonlyArray<IGeminiStreamCandidate>;\n}\n\nconst jsonObjectValidator: Validator<JsonObject> = Validators.isA<JsonObject>(\n 'JsonObject',\n (v): v is JsonObject => isJsonObject(v)\n);\n\nconst geminiFunctionCallInner: Validator<{ name?: string; args?: JsonObject }> = Validators.object<{\n name?: string;\n args?: JsonObject;\n}>(\n {\n name: Validators.string.optional(),\n args: jsonObjectValidator.optional()\n },\n { options: { optionalFields: ['name', 'args'] } }\n);\n\nconst geminiStreamPart: Validator<IGeminiStreamPart> = Validators.object<IGeminiStreamPart>(\n {\n text: Validators.string.optional(),\n functionCall: geminiFunctionCallInner.optional(),\n thoughtSignature: Validators.string.optional()\n },\n { options: { optionalFields: ['text', 'functionCall', 'thoughtSignature'] } }\n);\n\nconst geminiStreamContent: Validator<{ parts?: ReadonlyArray<IGeminiStreamPart> }> = Validators.object<{\n parts?: ReadonlyArray<IGeminiStreamPart>;\n}>({ parts: Validators.arrayOf(geminiStreamPart).optional() }, { options: { optionalFields: ['parts'] } });\n\nconst geminiStreamCandidate: Validator<IGeminiStreamCandidate> = Validators.object<IGeminiStreamCandidate>(\n {\n content: geminiStreamContent.optional(),\n finishReason: Validators.string.optional()\n },\n { options: { optionalFields: ['content', 'finishReason'] } }\n);\n\nconst geminiStreamChunk: Validator<IGeminiStreamChunk> = Validators.object<IGeminiStreamChunk>({\n candidates: Validators.arrayOf(geminiStreamCandidate)\n});\n\n// ============================================================================\n// Stream translator\n// ============================================================================\n\n/**\n * Translates a Gemini streamGenerateContent SSE stream into unified events.\n *\n * @internal\n */\nasync function* translateGeminiStream(\n response: Response,\n functionCalls: IAccumulatedGeminiFunctionCall[]\n): AsyncGenerator<IAiStreamEvent> {\n let fullText = '';\n let truncated = false;\n let receivedFinishReason = false;\n\n try {\n /* c8 ignore next - body is non-null at this point per openSseConnection */\n if (!response.body) return;\n for await (const message of readSseEvents(response.body)) {\n const json = parseSseEventJson(message.data);\n /* c8 ignore next 3 - defensive: malformed SSE events skipped */\n if (json === undefined) {\n continue;\n }\n const chunk = validateEventPayload(json, geminiStreamChunk);\n /* c8 ignore next 1 - defensive: chunk?.candidates optional chain unreachable after validation */\n const candidate = chunk?.candidates[0];\n /* c8 ignore next 3 - defensive: SSE events without candidates skipped */\n if (!candidate) {\n continue;\n }\n /* c8 ignore next 1 - defensive: candidate.content?.parts null branch unreachable after validation */\n const parts = candidate.content?.parts;\n if (parts) {\n for (const part of parts) {\n if (typeof part.text === 'string' && part.text.length > 0) {\n fullText += part.text;\n yield { type: 'text-delta', delta: part.text };\n /* c8 ignore next 1 - defensive: functionCall parts without a `name` are silently dropped (cannot construct a continuation builder entry without one) */\n } else if (part.functionCall?.name) {\n const { name, args } = part.functionCall;\n /* c8 ignore next 1 - defensive: Gemini always sends args; {} fallback unreachable in practice */\n const callArgs = args ?? {};\n // Capture the part-level thoughtSignature (sibling of functionCall) so the\n // continuation builder can replay it on the model turn. Reads as undefined\n // when thinking is disabled; the builder omits the key in that case.\n functionCalls.push({ name, args: callArgs, thoughtSignature: part.thoughtSignature });\n yield { type: 'client-tool-call-done', toolName: name, args: callArgs };\n }\n }\n }\n const finishReason = candidate.finishReason;\n if (typeof finishReason === 'string' && finishReason.length > 0) {\n truncated = finishReason === 'MAX_TOKENS';\n receivedFinishReason = true;\n }\n }\n } catch (err: unknown) /* c8 ignore start - defensive: stream errors are always Error instances */ {\n yield { type: 'error', message: err instanceof Error ? err.message : String(err) };\n return;\n } /* c8 ignore stop */\n\n if (receivedFinishReason) {\n yield { type: 'done', truncated, fullText };\n } else {\n yield { type: 'error', message: 'Gemini stream ended without a finishReason' };\n }\n}\n\n// ============================================================================\n// Per-format request caller\n// ============================================================================\n\n/**\n * Issues a streaming Gemini request and returns the unified-event iterable\n * on success.\n *\n * @internal\n */\nexport async function callGeminiStream(\n config: IStreamApiConfig,\n prompt: AiPrompt,\n messagesBefore: ReadonlyArray<IChatMessage> | undefined,\n temperature: number | undefined,\n tools: ReadonlyArray<AiToolConfig> | undefined,\n logger?: Logging.ILogger,\n signal?: AbortSignal,\n resolvedThinking?: IResolvedThinkingConfig,\n functionCalls?: IAccumulatedGeminiFunctionCall[],\n continuationMessages?: ReadonlyArray<JsonObject>,\n maxTokens?: number\n): Promise<Result<AsyncIterable<IAiStreamEvent>>> {\n const url = `${config.baseUrl}/models/${config.model}:streamGenerateContent?alt=sse`;\n const contents = buildGeminiContents(prompt, {\n head: messagesBefore,\n rawTail: continuationMessages\n });\n // Temperature is sent only when explicitly provided; otherwise Gemini's default applies.\n const generationConfig: Record<string, unknown> = {};\n if (temperature !== undefined) {\n generationConfig.temperature = temperature;\n }\n if (maxTokens !== undefined) {\n generationConfig.maxOutputTokens = maxTokens;\n }\n if (resolvedThinking?.geminiThinkingBudget !== undefined) {\n generationConfig.thinkingConfig = { thinkingBudget: resolvedThinking.geminiThinkingBudget };\n }\n if (resolvedThinking?.otherParams !== undefined) {\n Object.assign(generationConfig, resolvedThinking.otherParams);\n }\n const body: Record<string, unknown> = {\n systemInstruction: { parts: [{ text: prompt.system }] },\n contents,\n generationConfig\n };\n /* c8 ignore next 3 - tools branch not exercised in streaming tests */\n if (tools && tools.length > 0) {\n body.tools = toGeminiTools(tools);\n }\n const headers: Record<string, string> = geminiAuthHeader(config.apiKey);\n /* c8 ignore next 4 - optional logger diagnostic output */\n if (logger) {\n const toolTypes = tools && tools.length > 0 ? tools.map((t) => t.type).join(',') : 'none';\n logger.info(`Gemini streaming: model=${config.model}, tools=${toolTypes}`);\n }\n const calls = functionCalls ?? [];\n const conn = await openSseConnection(url, headers, body, logger, signal);\n return conn.onSuccess((response) => succeed(translateGeminiStream(response, calls)));\n}\n"]}
|
|
@@ -62,6 +62,43 @@ export function fromBase64(base64) {
|
|
|
62
62
|
}
|
|
63
63
|
return bytes;
|
|
64
64
|
}
|
|
65
|
+
/* c8 ignore stop */
|
|
66
|
+
/**
|
|
67
|
+
* Decodes a base64 string to a `Uint8Array`, **rejecting input that is not
|
|
68
|
+
* well-formed base64** instead of silently salvaging what it can.
|
|
69
|
+
*
|
|
70
|
+
* @remarks
|
|
71
|
+
* The difference from {@link CryptoUtils.fromBase64 | fromBase64} is the failure
|
|
72
|
+
* mode, and it is the whole reason this exists. `fromBase64` is `Buffer`-first
|
|
73
|
+
* where a `Buffer` exists, and `Buffer.from(s, 'base64')` **discards** characters
|
|
74
|
+
* outside the base64 alphabet rather than complaining — so a corrupted or
|
|
75
|
+
* truncated payload decodes to plausible-looking garbage and the corruption is
|
|
76
|
+
* discovered, if ever, much further downstream. Use this variant whenever the
|
|
77
|
+
* base64 arrived from somewhere you do not control (a wire response, a file, user
|
|
78
|
+
* input) and a malformed value means "something is wrong", not "do your best".
|
|
79
|
+
*
|
|
80
|
+
* Implemented over `atob`, which rejects out-of-alphabet characters and bad
|
|
81
|
+
* lengths. Note it inherits `atob`'s one leniency: per the WHATWG forgiving-base64
|
|
82
|
+
* algorithm, ASCII whitespace inside the input is stripped rather than rejected.
|
|
83
|
+
* That is deliberate — line-wrapped base64 is common and benign — and it does not
|
|
84
|
+
* weaken the guarantee that matters here, which is that corrupt bytes fail loudly.
|
|
85
|
+
* @param base64 - Base64 string to decode.
|
|
86
|
+
* @returns `Success` with the decoded bytes, or `Failure` if `base64` is not
|
|
87
|
+
* well-formed.
|
|
88
|
+
* @public
|
|
89
|
+
*/
|
|
90
|
+
export function fromBase64Strict(base64) {
|
|
91
|
+
return captureResult(() => {
|
|
92
|
+
// `atob` yields a "binary string": one UTF-16 code unit per byte, each in
|
|
93
|
+
// 0..255, so `charCodeAt` reads the bytes back losslessly for all 256 values.
|
|
94
|
+
const binary = atob(base64);
|
|
95
|
+
const bytes = new Uint8Array(binary.length);
|
|
96
|
+
for (let i = 0; i < binary.length; i++) {
|
|
97
|
+
bytes[i] = binary.charCodeAt(i);
|
|
98
|
+
}
|
|
99
|
+
return bytes;
|
|
100
|
+
}).withErrorFormat(() => 'invalid base64 string');
|
|
101
|
+
}
|
|
65
102
|
// ============================================================================
|
|
66
103
|
// Encryption Functions
|
|
67
104
|
// ============================================================================
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encryptedFile.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/encryptedFile.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAGZ,OAAO,EAAE,aAAa,EAAa,IAAI,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AAChF,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAyD,eAAe,EAAE,MAAM,SAAS,CAAC;AAEjG,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;GAKG;AACH,qFAAqF;AACrF,MAAM,UAAU,QAAQ,CAAC,KAAiB;IACxC,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC/C,CAAC;IACD,mBA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,GAAe,EACf,cAA+B,EAC/B,gBAAsC,EACtC,iBAAwC;IAExC,kCAAkC;IAClC,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC,uBAAuB,CAAC,CAAC;IACvC,CAAC;IAED,+CAA+C;IAC/C,MAAM,aAAa,GAAG,4BAA4B,CAAC,iBAAiB,CAAC,CAAC;IACtE,MAAM,UAAU,GAAG,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC,kCAAkC,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAED,OAAO,WAAW,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { JsonValue } from '@fgv/ts-json-base';\nimport { captureResult, Converter, fail, Result, succeed } from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { createEncryptedFileConverter } from './converters';\nimport { ICryptoProvider, IEncryptedFile, IKeyDerivationParams, isEncryptedFile } from './model';\n\n// ============================================================================\n// Base64 Utilities\n// ============================================================================\n\n/**\n * Encodes a `Uint8Array` to a base64 string.\n * @param bytes - Bytes to encode\n * @returns Base64 string\n * @public\n */\n/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */\nexport function toBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n // Browser fallback\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n/* c8 ignore stop */\n\n/**\n * Decodes a base64 string to a `Uint8Array`.\n * @param base64 - Base64 string to decode\n * @returns Decoded bytes\n * @public\n */\n/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */\nexport function fromBase64(base64: string): Uint8Array {\n if (typeof Buffer !== 'undefined') {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n // Browser fallback\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n/* c8 ignore stop */\n\n// ============================================================================\n// Create Encrypted File Parameters\n// ============================================================================\n\n/**\n * Parameters for creating an {@link CryptoUtils.IEncryptedFile | encrypted file}.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @public\n */\nexport interface ICreateEncryptedFileParams<TMetadata = JsonValue> {\n /**\n * The JSON content to encrypt.\n */\n readonly content: JsonValue;\n\n /**\n * Name of the secret used for encryption.\n */\n readonly secretName: string;\n\n /**\n * The encryption key (32 bytes for AES-256).\n */\n readonly key: Uint8Array;\n\n /**\n * {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for encryption.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * Optional metadata to include unencrypted.\n */\n readonly metadata?: TMetadata;\n\n /**\n * Optional converter to validate metadata before including.\n * If provided, metadata will be validated before encryption.\n */\n readonly metadataConverter?: Converter<TMetadata>;\n\n /**\n * Optional {@link CryptoUtils.IKeyDerivationParams | key derivation parameters}.\n * If provided, stores the salt and iterations used to derive the key from a password.\n * This allows decryption using only a password (the salt/iterations are read from the file).\n */\n readonly keyDerivation?: IKeyDerivationParams;\n}\n\n// ============================================================================\n// Encryption Functions\n// ============================================================================\n\n/**\n * Creates an {@link CryptoUtils.IEncryptedFile | encrypted file} from JSON content.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @param params - Encryption parameters\n * @returns `Success` with encrypted file structure, or `Failure` with an error.\n * @public\n */\nexport async function createEncryptedFile<TMetadata = JsonValue>(\n params: ICreateEncryptedFileParams<TMetadata>\n): Promise<Result<IEncryptedFile<TMetadata>>> {\n const { content, secretName, key, metadata, metadataConverter, keyDerivation, cryptoProvider } = params;\n\n // Validate metadata if converter provided\n /* c8 ignore next 6 - metadata validation path exercised via higher-level tests */\n if (metadata !== undefined && metadataConverter !== undefined) {\n const metadataResult = metadataConverter.convert(metadata);\n if (metadataResult.isFailure()) {\n return fail(`Invalid metadata: ${metadataResult.message}`);\n }\n }\n\n // Serialize content to JSON string\n const jsonResult = captureResult(() => JSON.stringify(content));\n if (jsonResult.isFailure()) {\n return fail(`Failed to serialize content: ${jsonResult.message}`);\n }\n\n // Encrypt the JSON string\n const encryptResult = await cryptoProvider.encrypt(jsonResult.value, key);\n if (encryptResult.isFailure()) {\n return fail(`Encryption failed: ${encryptResult.message}`);\n }\n\n const { iv, authTag, encryptedData } = encryptResult.value;\n\n // Build the encrypted file structure\n const encryptedFile: IEncryptedFile<TMetadata> = {\n format: Constants.ENCRYPTED_FILE_FORMAT,\n secretName,\n algorithm: Constants.DEFAULT_ALGORITHM,\n iv: toBase64(iv),\n authTag: toBase64(authTag),\n encryptedData: toBase64(encryptedData),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(keyDerivation !== undefined ? { keyDerivation } : {})\n };\n\n return succeed(encryptedFile);\n}\n\n// ============================================================================\n// Decryption Functions\n// ============================================================================\n\n/**\n * Decrypts an {@link CryptoUtils.IEncryptedFile | encrypted file} and returns the JSON content.\n * @typeParam TPayload - Expected type of decrypted content\n * @param file - The encrypted file structure\n * @param key - The decryption key (32 bytes for AES-256)\n * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption\n * @param payloadConverter - Optional converter to validate and convert decrypted content\n * @returns `Success` with decrypted content, or `Failure` with an error.\n * @public\n */\nexport async function decryptFile<TPayload extends JsonValue = JsonValue>(\n file: IEncryptedFile<unknown>,\n key: Uint8Array,\n cryptoProvider: ICryptoProvider,\n payloadConverter?: Converter<TPayload>\n): Promise<Result<TPayload>> {\n // Decode base64 values\n const iv = fromBase64(file.iv);\n const authTag = fromBase64(file.authTag);\n const encryptedData = fromBase64(file.encryptedData);\n\n // Decrypt\n const decryptResult = await cryptoProvider.decrypt(encryptedData, key, iv, authTag);\n if (decryptResult.isFailure()) {\n return fail(decryptResult.message);\n }\n\n // Parse JSON\n const parseResult = captureResult(() => JSON.parse(decryptResult.value) as TPayload).withErrorFormat(\n (e) => `Failed to parse decrypted content as JSON: ${e}`\n );\n\n /* c8 ignore next 3 - JSON parse failure only occurs with corrupted encrypted data */\n if (parseResult.isFailure()) {\n return parseResult;\n }\n\n // Validate with converter if provided\n /* c8 ignore next 3 - payload converter path exercised via higher-level tests */\n if (payloadConverter !== undefined) {\n return payloadConverter.convert(parseResult.value);\n }\n\n return parseResult;\n}\n\n/**\n * Attempts to parse and decrypt a JSON object as an {@link CryptoUtils.IEncryptedFile | encrypted file}.\n * @typeParam TPayload - Expected type of decrypted content\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @param json - JSON object that may be an encrypted file\n * @param key - The decryption key (32 bytes for AES-256)\n * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption\n * @param payloadConverter - Optional converter to validate and convert decrypted content\n * @param metadataConverter - Optional converter to validate metadata before decryption\n * @returns `Success` with decrypted content, or `Failure` with an error (including if not encrypted)\n * @public\n */\nexport async function tryDecryptFile<TPayload extends JsonValue = JsonValue, TMetadata = JsonValue>(\n json: JsonValue,\n key: Uint8Array,\n cryptoProvider: ICryptoProvider,\n payloadConverter?: Converter<TPayload>,\n metadataConverter?: Converter<TMetadata>\n): Promise<Result<TPayload>> {\n // Check if it's an encrypted file\n if (!isEncryptedFile(json)) {\n return fail('Not an encrypted file');\n }\n\n // Validate and convert to typed encrypted file\n const fileConverter = createEncryptedFileConverter(metadataConverter);\n const fileResult = fileConverter.convert(json);\n if (fileResult.isFailure()) {\n return fail(`Invalid encrypted file format: ${fileResult.message}`);\n }\n\n return decryptFile(fileResult.value, key, cryptoProvider, payloadConverter);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"encryptedFile.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/encryptedFile.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAGZ,OAAO,EAAE,aAAa,EAAa,IAAI,EAAU,OAAO,EAAE,MAAM,eAAe,CAAC;AAChF,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAyD,eAAe,EAAE,MAAM,SAAS,CAAC;AAEjG,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;GAKG;AACH,qFAAqF;AACrF,MAAM,UAAU,Q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,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { JsonValue } from '@fgv/ts-json-base';\nimport { captureResult, Converter, fail, Result, succeed } from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { createEncryptedFileConverter } from './converters';\nimport { ICryptoProvider, IEncryptedFile, IKeyDerivationParams, isEncryptedFile } from './model';\n\n// ============================================================================\n// Base64 Utilities\n// ============================================================================\n\n/**\n * Encodes a `Uint8Array` to a base64 string.\n * @param bytes - Bytes to encode\n * @returns Base64 string\n * @public\n */\n/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */\nexport function toBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(bytes).toString('base64');\n }\n // Browser fallback\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n/* c8 ignore stop */\n\n/**\n * Decodes a base64 string to a `Uint8Array`.\n * @param base64 - Base64 string to decode\n * @returns Decoded bytes\n * @public\n */\n/* c8 ignore start - Browser-only fallback cannot be tested in Node.js environment */\nexport function fromBase64(base64: string): Uint8Array {\n if (typeof Buffer !== 'undefined') {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n // Browser fallback\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n/* c8 ignore stop */\n\n/**\n * Decodes a base64 string to a `Uint8Array`, **rejecting input that is not\n * well-formed base64** instead of silently salvaging what it can.\n *\n * @remarks\n * The difference from {@link CryptoUtils.fromBase64 | fromBase64} is the failure\n * mode, and it is the whole reason this exists. `fromBase64` is `Buffer`-first\n * where a `Buffer` exists, and `Buffer.from(s, 'base64')` **discards** characters\n * outside the base64 alphabet rather than complaining — so a corrupted or\n * truncated payload decodes to plausible-looking garbage and the corruption is\n * discovered, if ever, much further downstream. Use this variant whenever the\n * base64 arrived from somewhere you do not control (a wire response, a file, user\n * input) and a malformed value means \"something is wrong\", not \"do your best\".\n *\n * Implemented over `atob`, which rejects out-of-alphabet characters and bad\n * lengths. Note it inherits `atob`'s one leniency: per the WHATWG forgiving-base64\n * algorithm, ASCII whitespace inside the input is stripped rather than rejected.\n * That is deliberate — line-wrapped base64 is common and benign — and it does not\n * weaken the guarantee that matters here, which is that corrupt bytes fail loudly.\n * @param base64 - Base64 string to decode.\n * @returns `Success` with the decoded bytes, or `Failure` if `base64` is not\n * well-formed.\n * @public\n */\nexport function fromBase64Strict(base64: string): Result<Uint8Array> {\n return captureResult(() => {\n // `atob` yields a \"binary string\": one UTF-16 code unit per byte, each in\n // 0..255, so `charCodeAt` reads the bytes back losslessly for all 256 values.\n const binary: string = atob(base64);\n const bytes: Uint8Array = new Uint8Array(binary.length);\n for (let i: number = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }).withErrorFormat(() => 'invalid base64 string');\n}\n\n// ============================================================================\n// Create Encrypted File Parameters\n// ============================================================================\n\n/**\n * Parameters for creating an {@link CryptoUtils.IEncryptedFile | encrypted file}.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @public\n */\nexport interface ICreateEncryptedFileParams<TMetadata = JsonValue> {\n /**\n * The JSON content to encrypt.\n */\n readonly content: JsonValue;\n\n /**\n * Name of the secret used for encryption.\n */\n readonly secretName: string;\n\n /**\n * The encryption key (32 bytes for AES-256).\n */\n readonly key: Uint8Array;\n\n /**\n * {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for encryption.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * Optional metadata to include unencrypted.\n */\n readonly metadata?: TMetadata;\n\n /**\n * Optional converter to validate metadata before including.\n * If provided, metadata will be validated before encryption.\n */\n readonly metadataConverter?: Converter<TMetadata>;\n\n /**\n * Optional {@link CryptoUtils.IKeyDerivationParams | key derivation parameters}.\n * If provided, stores the salt and iterations used to derive the key from a password.\n * This allows decryption using only a password (the salt/iterations are read from the file).\n */\n readonly keyDerivation?: IKeyDerivationParams;\n}\n\n// ============================================================================\n// Encryption Functions\n// ============================================================================\n\n/**\n * Creates an {@link CryptoUtils.IEncryptedFile | encrypted file} from JSON content.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @param params - Encryption parameters\n * @returns `Success` with encrypted file structure, or `Failure` with an error.\n * @public\n */\nexport async function createEncryptedFile<TMetadata = JsonValue>(\n params: ICreateEncryptedFileParams<TMetadata>\n): Promise<Result<IEncryptedFile<TMetadata>>> {\n const { content, secretName, key, metadata, metadataConverter, keyDerivation, cryptoProvider } = params;\n\n // Validate metadata if converter provided\n /* c8 ignore next 6 - metadata validation path exercised via higher-level tests */\n if (metadata !== undefined && metadataConverter !== undefined) {\n const metadataResult = metadataConverter.convert(metadata);\n if (metadataResult.isFailure()) {\n return fail(`Invalid metadata: ${metadataResult.message}`);\n }\n }\n\n // Serialize content to JSON string\n const jsonResult = captureResult(() => JSON.stringify(content));\n if (jsonResult.isFailure()) {\n return fail(`Failed to serialize content: ${jsonResult.message}`);\n }\n\n // Encrypt the JSON string\n const encryptResult = await cryptoProvider.encrypt(jsonResult.value, key);\n if (encryptResult.isFailure()) {\n return fail(`Encryption failed: ${encryptResult.message}`);\n }\n\n const { iv, authTag, encryptedData } = encryptResult.value;\n\n // Build the encrypted file structure\n const encryptedFile: IEncryptedFile<TMetadata> = {\n format: Constants.ENCRYPTED_FILE_FORMAT,\n secretName,\n algorithm: Constants.DEFAULT_ALGORITHM,\n iv: toBase64(iv),\n authTag: toBase64(authTag),\n encryptedData: toBase64(encryptedData),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(keyDerivation !== undefined ? { keyDerivation } : {})\n };\n\n return succeed(encryptedFile);\n}\n\n// ============================================================================\n// Decryption Functions\n// ============================================================================\n\n/**\n * Decrypts an {@link CryptoUtils.IEncryptedFile | encrypted file} and returns the JSON content.\n * @typeParam TPayload - Expected type of decrypted content\n * @param file - The encrypted file structure\n * @param key - The decryption key (32 bytes for AES-256)\n * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption\n * @param payloadConverter - Optional converter to validate and convert decrypted content\n * @returns `Success` with decrypted content, or `Failure` with an error.\n * @public\n */\nexport async function decryptFile<TPayload extends JsonValue = JsonValue>(\n file: IEncryptedFile<unknown>,\n key: Uint8Array,\n cryptoProvider: ICryptoProvider,\n payloadConverter?: Converter<TPayload>\n): Promise<Result<TPayload>> {\n // Decode base64 values\n const iv = fromBase64(file.iv);\n const authTag = fromBase64(file.authTag);\n const encryptedData = fromBase64(file.encryptedData);\n\n // Decrypt\n const decryptResult = await cryptoProvider.decrypt(encryptedData, key, iv, authTag);\n if (decryptResult.isFailure()) {\n return fail(decryptResult.message);\n }\n\n // Parse JSON\n const parseResult = captureResult(() => JSON.parse(decryptResult.value) as TPayload).withErrorFormat(\n (e) => `Failed to parse decrypted content as JSON: ${e}`\n );\n\n /* c8 ignore next 3 - JSON parse failure only occurs with corrupted encrypted data */\n if (parseResult.isFailure()) {\n return parseResult;\n }\n\n // Validate with converter if provided\n /* c8 ignore next 3 - payload converter path exercised via higher-level tests */\n if (payloadConverter !== undefined) {\n return payloadConverter.convert(parseResult.value);\n }\n\n return parseResult;\n}\n\n/**\n * Attempts to parse and decrypt a JSON object as an {@link CryptoUtils.IEncryptedFile | encrypted file}.\n * @typeParam TPayload - Expected type of decrypted content\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @param json - JSON object that may be an encrypted file\n * @param key - The decryption key (32 bytes for AES-256)\n * @param cryptoProvider - {@link CryptoUtils.ICryptoProvider | Crypto provider} to use for decryption\n * @param payloadConverter - Optional converter to validate and convert decrypted content\n * @param metadataConverter - Optional converter to validate metadata before decryption\n * @returns `Success` with decrypted content, or `Failure` with an error (including if not encrypted)\n * @public\n */\nexport async function tryDecryptFile<TPayload extends JsonValue = JsonValue, TMetadata = JsonValue>(\n json: JsonValue,\n key: Uint8Array,\n cryptoProvider: ICryptoProvider,\n payloadConverter?: Converter<TPayload>,\n metadataConverter?: Converter<TMetadata>\n): Promise<Result<TPayload>> {\n // Check if it's an encrypted file\n if (!isEncryptedFile(json)) {\n return fail('Not an encrypted file');\n }\n\n // Validate and convert to typed encrypted file\n const fileConverter = createEncryptedFileConverter(metadataConverter);\n const fileResult = fileConverter.convert(json);\n if (fileResult.isFailure()) {\n return fail(`Invalid encrypted file format: ${fileResult.message}`);\n }\n\n return decryptFile(fileResult.value, key, cryptoProvider, payloadConverter);\n}\n"]}
|
|
@@ -41,7 +41,7 @@ export { deriveKeyPairFromSeed } from './seedDerivedKeyPair';
|
|
|
41
41
|
// Node.js crypto provider (Node.js environment only)
|
|
42
42
|
export { NodeCryptoProvider, nodeCryptoProvider } from './nodeCryptoProvider';
|
|
43
43
|
// Encrypted file helpers
|
|
44
|
-
export { createEncryptedFile, decryptFile, fromBase64, toBase64, tryDecryptFile } from './encryptedFile';
|
|
44
|
+
export { createEncryptedFile, decryptFile, fromBase64, fromBase64Strict, toBase64, tryDecryptFile } from './encryptedFile';
|
|
45
45
|
// Multibase/SPKI + base64url helpers
|
|
46
46
|
export { base64UrlNoPadDecode, base64UrlNoPadEncode, exportPublicKeyAsMultibaseSpki, hexDecode, hexEncode, importPublicKeyFromMultibaseSpki, isValidMultibaseSpkiPublicKey, MultibaseSpkiPublicKeyRegExp, multibaseBase64UrlDecode, multibaseBase64UrlEncode, spkiToRawX25519 } from './spkiHelpers';
|
|
47
47
|
// HPKE base mode (RFC 9180) — DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + AES-256-GCM
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/index.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ;;;GAGG;AAEH,iCAAiC;AACjC,cAAc,SAAS,CAAC;AAExB,YAAY;AACZ,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,CAAC;AAErB,qBAAqB;AACrB,OAAO,KAAK,QAAQ,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,CAAC;AAEpB,uBAAuB;AACvB,OAAO,KAAK,UAAU,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,CAAC;AAEtB,6BAA6B;AAC7B,OAAO,EAAE,wBAAwB,EAAmC,MAAM,4BAA4B,CAAC;AAEvG,8D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kB,EAAE,MAAM,sBAAsB,CAAC;AAE9E,yBAAyB;AACzB,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,UAAU,EACV,gBAAgB,EAEhB,QAAQ,EACR,cAAc,EACf,MAAM,iBAAiB,CAAC;AAEzB,qCAAqC;AACrC,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,8BAA8B,EAC9B,SAAS,EACT,SAAS,EACT,gCAAgC,EAChC,6BAA6B,EAC7B,4BAA4B,EAC5B,wBAAwB,EACxB,wBAAwB,EACxB,eAAe,EAChB,MAAM,eAAe,CAAC;AAEvB,qFAAqF;AACrF,OAAO,EAAE,YAAY,EAAmB,MAAM,gBAAgB,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Crypto utilities for encrypted file handling and key management.\n * @packageDocumentation\n */\n\n// Re-export all types from model\nexport * from './model';\n\n// Constants\nimport * as Constants from './constants';\nexport { Constants };\n\n// KeyStore namespace\nimport * as KeyStore from './keystore';\nexport { KeyStore };\n\n// Converters namespace\nimport * as Converters from './converters';\nexport { Converters };\n\n// Direct encryption provider\nexport { DirectEncryptionProvider, IDirectEncryptionProviderParams } from './directEncryptionProvider';\n\n// WebCrypto parameter table for asymmetric keypair algorithms\nexport { IKeyPairAlgorithmParams, keyPairAlgorithmParams } from './keyPairAlgorithmParams';\n\n// Deterministic seed → keypair derivation shared by the Node/browser providers\nexport { deriveKeyPairFromSeed } from './seedDerivedKeyPair';\n\n// Node.js crypto provider (Node.js environment only)\nexport { NodeCryptoProvider, nodeCryptoProvider } from './nodeCryptoProvider';\n\n// Encrypted file helpers\nexport {\n createEncryptedFile,\n decryptFile,\n fromBase64,\n fromBase64Strict,\n ICreateEncryptedFileParams,\n toBase64,\n tryDecryptFile\n} from './encryptedFile';\n\n// Multibase/SPKI + base64url helpers\nexport {\n base64UrlNoPadDecode,\n base64UrlNoPadEncode,\n exportPublicKeyAsMultibaseSpki,\n hexDecode,\n hexEncode,\n importPublicKeyFromMultibaseSpki,\n isValidMultibaseSpkiPublicKey,\n MultibaseSpkiPublicKeyRegExp,\n multibaseBase64UrlDecode,\n multibaseBase64UrlEncode,\n spkiToRawX25519\n} from './spkiHelpers';\n\n// HPKE base mode (RFC 9180) — DHKEM(X25519, HKDF-SHA256) + HKDF-SHA256 + AES-256-GCM\nexport { HpkeProvider, IHpkeSealResult } from './hpkeProvider';\n"]}
|
|
@@ -64,9 +64,11 @@ export class ZipFileItem {
|
|
|
64
64
|
if (typeof contents === 'string') {
|
|
65
65
|
this._contents = contents;
|
|
66
66
|
this._bytes = new TextEncoder().encode(contents);
|
|
67
|
+
this._bytesAreOriginal = false;
|
|
67
68
|
}
|
|
68
69
|
else {
|
|
69
70
|
this._bytes = contents;
|
|
71
|
+
this._bytesAreOriginal = true;
|
|
70
72
|
}
|
|
71
73
|
this._accessors = accessors;
|
|
72
74
|
this.absolutePath = '/' + zipFilePath;
|
|
@@ -124,6 +126,23 @@ export class ZipFileItem {
|
|
|
124
126
|
getRawBytes() {
|
|
125
127
|
return succeed(this._bytes);
|
|
126
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* Gets the file's contents, decoding UTF-8 strictly.
|
|
131
|
+
*
|
|
132
|
+
* @remarks
|
|
133
|
+
* Decidable for an entry read out of the archive, which is byte-native: this
|
|
134
|
+
* item holds exactly the bytes the archive carried. An item constructed from
|
|
135
|
+
* already-decoded text fails instead — its bytes are a re-encode, so they are
|
|
136
|
+
* well-formed UTF-8 by construction and a success would say nothing.
|
|
137
|
+
* @returns `Success` with the decoded text; `Failure` if the entry's bytes are
|
|
138
|
+
* not valid UTF-8, or if this item never held the original bytes.
|
|
139
|
+
*/
|
|
140
|
+
getTextStrict() {
|
|
141
|
+
if (!this._bytesAreOriginal) {
|
|
142
|
+
return fail(`${this.absolutePath}: cannot decode strictly - this item was constructed from already-decoded text, not the original bytes`);
|
|
143
|
+
}
|
|
144
|
+
return captureResult(() => new TextDecoder('utf-8', { fatal: true }).decode(this._bytes));
|
|
145
|
+
}
|
|
127
146
|
}
|
|
128
147
|
/**
|
|
129
148
|
* Implementation of `IFileTreeDirectoryItem` for directories in a ZIP archive.
|
|
@@ -347,6 +366,19 @@ export class ZipFileTreeAccessors {
|
|
|
347
366
|
getFileBytes(path) {
|
|
348
367
|
return this._getFileItem(path).onSuccess((item) => item.getRawBytes());
|
|
349
368
|
}
|
|
369
|
+
/**
|
|
370
|
+
* Gets the contents of a file in the file tree, decoding UTF-8 strictly.
|
|
371
|
+
*
|
|
372
|
+
* @remarks
|
|
373
|
+
* Always decidable here: ZIP entries are byte-native, so this store holds
|
|
374
|
+
* exactly the bytes the archive carried.
|
|
375
|
+
* @param path - Absolute path of the entry.
|
|
376
|
+
* @returns `Success` with the decoded text; `Failure` if the entry's bytes are
|
|
377
|
+
* not valid UTF-8.
|
|
378
|
+
*/
|
|
379
|
+
getFileTextStrict(path) {
|
|
380
|
+
return this._getFileItem(path).onSuccess((item) => item.getTextStrict());
|
|
381
|
+
}
|
|
350
382
|
/**
|
|
351
383
|
* Resolves a path to the ZIP file item it names.
|
|
352
384
|
* @param path - Path of the entry to look up.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zipFileTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/zip-file-tree/zipFileTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,SAAS,EAAE,KAAK,EAAY,MAAM,QAAQ,CAAC;AACpD,OAAO,EAAU,OAAO,EAAE,IAAI,EAAE,aAAa,EAAwB,MAAM,eAAe,CAAC;AAG3F;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,WAAW;IA0BtB;;OAEG;IACH,IAAW,WAAW;QACpB,IAAI,IAAI,CAAC,YAAY,KAAK,SAAS,IAAI,IAAI,CAAC,uBAAuB,EAAE,CAAC;YACpE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,UAAU,CAAC,kBAAkB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,SAAS,EAAE,CAAC;YACtF,IAAI,CAAC,uBAAuB,GAAG,KAAK,CAAC;QACvC,CAAC;QACD,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;IA2BD;;;;;;;OAOG;IACH,YACE,WAAmB,EACnB,QAA6B,EAC7B,SAAoC;QAxEtC;;WAEG;QACa,SAAI,GAAW,MAAM,CAAC;QAqDtC;;WAEG;QACK,4BAAuB,GAAY,IAAI,CAAC;QAe9C,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;YACjC,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;YAC1B,IAAI,CAAC,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC;QACzB,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QA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oC;QACpC,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC,gBAAgB,GAAG,GAAG,CAAC,EAAE,CAAC;YACxD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,6CAA6C;QAC7C,MAAM,YAAY,GAAG,eAAe,CAAC,SAAS,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAE5E,gEAAgE;QAChE,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { unzipSync, unzip, Unzipped } from 'fflate';\nimport { Result, succeed, fail, captureResult, Converter, Validator } from '@fgv/ts-utils';\nimport { FileTree, JsonValue } from '@fgv/ts-json-base';\n\n/**\n * Implementation of `FileTree.IFileTreeFileItem` for files in a ZIP archive.\n * ZIP files are read-only, so this item does not support mutation.\n * Use {@link FileTree.isMutableFileItem | isMutableFileItem} to check before attempting mutations.\n *\n * @remarks\n * ZIP entries are byte-native, so this item also implements the read half of the\n * optional binary capability (`FileTree.IBinaryFileTreeFileItem`) — use\n * `FileTree.isBinaryFileItem` to narrow and `getRawBytes()` to read the entry's\n * undecoded bytes.\n * @public\n */\nexport class ZipFileItem<TCT extends string = string> implements FileTree.IBinaryFileTreeFileItem<TCT> {\n /**\n * Indicates that this `FileTree.FileTreeItem` is a file.\n */\n public readonly type: 'file' = 'file';\n\n /**\n * The absolute path of the file within the ZIP archive.\n */\n public readonly absolutePath: string;\n\n /**\n * The name of the file\n */\n public readonly name: string;\n\n /**\n * The base name of the file (without extension)\n */\n public readonly baseName: string;\n\n /**\n * The extension of the file\n */\n public readonly extension: string;\n\n /**\n * The content type of the file.\n */\n public get contentType(): TCT | undefined {\n if (this._contentType === undefined && this._shouldInferContentType) {\n this._contentType = this._accessors.getFileContentType(this.absolutePath).orDefault();\n this._shouldInferContentType = false;\n }\n return this._contentType;\n }\n\n /**\n * The pre-loaded raw bytes of the ZIP entry.\n */\n private readonly _bytes: Uint8Array;\n\n /**\n * Text form of the entry, decoded lazily from the raw bytes on first text read.\n */\n private _contents: string | undefined;\n\n /**\n * The ZIP file tree accessors that created this item.\n */\n private readonly _accessors: ZipFileTreeAccessors<TCT>;\n\n /**\n * Mutable content type of the file.\n */\n private _contentType: TCT | undefined;\n\n /**\n * Flag to track if content type should be inferred on first access.\n */\n private _shouldInferContentType: boolean = true;\n\n /**\n * Constructor for ZipFileItem.\n * @param zipFilePath - The path of the file within the ZIP.\n * @param contents - The pre-loaded contents of the entry, either as raw bytes or as\n * already-decoded text. Text is encoded as UTF-8 for the byte accessor and is also\n * retained verbatim, so supplying text never round-trips through a decode.\n * @param accessors - The ZIP file tree accessors.\n */\n public constructor(\n zipFilePath: string,\n contents: string | Uint8Array,\n accessors: ZipFileTreeAccessors<TCT>\n ) {\n if (typeof contents === 'string') {\n this._contents = contents;\n this._bytes = new TextEncoder().encode(contents);\n } else {\n this._bytes = contents;\n }\n this._accessors = accessors;\n this.absolutePath = '/' + zipFilePath;\n this.name = accessors.getBaseName(zipFilePath);\n this.extension = accessors.getExtension(zipFilePath);\n this.baseName = accessors.getBaseName(zipFilePath, this.extension);\n }\n\n /**\n * Sets the content type of the file.\n * @param contentType - The content type of the file.\n */\n public setContentType(contentType: TCT | undefined): void {\n this._contentType = contentType;\n this._shouldInferContentType = false;\n }\n\n /**\n * Gets the contents of the file as parsed JSON.\n */\n public getContents(): Result<JsonValue>;\n public getContents<T>(converter: Validator<T> | Converter<T>): Result<T>;\n public getContents<T>(converter?: Validator<T> | Converter<T>): Result<T | JsonValue> {\n return this.getRawContents()\n .onSuccess((contents) => {\n return captureResult(() => JSON.parse(contents))\n .onSuccess((parsed) => {\n if (converter) {\n return converter.convert(parsed) as Result<T | JsonValue>;\n }\n return succeed(parsed as JsonValue);\n })\n .onFailure(() => {\n return fail(`Failed to parse JSON from file: ${this.absolutePath}`);\n });\n })\n .onFailure((error) => {\n return fail(`Failed to get contents from file: ${error}`);\n });\n }\n\n /**\n * Gets the raw contents of the file as a string.\n *\n * @remarks\n * The entry's bytes are decoded as UTF-8 with the lenient WHATWG default, so\n * malformed input is silently replaced with U+FFFD. Use `getRawBytes()` for the\n * undecoded bytes — and `new TextDecoder('utf-8', { fatal: true }).decode(bytes)`\n * for a decode that fails loudly instead.\n */\n public getRawContents(): Result<string> {\n if (this._contents === undefined) {\n this._contents = new TextDecoder().decode(this._bytes);\n }\n return succeed(this._contents);\n }\n\n /**\n * Gets the raw bytes of the ZIP entry, with no text decoding applied.\n *\n * @remarks\n * The returned array is the item's internal buffer and must not be modified.\n */\n public getRawBytes(): Result<Uint8Array> {\n return succeed(this._bytes);\n }\n}\n\n/**\n * Implementation of `IFileTreeDirectoryItem` for directories in a ZIP archive.\n * @public\n */\nexport class ZipDirectoryItem<TCT extends string = string> implements FileTree.IFileTreeDirectoryItem<TCT> {\n /**\n * Indicates that this `FileTree.FileTreeItem` is a directory.\n */\n public readonly type: 'directory' = 'directory';\n\n /**\n * The absolute path of the directory within the ZIP archive.\n */\n public readonly absolutePath: string;\n\n /**\n * The name of the directory\n */\n public readonly name: string;\n\n /**\n * The ZIP file tree accessors that created this item.\n */\n private readonly _accessors: ZipFileTreeAccessors<TCT>;\n\n /**\n * Constructor for ZipDirectoryItem.\n * @param directoryPath - The path of the directory within the ZIP.\n * @param accessors - The ZIP file tree accessors.\n */\n public constructor(directoryPath: string, accessors: ZipFileTreeAccessors<TCT>) {\n this._accessors = accessors;\n this.absolutePath = '/' + directoryPath.replace(/\\/$/, ''); // Normalize path\n this.name = accessors.getBaseName(directoryPath);\n }\n\n /**\n * Gets the children of the directory.\n */\n public getChildren(): Result<ReadonlyArray<FileTree.FileTreeItem<TCT>>> {\n return this._accessors.getChildren(this.absolutePath);\n }\n}\n\n/**\n * Read-only file tree accessors for ZIP archives.\n * ZIP archives are read-only by design — use {@link FileTree.isMutableAccessors | isMutableAccessors}\n * to check before attempting mutations.\n *\n * @remarks\n * ZIP entries are byte-native, so these accessors also implement the read half of the\n * optional binary capability (`FileTree.IBinaryFileTreeAccessors`) — use\n * `FileTree.isBinaryAccessors` to narrow and `getFileBytes()` to read an entry's\n * undecoded bytes.\n * @public\n */\nexport class ZipFileTreeAccessors<TCT extends string = string>\n implements FileTree.IBinaryFileTreeAccessors<TCT>\n{\n /**\n * The unzipped file data.\n */\n private readonly _files: Unzipped;\n\n /**\n * Optional prefix to prepend to paths.\n */\n private readonly _prefix: string;\n\n /**\n * Content type inference function.\n */\n private readonly _inferContentType: FileTree.ContentTypeFactory<TCT>;\n\n /**\n * Cache of all items in the ZIP for efficient lookups.\n */\n private readonly _itemCache: Map<string, FileTree.FileTreeItem<TCT>> = new Map();\n\n /**\n * Constructor for ZipFileTreeAccessors.\n * @param files - The unzipped file data from fflate.\n * @param params - Optional initialization parameters.\n */\n private constructor(files: Unzipped, params?: FileTree.IFileTreeInitParams<TCT>) {\n this._files = files;\n this._prefix = params?.prefix || '';\n this._inferContentType = params?.inferContentType ?? ZipFileTreeAccessors.defaultInferContentType;\n this._buildItemCache();\n }\n\n /**\n * Default function to infer the content type of a file.\n * @param __filePath - The path of the file.\n * @param __provided - Optional supplied content type.\n * @returns `Success` with the content type of the file if successful, or\n * `Failure` with an error message otherwise.\n * @remarks This default implementation always returns `Success` with `undefined`.\n * @public\n */\n public static defaultInferContentType<TCT extends string = string>(\n __filePath: string,\n __provided?: string\n ): Result<TCT | undefined> {\n return succeed(undefined);\n }\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a ZIP file buffer (synchronous).\n * @param zipBuffer - The ZIP file as an ArrayBuffer or Uint8Array.\n * @param prefix - Optional prefix to prepend to paths.\n * @returns Result containing the ZipFileTreeAccessors instance.\n */\n public static fromBuffer<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n prefix?: string\n ): Result<ZipFileTreeAccessors<TCT>>;\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a ZIP file buffer (synchronous).\n * @param zipBuffer - The ZIP file as an ArrayBuffer or Uint8Array.\n * @param params - Optional initialization parameters.\n * @returns Result containing the ZipFileTreeAccessors instance.\n */\n public static fromBuffer<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Result<ZipFileTreeAccessors<TCT>>;\n\n public static fromBuffer<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n params?: FileTree.IFileTreeInitParams<TCT> | string\n ): Result<ZipFileTreeAccessors<TCT>> {\n try {\n /* c8 ignore next 1 - defense in depth */\n const uint8Buffer = zipBuffer instanceof Uint8Array ? zipBuffer : new Uint8Array(zipBuffer);\n const files = unzipSync(uint8Buffer);\n const normalizedParams = typeof params === 'string' ? { prefix: params } : params;\n return succeed(new ZipFileTreeAccessors<TCT>(files, normalizedParams));\n } catch (error) {\n /* c8 ignore next 1 - defensive coding: fflate always throws Error objects in practice */\n return fail(`Failed to load ZIP archive: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a ZIP file buffer (asynchronous).\n * @param zipBuffer - The ZIP file as an ArrayBuffer or Uint8Array.\n * @param prefix - Optional prefix to prepend to paths.\n * @returns Promise containing Result with the ZipFileTreeAccessors instance.\n */\n public static async fromBufferAsync<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n prefix?: string\n ): Promise<Result<ZipFileTreeAccessors<TCT>>>;\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a ZIP file buffer (asynchronous).\n * @param zipBuffer - The ZIP file as an ArrayBuffer or Uint8Array.\n * @param params - Optional initialization parameters.\n * @returns Promise containing Result with the ZipFileTreeAccessors instance.\n */\n public static async fromBufferAsync<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<ZipFileTreeAccessors<TCT>>>;\n\n public static async fromBufferAsync<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n params?: FileTree.IFileTreeInitParams<TCT> | string\n ): Promise<Result<ZipFileTreeAccessors<TCT>>> {\n return new Promise((resolve) => {\n try {\n /* c8 ignore next 1 - defense in depth */\n const uint8Buffer = zipBuffer instanceof Uint8Array ? zipBuffer : new Uint8Array(zipBuffer);\n unzip(uint8Buffer, (err, files) => {\n if (err) {\n resolve(fail(`Failed to load ZIP archive: ${err.message}`));\n } else {\n const normalizedParams = typeof params === 'string' ? { prefix: params } : params;\n resolve(succeed(new ZipFileTreeAccessors<TCT>(files, normalizedParams)));\n }\n });\n /* c8 ignore next 5 - defensive coding: fflate reports errors via callback, not exceptions */\n } catch (error) {\n resolve(\n fail(`Failed to load ZIP archive: ${error instanceof Error ? error.message : String(error)}`)\n );\n }\n });\n }\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a File object (browser environment).\n * @param file - The File object containing ZIP data.\n * @param params - Optional initialization parameters.\n * @returns Result containing the ZipFileTreeAccessors instance.\n */\n public static async fromFile<TCT extends string = string>(\n file: File,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<ZipFileTreeAccessors<TCT>>> {\n try {\n const arrayBuffer = await file.arrayBuffer();\n const uint8Buffer = new Uint8Array(arrayBuffer);\n\n return await ZipFileTreeAccessors.fromBufferAsync<TCT>(uint8Buffer, params);\n } catch (error) {\n return fail(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Builds the cache of all items in the ZIP archive.\n */\n private _buildItemCache(): void {\n const directories = new Set<string>();\n\n // Process all files and collect directory paths\n for (const [relativePath, fileData] of Object.entries(this._files)) {\n // Skip directories in fflate output (they have null data)\n /* c8 ignore next 5 - handles explicit directory entries from external ZIP tools (fflate doesn't create these) */\n if (fileData === null || fileData === undefined) {\n const dirPath = relativePath.replace(/\\/$/, '');\n if (dirPath) {\n directories.add(dirPath);\n }\n } else {\n // Extract directory paths from file paths\n const pathParts = relativePath.split('/');\n for (let i = 1; i < pathParts.length; i++) {\n const dirPath = pathParts.slice(0, i).join('/');\n if (dirPath) {\n directories.add(dirPath);\n }\n }\n\n // Add the file item with its raw bytes; text is decoded lazily on demand.\n const absolutePath = this.resolveAbsolutePath(relativePath);\n const item = new ZipFileItem<TCT>(relativePath, fileData, this);\n this._itemCache.set(absolutePath, item);\n }\n }\n\n // Add directory items to cache\n directories.forEach((dirPath) => {\n const absolutePath = this.resolveAbsolutePath(dirPath);\n const item = new ZipDirectoryItem<TCT>(dirPath, this);\n this._itemCache.set(absolutePath, item);\n });\n }\n\n /**\n * Resolves paths to an absolute path.\n */\n public resolveAbsolutePath(...paths: string[]): string {\n const joinedPath = this.joinPaths(...paths);\n const prefixed = this._prefix ? this.joinPaths(this._prefix, joinedPath) : joinedPath;\n return prefixed.startsWith('/') ? prefixed : '/' + prefixed;\n }\n\n /**\n * Gets the extension of a path.\n */\n public getExtension(path: string): string {\n const name = this.getBaseName(path);\n const lastDotIndex = name.lastIndexOf('.');\n return lastDotIndex >= 0 ? name.substring(lastDotIndex) : '';\n }\n\n /**\n * Gets the base name of a path.\n */\n public getBaseName(path: string, suffix?: string): string {\n const normalizedPath = path.replace(/\\/$/, ''); // Remove trailing slash\n const parts = normalizedPath.split('/');\n let baseName = parts[parts.length - 1] || '';\n\n if (suffix && baseName.endsWith(suffix)) {\n baseName = baseName.substring(0, baseName.length - suffix.length);\n }\n\n return baseName;\n }\n\n /**\n * Joins paths together.\n */\n public joinPaths(...paths: string[]): string {\n return paths\n .filter((p) => p && p.length > 0)\n .map((p) => p.replace(/^\\/+|\\/+$/g, '')) // Remove leading/trailing slashes\n .join('/')\n .replace(/\\/+/g, '/'); // Normalize multiple slashes\n }\n\n /**\n * Gets an item from the file tree.\n */\n public getItem(path: string): Result<FileTree.FileTreeItem<TCT>> {\n const absolutePath = this.resolveAbsolutePath(path);\n const item = this._itemCache.get(absolutePath);\n\n if (item) {\n return succeed(item);\n }\n\n return fail(`Item not found: ${absolutePath}`);\n }\n\n /**\n * Gets the contents of a file in the file tree.\n *\n * @remarks\n * The entry's bytes are decoded as UTF-8 with the lenient WHATWG default. Use\n * `getFileBytes()` for the undecoded bytes.\n */\n public getFileContents(path: string): Result<string> {\n return this._getFileItem(path).onSuccess((item) => item.getRawContents());\n }\n\n /**\n * Gets the raw bytes of a ZIP entry, with no text decoding applied.\n *\n * @remarks\n * The returned array is the archive's internal buffer and must not be modified.\n */\n public getFileBytes(path: string): Result<Uint8Array> {\n return this._getFileItem(path).onSuccess((item) => item.getRawBytes());\n }\n\n /**\n * Resolves a path to the ZIP file item it names.\n * @param path - Path of the entry to look up.\n * @returns `Success` with the item, or `Failure` if it is missing or is a directory.\n */\n private _getFileItem(path: string): Result<ZipFileItem<TCT>> {\n return this.getItem(path).onSuccess((item) => {\n if (!(item instanceof ZipFileItem)) {\n return fail(`Path is not a file: ${path}`);\n }\n return succeed(item);\n });\n }\n\n /**\n * Gets the content type of a file in the file tree.\n */\n public getFileContentType(path: string, provided?: string): Result<TCT | undefined> {\n // If provided contentType is given, use it directly (highest priority)\n if (provided !== undefined) {\n return succeed(provided as TCT);\n }\n\n // For files that exist in the ZIP, we don't store explicit contentType\n // so we always fall back to inference\n return this._inferContentType(path);\n }\n\n /**\n * Gets the children of a directory in the file tree.\n */\n public getChildren(path: string): Result<ReadonlyArray<FileTree.FileTreeItem<TCT>>> {\n const absolutePath = this.resolveAbsolutePath(path);\n const children: FileTree.FileTreeItem<TCT>[] = [];\n\n // Find all items that are direct children of this directory\n for (const [itemPath, item] of this._itemCache) {\n if (this._isDirectChild(absolutePath, itemPath)) {\n children.push(item);\n }\n }\n\n return succeed(children);\n }\n\n /**\n * Checks if childPath is a direct child of parentPath.\n */\n private _isDirectChild(parentPath: string, childPath: string): boolean {\n // Normalize paths\n const normalizedParent = parentPath.replace(/\\/$/, '');\n const normalizedChild = childPath.replace(/\\/$/, '');\n\n // Child must start with parent path\n if (!normalizedChild.startsWith(normalizedParent + '/')) {\n return false;\n }\n\n // Get the relative path from parent to child\n const relativePath = normalizedChild.substring(normalizedParent.length + 1);\n\n // Direct child means no additional slashes in the relative path\n return !relativePath.includes('/');\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"zipFileTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/zip-file-tree/zipFileTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,SAAS,EAAE,KAAK,EAAY,MAAM,QAAQ,CAAC;AACpD,OAAO,EAAU,OAAO,EAAE,IAAI,EAAE,aAAa,EAAwB,MAAM,eAAe,CAAC;AAG3F;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,WAAW;IA4BtB;;OAEG;IACH,IAAW,WAAW;QACpB,IAAI,IAAI,CAAC,YAAY,KAAK,SAAS,IAAI,IAAI,CAAC,uBAAuB,EAAE,CAAC;YACpE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,UAAU,CAAC,kBAAkB,CAAC,IAAI,CAAC,YAAY,CAA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AAe,CAAC,UAAU,CAAC,gBAAgB,GAAG,GAAG,CAAC,EAAE,CAAC;YACxD,OAAO,KAAK,CAAC;QACf,CAAC;QAED,6CAA6C;QAC7C,MAAM,YAAY,GAAG,eAAe,CAAC,SAAS,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAE5E,gEAAgE;QAChE,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2025 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { unzipSync, unzip, Unzipped } from 'fflate';\nimport { Result, succeed, fail, captureResult, Converter, Validator } from '@fgv/ts-utils';\nimport { FileTree, JsonValue } from '@fgv/ts-json-base';\n\n/**\n * Implementation of `FileTree.IFileTreeFileItem` for files in a ZIP archive.\n * ZIP files are read-only, so this item does not support mutation.\n * Use {@link FileTree.isMutableFileItem | isMutableFileItem} to check before attempting mutations.\n *\n * @remarks\n * ZIP entries are byte-native, so this item also implements the read half of the\n * optional binary capability (`FileTree.IBinaryFileTreeFileItem`) — use\n * `FileTree.isBinaryFileItem` to narrow and `getRawBytes()` to read the entry's\n * undecoded bytes.\n * @public\n */\nexport class ZipFileItem<TCT extends string = string>\n implements FileTree.IBinaryFileTreeFileItem<TCT>, FileTree.IStrictTextFileTreeFileItem<TCT>\n{\n /**\n * Indicates that this `FileTree.FileTreeItem` is a file.\n */\n public readonly type: 'file' = 'file';\n\n /**\n * The absolute path of the file within the ZIP archive.\n */\n public readonly absolutePath: string;\n\n /**\n * The name of the file\n */\n public readonly name: string;\n\n /**\n * The base name of the file (without extension)\n */\n public readonly baseName: string;\n\n /**\n * The extension of the file\n */\n public readonly extension: string;\n\n /**\n * The content type of the file.\n */\n public get contentType(): TCT | undefined {\n if (this._contentType === undefined && this._shouldInferContentType) {\n this._contentType = this._accessors.getFileContentType(this.absolutePath).orDefault();\n this._shouldInferContentType = false;\n }\n return this._contentType;\n }\n\n /**\n * The pre-loaded raw bytes of the ZIP entry.\n */\n private readonly _bytes: Uint8Array;\n\n /**\n * Text form of the entry, decoded lazily from the raw bytes on first text read.\n */\n private _contents: string | undefined;\n\n /**\n * Whether `_bytes` is what the archive carried, rather than a re-encode of text\n * supplied to the constructor. Only the former can answer \"was this valid UTF-8?\".\n */\n private readonly _bytesAreOriginal: boolean;\n\n /**\n * The ZIP file tree accessors that created this item.\n */\n private readonly _accessors: ZipFileTreeAccessors<TCT>;\n\n /**\n * Mutable content type of the file.\n */\n private _contentType: TCT | undefined;\n\n /**\n * Flag to track if content type should be inferred on first access.\n */\n private _shouldInferContentType: boolean = true;\n\n /**\n * Constructor for ZipFileItem.\n * @param zipFilePath - The path of the file within the ZIP.\n * @param contents - The pre-loaded contents of the entry, either as raw bytes or as\n * already-decoded text. Text is encoded as UTF-8 for the byte accessor and is also\n * retained verbatim, so supplying text never round-trips through a decode.\n * @param accessors - The ZIP file tree accessors.\n */\n public constructor(\n zipFilePath: string,\n contents: string | Uint8Array,\n accessors: ZipFileTreeAccessors<TCT>\n ) {\n if (typeof contents === 'string') {\n this._contents = contents;\n this._bytes = new TextEncoder().encode(contents);\n this._bytesAreOriginal = false;\n } else {\n this._bytes = contents;\n this._bytesAreOriginal = true;\n }\n this._accessors = accessors;\n this.absolutePath = '/' + zipFilePath;\n this.name = accessors.getBaseName(zipFilePath);\n this.extension = accessors.getExtension(zipFilePath);\n this.baseName = accessors.getBaseName(zipFilePath, this.extension);\n }\n\n /**\n * Sets the content type of the file.\n * @param contentType - The content type of the file.\n */\n public setContentType(contentType: TCT | undefined): void {\n this._contentType = contentType;\n this._shouldInferContentType = false;\n }\n\n /**\n * Gets the contents of the file as parsed JSON.\n */\n public getContents(): Result<JsonValue>;\n public getContents<T>(converter: Validator<T> | Converter<T>): Result<T>;\n public getContents<T>(converter?: Validator<T> | Converter<T>): Result<T | JsonValue> {\n return this.getRawContents()\n .onSuccess((contents) => {\n return captureResult(() => JSON.parse(contents))\n .onSuccess((parsed) => {\n if (converter) {\n return converter.convert(parsed) as Result<T | JsonValue>;\n }\n return succeed(parsed as JsonValue);\n })\n .onFailure(() => {\n return fail(`Failed to parse JSON from file: ${this.absolutePath}`);\n });\n })\n .onFailure((error) => {\n return fail(`Failed to get contents from file: ${error}`);\n });\n }\n\n /**\n * Gets the raw contents of the file as a string.\n *\n * @remarks\n * The entry's bytes are decoded as UTF-8 with the lenient WHATWG default, so\n * malformed input is silently replaced with U+FFFD. Use `getRawBytes()` for the\n * undecoded bytes — and `new TextDecoder('utf-8', { fatal: true }).decode(bytes)`\n * for a decode that fails loudly instead.\n */\n public getRawContents(): Result<string> {\n if (this._contents === undefined) {\n this._contents = new TextDecoder().decode(this._bytes);\n }\n return succeed(this._contents);\n }\n\n /**\n * Gets the raw bytes of the ZIP entry, with no text decoding applied.\n *\n * @remarks\n * The returned array is the item's internal buffer and must not be modified.\n */\n public getRawBytes(): Result<Uint8Array> {\n return succeed(this._bytes);\n }\n\n /**\n * Gets the file's contents, decoding UTF-8 strictly.\n *\n * @remarks\n * Decidable for an entry read out of the archive, which is byte-native: this\n * item holds exactly the bytes the archive carried. An item constructed from\n * already-decoded text fails instead — its bytes are a re-encode, so they are\n * well-formed UTF-8 by construction and a success would say nothing.\n * @returns `Success` with the decoded text; `Failure` if the entry's bytes are\n * not valid UTF-8, or if this item never held the original bytes.\n */\n public getTextStrict(): Result<string> {\n if (!this._bytesAreOriginal) {\n return fail(\n `${this.absolutePath}: cannot decode strictly - this item was constructed from already-decoded text, not the original bytes`\n );\n }\n return captureResult(() => new TextDecoder('utf-8', { fatal: true }).decode(this._bytes));\n }\n}\n\n/**\n * Implementation of `IFileTreeDirectoryItem` for directories in a ZIP archive.\n * @public\n */\nexport class ZipDirectoryItem<TCT extends string = string> implements FileTree.IFileTreeDirectoryItem<TCT> {\n /**\n * Indicates that this `FileTree.FileTreeItem` is a directory.\n */\n public readonly type: 'directory' = 'directory';\n\n /**\n * The absolute path of the directory within the ZIP archive.\n */\n public readonly absolutePath: string;\n\n /**\n * The name of the directory\n */\n public readonly name: string;\n\n /**\n * The ZIP file tree accessors that created this item.\n */\n private readonly _accessors: ZipFileTreeAccessors<TCT>;\n\n /**\n * Constructor for ZipDirectoryItem.\n * @param directoryPath - The path of the directory within the ZIP.\n * @param accessors - The ZIP file tree accessors.\n */\n public constructor(directoryPath: string, accessors: ZipFileTreeAccessors<TCT>) {\n this._accessors = accessors;\n this.absolutePath = '/' + directoryPath.replace(/\\/$/, ''); // Normalize path\n this.name = accessors.getBaseName(directoryPath);\n }\n\n /**\n * Gets the children of the directory.\n */\n public getChildren(): Result<ReadonlyArray<FileTree.FileTreeItem<TCT>>> {\n return this._accessors.getChildren(this.absolutePath);\n }\n}\n\n/**\n * Read-only file tree accessors for ZIP archives.\n * ZIP archives are read-only by design — use {@link FileTree.isMutableAccessors | isMutableAccessors}\n * to check before attempting mutations.\n *\n * @remarks\n * ZIP entries are byte-native, so these accessors also implement the read half of the\n * optional binary capability (`FileTree.IBinaryFileTreeAccessors`) — use\n * `FileTree.isBinaryAccessors` to narrow and `getFileBytes()` to read an entry's\n * undecoded bytes.\n * @public\n */\nexport class ZipFileTreeAccessors<TCT extends string = string>\n implements FileTree.IBinaryFileTreeAccessors<TCT>, FileTree.IStrictTextFileTreeAccessors<TCT>\n{\n /**\n * The unzipped file data.\n */\n private readonly _files: Unzipped;\n\n /**\n * Optional prefix to prepend to paths.\n */\n private readonly _prefix: string;\n\n /**\n * Content type inference function.\n */\n private readonly _inferContentType: FileTree.ContentTypeFactory<TCT>;\n\n /**\n * Cache of all items in the ZIP for efficient lookups.\n */\n private readonly _itemCache: Map<string, FileTree.FileTreeItem<TCT>> = new Map();\n\n /**\n * Constructor for ZipFileTreeAccessors.\n * @param files - The unzipped file data from fflate.\n * @param params - Optional initialization parameters.\n */\n private constructor(files: Unzipped, params?: FileTree.IFileTreeInitParams<TCT>) {\n this._files = files;\n this._prefix = params?.prefix || '';\n this._inferContentType = params?.inferContentType ?? ZipFileTreeAccessors.defaultInferContentType;\n this._buildItemCache();\n }\n\n /**\n * Default function to infer the content type of a file.\n * @param __filePath - The path of the file.\n * @param __provided - Optional supplied content type.\n * @returns `Success` with the content type of the file if successful, or\n * `Failure` with an error message otherwise.\n * @remarks This default implementation always returns `Success` with `undefined`.\n * @public\n */\n public static defaultInferContentType<TCT extends string = string>(\n __filePath: string,\n __provided?: string\n ): Result<TCT | undefined> {\n return succeed(undefined);\n }\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a ZIP file buffer (synchronous).\n * @param zipBuffer - The ZIP file as an ArrayBuffer or Uint8Array.\n * @param prefix - Optional prefix to prepend to paths.\n * @returns Result containing the ZipFileTreeAccessors instance.\n */\n public static fromBuffer<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n prefix?: string\n ): Result<ZipFileTreeAccessors<TCT>>;\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a ZIP file buffer (synchronous).\n * @param zipBuffer - The ZIP file as an ArrayBuffer or Uint8Array.\n * @param params - Optional initialization parameters.\n * @returns Result containing the ZipFileTreeAccessors instance.\n */\n public static fromBuffer<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Result<ZipFileTreeAccessors<TCT>>;\n\n public static fromBuffer<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n params?: FileTree.IFileTreeInitParams<TCT> | string\n ): Result<ZipFileTreeAccessors<TCT>> {\n try {\n /* c8 ignore next 1 - defense in depth */\n const uint8Buffer = zipBuffer instanceof Uint8Array ? zipBuffer : new Uint8Array(zipBuffer);\n const files = unzipSync(uint8Buffer);\n const normalizedParams = typeof params === 'string' ? { prefix: params } : params;\n return succeed(new ZipFileTreeAccessors<TCT>(files, normalizedParams));\n } catch (error) {\n /* c8 ignore next 1 - defensive coding: fflate always throws Error objects in practice */\n return fail(`Failed to load ZIP archive: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a ZIP file buffer (asynchronous).\n * @param zipBuffer - The ZIP file as an ArrayBuffer or Uint8Array.\n * @param prefix - Optional prefix to prepend to paths.\n * @returns Promise containing Result with the ZipFileTreeAccessors instance.\n */\n public static async fromBufferAsync<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n prefix?: string\n ): Promise<Result<ZipFileTreeAccessors<TCT>>>;\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a ZIP file buffer (asynchronous).\n * @param zipBuffer - The ZIP file as an ArrayBuffer or Uint8Array.\n * @param params - Optional initialization parameters.\n * @returns Promise containing Result with the ZipFileTreeAccessors instance.\n */\n public static async fromBufferAsync<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<ZipFileTreeAccessors<TCT>>>;\n\n public static async fromBufferAsync<TCT extends string = string>(\n zipBuffer: ArrayBuffer | Uint8Array,\n params?: FileTree.IFileTreeInitParams<TCT> | string\n ): Promise<Result<ZipFileTreeAccessors<TCT>>> {\n return new Promise((resolve) => {\n try {\n /* c8 ignore next 1 - defense in depth */\n const uint8Buffer = zipBuffer instanceof Uint8Array ? zipBuffer : new Uint8Array(zipBuffer);\n unzip(uint8Buffer, (err, files) => {\n if (err) {\n resolve(fail(`Failed to load ZIP archive: ${err.message}`));\n } else {\n const normalizedParams = typeof params === 'string' ? { prefix: params } : params;\n resolve(succeed(new ZipFileTreeAccessors<TCT>(files, normalizedParams)));\n }\n });\n /* c8 ignore next 5 - defensive coding: fflate reports errors via callback, not exceptions */\n } catch (error) {\n resolve(\n fail(`Failed to load ZIP archive: ${error instanceof Error ? error.message : String(error)}`)\n );\n }\n });\n }\n\n /**\n * Creates a new ZipFileTreeAccessors instance from a File object (browser environment).\n * @param file - The File object containing ZIP data.\n * @param params - Optional initialization parameters.\n * @returns Result containing the ZipFileTreeAccessors instance.\n */\n public static async fromFile<TCT extends string = string>(\n file: File,\n params?: FileTree.IFileTreeInitParams<TCT>\n ): Promise<Result<ZipFileTreeAccessors<TCT>>> {\n try {\n const arrayBuffer = await file.arrayBuffer();\n const uint8Buffer = new Uint8Array(arrayBuffer);\n\n return await ZipFileTreeAccessors.fromBufferAsync<TCT>(uint8Buffer, params);\n } catch (error) {\n return fail(`Failed to read file: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Builds the cache of all items in the ZIP archive.\n */\n private _buildItemCache(): void {\n const directories = new Set<string>();\n\n // Process all files and collect directory paths\n for (const [relativePath, fileData] of Object.entries(this._files)) {\n // Skip directories in fflate output (they have null data)\n /* c8 ignore next 5 - handles explicit directory entries from external ZIP tools (fflate doesn't create these) */\n if (fileData === null || fileData === undefined) {\n const dirPath = relativePath.replace(/\\/$/, '');\n if (dirPath) {\n directories.add(dirPath);\n }\n } else {\n // Extract directory paths from file paths\n const pathParts = relativePath.split('/');\n for (let i = 1; i < pathParts.length; i++) {\n const dirPath = pathParts.slice(0, i).join('/');\n if (dirPath) {\n directories.add(dirPath);\n }\n }\n\n // Add the file item with its raw bytes; text is decoded lazily on demand.\n const absolutePath = this.resolveAbsolutePath(relativePath);\n const item = new ZipFileItem<TCT>(relativePath, fileData, this);\n this._itemCache.set(absolutePath, item);\n }\n }\n\n // Add directory items to cache\n directories.forEach((dirPath) => {\n const absolutePath = this.resolveAbsolutePath(dirPath);\n const item = new ZipDirectoryItem<TCT>(dirPath, this);\n this._itemCache.set(absolutePath, item);\n });\n }\n\n /**\n * Resolves paths to an absolute path.\n */\n public resolveAbsolutePath(...paths: string[]): string {\n const joinedPath = this.joinPaths(...paths);\n const prefixed = this._prefix ? this.joinPaths(this._prefix, joinedPath) : joinedPath;\n return prefixed.startsWith('/') ? prefixed : '/' + prefixed;\n }\n\n /**\n * Gets the extension of a path.\n */\n public getExtension(path: string): string {\n const name = this.getBaseName(path);\n const lastDotIndex = name.lastIndexOf('.');\n return lastDotIndex >= 0 ? name.substring(lastDotIndex) : '';\n }\n\n /**\n * Gets the base name of a path.\n */\n public getBaseName(path: string, suffix?: string): string {\n const normalizedPath = path.replace(/\\/$/, ''); // Remove trailing slash\n const parts = normalizedPath.split('/');\n let baseName = parts[parts.length - 1] || '';\n\n if (suffix && baseName.endsWith(suffix)) {\n baseName = baseName.substring(0, baseName.length - suffix.length);\n }\n\n return baseName;\n }\n\n /**\n * Joins paths together.\n */\n public joinPaths(...paths: string[]): string {\n return paths\n .filter((p) => p && p.length > 0)\n .map((p) => p.replace(/^\\/+|\\/+$/g, '')) // Remove leading/trailing slashes\n .join('/')\n .replace(/\\/+/g, '/'); // Normalize multiple slashes\n }\n\n /**\n * Gets an item from the file tree.\n */\n public getItem(path: string): Result<FileTree.FileTreeItem<TCT>> {\n const absolutePath = this.resolveAbsolutePath(path);\n const item = this._itemCache.get(absolutePath);\n\n if (item) {\n return succeed(item);\n }\n\n return fail(`Item not found: ${absolutePath}`);\n }\n\n /**\n * Gets the contents of a file in the file tree.\n *\n * @remarks\n * The entry's bytes are decoded as UTF-8 with the lenient WHATWG default. Use\n * `getFileBytes()` for the undecoded bytes.\n */\n public getFileContents(path: string): Result<string> {\n return this._getFileItem(path).onSuccess((item) => item.getRawContents());\n }\n\n /**\n * Gets the raw bytes of a ZIP entry, with no text decoding applied.\n *\n * @remarks\n * The returned array is the archive's internal buffer and must not be modified.\n */\n public getFileBytes(path: string): Result<Uint8Array> {\n return this._getFileItem(path).onSuccess((item) => item.getRawBytes());\n }\n\n /**\n * Gets the contents of a file in the file tree, decoding UTF-8 strictly.\n *\n * @remarks\n * Always decidable here: ZIP entries are byte-native, so this store holds\n * exactly the bytes the archive carried.\n * @param path - Absolute path of the entry.\n * @returns `Success` with the decoded text; `Failure` if the entry's bytes are\n * not valid UTF-8.\n */\n public getFileTextStrict(path: string): Result<string> {\n return this._getFileItem(path).onSuccess((item) => item.getTextStrict());\n }\n\n /**\n * Resolves a path to the ZIP file item it names.\n * @param path - Path of the entry to look up.\n * @returns `Success` with the item, or `Failure` if it is missing or is a directory.\n */\n private _getFileItem(path: string): Result<ZipFileItem<TCT>> {\n return this.getItem(path).onSuccess((item) => {\n if (!(item instanceof ZipFileItem)) {\n return fail(`Path is not a file: ${path}`);\n }\n return succeed(item);\n });\n }\n\n /**\n * Gets the content type of a file in the file tree.\n */\n public getFileContentType(path: string, provided?: string): Result<TCT | undefined> {\n // If provided contentType is given, use it directly (highest priority)\n if (provided !== undefined) {\n return succeed(provided as TCT);\n }\n\n // For files that exist in the ZIP, we don't store explicit contentType\n // so we always fall back to inference\n return this._inferContentType(path);\n }\n\n /**\n * Gets the children of a directory in the file tree.\n */\n public getChildren(path: string): Result<ReadonlyArray<FileTree.FileTreeItem<TCT>>> {\n const absolutePath = this.resolveAbsolutePath(path);\n const children: FileTree.FileTreeItem<TCT>[] = [];\n\n // Find all items that are direct children of this directory\n for (const [itemPath, item] of this._itemCache) {\n if (this._isDirectChild(absolutePath, itemPath)) {\n children.push(item);\n }\n }\n\n return succeed(children);\n }\n\n /**\n * Checks if childPath is a direct child of parentPath.\n */\n private _isDirectChild(parentPath: string, childPath: string): boolean {\n // Normalize paths\n const normalizedParent = parentPath.replace(/\\/$/, '');\n const normalizedChild = childPath.replace(/\\/$/, '');\n\n // Child must start with parent path\n if (!normalizedChild.startsWith(normalizedParent + '/')) {\n return false;\n }\n\n // Get the relative path from parent to child\n const relativePath = normalizedChild.substring(normalizedParent.length + 1);\n\n // Direct child means no additional slashes in the relative path\n return !relativePath.includes('/');\n }\n}\n"]}
|
package/dist/ts-extras.d.ts
CHANGED
|
@@ -184,12 +184,12 @@ declare namespace AiAssist {
|
|
|
184
184
|
DEFAULT_MODEL_CAPABILITY_CONFIG,
|
|
185
185
|
callProviderCompletion,
|
|
186
186
|
callProxiedCompletion,
|
|
187
|
+
IProviderCompletionParams,
|
|
187
188
|
callProviderImageGeneration,
|
|
188
189
|
callProxiedImageGeneration,
|
|
190
|
+
IProviderImageGenerationParams,
|
|
189
191
|
callProviderListModels,
|
|
190
192
|
callProxiedListModels,
|
|
191
|
-
IProviderCompletionParams,
|
|
192
|
-
IProviderImageGenerationParams,
|
|
193
193
|
IProviderListModelsParams,
|
|
194
194
|
callProviderEmbedding,
|
|
195
195
|
callProxiedEmbedding,
|
|
@@ -1038,6 +1038,7 @@ declare namespace CryptoUtils {
|
|
|
1038
1038
|
createEncryptedFile,
|
|
1039
1039
|
decryptFile,
|
|
1040
1040
|
fromBase64,
|
|
1041
|
+
fromBase64Strict,
|
|
1041
1042
|
ICreateEncryptedFileParams,
|
|
1042
1043
|
toBase64,
|
|
1043
1044
|
tryDecryptFile,
|
|
@@ -1882,6 +1883,32 @@ declare type FormattersByTarget<T> = FormattersByExtendedTarget<FormatTargets, T
|
|
|
1882
1883
|
*/
|
|
1883
1884
|
declare function fromBase64(base64: string): Uint8Array;
|
|
1884
1885
|
|
|
1886
|
+
/**
|
|
1887
|
+
* Decodes a base64 string to a `Uint8Array`, **rejecting input that is not
|
|
1888
|
+
* well-formed base64** instead of silently salvaging what it can.
|
|
1889
|
+
*
|
|
1890
|
+
* @remarks
|
|
1891
|
+
* The difference from {@link CryptoUtils.fromBase64 | fromBase64} is the failure
|
|
1892
|
+
* mode, and it is the whole reason this exists. `fromBase64` is `Buffer`-first
|
|
1893
|
+
* where a `Buffer` exists, and `Buffer.from(s, 'base64')` **discards** characters
|
|
1894
|
+
* outside the base64 alphabet rather than complaining — so a corrupted or
|
|
1895
|
+
* truncated payload decodes to plausible-looking garbage and the corruption is
|
|
1896
|
+
* discovered, if ever, much further downstream. Use this variant whenever the
|
|
1897
|
+
* base64 arrived from somewhere you do not control (a wire response, a file, user
|
|
1898
|
+
* input) and a malformed value means "something is wrong", not "do your best".
|
|
1899
|
+
*
|
|
1900
|
+
* Implemented over `atob`, which rejects out-of-alphabet characters and bad
|
|
1901
|
+
* lengths. Note it inherits `atob`'s one leniency: per the WHATWG forgiving-base64
|
|
1902
|
+
* algorithm, ASCII whitespace inside the input is stripped rather than rejected.
|
|
1903
|
+
* That is deliberate — line-wrapped base64 is common and benign — and it does not
|
|
1904
|
+
* weaken the guarantee that matters here, which is that corrupt bytes fail loudly.
|
|
1905
|
+
* @param base64 - Base64 string to decode.
|
|
1906
|
+
* @returns `Success` with the decoded bytes, or `Failure` if `base64` is not
|
|
1907
|
+
* well-formed.
|
|
1908
|
+
* @public
|
|
1909
|
+
*/
|
|
1910
|
+
declare function fromBase64Strict(base64: string): Result<Uint8Array>;
|
|
1911
|
+
|
|
1885
1912
|
/**
|
|
1886
1913
|
* Auth tag size in bytes for GCM mode.
|
|
1887
1914
|
* @public
|
|
@@ -8337,7 +8364,7 @@ declare class ZipDirectoryItem<TCT extends string = string> implements FileTree.
|
|
|
8337
8364
|
* undecoded bytes.
|
|
8338
8365
|
* @public
|
|
8339
8366
|
*/
|
|
8340
|
-
declare class ZipFileItem<TCT extends string = string> implements FileTree.IBinaryFileTreeFileItem<TCT> {
|
|
8367
|
+
declare class ZipFileItem<TCT extends string = string> implements FileTree.IBinaryFileTreeFileItem<TCT>, FileTree.IStrictTextFileTreeFileItem<TCT> {
|
|
8341
8368
|
/**
|
|
8342
8369
|
* Indicates that this `FileTree.FileTreeItem` is a file.
|
|
8343
8370
|
*/
|
|
@@ -8370,6 +8397,11 @@ declare class ZipFileItem<TCT extends string = string> implements FileTree.IBina
|
|
|
8370
8397
|
* Text form of the entry, decoded lazily from the raw bytes on first text read.
|
|
8371
8398
|
*/
|
|
8372
8399
|
private _contents;
|
|
8400
|
+
/**
|
|
8401
|
+
* Whether `_bytes` is what the archive carried, rather than a re-encode of text
|
|
8402
|
+
* supplied to the constructor. Only the former can answer "was this valid UTF-8?".
|
|
8403
|
+
*/
|
|
8404
|
+
private readonly _bytesAreOriginal;
|
|
8373
8405
|
/**
|
|
8374
8406
|
* The ZIP file tree accessors that created this item.
|
|
8375
8407
|
*/
|
|
@@ -8418,6 +8450,18 @@ declare class ZipFileItem<TCT extends string = string> implements FileTree.IBina
|
|
|
8418
8450
|
* The returned array is the item's internal buffer and must not be modified.
|
|
8419
8451
|
*/
|
|
8420
8452
|
getRawBytes(): Result<Uint8Array>;
|
|
8453
|
+
/**
|
|
8454
|
+
* Gets the file's contents, decoding UTF-8 strictly.
|
|
8455
|
+
*
|
|
8456
|
+
* @remarks
|
|
8457
|
+
* Decidable for an entry read out of the archive, which is byte-native: this
|
|
8458
|
+
* item holds exactly the bytes the archive carried. An item constructed from
|
|
8459
|
+
* already-decoded text fails instead — its bytes are a re-encode, so they are
|
|
8460
|
+
* well-formed UTF-8 by construction and a success would say nothing.
|
|
8461
|
+
* @returns `Success` with the decoded text; `Failure` if the entry's bytes are
|
|
8462
|
+
* not valid UTF-8, or if this item never held the original bytes.
|
|
8463
|
+
*/
|
|
8464
|
+
getTextStrict(): Result<string>;
|
|
8421
8465
|
}
|
|
8422
8466
|
|
|
8423
8467
|
declare namespace ZipFileTree {
|
|
@@ -8447,7 +8491,7 @@ export { ZipFileTree }
|
|
|
8447
8491
|
* undecoded bytes.
|
|
8448
8492
|
* @public
|
|
8449
8493
|
*/
|
|
8450
|
-
declare class ZipFileTreeAccessors<TCT extends string = string> implements FileTree.IBinaryFileTreeAccessors<TCT> {
|
|
8494
|
+
declare class ZipFileTreeAccessors<TCT extends string = string> implements FileTree.IBinaryFileTreeAccessors<TCT>, FileTree.IStrictTextFileTreeAccessors<TCT> {
|
|
8451
8495
|
/**
|
|
8452
8496
|
* The unzipped file data.
|
|
8453
8497
|
*/
|
|
@@ -8554,6 +8598,17 @@ declare class ZipFileTreeAccessors<TCT extends string = string> implements FileT
|
|
|
8554
8598
|
* The returned array is the archive's internal buffer and must not be modified.
|
|
8555
8599
|
*/
|
|
8556
8600
|
getFileBytes(path: string): Result<Uint8Array>;
|
|
8601
|
+
/**
|
|
8602
|
+
* Gets the contents of a file in the file tree, decoding UTF-8 strictly.
|
|
8603
|
+
*
|
|
8604
|
+
* @remarks
|
|
8605
|
+
* Always decidable here: ZIP entries are byte-native, so this store holds
|
|
8606
|
+
* exactly the bytes the archive carried.
|
|
8607
|
+
* @param path - Absolute path of the entry.
|
|
8608
|
+
* @returns `Success` with the decoded text; `Failure` if the entry's bytes are
|
|
8609
|
+
* not valid UTF-8.
|
|
8610
|
+
*/
|
|
8611
|
+
getFileTextStrict(path: string): Result<string>;
|
|
8557
8612
|
/**
|
|
8558
8613
|
* Resolves a path to the ZIP file item it names.
|
|
8559
8614
|
* @param path - Path of the entry to look up.
|