@karmaniverous/get-dotenv 6.2.2 → 6.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/chunks/AwsRestJsonProtocol-Bq1HE-Ln.mjs +932 -0
  2. package/dist/chunks/createCli-BY6_cfZr.mjs +439 -0
  3. package/dist/chunks/externalDataInterceptor-CbsdEYa-.mjs +19 -0
  4. package/dist/chunks/getSSOTokenFromFile-hUSpR7Wf.mjs +22 -0
  5. package/dist/chunks/helpConfig-CGejgwWW.mjs +12 -0
  6. package/dist/chunks/index-B5JKTBOL.mjs +443 -0
  7. package/dist/chunks/index-BEJFiHMX.mjs +522 -0
  8. package/dist/chunks/index-BPYF6K_G.mjs +82 -0
  9. package/dist/chunks/index-Bc3h0a95.mjs +374 -0
  10. package/dist/chunks/index-BpCF5UKx.mjs +272 -0
  11. package/dist/chunks/index-C_wqbTwI.mjs +187 -0
  12. package/dist/chunks/index-CeCufHlm.mjs +9374 -0
  13. package/dist/chunks/index-Cu7rdyqN.mjs +102 -0
  14. package/dist/chunks/index-DWAtHEA-.mjs +379 -0
  15. package/dist/chunks/index-Dp1Ip6Ra.mjs +354 -0
  16. package/dist/chunks/index-DyU5pKKi.mjs +24 -0
  17. package/dist/chunks/index-c7zKtEuy.mjs +578 -0
  18. package/dist/chunks/index-cIunyiUQ.mjs +702 -0
  19. package/dist/chunks/invoke-DuRPU1oC.mjs +60 -0
  20. package/dist/chunks/loadModuleDefault-Dj8B3Stt.mjs +123 -0
  21. package/dist/chunks/loadSso-w1eTVg0O.mjs +412 -0
  22. package/dist/chunks/loader-DnhPeGfq.mjs +346 -0
  23. package/dist/chunks/overlayEnv-Bs2kVayG.mjs +234 -0
  24. package/dist/chunks/package-boo9EyYs.mjs +5 -0
  25. package/dist/chunks/parseKnownFiles-B9cDK21V.mjs +23 -0
  26. package/dist/chunks/readMergedOptions-Nt0TR7dX.mjs +1626 -0
  27. package/dist/chunks/resolveCliOptions-TFRzhB2c.mjs +138 -0
  28. package/dist/chunks/sdk-stream-mixin-BZoJ5jy9.mjs +167 -0
  29. package/dist/chunks/spawnEnv-CN8a7cNR.mjs +306 -0
  30. package/dist/chunks/types-DJ-BGABd.mjs +59 -0
  31. package/dist/chunks/validate-CDl0rE6k.mjs +61 -0
  32. package/dist/cli.mjs +39 -19307
  33. package/dist/cliHost.mjs +20 -2800
  34. package/dist/config.mjs +10 -509
  35. package/dist/env-overlay.mjs +6 -337
  36. package/dist/getdotenv.cli.mjs +39 -19305
  37. package/dist/index.mjs +39 -19396
  38. package/dist/plugins-aws.d.ts +1 -4
  39. package/dist/plugins-aws.mjs +65 -2568
  40. package/dist/plugins-batch.mjs +16 -2573
  41. package/dist/plugins-cmd.mjs +19 -3094
  42. package/dist/plugins-init.d.ts +8 -0
  43. package/dist/plugins-init.mjs +85 -2297
  44. package/dist/plugins.mjs +36 -18817
  45. package/package.json +1 -2
  46. package/dist/templates/cli/index.ts +0 -25
  47. package/dist/templates/cli/plugins/hello/defaultAction.ts +0 -27
  48. package/dist/templates/cli/plugins/hello/index.ts +0 -26
  49. package/dist/templates/cli/plugins/hello/options.ts +0 -31
  50. package/dist/templates/cli/plugins/hello/strangerAction.ts +0 -20
  51. package/dist/templates/cli/plugins/hello/types.ts +0 -13
  52. package/dist/templates/config/js/getdotenv.config.js +0 -20
  53. package/dist/templates/config/json/local/getdotenv.config.local.json +0 -7
  54. package/dist/templates/config/json/public/getdotenv.config.json +0 -9
  55. package/dist/templates/config/public/getdotenv.config.json +0 -8
  56. package/dist/templates/config/ts/getdotenv.config.ts +0 -28
  57. package/dist/templates/config/yaml/local/getdotenv.config.local.yaml +0 -7
  58. package/dist/templates/config/yaml/public/getdotenv.config.yaml +0 -7
  59. package/dist/templates/defaultAction.ts +0 -27
  60. package/dist/templates/getdotenv.config.js +0 -20
  61. package/dist/templates/getdotenv.config.json +0 -9
  62. package/dist/templates/getdotenv.config.local.json +0 -7
  63. package/dist/templates/getdotenv.config.local.yaml +0 -7
  64. package/dist/templates/getdotenv.config.ts +0 -28
  65. package/dist/templates/getdotenv.config.yaml +0 -7
  66. package/dist/templates/hello/defaultAction.ts +0 -27
  67. package/dist/templates/hello/index.ts +0 -26
  68. package/dist/templates/hello/options.ts +0 -31
  69. package/dist/templates/hello/strangerAction.ts +0 -20
  70. package/dist/templates/hello/types.ts +0 -13
  71. package/dist/templates/index.ts +0 -26
  72. package/dist/templates/js/getdotenv.config.js +0 -20
  73. package/dist/templates/json/local/getdotenv.config.local.json +0 -7
  74. package/dist/templates/json/public/getdotenv.config.json +0 -9
  75. package/dist/templates/local/getdotenv.config.local.json +0 -7
  76. package/dist/templates/local/getdotenv.config.local.yaml +0 -7
  77. package/dist/templates/options.ts +0 -31
  78. package/dist/templates/plugins/hello/defaultAction.ts +0 -27
  79. package/dist/templates/plugins/hello/index.ts +0 -26
  80. package/dist/templates/plugins/hello/options.ts +0 -31
  81. package/dist/templates/plugins/hello/strangerAction.ts +0 -20
  82. package/dist/templates/plugins/hello/types.ts +0 -13
  83. package/dist/templates/public/getdotenv.config.json +0 -9
  84. package/dist/templates/public/getdotenv.config.yaml +0 -7
  85. package/dist/templates/strangerAction.ts +0 -20
  86. package/dist/templates/ts/getdotenv.config.ts +0 -28
  87. package/dist/templates/types.ts +0 -13
  88. package/dist/templates/yaml/local/getdotenv.config.local.yaml +0 -7
  89. package/dist/templates/yaml/public/getdotenv.config.yaml +0 -7
@@ -0,0 +1,374 @@
1
+ import { l as redactTriple, m as maybeWarnEntropy, r as readMergedOptions, c as getDotenvCliOptions2Options, d as definePlugin } from './readMergedOptions-Nt0TR7dX.mjs';
2
+ import 'execa';
3
+ import 'fs-extra';
4
+ import 'crypto';
5
+ import 'path';
6
+ import 'url';
7
+ import '@commander-js/extra-typings';
8
+ import 'nanoid';
9
+ import 'dotenv';
10
+ import './loader-DnhPeGfq.mjs';
11
+ import 'package-directory';
12
+ import 'yaml';
13
+ import { z } from 'zod';
14
+ import { c as resolveCommand, d as resolveShell, t as tokenize, s as shouldCapture, r as runCommand, b as buildSpawnEnv } from './spawnEnv-CN8a7cNR.mjs';
15
+ import { m as maybePreserveNodeEvalArgv, c as composeNestedEnv, s as stripOne } from './invoke-DuRPU1oC.mjs';
16
+ import { b as dotenvExpandFromProcessEnv } from './overlayEnv-Bs2kVayG.mjs';
17
+ import { r as resolveCliOptions, b as baseGetDotenvCliOptions } from './resolveCliOptions-TFRzhB2c.mjs';
18
+
19
+ /**
20
+ * Trace child env composition with redaction and entropy warnings.
21
+ * Presentation-only: does not mutate env; writes lines via the provided sink.
22
+ */
23
+ function traceChildEnv(opts) {
24
+ const { parentEnv, dotenv, keys, redact, redactPatterns, warnEntropy, entropyThreshold, entropyMinLength, entropyWhitelist, write, } = opts;
25
+ const parentKeys = Object.keys(parentEnv);
26
+ const dotenvKeys = Object.keys(dotenv);
27
+ const allKeys = Array.from(new Set([...parentKeys, ...dotenvKeys])).sort();
28
+ const effectiveKeys = Array.isArray(keys) && keys.length > 0 ? keys : allKeys;
29
+ // Redaction options for display
30
+ const redOpts = {};
31
+ if (redact) {
32
+ redOpts.redact = true;
33
+ if (Array.isArray(redactPatterns))
34
+ redOpts.redactPatterns = redactPatterns;
35
+ }
36
+ // Entropy warning options
37
+ const entOpts = {};
38
+ if (typeof warnEntropy === 'boolean')
39
+ entOpts.warnEntropy = warnEntropy;
40
+ if (typeof entropyThreshold === 'number')
41
+ entOpts.entropyThreshold = entropyThreshold;
42
+ if (typeof entropyMinLength === 'number')
43
+ entOpts.entropyMinLength = entropyMinLength;
44
+ if (Array.isArray(entropyWhitelist))
45
+ entOpts.entropyWhitelist = entropyWhitelist;
46
+ for (const k of effectiveKeys) {
47
+ const parentVal = parentEnv[k];
48
+ const dot = dotenv[k];
49
+ const final = dot !== undefined ? dot : parentVal;
50
+ const origin = dot !== undefined
51
+ ? 'dotenv'
52
+ : parentVal !== undefined
53
+ ? 'parent'
54
+ : 'unset';
55
+ const tripleIn = {};
56
+ if (parentVal !== undefined)
57
+ tripleIn.parent = parentVal;
58
+ if (dot !== undefined)
59
+ tripleIn.dotenv = dot;
60
+ if (final !== undefined)
61
+ tripleIn.final = final;
62
+ const triple = redactTriple(k, tripleIn, redOpts);
63
+ write(`[trace] key=${k} origin=${origin} parent=${triple.parent ?? ''} dotenv=${triple.dotenv ?? ''} final=${triple.final ?? ''}`);
64
+ maybeWarnEntropy(k, final, origin, entOpts, (line) => {
65
+ write(line);
66
+ });
67
+ }
68
+ }
69
+
70
+ /** src/plugins/cmd/actions/runner.ts
71
+ * Unified runner for cmd subcommand and parent alias.
72
+ * - Resolves command via scripts
73
+ * - Emits --trace diagnostics (centralized helper with redaction/entropy)
74
+ * - Preserves Node -e argv under shell-off
75
+ * - Normalizes child env and honors capture
76
+ */
77
+ /**
78
+ * Execute a command using the current CLI context.
79
+ * Resolves command/shell via scripts, emits traces, and handles execution.
80
+ *
81
+ * @param cli - The CLI instance.
82
+ * @param merged - Merged CLI options.
83
+ * @param command - Command string or array of args.
84
+ * @param _opts - Execution options (e.g. origin label).
85
+ */
86
+ async function runCmdWithContext(cli, merged, command, _opts) {
87
+ const { logger, debug, capture, scripts: scriptsCfg, shell: shellPref, trace, redact, redactPatterns, warnEntropy, entropyThreshold, entropyMinLength, entropyWhitelist, } = merged;
88
+ const dotenv = cli.getCtx().dotenv;
89
+ // Build input string and note original argv (when available).
90
+ const parts = Array.isArray(command) ? command.map(String) : [];
91
+ const inputStr = Array.isArray(command) ? parts.join(' ') : command;
92
+ // Resolve command and shell from scripts/global.
93
+ const resolved = resolveCommand(scriptsCfg, inputStr);
94
+ if (debug)
95
+ logger.debug('\n*** command ***\n', `'${resolved}'`);
96
+ const shellSetting = resolveShell(scriptsCfg, inputStr, shellPref);
97
+ // Diagnostics: --trace [keys...]
98
+ const traceOpt = trace;
99
+ if (traceOpt) {
100
+ traceChildEnv({
101
+ parentEnv: process.env,
102
+ dotenv,
103
+ ...(Array.isArray(traceOpt) ? { keys: traceOpt } : {}),
104
+ ...(redact ? { redact: true } : {}),
105
+ ...(redact && Array.isArray(redactPatterns) ? { redactPatterns } : {}),
106
+ ...(typeof warnEntropy === 'boolean' ? { warnEntropy } : {}),
107
+ ...(typeof entropyThreshold === 'number' ? { entropyThreshold } : {}),
108
+ ...(typeof entropyMinLength === 'number' ? { entropyMinLength } : {}),
109
+ ...(Array.isArray(entropyWhitelist) ? { entropyWhitelist } : {}),
110
+ write: (line) => {
111
+ try {
112
+ process.stderr.write(line + '\n');
113
+ }
114
+ catch {
115
+ /* ignore */
116
+ }
117
+ },
118
+ });
119
+ }
120
+ // Preserve Node -e argv under shell-off when the script did not remap input.
121
+ let commandArg = resolved;
122
+ if (shellSetting === false && resolved === inputStr) {
123
+ if (Array.isArray(command)) {
124
+ commandArg = maybePreserveNodeEvalArgv(parts);
125
+ }
126
+ else {
127
+ const toks = tokenize(inputStr, { preserveDoubledQuotes: true });
128
+ if (toks.length >= 3 &&
129
+ (toks[0] ?? '').toLowerCase() === 'node' &&
130
+ (toks[1] === '-e' || toks[1] === '--eval')) {
131
+ toks[2] = stripOne(toks[2] ?? '');
132
+ commandArg = toks;
133
+ }
134
+ }
135
+ }
136
+ // Child env: compose nested bag and sanitize.
137
+ const childOverlay = composeNestedEnv(merged, dotenv);
138
+ const captureFlag = shouldCapture(capture);
139
+ let exit;
140
+ try {
141
+ exit = await runCommand(commandArg, shellSetting, {
142
+ env: buildSpawnEnv(process.env, childOverlay),
143
+ stdio: captureFlag ? 'pipe' : 'inherit',
144
+ });
145
+ }
146
+ catch (e) {
147
+ // Under unit tests, execa may be mocked to return undefined which causes
148
+ // pickResult access to throw. Treat as success to allow call-count assertions.
149
+ if (process.env.VITEST_WORKER_ID)
150
+ return 0;
151
+ throw e;
152
+ }
153
+ return typeof exit === 'number' ? exit : 0;
154
+ }
155
+
156
+ /**
157
+ * Attach the default "cmd" subcommand action.
158
+ * Mirrors the prior inline implementation in cmd/index.ts.
159
+ */
160
+ const attachCmdDefaultAction = (cli, cmd, aliasKey) => {
161
+ cmd.action(async function (...allArgs) {
162
+ // Commander passes: [...positionals, options, thisCommand]
163
+ const thisCommand = allArgs[allArgs.length - 1];
164
+ const commandParts = allArgs[0];
165
+ const args = Array.isArray(commandParts)
166
+ ? commandParts.map(String)
167
+ : [];
168
+ // No-op when invoked as the default command with no args.
169
+ if (args.length === 0)
170
+ return;
171
+ const merged = readMergedOptions(thisCommand);
172
+ const parent = thisCommand.parent;
173
+ if (!parent)
174
+ throw new Error('parent command not found');
175
+ // Conflict detection: if an alias option is present on parent, do not
176
+ // also accept positional cmd args.
177
+ if (aliasKey) {
178
+ const p = parent;
179
+ const pv = typeof p.optsWithGlobals === 'function'
180
+ ? p.optsWithGlobals()
181
+ : typeof p.opts === 'function'
182
+ ? p.opts()
183
+ : {};
184
+ const ov = pv[aliasKey];
185
+ if (ov !== undefined) {
186
+ merged.logger.error(`--${aliasKey} option conflicts with cmd subcommand.`);
187
+ process.exit(0);
188
+ }
189
+ }
190
+ await runCmdWithContext(cli, merged, args);
191
+ });
192
+ };
193
+
194
+ /**
195
+ * Attach options/arguments for the cmd plugin mount.
196
+ *
197
+ * Note: the plugin description is owned by `src/plugins/cmd/index.ts` and must
198
+ * not be set here.
199
+ *
200
+ * @param cli - The `cmd` command mount.
201
+ * @returns The same `cli` instance for chaining.
202
+ *
203
+ * @internal
204
+ */
205
+ function attachCmdOptions(cli) {
206
+ return cli
207
+ .enablePositionalOptions()
208
+ .passThroughOptions()
209
+ .argument('[command...]');
210
+ }
211
+
212
+ /**
213
+ * Install the parent-level invoker (alias) for the cmd plugin.
214
+ * Unifies naming with batch attachParentInvoker; behavior unchanged.
215
+ */
216
+ const attachCmdParentInvoker = (cli, options, plugin) => {
217
+ const dbg = (...args) => {
218
+ if (process.env.GETDOTENV_DEBUG) {
219
+ try {
220
+ const line = args
221
+ .map((a) => (typeof a === 'string' ? a : JSON.stringify(a)))
222
+ .join(' ');
223
+ process.stderr.write(`[getdotenv:alias] ${line}\n`);
224
+ }
225
+ catch {
226
+ /* ignore */
227
+ }
228
+ }
229
+ };
230
+ const aliasSpec = typeof options.optionAlias === 'string'
231
+ ? { flags: options.optionAlias, description: undefined}
232
+ : options.optionAlias;
233
+ if (!aliasSpec)
234
+ return;
235
+ const deriveKey = (flags) => {
236
+ // install alias option
237
+ if (process.env.GETDOTENV_DEBUG) {
238
+ console.error('[getdotenv:alias] install alias option', flags);
239
+ }
240
+ const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
241
+ const name = long.replace(/^--/, '');
242
+ return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
243
+ };
244
+ const aliasKey = deriveKey(aliasSpec.flags);
245
+ // Expose the option on the parent (root) command.
246
+ const parentCmd = cli.parent ??
247
+ cli;
248
+ const desc = aliasSpec.description ??
249
+ 'alias of cmd subcommand; provide command tokens (variadic)';
250
+ parentCmd.option(aliasSpec.flags, desc);
251
+ // Tag the just-added parent option for grouped help rendering at the root.
252
+ const optsArr = parentCmd.options;
253
+ if (optsArr.length > 0) {
254
+ const last = optsArr[optsArr.length - 1];
255
+ if (last)
256
+ parentCmd.setOptionGroup(last, 'plugin:cmd');
257
+ }
258
+ // Shared alias executor for either preAction or preSubcommand hooks.
259
+ // Ensure we only execute once even if both hooks fire in a single parse.
260
+ const aliasState = { handled: false };
261
+ const maybeRun = async (thisCommand) => {
262
+ dbg('maybeRun:start');
263
+ // Read plugin config expand default; fall back to undefined (handled in maybeRunAlias)
264
+ let expandDefault = undefined;
265
+ try {
266
+ const cfg = plugin.readConfig(cli);
267
+ if (typeof cfg.expand === 'boolean')
268
+ expandDefault = cfg.expand;
269
+ }
270
+ catch {
271
+ /* config may be unavailable before resolve; default handled downstream */
272
+ }
273
+ // Inspect parent options and rawArgs to detect alias-only invocation.
274
+ if (aliasState.handled)
275
+ return;
276
+ const cmd = thisCommand;
277
+ dbg('maybeRun:rawArgs', cmd.rawArgs ?? []);
278
+ const raw = typeof cmd.opts === 'function' ? cmd.opts() : {};
279
+ const val = raw[aliasKey];
280
+ const provided = typeof val === 'string'
281
+ ? val.length > 0
282
+ : Array.isArray(val)
283
+ ? val.length > 0
284
+ : false;
285
+ dbg('maybeRun:aliasKey', aliasKey, 'provided', provided, 'value', val);
286
+ if (!provided)
287
+ return;
288
+ const childNames = cmd.commands.flatMap((c) => [c.name(), ...c.aliases()]);
289
+ dbg('maybeRun:childNames', childNames);
290
+ const hasSub = (cmd.rawArgs ?? []).some((t) => childNames.includes(t));
291
+ dbg('maybeRun:hasSub', hasSub);
292
+ if (hasSub)
293
+ return; // do not run alias when an explicit subcommand is present
294
+ aliasState.handled = true;
295
+ // Merge CLI options and resolve dotenv context for this invocation.
296
+ const { merged } = resolveCliOptions(raw, baseGetDotenvCliOptions, process.env.getDotenvCliOptions);
297
+ const serviceOptions = getDotenvCliOptions2Options(merged);
298
+ await cli.resolveAndLoad(serviceOptions);
299
+ // Build input string and apply optional expansion (by config default).
300
+ const joined = typeof val === 'string'
301
+ ? val
302
+ : Array.isArray(val)
303
+ ? val.map(String).join(' ')
304
+ : '';
305
+ const effectiveExpand = expandDefault !== false;
306
+ const expanded = dotenvExpandFromProcessEnv(joined);
307
+ const input = effectiveExpand && expanded !== undefined ? expanded : joined;
308
+ // Hand off to shared runner and terminate (except under tests).
309
+ const exitCode = await runCmdWithContext(cli, merged, input);
310
+ const underTests = process.env.GETDOTENV_TEST === '1' ||
311
+ typeof process.env.VITEST_WORKER_ID === 'string';
312
+ if (!underTests) {
313
+ process.exit(typeof exitCode === 'number' ? exitCode : 0);
314
+ }
315
+ };
316
+ parentCmd.hook('preAction', async (thisCommand) => {
317
+ await maybeRun(thisCommand);
318
+ });
319
+ parentCmd.hook('preSubcommand', async (thisCommand) => {
320
+ await maybeRun(thisCommand);
321
+ });
322
+ };
323
+
324
+ /**
325
+ * Zod schema for cmd plugin configuration.
326
+ */
327
+ const cmdPluginConfigSchema = z
328
+ .object({
329
+ /** When true, expand the alias value before execution (default behavior when omitted). */
330
+ expand: z.boolean().optional(),
331
+ })
332
+ .strict();
333
+
334
+ /**
335
+ * @packageDocumentation
336
+ * Cmd plugin subpath. Provides the `cmd` subcommand and an optional parent‑level
337
+ * alias to execute a command within the resolved dotenv context.
338
+ */
339
+ /**
340
+ * Cmd plugin: executes a command using the current getdotenv CLI context.
341
+ * Registers the `cmd` subcommand and optionally attaches a parent-level alias (e.g. `-c`).
342
+ *
343
+ * @param options - Plugin configuration options.
344
+ */
345
+ const cmdPlugin = (options = {}) => {
346
+ const plugin = definePlugin({
347
+ ns: 'cmd',
348
+ configSchema: cmdPluginConfigSchema,
349
+ setup(cli) {
350
+ const aliasSpec = typeof options.optionAlias === 'string'
351
+ ? { flags: options.optionAlias}
352
+ : options.optionAlias;
353
+ const deriveKey = (flags) => {
354
+ const long = flags.split(/[ ,|]+/).find((f) => f.startsWith('--')) ?? '--cmd';
355
+ const name = long.replace(/^--/, '');
356
+ return name.replace(/-([a-z])/g, (_m, c) => c.toUpperCase());
357
+ };
358
+ const aliasKey = aliasSpec ? deriveKey(aliasSpec.flags) : undefined;
359
+ // Mount is the command ('cmd'); attach default action.
360
+ cli.description('Execute command according to the --shell option, conflicts with --command option (default subcommand)');
361
+ // Options/arguments (positional payload, argv routing) are attached separately.
362
+ attachCmdOptions(cli);
363
+ attachCmdDefaultAction(cli, cli, aliasKey);
364
+ // Parent-attached option alias (optional, unified naming).
365
+ if (aliasSpec !== undefined) {
366
+ attachCmdParentInvoker(cli, options, plugin);
367
+ }
368
+ return undefined;
369
+ },
370
+ });
371
+ return plugin;
372
+ };
373
+
374
+ export { cmdPlugin as c, traceChildEnv as t };
@@ -0,0 +1,272 @@
1
+ import { t as toUtf8, i as fromUtf8 } from './index-CeCufHlm.mjs';
2
+ import './readMergedOptions-Nt0TR7dX.mjs';
3
+ import 'zod';
4
+ import '@commander-js/extra-typings';
5
+ import './overlayEnv-Bs2kVayG.mjs';
6
+ import 'fs-extra';
7
+ import './loadModuleDefault-Dj8B3Stt.mjs';
8
+ import 'crypto';
9
+ import 'path';
10
+ import 'url';
11
+ import 'nanoid';
12
+ import 'dotenv';
13
+ import './loader-DnhPeGfq.mjs';
14
+ import 'package-directory';
15
+ import 'yaml';
16
+ import 'execa';
17
+ import 'buffer';
18
+ import 'os';
19
+ import 'node:fs/promises';
20
+ import 'http';
21
+ import 'https';
22
+ import 'stream';
23
+ import 'process';
24
+ import 'node:fs';
25
+
26
+ class EventStreamSerde {
27
+ marshaller;
28
+ serializer;
29
+ deserializer;
30
+ serdeContext;
31
+ defaultContentType;
32
+ constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, }) {
33
+ this.marshaller = marshaller;
34
+ this.serializer = serializer;
35
+ this.deserializer = deserializer;
36
+ this.serdeContext = serdeContext;
37
+ this.defaultContentType = defaultContentType;
38
+ }
39
+ async serializeEventStream({ eventStream, requestSchema, initialRequest, }) {
40
+ const marshaller = this.marshaller;
41
+ const eventStreamMember = requestSchema.getEventStreamMember();
42
+ const unionSchema = requestSchema.getMemberSchema(eventStreamMember);
43
+ const serializer = this.serializer;
44
+ const defaultContentType = this.defaultContentType;
45
+ const initialRequestMarker = Symbol("initialRequestMarker");
46
+ const eventStreamIterable = {
47
+ async *[Symbol.asyncIterator]() {
48
+ if (initialRequest) {
49
+ const headers = {
50
+ ":event-type": { type: "string", value: "initial-request" },
51
+ ":message-type": { type: "string", value: "event" },
52
+ ":content-type": { type: "string", value: defaultContentType },
53
+ };
54
+ serializer.write(requestSchema, initialRequest);
55
+ const body = serializer.flush();
56
+ yield {
57
+ [initialRequestMarker]: true,
58
+ headers,
59
+ body,
60
+ };
61
+ }
62
+ for await (const page of eventStream) {
63
+ yield page;
64
+ }
65
+ },
66
+ };
67
+ return marshaller.serialize(eventStreamIterable, (event) => {
68
+ if (event[initialRequestMarker]) {
69
+ return {
70
+ headers: event.headers,
71
+ body: event.body,
72
+ };
73
+ }
74
+ const unionMember = Object.keys(event).find((key) => {
75
+ return key !== "__type";
76
+ }) ?? "";
77
+ const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event);
78
+ const headers = {
79
+ ":event-type": { type: "string", value: eventType },
80
+ ":message-type": { type: "string", value: "event" },
81
+ ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType },
82
+ ...additionalHeaders,
83
+ };
84
+ return {
85
+ headers,
86
+ body,
87
+ };
88
+ });
89
+ }
90
+ async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) {
91
+ const marshaller = this.marshaller;
92
+ const eventStreamMember = responseSchema.getEventStreamMember();
93
+ const unionSchema = responseSchema.getMemberSchema(eventStreamMember);
94
+ const memberSchemas = unionSchema.getMemberSchemas();
95
+ const initialResponseMarker = Symbol("initialResponseMarker");
96
+ const asyncIterable = marshaller.deserialize(response.body, async (event) => {
97
+ const unionMember = Object.keys(event).find((key) => {
98
+ return key !== "__type";
99
+ }) ?? "";
100
+ const body = event[unionMember].body;
101
+ if (unionMember === "initial-response") {
102
+ const dataObject = await this.deserializer.read(responseSchema, body);
103
+ delete dataObject[eventStreamMember];
104
+ return {
105
+ [initialResponseMarker]: true,
106
+ ...dataObject,
107
+ };
108
+ }
109
+ else if (unionMember in memberSchemas) {
110
+ const eventStreamSchema = memberSchemas[unionMember];
111
+ if (eventStreamSchema.isStructSchema()) {
112
+ const out = {};
113
+ let hasBindings = false;
114
+ for (const [name, member] of eventStreamSchema.structIterator()) {
115
+ const { eventHeader, eventPayload } = member.getMergedTraits();
116
+ hasBindings = hasBindings || Boolean(eventHeader || eventPayload);
117
+ if (eventPayload) {
118
+ if (member.isBlobSchema()) {
119
+ out[name] = body;
120
+ }
121
+ else if (member.isStringSchema()) {
122
+ out[name] = (this.serdeContext?.utf8Encoder ?? toUtf8)(body);
123
+ }
124
+ else if (member.isStructSchema()) {
125
+ out[name] = await this.deserializer.read(member, body);
126
+ }
127
+ }
128
+ else if (eventHeader) {
129
+ const value = event[unionMember].headers[name]?.value;
130
+ if (value != null) {
131
+ if (member.isNumericSchema()) {
132
+ if (value && typeof value === "object" && "bytes" in value) {
133
+ out[name] = BigInt(value.toString());
134
+ }
135
+ else {
136
+ out[name] = Number(value);
137
+ }
138
+ }
139
+ else {
140
+ out[name] = value;
141
+ }
142
+ }
143
+ }
144
+ }
145
+ if (hasBindings) {
146
+ return {
147
+ [unionMember]: out,
148
+ };
149
+ }
150
+ }
151
+ return {
152
+ [unionMember]: await this.deserializer.read(eventStreamSchema, body),
153
+ };
154
+ }
155
+ else {
156
+ return {
157
+ $unknown: event,
158
+ };
159
+ }
160
+ });
161
+ const asyncIterator = asyncIterable[Symbol.asyncIterator]();
162
+ const firstEvent = await asyncIterator.next();
163
+ if (firstEvent.done) {
164
+ return asyncIterable;
165
+ }
166
+ if (firstEvent.value?.[initialResponseMarker]) {
167
+ if (!responseSchema) {
168
+ throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");
169
+ }
170
+ for (const [key, value] of Object.entries(firstEvent.value)) {
171
+ initialResponseContainer[key] = value;
172
+ }
173
+ }
174
+ return {
175
+ async *[Symbol.asyncIterator]() {
176
+ if (!firstEvent?.value?.[initialResponseMarker]) {
177
+ yield firstEvent.value;
178
+ }
179
+ while (true) {
180
+ const { done, value } = await asyncIterator.next();
181
+ if (done) {
182
+ break;
183
+ }
184
+ yield value;
185
+ }
186
+ },
187
+ };
188
+ }
189
+ writeEventBody(unionMember, unionSchema, event) {
190
+ const serializer = this.serializer;
191
+ let eventType = unionMember;
192
+ let explicitPayloadMember = null;
193
+ let explicitPayloadContentType;
194
+ const isKnownSchema = (() => {
195
+ const struct = unionSchema.getSchema();
196
+ return struct[4].includes(unionMember);
197
+ })();
198
+ const additionalHeaders = {};
199
+ if (!isKnownSchema) {
200
+ const [type, value] = event[unionMember];
201
+ eventType = type;
202
+ serializer.write(15, value);
203
+ }
204
+ else {
205
+ const eventSchema = unionSchema.getMemberSchema(unionMember);
206
+ if (eventSchema.isStructSchema()) {
207
+ for (const [memberName, memberSchema] of eventSchema.structIterator()) {
208
+ const { eventHeader, eventPayload } = memberSchema.getMergedTraits();
209
+ if (eventPayload) {
210
+ explicitPayloadMember = memberName;
211
+ }
212
+ else if (eventHeader) {
213
+ const value = event[unionMember][memberName];
214
+ let type = "binary";
215
+ if (memberSchema.isNumericSchema()) {
216
+ if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) {
217
+ type = "integer";
218
+ }
219
+ else {
220
+ type = "long";
221
+ }
222
+ }
223
+ else if (memberSchema.isTimestampSchema()) {
224
+ type = "timestamp";
225
+ }
226
+ else if (memberSchema.isStringSchema()) {
227
+ type = "string";
228
+ }
229
+ else if (memberSchema.isBooleanSchema()) {
230
+ type = "boolean";
231
+ }
232
+ if (value != null) {
233
+ additionalHeaders[memberName] = {
234
+ type,
235
+ value,
236
+ };
237
+ delete event[unionMember][memberName];
238
+ }
239
+ }
240
+ }
241
+ if (explicitPayloadMember !== null) {
242
+ const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember);
243
+ if (payloadSchema.isBlobSchema()) {
244
+ explicitPayloadContentType = "application/octet-stream";
245
+ }
246
+ else if (payloadSchema.isStringSchema()) {
247
+ explicitPayloadContentType = "text/plain";
248
+ }
249
+ serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]);
250
+ }
251
+ else {
252
+ serializer.write(eventSchema, event[unionMember]);
253
+ }
254
+ }
255
+ else {
256
+ throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union.");
257
+ }
258
+ }
259
+ const messageSerialization = serializer.flush();
260
+ const body = typeof messageSerialization === "string"
261
+ ? (this.serdeContext?.utf8Decoder ?? fromUtf8)(messageSerialization)
262
+ : messageSerialization;
263
+ return {
264
+ body,
265
+ eventType,
266
+ explicitPayloadContentType,
267
+ additionalHeaders,
268
+ };
269
+ }
270
+ }
271
+
272
+ export { EventStreamSerde };