diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/asset.456da4984f762c1c25e94bd5f2df6758d2b0884d0dae8ca59bb8f4e3de7c2136.bundle/index.js b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/asset.456da4984f762c1c25e94bd5f2df6758d2b0884d0dae8ca59bb8f4e3de7c2136.bundle/index.js deleted file mode 100644 index afcb0cbcfe30a..0000000000000 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/asset.456da4984f762c1c25e94bd5f2df6758d2b0884d0dae8ca59bb8f4e3de7c2136.bundle/index.js +++ /dev/null @@ -1,668 +0,0 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// lib/assertions/providers/lambda-handler/index.ts -var lambda_handler_exports = {}; -__export(lambda_handler_exports, { - handler: () => handler -}); -module.exports = __toCommonJS(lambda_handler_exports); - -// ../assertions/lib/matcher.ts -var Matcher = class { - static isMatcher(x) { - return x && x instanceof Matcher; - } -}; -var MatchResult = class { - constructor(target) { - this.failures = []; - this.captures = /* @__PURE__ */ new Map(); - this.finalized = false; - this.target = target; - } - push(matcher, path, message) { - return this.recordFailure({ matcher, path, message }); - } - recordFailure(failure) { - this.failures.push(failure); - return this; - } - hasFailed() { - return this.failures.length !== 0; - } - get failCount() { - return this.failures.length; - } - compose(id, inner) { - const innerF = inner.failures; - this.failures.push(...innerF.map((f) => { - return { path: [id, ...f.path], message: f.message, matcher: f.matcher }; - })); - inner.captures.forEach((vals, capture) => { - vals.forEach((value) => this.recordCapture({ capture, value })); - }); - return this; - } - finished() { - if (this.finalized) { - return this; - } - if (this.failCount === 0) { - this.captures.forEach((vals, cap) => cap._captured.push(...vals)); - } - this.finalized = true; - return this; - } - toHumanStrings() { - return this.failures.map((r) => { - const loc = r.path.length === 0 ? "" : ` at ${r.path.join("")}`; - return "" + r.message + loc + ` (using ${r.matcher.name} matcher)`; - }); - } - recordCapture(options) { - let values = this.captures.get(options.capture); - if (values === void 0) { - values = []; - } - values.push(options.value); - this.captures.set(options.capture, values); - } -}; - -// ../assertions/lib/private/matchers/absent.ts -var AbsentMatch = class extends Matcher { - constructor(name) { - super(); - this.name = name; - } - test(actual) { - const result = new MatchResult(actual); - if (actual !== void 0) { - result.recordFailure({ - matcher: this, - path: [], - message: `Received ${actual}, but key should be absent` - }); - } - return result; - } -}; - -// ../assertions/lib/private/type.ts -function getType(obj) { - return Array.isArray(obj) ? "array" : typeof obj; -} - -// ../assertions/lib/match.ts -var Match = class { - static absent() { - return new AbsentMatch("absent"); - } - static arrayWith(pattern) { - return new ArrayMatch("arrayWith", pattern); - } - static arrayEquals(pattern) { - return new ArrayMatch("arrayEquals", pattern, { subsequence: false }); - } - static exact(pattern) { - return new LiteralMatch("exact", pattern, { partialObjects: false }); - } - static objectLike(pattern) { - return new ObjectMatch("objectLike", pattern); - } - static objectEquals(pattern) { - return new ObjectMatch("objectEquals", pattern, { partial: false }); - } - static not(pattern) { - return new NotMatch("not", pattern); - } - static serializedJson(pattern) { - return new SerializedJson("serializedJson", pattern); - } - static anyValue() { - return new AnyMatch("anyValue"); - } - static stringLikeRegexp(pattern) { - return new StringLikeRegexpMatch("stringLikeRegexp", pattern); - } -}; -var LiteralMatch = class extends Matcher { - constructor(name, pattern, options = {}) { - super(); - this.name = name; - this.pattern = pattern; - this.partialObjects = options.partialObjects ?? false; - if (Matcher.isMatcher(this.pattern)) { - throw new Error("LiteralMatch cannot directly contain another matcher. Remove the top-level matcher or nest it more deeply."); - } - } - test(actual) { - if (Array.isArray(this.pattern)) { - return new ArrayMatch(this.name, this.pattern, { subsequence: false, partialObjects: this.partialObjects }).test(actual); - } - if (typeof this.pattern === "object") { - return new ObjectMatch(this.name, this.pattern, { partial: this.partialObjects }).test(actual); - } - const result = new MatchResult(actual); - if (typeof this.pattern !== typeof actual) { - result.recordFailure({ - matcher: this, - path: [], - message: `Expected type ${typeof this.pattern} but received ${getType(actual)}` - }); - return result; - } - if (actual !== this.pattern) { - result.recordFailure({ - matcher: this, - path: [], - message: `Expected ${this.pattern} but received ${actual}` - }); - } - return result; - } -}; -var ArrayMatch = class extends Matcher { - constructor(name, pattern, options = {}) { - super(); - this.name = name; - this.pattern = pattern; - this.subsequence = options.subsequence ?? true; - this.partialObjects = options.partialObjects ?? false; - } - test(actual) { - if (!Array.isArray(actual)) { - return new MatchResult(actual).recordFailure({ - matcher: this, - path: [], - message: `Expected type array but received ${getType(actual)}` - }); - } - if (!this.subsequence && this.pattern.length !== actual.length) { - return new MatchResult(actual).recordFailure({ - matcher: this, - path: [], - message: `Expected array of length ${this.pattern.length} but received ${actual.length}` - }); - } - let patternIdx = 0; - let actualIdx = 0; - const result = new MatchResult(actual); - while (patternIdx < this.pattern.length && actualIdx < actual.length) { - const patternElement = this.pattern[patternIdx]; - const matcher = Matcher.isMatcher(patternElement) ? patternElement : new LiteralMatch(this.name, patternElement, { partialObjects: this.partialObjects }); - const matcherName = matcher.name; - if (this.subsequence && (matcherName == "absent" || matcherName == "anyValue")) { - throw new Error(`The Matcher ${matcherName}() cannot be nested within arrayWith()`); - } - const innerResult = matcher.test(actual[actualIdx]); - if (!this.subsequence || !innerResult.hasFailed()) { - result.compose(`[${actualIdx}]`, innerResult); - patternIdx++; - actualIdx++; - } else { - actualIdx++; - } - } - for (; patternIdx < this.pattern.length; patternIdx++) { - const pattern = this.pattern[patternIdx]; - const element = Matcher.isMatcher(pattern) || typeof pattern === "object" ? " " : ` [${pattern}] `; - result.recordFailure({ - matcher: this, - path: [], - message: `Missing element${element}at pattern index ${patternIdx}` - }); - } - return result; - } -}; -var ObjectMatch = class extends Matcher { - constructor(name, pattern, options = {}) { - super(); - this.name = name; - this.pattern = pattern; - this.partial = options.partial ?? true; - } - test(actual) { - if (typeof actual !== "object" || Array.isArray(actual)) { - return new MatchResult(actual).recordFailure({ - matcher: this, - path: [], - message: `Expected type object but received ${getType(actual)}` - }); - } - const result = new MatchResult(actual); - if (!this.partial) { - for (const a of Object.keys(actual)) { - if (!(a in this.pattern)) { - result.recordFailure({ - matcher: this, - path: [`/${a}`], - message: "Unexpected key" - }); - } - } - } - for (const [patternKey, patternVal] of Object.entries(this.pattern)) { - if (!(patternKey in actual) && !(patternVal instanceof AbsentMatch)) { - result.recordFailure({ - matcher: this, - path: [`/${patternKey}`], - message: `Missing key '${patternKey}' among {${Object.keys(actual).join(",")}}` - }); - continue; - } - const matcher = Matcher.isMatcher(patternVal) ? patternVal : new LiteralMatch(this.name, patternVal, { partialObjects: this.partial }); - const inner = matcher.test(actual[patternKey]); - result.compose(`/${patternKey}`, inner); - } - return result; - } -}; -var SerializedJson = class extends Matcher { - constructor(name, pattern) { - super(); - this.name = name; - this.pattern = pattern; - } - test(actual) { - const result = new MatchResult(actual); - if (getType(actual) !== "string") { - result.recordFailure({ - matcher: this, - path: [], - message: `Expected JSON as a string but found ${getType(actual)}` - }); - return result; - } - let parsed; - try { - parsed = JSON.parse(actual); - } catch (err) { - if (err instanceof SyntaxError) { - result.recordFailure({ - matcher: this, - path: [], - message: `Invalid JSON string: ${actual}` - }); - return result; - } else { - throw err; - } - } - const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); - const innerResult = matcher.test(parsed); - result.compose(`(${this.name})`, innerResult); - return result; - } -}; -var NotMatch = class extends Matcher { - constructor(name, pattern) { - super(); - this.name = name; - this.pattern = pattern; - } - test(actual) { - const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); - const innerResult = matcher.test(actual); - const result = new MatchResult(actual); - if (innerResult.failCount === 0) { - result.recordFailure({ - matcher: this, - path: [], - message: `Found unexpected match: ${JSON.stringify(actual, void 0, 2)}` - }); - } - return result; - } -}; -var AnyMatch = class extends Matcher { - constructor(name) { - super(); - this.name = name; - } - test(actual) { - const result = new MatchResult(actual); - if (actual == null) { - result.recordFailure({ - matcher: this, - path: [], - message: "Expected a value but found none" - }); - } - return result; - } -}; -var StringLikeRegexpMatch = class extends Matcher { - constructor(name, pattern) { - super(); - this.name = name; - this.pattern = pattern; - } - test(actual) { - const result = new MatchResult(actual); - const regex = new RegExp(this.pattern, "gm"); - if (typeof actual !== "string") { - result.recordFailure({ - matcher: this, - path: [], - message: `Expected a string, but got '${typeof actual}'` - }); - } - if (!regex.test(actual)) { - result.recordFailure({ - matcher: this, - path: [], - message: `String '${actual}' did not match pattern '${this.pattern}'` - }); - } - return result; - } -}; - -// lib/assertions/providers/lambda-handler/base.ts -var https = __toESM(require("https")); -var url = __toESM(require("url")); -var CustomResourceHandler = class { - constructor(event, context) { - this.event = event; - this.context = context; - this.timedOut = false; - this.timeout = setTimeout(async () => { - await this.respond({ - status: "FAILED", - reason: "Lambda Function Timeout", - data: this.context.logStreamName - }); - this.timedOut = true; - }, context.getRemainingTimeInMillis() - 1200); - this.event = event; - this.physicalResourceId = extractPhysicalResourceId(event); - } - async handle() { - try { - const response = await this.processEvent(this.event.ResourceProperties); - return response; - } catch (e) { - console.log(e); - throw e; - } finally { - clearTimeout(this.timeout); - } - } - respond(response) { - if (this.timedOut) { - return; - } - const cfResponse = { - Status: response.status, - Reason: response.reason, - PhysicalResourceId: this.physicalResourceId, - StackId: this.event.StackId, - RequestId: this.event.RequestId, - LogicalResourceId: this.event.LogicalResourceId, - NoEcho: false, - Data: response.data - }; - const responseBody = JSON.stringify(cfResponse); - console.log("Responding to CloudFormation", responseBody); - const parsedUrl = url.parse(this.event.ResponseURL); - const requestOptions = { - hostname: parsedUrl.hostname, - path: parsedUrl.path, - method: "PUT", - headers: { "content-type": "", "content-length": responseBody.length } - }; - return new Promise((resolve, reject) => { - try { - const request2 = https.request(requestOptions, resolve); - request2.on("error", reject); - request2.write(responseBody); - request2.end(); - } catch (e) { - reject(e); - } - }); - } -}; -function extractPhysicalResourceId(event) { - switch (event.RequestType) { - case "Create": - return event.LogicalResourceId; - case "Update": - case "Delete": - return event.PhysicalResourceId; - } -} - -// lib/assertions/providers/lambda-handler/assertion.ts -var AssertionHandler = class extends CustomResourceHandler { - async processEvent(request2) { - let actual = decodeCall(request2.actual); - const expected = decodeCall(request2.expected); - let result; - const matcher = new MatchCreator(expected).getMatcher(); - console.log(`Testing equality between ${JSON.stringify(request2.actual)} and ${JSON.stringify(request2.expected)}`); - const matchResult = matcher.test(actual); - matchResult.finished(); - if (matchResult.hasFailed()) { - result = { - failed: true, - assertion: JSON.stringify({ - status: "fail", - message: [ - ...matchResult.toHumanStrings(), - JSON.stringify(matchResult.target, void 0, 2) - ].join("\n") - }) - }; - if (request2.failDeployment) { - throw new Error(result.assertion); - } - } else { - result = { - assertion: JSON.stringify({ - status: "success" - }) - }; - } - return result; - } -}; -var MatchCreator = class { - constructor(obj) { - this.parsedObj = { - matcher: obj - }; - } - getMatcher() { - try { - const final = JSON.parse(JSON.stringify(this.parsedObj), function(_k, v) { - const nested = Object.keys(v)[0]; - switch (nested) { - case "$ArrayWith": - return Match.arrayWith(v[nested]); - case "$ObjectLike": - return Match.objectLike(v[nested]); - case "$StringLike": - return Match.stringLikeRegexp(v[nested]); - default: - return v; - } - }); - if (Matcher.isMatcher(final.matcher)) { - return final.matcher; - } - return Match.exact(final.matcher); - } catch { - return Match.exact(this.parsedObj.matcher); - } - } -}; -function decodeCall(call) { - if (!call) { - return void 0; - } - try { - const parsed = JSON.parse(call); - return parsed; - } catch (e) { - return call; - } -} - -// lib/assertions/providers/lambda-handler/utils.ts -function decode(object) { - return JSON.parse(JSON.stringify(object), (_k, v) => { - switch (v) { - case "TRUE:BOOLEAN": - return true; - case "FALSE:BOOLEAN": - return false; - default: - return v; - } - }); -} - -// lib/assertions/providers/lambda-handler/sdk.ts -function flatten(object) { - return Object.assign( - {}, - ...function _flatten(child, path = []) { - return [].concat(...Object.keys(child).map((key) => { - let childKey = Buffer.isBuffer(child[key]) ? child[key].toString("utf8") : child[key]; - if (typeof childKey === "string") { - childKey = isJsonString(childKey); - } - return typeof childKey === "object" && childKey !== null ? _flatten(childKey, path.concat([key])) : { [path.concat([key]).join(".")]: childKey }; - })); - }(object) - ); -} -var AwsApiCallHandler = class extends CustomResourceHandler { - async processEvent(request2) { - const AWS = require("aws-sdk"); - console.log(`AWS SDK VERSION: ${AWS.VERSION}`); - if (!Object.prototype.hasOwnProperty.call(AWS, request2.service)) { - throw Error(`Service ${request2.service} does not exist in AWS SDK version ${AWS.VERSION}.`); - } - const service = new AWS[request2.service](); - const response = await service[request2.api](request2.parameters && decode(request2.parameters)).promise(); - console.log(`SDK response received ${JSON.stringify(response)}`); - delete response.ResponseMetadata; - const respond = { - apiCallResponse: response - }; - const flatData = { - ...flatten(respond) - }; - const resp = request2.flattenResponse === "true" ? flatData : respond; - console.log(`Returning result ${JSON.stringify(resp)}`); - return resp; - } -}; -function isJsonString(value) { - try { - return JSON.parse(value); - } catch { - return value; - } -} - -// lib/assertions/providers/lambda-handler/types.ts -var ASSERT_RESOURCE_TYPE = "Custom::DeployAssert@AssertEquals"; -var SDK_RESOURCE_TYPE_PREFIX = "Custom::DeployAssert@SdkCall"; - -// lib/assertions/providers/lambda-handler/index.ts -async function handler(event, context) { - console.log(`Event: ${JSON.stringify({ ...event, ResponseURL: "..." })}`); - const provider = createResourceHandler(event, context); - try { - if (event.RequestType === "Delete") { - await provider.respond({ - status: "SUCCESS", - reason: "OK" - }); - return; - } - const result = await provider.handle(); - const actualPath = event.ResourceProperties.actualPath; - const actual = actualPath ? result[`apiCallResponse.${actualPath}`] : result.apiCallResponse; - if ("expected" in event.ResourceProperties) { - const assertion = new AssertionHandler({ - ...event, - ResourceProperties: { - ServiceToken: event.ServiceToken, - actual, - expected: event.ResourceProperties.expected - } - }, context); - try { - const assertionResult = await assertion.handle(); - await provider.respond({ - status: "SUCCESS", - reason: "OK", - data: { - ...assertionResult, - ...result - } - }); - return; - } catch (e) { - await provider.respond({ - status: "FAILED", - reason: e.message ?? "Internal Error" - }); - return; - } - } - await provider.respond({ - status: "SUCCESS", - reason: "OK", - data: result - }); - } catch (e) { - await provider.respond({ - status: "FAILED", - reason: e.message ?? "Internal Error" - }); - return; - } - return; -} -function createResourceHandler(event, context) { - if (event.ResourceType.startsWith(SDK_RESOURCE_TYPE_PREFIX)) { - return new AwsApiCallHandler(event, context); - } else if (event.ResourceType.startsWith(ASSERT_RESOURCE_TYPE)) { - return new AssertionHandler(event, context); - } else { - throw new Error(`Unsupported resource type "${event.ResourceType}`); - } -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - handler -}); diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js new file mode 100644 index 0000000000000..c29f3db7d5483 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js @@ -0,0 +1,7272 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; + +// ../../aws-cdk-lib/assertions/lib/matcher.ts +var matcher_exports = {}; +__export(matcher_exports, { + MatchResult: () => MatchResult, + Matcher: () => Matcher +}); +function* range(n) { + for (let i2 = 0; i2 < n; i2++) { + yield i2; + } +} +function* enumFirst(xs) { + let first = true; + for (const x2 of xs) { + yield [first, x2]; + first = false; + } +} +var Matcher, MatchResult; +var init_matcher = __esm({ + "../../aws-cdk-lib/assertions/lib/matcher.ts"() { + "use strict"; + Matcher = class { + /** + * Check whether the provided object is a subtype of the `IMatcher`. + */ + static isMatcher(x2) { + return x2 && x2 instanceof Matcher; + } + }; + MatchResult = class { + constructor(target) { + this.failuresHere = /* @__PURE__ */ new Map(); + this.captures = /* @__PURE__ */ new Map(); + this.finalized = false; + this.innerMatchFailures = /* @__PURE__ */ new Map(); + this._hasFailed = false; + this._failCount = 0; + this._cost = 0; + this.target = target; + } + /** + * DEPRECATED + * @deprecated use recordFailure() + */ + push(matcher, path, message) { + return this.recordFailure({ matcher, path, message }); + } + /** + * Record a new failure into this result at a specific path. + */ + recordFailure(failure) { + const failKey = failure.path.join("."); + let list = this.failuresHere.get(failKey); + if (!list) { + list = []; + this.failuresHere.set(failKey, list); + } + this._failCount += 1; + this._cost += failure.cost ?? 1; + list.push(failure); + this._hasFailed = true; + return this; + } + /** Whether the match is a success */ + get isSuccess() { + return !this._hasFailed; + } + /** Does the result contain any failures. If not, the result is a success */ + hasFailed() { + return this._hasFailed; + } + /** The number of failures */ + get failCount() { + return this._failCount; + } + /** The cost of the failures so far */ + get failCost() { + return this._cost; + } + /** + * Compose the results of a previous match as a subtree. + * @param id the id of the parent tree. + */ + compose(id, inner) { + if (inner.hasFailed()) { + this._hasFailed = true; + this._failCount += inner.failCount; + this._cost += inner._cost; + this.innerMatchFailures.set(id, inner); + } + inner.captures.forEach((vals, capture) => { + vals.forEach((value) => this.recordCapture({ capture, value })); + }); + return this; + } + /** + * Prepare the result to be analyzed. + * This API *must* be called prior to analyzing these results. + */ + finished() { + if (this.finalized) { + return this; + } + if (this.failCount === 0) { + this.captures.forEach((vals, cap) => cap._captured.push(...vals)); + } + this.finalized = true; + return this; + } + /** + * Render the failed match in a presentable way + * + * Prefer using `renderMismatch` over this method. It is left for backwards + * compatibility for test suites that expect it, but `renderMismatch()` will + * produce better output. + */ + toHumanStrings() { + const failures = new Array(); + debugger; + recurse(this, []); + return failures.map((r2) => { + const loc = r2.path.length === 0 ? "" : ` at /${r2.path.join("/")}`; + return "" + r2.message + loc + ` (using ${r2.matcher.name} matcher)`; + }); + function recurse(x2, prefix) { + for (const fail of Array.from(x2.failuresHere.values()).flat()) { + failures.push({ + matcher: fail.matcher, + message: fail.message, + path: [...prefix, ...fail.path] + }); + } + for (const [key, inner] of x2.innerMatchFailures.entries()) { + recurse(inner, [...prefix, key]); + } + } + } + /** + * Do a deep render of the match result, showing the structure mismatches in context + */ + renderMismatch() { + if (!this.hasFailed()) { + return ""; + } + const parts = new Array(); + const indents = new Array(); + emitFailures(this, ""); + recurse(this); + return moveMarkersToFront(parts.join("").trimEnd()); + function emit(x2) { + if (x2 === void 0) { + debugger; + } + parts.push(x2.replace(/\n/g, ` +${indents.join("")}`)); + } + function emitFailures(r2, path, scrapSet) { + for (const fail of r2.failuresHere.get(path) ?? []) { + emit(`!! ${fail.message} +`); + } + scrapSet == null ? void 0 : scrapSet.delete(path); + } + function recurse(r2) { + const remainingFailures = new Set(Array.from(r2.failuresHere.keys()).filter((x2) => x2 !== "")); + if (Array.isArray(r2.target)) { + indents.push(" "); + emit("[\n"); + for (const [first, i2] of enumFirst(range(r2.target.length))) { + if (!first) { + emit(",\n"); + } + emitFailures(r2, `${i2}`, remainingFailures); + const innerMatcher = r2.innerMatchFailures.get(`${i2}`); + if (innerMatcher) { + emitFailures(innerMatcher, ""); + recurseComparingValues(innerMatcher, r2.target[i2]); + } else { + emit(renderAbridged(r2.target[i2])); + } + } + emitRemaining(); + indents.pop(); + emit("\n]"); + return; + } + if (r2.target && typeof r2.target === "object") { + indents.push(" "); + emit("{\n"); + const keys = Array.from(/* @__PURE__ */ new Set([ + ...Object.keys(r2.target), + ...Array.from(remainingFailures) + ])).sort(); + for (const [first, key] of enumFirst(keys)) { + if (!first) { + emit(",\n"); + } + emitFailures(r2, key, remainingFailures); + const innerMatcher = r2.innerMatchFailures.get(key); + if (innerMatcher) { + emitFailures(innerMatcher, ""); + emit(`${jsonify(key)}: `); + recurseComparingValues(innerMatcher, r2.target[key]); + } else { + emit(`${jsonify(key)}: `); + emit(renderAbridged(r2.target[key])); + } + } + emitRemaining(); + indents.pop(); + emit("\n}"); + return; + } + emitRemaining(); + emit(jsonify(r2.target)); + function emitRemaining() { + if (remainingFailures.size > 0) { + emit("\n"); + } + for (const key of remainingFailures) { + emitFailures(r2, key); + } + } + } + function recurseComparingValues(inner, actualValue) { + if (inner.target === actualValue) { + return recurse(inner); + } + emit(renderAbridged(actualValue)); + emit(" <*> "); + recurse(inner); + } + function renderAbridged(x2) { + if (Array.isArray(x2)) { + switch (x2.length) { + case 0: + return "[]"; + case 1: + return `[ ${renderAbridged(x2[0])} ]`; + case 2: + if (x2.every((e2) => ["number", "boolean", "string"].includes(typeof e2))) { + return `[ ${x2.map(renderAbridged).join(", ")} ]`; + } + return "[ ... ]"; + default: + return "[ ... ]"; + } + } + if (x2 && typeof x2 === "object") { + const keys = Object.keys(x2); + switch (keys.length) { + case 0: + return "{}"; + case 1: + return `{ ${JSON.stringify(keys[0])}: ${renderAbridged(x2[keys[0]])} }`; + default: + return "{ ... }"; + } + } + return jsonify(x2); + } + function jsonify(x2) { + return JSON.stringify(x2) ?? "undefined"; + } + function moveMarkersToFront(x2) { + const re = /^(\s+)!!/gm; + return x2.replace(re, (_, spaces) => `!!${spaces.substring(0, spaces.length - 2)}`); + } + } + /** + * Record a capture against in this match result. + */ + recordCapture(options) { + let values = this.captures.get(options.capture); + if (values === void 0) { + values = []; + } + values.push(options.value); + this.captures.set(options.capture, values); + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/matchers/absent.ts +var AbsentMatch; +var init_absent = __esm({ + "../../aws-cdk-lib/assertions/lib/private/matchers/absent.ts"() { + "use strict"; + init_matcher(); + AbsentMatch = class extends Matcher { + constructor(name) { + super(); + this.name = name; + } + test(actual) { + const result = new MatchResult(actual); + if (actual !== void 0) { + result.recordFailure({ + matcher: this, + path: [], + message: `Received ${actual}, but key should be absent` + }); + } + return result; + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/sorting.ts +function sortKeyComparator(keyFn) { + return (a, b) => { + const ak = keyFn(a); + const bk = keyFn(b); + for (let i2 = 0; i2 < ak.length && i2 < bk.length; i2++) { + const av = ak[i2]; + const bv = bk[i2]; + let diff = 0; + if (typeof av === "number" && typeof bv === "number") { + diff = av - bv; + } else if (typeof av === "string" && typeof bv === "string") { + diff = av.localeCompare(bv); + } + if (diff !== 0) { + return diff; + } + } + return bk.length - ak.length; + }; +} +var init_sorting = __esm({ + "../../aws-cdk-lib/assertions/lib/private/sorting.ts"() { + "use strict"; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/sparse-matrix.ts +var SparseMatrix; +var init_sparse_matrix = __esm({ + "../../aws-cdk-lib/assertions/lib/private/sparse-matrix.ts"() { + "use strict"; + SparseMatrix = class { + constructor() { + this.matrix = /* @__PURE__ */ new Map(); + } + get(row, col) { + var _a4; + return (_a4 = this.matrix.get(row)) == null ? void 0 : _a4.get(col); + } + row(row) { + var _a4; + return Array.from(((_a4 = this.matrix.get(row)) == null ? void 0 : _a4.entries()) ?? []); + } + set(row, col, value) { + let r2 = this.matrix.get(row); + if (!r2) { + r2 = /* @__PURE__ */ new Map(); + this.matrix.set(row, r2); + } + r2.set(col, value); + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/type.ts +function getType(obj) { + return Array.isArray(obj) ? "array" : typeof obj; +} +var init_type = __esm({ + "../../aws-cdk-lib/assertions/lib/private/type.ts"() { + "use strict"; + } +}); + +// ../../aws-cdk-lib/assertions/lib/match.ts +var match_exports = {}; +__export(match_exports, { + Match: () => Match +}); +var Match, LiteralMatch, ArrayMatch, ObjectMatch, SerializedJson, NotMatch, AnyMatch, StringLikeRegexpMatch; +var init_match = __esm({ + "../../aws-cdk-lib/assertions/lib/match.ts"() { + "use strict"; + init_matcher(); + init_absent(); + init_sorting(); + init_sparse_matrix(); + init_type(); + Match = class { + /** + * Use this matcher in the place of a field's value, if the field must not be present. + */ + static absent() { + return new AbsentMatch("absent"); + } + /** + * Matches the specified pattern with the array found in the same relative path of the target. + * The set of elements (or matchers) must be in the same order as would be found. + * @param pattern the pattern to match + */ + static arrayWith(pattern) { + return new ArrayMatch("arrayWith", pattern); + } + /** + * Matches the specified pattern with the array found in the same relative path of the target. + * The set of elements (or matchers) must match exactly and in order. + * @param pattern the pattern to match + */ + static arrayEquals(pattern) { + return new ArrayMatch("arrayEquals", pattern, { subsequence: false }); + } + /** + * Deep exact matching of the specified pattern to the target. + * @param pattern the pattern to match + */ + static exact(pattern) { + return new LiteralMatch("exact", pattern, { partialObjects: false }); + } + /** + * Matches the specified pattern to an object found in the same relative path of the target. + * The keys and their values (or matchers) must be present in the target but the target can be a superset. + * @param pattern the pattern to match + */ + static objectLike(pattern) { + return new ObjectMatch("objectLike", pattern); + } + /** + * Matches the specified pattern to an object found in the same relative path of the target. + * The keys and their values (or matchers) must match exactly with the target. + * @param pattern the pattern to match + */ + static objectEquals(pattern) { + return new ObjectMatch("objectEquals", pattern, { partial: false }); + } + /** + * Matches any target which does NOT follow the specified pattern. + * @param pattern the pattern to NOT match + */ + static not(pattern) { + return new NotMatch("not", pattern); + } + /** + * Matches any string-encoded JSON and applies the specified pattern after parsing it. + * @param pattern the pattern to match after parsing the encoded JSON. + */ + static serializedJson(pattern) { + return new SerializedJson("serializedJson", pattern); + } + /** + * Matches any non-null value at the target. + */ + static anyValue() { + return new AnyMatch("anyValue"); + } + /** + * Matches targets according to a regular expression + */ + static stringLikeRegexp(pattern) { + return new StringLikeRegexpMatch("stringLikeRegexp", pattern); + } + }; + LiteralMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.partialObjects = options.partialObjects ?? false; + if (Matcher.isMatcher(this.pattern)) { + throw new Error("LiteralMatch cannot directly contain another matcher. Remove the top-level matcher or nest it more deeply."); + } + } + test(actual) { + if (Array.isArray(this.pattern)) { + return new ArrayMatch(this.name, this.pattern, { subsequence: false, partialObjects: this.partialObjects }).test(actual); + } + if (typeof this.pattern === "object") { + return new ObjectMatch(this.name, this.pattern, { partial: this.partialObjects }).test(actual); + } + const result = new MatchResult(actual); + if (typeof this.pattern !== typeof actual) { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected type ${typeof this.pattern} but received ${getType(actual)}` + }); + return result; + } + if (actual !== this.pattern) { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected ${this.pattern} but received ${actual}` + }); + } + return result; + } + }; + ArrayMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.subsequence = options.subsequence ?? true; + this.partialObjects = options.partialObjects ?? false; + } + test(actual) { + if (!Array.isArray(actual)) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected type array but received ${getType(actual)}` + }); + } + return this.subsequence ? this.testSubsequence(actual) : this.testFullArray(actual); + } + testFullArray(actual) { + const result = new MatchResult(actual); + let i2 = 0; + for (; i2 < this.pattern.length && i2 < actual.length; i2++) { + const patternElement = this.pattern[i2]; + const matcher = Matcher.isMatcher(patternElement) ? patternElement : new LiteralMatch(this.name, patternElement, { partialObjects: this.partialObjects }); + const innerResult = matcher.test(actual[i2]); + result.compose(`${i2}`, innerResult); + } + if (i2 < this.pattern.length) { + result.recordFailure({ + matcher: this, + message: `Not enough elements in array (expecting ${this.pattern.length}, got ${actual.length})`, + path: [`${i2}`] + }); + } + if (i2 < actual.length) { + result.recordFailure({ + matcher: this, + message: `Too many elements in array (expecting ${this.pattern.length}, got ${actual.length})`, + path: [`${i2}`] + }); + } + return result; + } + testSubsequence(actual) { + const result = new MatchResult(actual); + let patternIdx = 0; + let actualIdx = 0; + const matches = new SparseMatrix(); + while (patternIdx < this.pattern.length && actualIdx < actual.length) { + const patternElement = this.pattern[patternIdx]; + const matcher = Matcher.isMatcher(patternElement) ? patternElement : new LiteralMatch(this.name, patternElement, { partialObjects: this.partialObjects }); + const matcherName = matcher.name; + if (matcherName == "absent" || matcherName == "anyValue") { + throw new Error(`The Matcher ${matcherName}() cannot be nested within arrayWith()`); + } + const innerResult = matcher.test(actual[actualIdx]); + matches.set(patternIdx, actualIdx, innerResult); + actualIdx++; + if (innerResult.isSuccess) { + result.compose(`${actualIdx}`, innerResult); + patternIdx++; + } + } + if (patternIdx < this.pattern.length) { + for (let spi = 0; spi < patternIdx; spi++) { + const foundMatch = matches.row(spi).find(([, r2]) => r2.isSuccess); + if (!foundMatch) { + continue; + } + const [index] = foundMatch; + result.compose(`${index}`, new MatchResult(actual[index]).recordFailure({ + matcher: this, + message: `arrayWith pattern ${spi} matched here`, + path: [], + cost: 0 + // This is an informational message so it would be unfair to assign it cost + })); + } + const failedMatches = matches.row(patternIdx); + failedMatches.sort(sortKeyComparator(([i2, r2]) => [r2.failCost, i2])); + if (failedMatches.length > 0) { + const [index, innerResult] = failedMatches[0]; + result.recordFailure({ + matcher: this, + message: `Could not match arrayWith pattern ${patternIdx}. This is the closest match`, + path: [`${index}`], + cost: 0 + // Informational message + }); + result.compose(`${index}`, innerResult); + } else { + result.recordFailure({ + matcher: this, + message: `Could not match arrayWith pattern ${patternIdx}. No more elements to try`, + path: [`${actual.length}`] + }); + } + } + return result; + } + }; + ObjectMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.partial = options.partial ?? true; + } + test(actual) { + if (typeof actual !== "object" || Array.isArray(actual)) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected type object but received ${getType(actual)}` + }); + } + const result = new MatchResult(actual); + if (!this.partial) { + for (const a of Object.keys(actual)) { + if (!(a in this.pattern)) { + result.recordFailure({ + matcher: this, + path: [a], + message: `Unexpected key ${a}` + }); + } + } + } + for (const [patternKey, patternVal] of Object.entries(this.pattern)) { + if (!(patternKey in actual) && !(patternVal instanceof AbsentMatch)) { + result.recordFailure({ + matcher: this, + path: [patternKey], + message: `Missing key '${patternKey}'` + }); + continue; + } + const matcher = Matcher.isMatcher(patternVal) ? patternVal : new LiteralMatch(this.name, patternVal, { partialObjects: this.partial }); + const inner = matcher.test(actual[patternKey]); + result.compose(patternKey, inner); + } + return result; + } + }; + SerializedJson = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + if (getType(actual) !== "string") { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected JSON as a string but found ${getType(actual)}` + }); + } + let parsed; + try { + parsed = JSON.parse(actual); + } catch (err) { + if (err instanceof SyntaxError) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Invalid JSON string: ${actual}` + }); + } else { + throw err; + } + } + const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); + const innerResult = matcher.test(parsed); + if (innerResult.hasFailed()) { + innerResult.recordFailure({ + matcher: this, + path: [], + message: "Encoded JSON value does not match" + }); + } + return innerResult; + } + }; + NotMatch = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); + const innerResult = matcher.test(actual); + const result = new MatchResult(actual); + if (innerResult.failCount === 0) { + result.recordFailure({ + matcher: this, + path: [], + message: `Found unexpected match: ${JSON.stringify(actual, void 0, 2)}` + }); + } + return result; + } + }; + AnyMatch = class extends Matcher { + constructor(name) { + super(); + this.name = name; + } + test(actual) { + const result = new MatchResult(actual); + if (actual == null) { + result.recordFailure({ + matcher: this, + path: [], + message: "Expected a value but found none" + }); + } + return result; + } + }; + StringLikeRegexpMatch = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const result = new MatchResult(actual); + const regex = new RegExp(this.pattern, "gm"); + if (typeof actual !== "string") { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected a string, but got '${typeof actual}'` + }); + } + if (!regex.test(actual)) { + result.recordFailure({ + matcher: this, + path: [], + message: `String '${actual}' did not match pattern '${this.pattern}'` + }); + } + return result; + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/helpers-internal/index.js +var require_helpers_internal = __commonJS({ + "../../aws-cdk-lib/assertions/lib/helpers-internal/index.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + var desc = Object.getOwnPropertyDescriptor(m2, k); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + o[k2] = m2[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p in m2) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m2, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar((init_match(), __toCommonJS(match_exports)), exports); + __exportStar((init_matcher(), __toCommonJS(matcher_exports)), exports); + } +}); + +// ../../../node_modules/web-streams-polyfill/dist/ponyfill.es2018.js +var require_ponyfill_es2018 = __commonJS({ + "../../../node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports, module2) { + (function(global2, factory) { + typeof exports === "object" && typeof module2 !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); + })(exports, function(exports2) { + "use strict"; + const SymbolPolyfill = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol : (description) => `Symbol(${description})`; + function noop2() { + return void 0; + } + function getGlobals() { + if (typeof self !== "undefined") { + return self; + } else if (typeof window !== "undefined") { + return window; + } else if (typeof global !== "undefined") { + return global; + } + return void 0; + } + const globals = getGlobals(); + function typeIsObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + const rethrowAssertionErrorRejection = noop2; + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, void 0, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === "function") { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(void 0); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F2, V, args) { + if (typeof F2 !== "function") { + throw new TypeError("Argument is not a function"); + } + return Function.prototype.apply.call(F2, V, args); + } + function promiseCall(F2, V, args) { + try { + return promiseResolvedWith(reflectCall(F2, V, args)); + } catch (value) { + return promiseRejectedWith(value); + } + } + const QUEUE_MAX_ARRAY_SIZE = 16384; + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + this._front = { + _elements: [], + _next: void 0 + }; + this._back = this._front; + this._cursor = 0; + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: void 0 + }; + } + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + elements[oldCursor] = void 0; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i2 = this._cursor; + let node = this._front; + let elements = node._elements; + while (i2 !== elements.length || node._next !== void 0) { + if (i2 === elements.length) { + node = node._next; + elements = node._elements; + i2 = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i2]); + ++i2; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === "readable") { + defaultReaderClosedPromiseInitialize(reader); + } else if (stream._state === "closed") { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === "readable") { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = void 0; + reader._ownerReadableStream = void 0; + } + function readerLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released reader"); + } + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = void 0; + reader._closedPromise_reject = void 0; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === void 0) { + return; + } + reader._closedPromise_resolve(void 0); + reader._closedPromise_resolve = void 0; + reader._closedPromise_reject = void 0; + } + const AbortSteps = SymbolPolyfill("[[AbortSteps]]"); + const ErrorSteps = SymbolPolyfill("[[ErrorSteps]]"); + const CancelSteps = SymbolPolyfill("[[CancelSteps]]"); + const PullSteps = SymbolPolyfill("[[PullSteps]]"); + const NumberIsFinite = Number.isFinite || function(x2) { + return typeof x2 === "number" && isFinite(x2); + }; + const MathTrunc = Math.trunc || function(v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + function isDictionary(x2) { + return typeof x2 === "object" || typeof x2 === "function"; + } + function assertDictionary(obj, context) { + if (obj !== void 0 && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertFunction(x2, context) { + if (typeof x2 !== "function") { + throw new TypeError(`${context} is not a function.`); + } + } + function isObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + function assertObject(x2, context) { + if (!isObject(x2)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x2, position, context) { + if (x2 === void 0) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x2, field, context) { + if (x2 === void 0) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x2) { + return x2 === 0 ? 0 : x2; + } + function integerPart(x2) { + return censorNegativeZero(MathTrunc(x2)); + } + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x2 = Number(value); + x2 = censorNegativeZero(x2); + if (!NumberIsFinite(x2)) { + throw new TypeError(`${context} is not a finite number`); + } + x2 = integerPart(x2); + if (x2 < lowerBound || x2 > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x2) || x2 === 0) { + return 0; + } + return x2; + } + function assertReadableStream(x2, context) { + if (!IsReadableStream(x2)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === void 0) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = void 0) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("read")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: void 0, done: true }), + _errorSteps: (e2) => rejectPromise(e2) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === void 0) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamDefaultReader", + configurable: true + }); + } + function IsReadableStreamDefaultReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readRequests")) { + return false; + } + return x2 instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "closed") { + readRequest._closeSteps(); + } else if (stream._state === "errored") { + readRequest._errorSteps(stream._storedError); + } else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { + }).prototype); + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = void 0; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: void 0, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("iterate")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => { + this._ongoingPromise = void 0; + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = void 0; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: void 0, done: true }); + }, + _errorSteps: (reason) => { + this._ongoingPromise = void 0; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("finish iterating")); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== void 0) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_asyncIteratorImpl")) { + return false; + } + try { + return x2._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; + } catch (_a4) { + return false; + } + } + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + const NumberIsNaN = Number.isNaN || function(x2) { + return x2 !== x2; + }; + function CreateArrayFromList(elements) { + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + function TransferArrayBuffer(O) { + return O; + } + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function IsNonNegativeNumber(v) { + if (typeof v !== "number") { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError("Size must be a finite, non-NaN, non-negative number."); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("view"); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respond"); + } + assertRequiredArgument(bytesWritten, 1, "respond"); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter"); + if (this._associatedReadableByteStreamController === void 0) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(this._view.buffer)) + ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respondWithNewView"); + } + assertRequiredArgument(view, 1, "respondWithNewView"); + if (!ArrayBuffer.isView(view)) { + throw new TypeError("You can only respond with array buffer views"); + } + if (this._associatedReadableByteStreamController === void 0) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(view.buffer)) + ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamBYOBRequest", + configurable: true + }); + } + class ReadableByteStreamController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("byobRequest"); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("desiredSize"); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("close"); + } + if (this._closeRequested) { + throw new TypeError("The stream has already been closed; do not close it again!"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("enqueue"); + } + assertRequiredArgument(chunk, 1, "enqueue"); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError("chunk must be an array buffer view"); + } + if (chunk.byteLength === 0) { + throw new TypeError("chunk must have non-zero byteLength"); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError("stream is closed or draining"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e2 = void 0) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("error"); + } + ReadableByteStreamControllerError(this, e2); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== void 0) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: "default" + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableByteStreamController", + configurable: true + }); + } + function IsReadableByteStreamController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableByteStream")) { + return false; + } + return x2 instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_associatedReadableByteStreamController")) { + return false; + } + return x2 instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, (e2) => { + ReadableByteStreamControllerError(controller, e2); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === "closed") { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === "default") { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = void 0; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + const buffer = TransferArrayBuffer(view.buffer); + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: "byob" + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === "closed") { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e2); + readIntoRequest._errorSteps(e2); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + ReadableByteStreamControllerRespondInClosedState(controller); + } else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = void 0; + controller._cancelAlgorithm = void 0; + } + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e2); + throw e2; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) + ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } else if (ReadableStreamHasBYOBReader(stream)) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e2) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e2); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (bytesWritten !== 0) { + throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream"); + } + } else { + if (bytesWritten === 0) { + throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream"); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError("bytesWritten out of range"); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (view.byteLength !== 0) { + throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream"); + } + } else { + if (view.byteLength === 0) { + throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError("The region specified by view does not match byobRequest"); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError("The buffer of view has different capacity than byobRequest"); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError("The region specified by view is larger than byobRequest"); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + controller._queue = controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, (r2) => { + ReadableByteStreamControllerError(controller, r2); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => void 0; + let pullAlgorithm = () => promiseResolvedWith(void 0); + let cancelAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingByteSource.start !== void 0) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== void 0) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== void 0) { + cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError("autoAllocateChunkSize must be greater than 0"); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request2, controller, view) { + request2._associatedReadableByteStreamController = controller; + request2._view = view; + } + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === void 0) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = void 0) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("read")); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError("view must be an array buffer view")); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError("view must have non-zero byteLength")); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) + ; + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }), + _errorSteps: (e2) => rejectPromise(e2) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === void 0) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamBYOBReader", + configurable: true + }); + } + function IsReadableStreamBYOBReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readIntoRequests")) { + return false; + } + return x2 instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "errored") { + readIntoRequest._errorSteps(stream._storedError); + } else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === void 0) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError("Invalid highWaterMark"); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark), + size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return (chunk) => convertUnrestrictedDouble(fn(chunk)); + } + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function assertWritableStream(x2, context) { + if (!IsWritableStream(x2)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + function isAbortSignal2(value) { + if (typeof value !== "object" || value === null) { + return false; + } + try { + return typeof value.aborted === "boolean"; + } catch (_a4) { + return false; + } + } + const supportsAbortController = typeof AbortController === "function"; + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return void 0; + } + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === void 0) { + rawUnderlyingSink = null; + } else { + assertObject(rawUnderlyingSink, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter"); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== void 0) { + throw new RangeError("Invalid type is specified"); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("locked"); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = void 0) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("abort")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer")); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("close")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer")); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("getWriter"); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStream", + configurable: true + }); + } + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = "writable"; + stream._storedError = void 0; + stream._writer = void 0; + stream._writableStreamController = void 0; + stream._writeRequests = new SimpleQueue(); + stream._inFlightWriteRequest = void 0; + stream._closeRequest = void 0; + stream._inFlightCloseRequest = void 0; + stream._pendingAbortRequest = void 0; + stream._backpressure = false; + } + function IsWritableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_writableStreamController")) { + return false; + } + return x2 instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === void 0) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a4; + if (stream._state === "closed" || stream._state === "errored") { + return promiseResolvedWith(void 0); + } + stream._writableStreamController._abortReason = reason; + (_a4 = stream._writableStreamController._abortController) === null || _a4 === void 0 ? void 0 : _a4.abort(); + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseResolvedWith(void 0); + } + if (stream._pendingAbortRequest !== void 0) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === "erroring") { + wasAlreadyErroring = true; + reason = void 0; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: void 0, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== void 0 && stream._backpressure && state === "writable") { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === "writable") { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = "erroring"; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== void 0) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = "errored"; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach((writeRequest) => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === void 0) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = void 0; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(void 0); + stream._inFlightWriteRequest = void 0; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = void 0; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(void 0); + stream._inFlightCloseRequest = void 0; + const state = stream._state; + if (state === "erroring") { + stream._storedError = void 0; + if (stream._pendingAbortRequest !== void 0) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = void 0; + } + } + stream._state = "closed"; + const writer = stream._writer; + if (writer !== void 0) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = void 0; + if (stream._pendingAbortRequest !== void 0) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = void 0; + } + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = void 0; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== void 0) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = void 0; + } + const writer = stream._writer; + if (writer !== void 0) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== void 0 && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter"); + assertWritableStream(stream, "First parameter"); + if (IsWritableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive writing by another writer"); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === "writable") { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } else if (state === "erroring") { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } else if (state === "closed") { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("desiredSize"); + } + if (this._ownerWritableStream === void 0) { + throw defaultWriterLockException("desiredSize"); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("ready")); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = void 0) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("abort")); + } + if (this._ownerWritableStream === void 0) { + return promiseRejectedWith(defaultWriterLockException("abort")); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("close")); + } + const stream = this._ownerWritableStream; + if (stream === void 0) { + return promiseRejectedWith(defaultWriterLockException("close")); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("releaseLock"); + } + const stream = this._ownerWritableStream; + if (stream === void 0) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = void 0) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("write")); + } + if (this._ownerWritableStream === void 0) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStreamDefaultWriter", + configurable: true + }); + } + function IsWritableStreamDefaultWriter(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_ownerWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultWriter; + } + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseResolvedWith(void 0); + } + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === "pending") { + defaultWriterClosedPromiseReject(writer, error); + } else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === "pending") { + defaultWriterReadyPromiseReject(writer, error); + } else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === "errored" || state === "erroring") { + return null; + } + if (state === "closed") { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = void 0; + writer._ownerWritableStream = void 0; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + const state = stream._state; + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to")); + } + if (state === "erroring") { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + class WritableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("abortReason"); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("signal"); + } + if (this._abortController === void 0) { + throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported"); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e2 = void 0) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("error"); + } + const state = this._controlledWritableStream._state; + if (state !== "writable") { + return; + } + WritableStreamDefaultControllerError(this, e2); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStreamDefaultController", + configurable: true + }); + } + function IsWritableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + controller._queue = void 0; + controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._abortReason = void 0; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, (r2) => { + controller._started = true; + WritableStreamDealWithRejection(stream, r2); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => void 0; + let writeAlgorithm = () => promiseResolvedWith(void 0); + let closeAlgorithm = () => promiseResolvedWith(void 0); + let abortAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingSink.start !== void 0) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== void 0) { + writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== void 0) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== void 0) { + abortAlgorithm = (reason) => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = void 0; + controller._closeAlgorithm = void 0; + controller._abortAlgorithm = void 0; + controller._strategySizeAlgorithm = void 0; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== void 0) { + return; + } + const state = stream._state; + if (state === "erroring") { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === "writable") { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, (reason) => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, (reason) => { + if (stream._state === "writable") { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released writer"); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = "pending"; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = void 0; + writer._closedPromise_reject = void 0; + writer._closedPromiseState = "rejected"; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === void 0) { + return; + } + writer._closedPromise_resolve(void 0); + writer._closedPromise_resolve = void 0; + writer._closedPromise_reject = void 0; + writer._closedPromiseState = "resolved"; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = "pending"; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = void 0; + writer._readyPromise_reject = void 0; + writer._readyPromiseState = "rejected"; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === void 0) { + return; + } + writer._readyPromise_resolve(void 0); + writer._readyPromise_resolve = void 0; + writer._readyPromise_reject = void 0; + writer._readyPromiseState = "fulfilled"; + } + const NativeDOMException = typeof DOMException !== "undefined" ? DOMException : void 0; + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === "function" || typeof ctor === "object")) { + return false; + } + try { + new ctor(); + return true; + } catch (_a4) { + return false; + } + } + function createDOMExceptionPolyfill() { + const ctor = function DOMException3(message, name) { + this.message = message || ""; + this.name = name || "Error"; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true }); + return ctor; + } + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + let currentWrite = promiseResolvedWith(void 0); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== void 0) { + abortAlgorithm = () => { + const error = new DOMException$1("Aborted", "AbortError"); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === "writable") { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(void 0); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === "readable") { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(void 0); + }); + } + shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener("abort", abortAlgorithm); + } + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } else { + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: (chunk) => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + isOrBecomesErrored(source, reader._closedPromise, (storedError) => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + }); + isOrBecomesErrored(dest, writer._closedPromise, (storedError) => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + }); + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } else { + shutdown(); + } + }); + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") { + const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it"); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === "errored") { + action(stream._storedError); + } else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === "closed") { + action(); + } else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== void 0) { + signal.removeEventListener("abort", abortAlgorithm); + } + if (isError) { + reject(error); + } else { + resolve(void 0); + } + } + }); + } + class ReadableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("desiredSize"); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("close"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits close"); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = void 0) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("enqueue"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits enqueue"); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e2 = void 0) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("error"); + } + ReadableStreamDefaultControllerError(this, e2); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamDefaultController", + configurable: true + }); + } + function IsReadableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableStream")) { + return false; + } + return x2 instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, (e2) => { + ReadableStreamDefaultControllerError(controller, e2); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = void 0; + controller._cancelAlgorithm = void 0; + controller._strategySizeAlgorithm = void 0; + } + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e2) { + const stream = controller._controlledReadableStream; + if (stream._state !== "readable") { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e2); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === "readable") { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = void 0; + controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, (r2) => { + ReadableStreamDefaultControllerError(controller, r2); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => void 0; + let pullAlgorithm = () => promiseResolvedWith(void 0); + let cancelAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingSource.start !== void 0) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== void 0) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== void 0) { + cancelAlgorithm = (reason) => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(void 0); + } + reading = true; + const readRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(void 0); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r2) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r2); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, (r2) => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r2); + ReadableByteStreamControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: (chunk) => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== void 0) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(void 0); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(void 0); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(void 0); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(void 0); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== "bytes") { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== "byob") { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== void 0) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal2(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, "readable", "ReadableWritablePair"); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, "writable", "ReadableWritablePair"); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + class ReadableStream2 { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === void 0) { + rawUnderlyingSource = null; + } else { + assertObject(rawUnderlyingSource, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter"); + InitializeReadableStream(this); + if (underlyingSource.type === "bytes") { + if (strategy.size !== void 0) { + throw new RangeError("The strategy for a byte stream cannot have a size function"); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("locked"); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = void 0) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("cancel")); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader")); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = void 0) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("getReader"); + } + const options = convertReaderOptions(rawOptions, "First parameter"); + if (options.mode === void 0) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("pipeThrough"); + } + assertRequiredArgument(rawTransform, 1, "pipeThrough"); + const transform = convertReadableWritablePair(rawTransform, "First parameter"); + const options = convertPipeOptions(rawOptions, "Second parameter"); + if (IsReadableStreamLocked(this)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream"); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream"); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("pipeTo")); + } + if (destination === void 0) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, "Second parameter"); + } catch (e2) { + return promiseRejectedWith(e2); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("tee"); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = void 0) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("values"); + } + const options = convertIteratorOptions(rawOptions, "First parameter"); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream2.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStream", + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === "symbol") { + Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream2.prototype.values, + writable: true, + configurable: true + }); + } + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = "readable"; + stream._reader = void 0; + stream._storedError = void 0; + stream._disturbed = false; + } + function IsReadableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readableStreamController")) { + return false; + } + return x2 instanceof ReadableStream2; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === void 0) { + return false; + } + return true; + } + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === "closed") { + return promiseResolvedWith(void 0); + } + if (stream._state === "errored") { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._closeSteps(void 0); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop2); + } + function ReadableStreamClose(stream) { + stream._state = "closed"; + const reader = stream._reader; + if (reader === void 0) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach((readRequest) => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e2) { + stream._state = "errored"; + stream._storedError = e2; + const reader = stream._reader; + if (reader === void 0) { + return; + } + defaultReaderClosedPromiseReject(reader, e2); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach((readRequest) => { + readRequest._errorSteps(e2); + }); + reader._readRequests = new SimpleQueue(); + } else { + reader._readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._errorSteps(e2); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit"); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, "name", { + value: "size", + configurable: true + }); + } catch (_a4) { + } + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("highWaterMark"); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("size"); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: "ByteLengthQueuingStrategy", + configurable: true + }); + } + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_byteLengthQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof ByteLengthQueuingStrategy; + } + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, "name", { + value: "size", + configurable: true + }); + } catch (_a4) { + } + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "CountQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("highWaterMark"); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("size"); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: "CountQueuingStrategy", + configurable: true + }); + } + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_countQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof CountQueuingStrategy; + } + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === void 0) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter"); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter"); + const transformer = convertTransformer(rawTransformer, "First parameter"); + if (transformer.readableType !== void 0) { + throw new RangeError("Invalid readableType specified"); + } + if (transformer.writableType !== void 0) { + throw new RangeError("Invalid writableType specified"); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise((resolve) => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== void 0) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } else { + startPromise_resolve(void 0); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("readable"); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("writable"); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: "TransformStream", + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(void 0); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + stream._backpressure = void 0; + stream._backpressureChangePromise = void 0; + stream._backpressureChangePromise_resolve = void 0; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = void 0; + } + function IsTransformStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_transformStreamController")) { + return false; + } + return x2 instanceof TransformStream; + } + function TransformStreamError(stream, e2) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e2); + TransformStreamErrorWritableAndUnblockWrite(stream, e2); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e2) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e2); + if (stream._backpressure) { + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + if (stream._backpressureChangePromise !== void 0) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise((resolve) => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + class TransformStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("desiredSize"); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = void 0) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("enqueue"); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = void 0) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("error"); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("terminate"); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "TransformStreamDefaultController", + configurable: true + }); + } + function IsTransformStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledTransformStream")) { + return false; + } + return x2 instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(void 0); + } catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(void 0); + if (transformer.transform !== void 0) { + transformAlgorithm = (chunk) => transformer.transform(chunk, controller); + } + if (transformer.flush !== void 0) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = void 0; + controller._flushAlgorithm = void 0; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError("Readable side is not in a state that permits enqueue"); + } + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } catch (e2) { + TransformStreamErrorWritableAndUnblockWrite(stream, e2); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e2) { + TransformStreamError(controller._controlledTransformStream, e2); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, void 0, (r2) => { + TransformStreamError(controller._controlledTransformStream, r2); + throw r2; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError("TransformStream terminated"); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === "erroring") { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + TransformStreamError(stream, reason); + return promiseResolvedWith(void 0); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + return transformPromiseWith(flushPromise, () => { + if (readable._state === "errored") { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, (r2) => { + TransformStreamError(stream, r2); + throw readable._storedError; + }); + } + function TransformStreamDefaultSourcePullAlgorithm(stream) { + TransformStreamSetBackpressure(stream, false); + return stream._backpressureChangePromise; + } + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + exports2.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports2.CountQueuingStrategy = CountQueuingStrategy; + exports2.ReadableByteStreamController = ReadableByteStreamController; + exports2.ReadableStream = ReadableStream2; + exports2.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports2.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports2.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports2.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports2.TransformStream = TransformStream; + exports2.TransformStreamDefaultController = TransformStreamDefaultController; + exports2.WritableStream = WritableStream; + exports2.WritableStreamDefaultController = WritableStreamDefaultController; + exports2.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + Object.defineProperty(exports2, "__esModule", { value: true }); + }); + } +}); + +// ../../../node_modules/fetch-blob/streams.cjs +var require_streams = __commonJS({ + "../../../node_modules/fetch-blob/streams.cjs"() { + var POOL_SIZE2 = 65536; + if (!globalThis.ReadableStream) { + try { + const process2 = require("process"); + const { emitWarning } = process2; + try { + process2.emitWarning = () => { + }; + Object.assign(globalThis, require("stream/web")); + process2.emitWarning = emitWarning; + } catch (error) { + process2.emitWarning = emitWarning; + throw error; + } + } catch (error) { + Object.assign(globalThis, require_ponyfill_es2018()); + } + } + try { + const { Blob: Blob2 } = require("buffer"); + if (Blob2 && !Blob2.prototype.stream) { + Blob2.prototype.stream = function name(params) { + let position = 0; + const blob = this; + return new ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + ctrl.enqueue(new Uint8Array(buffer)); + if (position === blob.size) { + ctrl.close(); + } + } + }); + }; + } + } catch (error) { + } + } +}); + +// ../../../node_modules/fetch-blob/index.js +async function* toIterator(parts, clone2 = true) { + for (const part of parts) { + if ("stream" in part) { + yield* ( + /** @type {AsyncIterableIterator} */ + part.stream() + ); + } else if (ArrayBuffer.isView(part)) { + if (clone2) { + let position = part.byteOffset; + const end = part.byteOffset + part.byteLength; + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); + } + } else { + yield part; + } + } else { + let position = 0, b = ( + /** @type {Blob} */ + part + ); + while (position !== b.size) { + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); + } + } + } +} +var import_streams, POOL_SIZE, _parts, _type, _size, _endings, _a, _Blob, Blob, fetch_blob_default; +var init_fetch_blob = __esm({ + "../../../node_modules/fetch-blob/index.js"() { + import_streams = __toESM(require_streams(), 1); + POOL_SIZE = 65536; + _Blob = (_a = class { + /** + * The Blob() constructor returns a new Blob object. The content + * of the blob consists of the concatenation of the values given + * in the parameter array. + * + * @param {*} blobParts + * @param {{ type?: string, endings?: string }} [options] + */ + constructor(blobParts = [], options = {}) { + /** @type {Array.<(Blob|Uint8Array)>} */ + __privateAdd(this, _parts, []); + __privateAdd(this, _type, ""); + __privateAdd(this, _size, 0); + __privateAdd(this, _endings, "transparent"); + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence."); + } + if (typeof blobParts[Symbol.iterator] !== "function") { + throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property."); + } + if (typeof options !== "object" && typeof options !== "function") { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); + } + if (options === null) + options = {}; + const encoder = new TextEncoder(); + for (const element of blobParts) { + let part; + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)); + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)); + } else if (element instanceof _a) { + part = element; + } else { + part = encoder.encode(`${element}`); + } + __privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size)); + __privateGet(this, _parts).push(part); + } + __privateSet(this, _endings, `${options.endings === void 0 ? "transparent" : options.endings}`); + const type = options.type === void 0 ? "" : String(options.type); + __privateSet(this, _type, /^[\x20-\x7E]*$/.test(type) ? type : ""); + } + /** + * The Blob interface's size property returns the + * size of the Blob in bytes. + */ + get size() { + return __privateGet(this, _size); + } + /** + * The type property of a Blob object returns the MIME type of the file. + */ + get type() { + return __privateGet(this, _type); + } + /** + * The text() method in the Blob interface returns a Promise + * that resolves with a string containing the contents of + * the blob, interpreted as UTF-8. + * + * @return {Promise} + */ + async text() { + const decoder = new TextDecoder(); + let str = ""; + for await (const part of toIterator(__privateGet(this, _parts), false)) { + str += decoder.decode(part, { stream: true }); + } + str += decoder.decode(); + return str; + } + /** + * The arrayBuffer() method in the Blob interface returns a + * Promise that resolves with the contents of the blob as + * binary data contained in an ArrayBuffer. + * + * @return {Promise} + */ + async arrayBuffer() { + const data = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of toIterator(__privateGet(this, _parts), false)) { + data.set(chunk, offset); + offset += chunk.length; + } + return data.buffer; + } + stream() { + const it = toIterator(__privateGet(this, _parts), true); + return new globalThis.ReadableStream({ + // @ts-ignore + type: "bytes", + async pull(ctrl) { + const chunk = await it.next(); + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value); + }, + async cancel() { + await it.return(); + } + }); + } + /** + * The Blob interface's slice() method creates and returns a + * new Blob object which contains data from a subset of the + * blob on which it's called. + * + * @param {number} [start] + * @param {number} [end] + * @param {string} [type] + */ + slice(start = 0, end = this.size, type = "") { + const { size } = this; + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size); + const span = Math.max(relativeEnd - relativeStart, 0); + const parts = __privateGet(this, _parts); + const blobParts = []; + let added = 0; + for (const part of parts) { + if (added >= span) { + break; + } + const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && size2 <= relativeStart) { + relativeStart -= size2; + relativeEnd -= size2; + } else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.byteLength; + } else { + chunk = part.slice(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.size; + } + relativeEnd -= size2; + blobParts.push(chunk); + relativeStart = 0; + } + } + const blob = new _a([], { type: String(type).toLowerCase() }); + __privateSet(blob, _size, span); + __privateSet(blob, _parts, blobParts); + return blob; + } + get [Symbol.toStringTag]() { + return "Blob"; + } + static [Symbol.hasInstance](object) { + return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]); + } + }, _parts = new WeakMap(), _type = new WeakMap(), _size = new WeakMap(), _endings = new WeakMap(), _a); + Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } + }); + Blob = _Blob; + fetch_blob_default = Blob; + } +}); + +// ../../../node_modules/fetch-blob/file.js +var _lastModified, _name, _a2, _File, File, file_default; +var init_file = __esm({ + "../../../node_modules/fetch-blob/file.js"() { + init_fetch_blob(); + _File = (_a2 = class extends fetch_blob_default { + /** + * @param {*[]} fileBits + * @param {string} fileName + * @param {{lastModified?: number, type?: string}} options + */ + // @ts-ignore + constructor(fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`); + } + super(fileBits, options); + __privateAdd(this, _lastModified, 0); + __privateAdd(this, _name, ""); + if (options === null) + options = {}; + const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + __privateSet(this, _lastModified, lastModified); + } + __privateSet(this, _name, String(fileName)); + } + get name() { + return __privateGet(this, _name); + } + get lastModified() { + return __privateGet(this, _lastModified); + } + get [Symbol.toStringTag]() { + return "File"; + } + static [Symbol.hasInstance](object) { + return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]); + } + }, _lastModified = new WeakMap(), _name = new WeakMap(), _a2); + File = _File; + file_default = File; + } +}); + +// ../../../node_modules/formdata-polyfill/esm.min.js +function formDataToBlob(F2, B = fetch_blob_default) { + var b = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c = [], p = `--${b}\r +Content-Disposition: form-data; name="`; + F2.forEach((v, n) => typeof v == "string" ? c.push(p + e(n) + `"\r +\r +${v.replace(/\r(?!\n)|(? (a += "", /^(Blob|File)$/.test(b && b[t]) ? [(c = c !== void 0 ? c + "" : b[t] == "File" ? b.name : "blob", a), b.name !== c || b[t] == "blob" ? new file_default([b], c, b) : b] : [a, b + ""]); + e = (c, f3) => (f3 ? c : c.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); + x = (n, a, e2) => { + if (a.length < e2) { + throw new TypeError(`Failed to execute '${n}' on 'FormData': ${e2} arguments required, but only ${a.length} present.`); + } + }; + FormData = (_a3 = class { + constructor(...a) { + __privateAdd(this, _d, []); + if (a.length) + throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`); + } + get [t]() { + return "FormData"; + } + [i]() { + return this.entries(); + } + static [h](o) { + return o && typeof o === "object" && o[t] === "FormData" && !m.some((m2) => typeof o[m2] != "function"); + } + append(...a) { + x("append", arguments, 2); + __privateGet(this, _d).push(f(...a)); + } + delete(a) { + x("delete", arguments, 1); + a += ""; + __privateSet(this, _d, __privateGet(this, _d).filter(([b]) => b !== a)); + } + get(a) { + x("get", arguments, 1); + a += ""; + for (var b = __privateGet(this, _d), l = b.length, c = 0; c < l; c++) + if (b[c][0] === a) + return b[c][1]; + return null; + } + getAll(a, b) { + x("getAll", arguments, 1); + b = []; + a += ""; + __privateGet(this, _d).forEach((c) => c[0] === a && b.push(c[1])); + return b; + } + has(a) { + x("has", arguments, 1); + a += ""; + return __privateGet(this, _d).some((b) => b[0] === a); + } + forEach(a, b) { + x("forEach", arguments, 1); + for (var [c, d] of this) + a.call(b, d, c, this); + } + set(...a) { + x("set", arguments, 2); + var b = [], c = true; + a = f(...a); + __privateGet(this, _d).forEach((d) => { + d[0] === a[0] ? c && (c = !b.push(a)) : b.push(d); + }); + c && b.push(a); + __privateSet(this, _d, b); + } + *entries() { + yield* __privateGet(this, _d); + } + *keys() { + for (var [a] of this) + yield a; + } + *values() { + for (var [, a] of this) + yield a; + } + }, _d = new WeakMap(), _a3); + } +}); + +// ../../../node_modules/node-domexception/index.js +var require_node_domexception = __commonJS({ + "../../../node_modules/node-domexception/index.js"(exports, module2) { + if (!globalThis.DOMException) { + try { + const { MessageChannel } = require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer(); + port.postMessage(ab, [ab, ab]); + } catch (err) { + err.constructor.name === "DOMException" && (globalThis.DOMException = err.constructor); + } + } + module2.exports = globalThis.DOMException; + } +}); + +// ../../../node_modules/fetch-blob/from.js +var import_node_fs, import_node_domexception, stat, _path, _start, _BlobDataItem, BlobDataItem; +var init_from = __esm({ + "../../../node_modules/fetch-blob/from.js"() { + import_node_fs = require("fs"); + import_node_domexception = __toESM(require_node_domexception(), 1); + init_file(); + init_fetch_blob(); + ({ stat } = import_node_fs.promises); + _BlobDataItem = class { + constructor(options) { + __privateAdd(this, _path, void 0); + __privateAdd(this, _start, void 0); + __privateSet(this, _path, options.path); + __privateSet(this, _start, options.start); + this.size = options.size; + this.lastModified = options.lastModified; + } + /** + * Slicing arguments is first validated and formatted + * to not be out of range by Blob.prototype.slice + */ + slice(start, end) { + return new _BlobDataItem({ + path: __privateGet(this, _path), + lastModified: this.lastModified, + size: end - start, + start: __privateGet(this, _start) + start + }); + } + async *stream() { + const { mtimeMs } = await stat(__privateGet(this, _path)); + if (mtimeMs > this.lastModified) { + throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError"); + } + yield* (0, import_node_fs.createReadStream)(__privateGet(this, _path), { + start: __privateGet(this, _start), + end: __privateGet(this, _start) + this.size - 1 + }); + } + get [Symbol.toStringTag]() { + return "Blob"; + } + }; + BlobDataItem = _BlobDataItem; + _path = new WeakMap(); + _start = new WeakMap(); + } +}); + +// node_modules/node-fetch/src/utils/multipart-parser.js +var multipart_parser_exports = {}; +__export(multipart_parser_exports, { + toFormData: () => toFormData +}); +function _fileName(headerValue) { + const m2 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m2) { + return; + } + const match = m2[2] || m2[3] || ""; + let filename = match.slice(match.lastIndexOf("\\") + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m3, code) => { + return String.fromCharCode(code); + }); + return filename; +} +async function toFormData(Body2, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError("Failed to fetch"); + } + const m2 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (!m2) { + throw new TypeError("no or bad content-type header, no multipart boundary"); + } + const parser = new MultipartParser(m2[1] || m2[2]); + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData(); + const onPartData = (ui8a) => { + entryValue += decoder.decode(ui8a, { stream: true }); + }; + const appendToFile = (ui8a) => { + entryChunks.push(ui8a); + }; + const appendFileToFormData = () => { + const file = new file_default(entryChunks, filename, { type: contentType }); + formData.append(entryName, file); + }; + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + const decoder = new TextDecoder("utf-8"); + decoder.decode(); + parser.onPartBegin = function() { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + headerField = ""; + headerValue = ""; + entryValue = ""; + entryName = ""; + contentType = ""; + filename = null; + entryChunks.length = 0; + }; + parser.onHeaderField = function(ui8a) { + headerField += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderValue = function(ui8a) { + headerValue += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderEnd = function() { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + if (headerField === "content-disposition") { + const m3 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + if (m3) { + entryName = m3[2] || m3[3] || ""; + } + filename = _fileName(headerValue); + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === "content-type") { + contentType = headerValue; + } + headerValue = ""; + headerField = ""; + }; + for await (const chunk of Body2) { + parser.write(chunk); + } + parser.end(); + return formData; +} +var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser; +var init_multipart_parser = __esm({ + "node_modules/node-fetch/src/utils/multipart-parser.js"() { + init_from(); + init_esm_min(); + s = 0; + S = { + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + END: s++ + }; + f2 = 1; + F = { + PART_BOUNDARY: f2, + LAST_BOUNDARY: f2 *= 2 + }; + LF = 10; + CR = 13; + SPACE = 32; + HYPHEN = 45; + COLON = 58; + A = 97; + Z = 122; + lower = (c) => c | 32; + noop = () => { + }; + MultipartParser = class { + /** + * @param {string} boundary + */ + constructor(boundary) { + this.index = 0; + this.flags = 0; + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + this.boundaryChars = {}; + boundary = "\r\n--" + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i2 = 0; i2 < boundary.length; i2++) { + ui8a[i2] = boundary.charCodeAt(i2); + this.boundaryChars[ui8a[i2]] = true; + } + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + /** + * @param {Uint8Array} data + */ + write(data) { + let i2 = 0; + const length_ = data.length; + let previousIndex = this.index; + let { lookbehind, boundary, boundaryChars, index, state, flags } = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + const mark = (name) => { + this[name + "Mark"] = i2; + }; + const clear = (name) => { + delete this[name + "Mark"]; + }; + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === void 0 || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + const dataCallback = (name, clear2) => { + const markSymbol = name + "Mark"; + if (!(markSymbol in this)) { + return; + } + if (clear2) { + callback(name, this[markSymbol], i2, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + for (i2 = 0; i2 < length_; i2++) { + c = data[i2]; + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + } else { + return; + } + break; + } + if (c !== boundary[index + 2]) { + index = -2; + } + if (c === boundary[index + 2]) { + index++; + } + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark("onHeaderField"); + index = 0; + case S.HEADER_FIELD: + if (c === CR) { + clear("onHeaderField"); + state = S.HEADERS_ALMOST_DONE; + break; + } + index++; + if (c === HYPHEN) { + break; + } + if (c === COLON) { + if (index === 1) { + return; + } + dataCallback("onHeaderField", true); + state = S.HEADER_VALUE_START; + break; + } + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + mark("onHeaderValue"); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if (c === CR) { + dataCallback("onHeaderValue", true); + callback("onHeaderEnd"); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + callback("onHeadersEnd"); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark("onPartData"); + case S.PART_DATA: + previousIndex = index; + if (index === 0) { + i2 += boundaryEnd; + while (i2 < bufferLength && !(data[i2] in boundaryChars)) { + i2 += boundaryLength; + } + i2 -= boundaryEnd; + c = data[i2]; + } + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback("onPartData", true); + } + index++; + } else { + index = 0; + } + } else if (index === boundary.length) { + index++; + if (c === CR) { + flags |= F.PART_BOUNDARY; + } else if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 === boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c === LF) { + flags &= ~F.PART_BOUNDARY; + callback("onPartEnd"); + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback("onPartEnd"); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + if (index > 0) { + lookbehind[index - 1] = c; + } else if (previousIndex > 0) { + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback("onPartData", 0, previousIndex, _lookbehind); + previousIndex = 0; + mark("onPartData"); + i2--; + } + break; + case S.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } + } + dataCallback("onHeaderField"); + dataCallback("onHeaderValue"); + dataCallback("onPartData"); + this.index = index; + this.state = state; + this.flags = flags; + } + end() { + if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error("MultipartParser.end(): stream ended unexpectedly"); + } + } + }; + } +}); + +// lib/assertions/providers/lambda-handler/index.ts +var lambda_handler_exports = {}; +__export(lambda_handler_exports, { + handler: () => handler, + isComplete: () => isComplete, + onTimeout: () => onTimeout +}); +module.exports = __toCommonJS(lambda_handler_exports); + +// lib/assertions/providers/lambda-handler/assertion.ts +var import_helpers_internal = __toESM(require_helpers_internal()); + +// lib/assertions/providers/lambda-handler/base.ts +var https = __toESM(require("https")); +var url = __toESM(require("url")); +var AWS = __toESM(require("aws-sdk")); +var CustomResourceHandler = class { + constructor(event, context) { + this.event = event; + this.context = context; + this.timedOut = false; + this.timeout = setTimeout(async () => { + await this.respond({ + status: "FAILED", + reason: "Lambda Function Timeout", + data: this.context.logStreamName + }); + this.timedOut = true; + }, context.getRemainingTimeInMillis() - 1200); + this.event = event; + this.physicalResourceId = extractPhysicalResourceId(event); + } + /** + * Handles executing the custom resource event. If `stateMachineArn` is present + * in the props then trigger the waiter statemachine + */ + async handle() { + try { + if ("stateMachineArn" in this.event.ResourceProperties) { + const req = { + stateMachineArn: this.event.ResourceProperties.stateMachineArn, + name: this.event.RequestId, + input: JSON.stringify(this.event) + }; + await this.startExecution(req); + return; + } else { + const response = await this.processEvent(this.event.ResourceProperties); + return response; + } + } catch (e2) { + console.log(e2); + throw e2; + } finally { + clearTimeout(this.timeout); + } + } + /** + * Handle async requests from the waiter state machine + */ + async handleIsComplete() { + try { + const result = await this.processEvent(this.event.ResourceProperties); + return result; + } catch (e2) { + console.log(e2); + return; + } finally { + clearTimeout(this.timeout); + } + } + /** + * Start a step function state machine which will wait for the request + * to be successful. + */ + async startExecution(req) { + try { + const sfn = new AWS.StepFunctions(); + await sfn.startExecution(req).promise(); + } finally { + clearTimeout(this.timeout); + } + } + respond(response) { + if (this.timedOut) { + return; + } + const cfResponse = { + Status: response.status, + Reason: response.reason, + PhysicalResourceId: this.physicalResourceId, + StackId: this.event.StackId, + RequestId: this.event.RequestId, + LogicalResourceId: this.event.LogicalResourceId, + NoEcho: false, + Data: response.data + }; + const responseBody = JSON.stringify(cfResponse); + console.log("Responding to CloudFormation", responseBody); + const parsedUrl = url.parse(this.event.ResponseURL); + const requestOptions = { + hostname: parsedUrl.hostname, + path: parsedUrl.path, + method: "PUT", + headers: { + "content-type": "", + "content-length": Buffer.byteLength(responseBody, "utf8") + } + }; + return new Promise((resolve, reject) => { + try { + const request2 = https.request(requestOptions, resolve); + request2.on("error", reject); + request2.write(responseBody); + request2.end(); + } catch (e2) { + reject(e2); + } finally { + clearTimeout(this.timeout); + } + }); + } +}; +function extractPhysicalResourceId(event) { + switch (event.RequestType) { + case "Create": + return event.LogicalResourceId; + case "Update": + case "Delete": + return event.PhysicalResourceId; + } +} + +// lib/assertions/providers/lambda-handler/assertion.ts +var AssertionHandler = class extends CustomResourceHandler { + async processEvent(request2) { + let actual = decodeCall(request2.actual); + const expected = decodeCall(request2.expected); + let result; + const matcher = new MatchCreator(expected).getMatcher(); + console.log(`Testing equality between ${JSON.stringify(request2.actual)} and ${JSON.stringify(request2.expected)}`); + const matchResult = matcher.test(actual); + matchResult.finished(); + if (matchResult.hasFailed()) { + result = { + failed: true, + assertion: JSON.stringify({ + status: "fail", + message: matchResult.renderMismatch() + }) + }; + if (request2.failDeployment) { + throw new Error(result.assertion); + } + } else { + result = { + assertion: JSON.stringify({ + status: "success" + }) + }; + } + return result; + } +}; +var MatchCreator = class { + constructor(obj) { + this.parsedObj = { + matcher: obj + }; + } + /** + * Return a Matcher that can be tested against the actual results. + * This will convert the encoded matchers into their corresponding + * assertions matcher. + * + * For example: + * + * ExpectedResult.objectLike({ + * Messages: [{ + * Body: Match.objectLike({ + * Elements: Match.arrayWith([{ Asdf: 3 }]), + * Payload: Match.serializedJson({ key: 'value' }), + * }), + * }], + * }); + * + * Will be encoded as: + * { + * $ObjectLike: { + * Messages: [{ + * Body: { + * $ObjectLike: { + * Elements: { + * $ArrayWith: [{ Asdf: 3 }], + * }, + * Payload: { + * $SerializedJson: { key: 'value' } + * } + * }, + * }, + * }], + * }, + * } + * + * Which can then be parsed by this function. For each key (recursively) + * the parser will check if the value has one of the encoded matchers as a key + * and if so, it will set the value as the Matcher. So, + * + * { + * Body: { + * $ObjectLike: { + * Elements: { + * $ArrayWith: [{ Asdf: 3 }], + * }, + * Payload: { + * $SerializedJson: { key: 'value' } + * } + * }, + * }, + * } + * + * Will be converted to + * { + * Body: Match.objectLike({ + * Elements: Match.arrayWith([{ Asdf: 3 }]), + * Payload: Match.serializedJson({ key: 'value' }), + * }), + * } + */ + getMatcher() { + try { + const final = JSON.parse(JSON.stringify(this.parsedObj), function(_k, v) { + const nested = Object.keys(v)[0]; + switch (nested) { + case "$ArrayWith": + return import_helpers_internal.Match.arrayWith(v[nested]); + case "$ObjectLike": + return import_helpers_internal.Match.objectLike(v[nested]); + case "$StringLike": + return import_helpers_internal.Match.stringLikeRegexp(v[nested]); + case "$SerializedJson": + return import_helpers_internal.Match.serializedJson(v[nested]); + default: + return v; + } + }); + if (import_helpers_internal.Matcher.isMatcher(final.matcher)) { + return final.matcher; + } + return import_helpers_internal.Match.exact(final.matcher); + } catch { + return import_helpers_internal.Match.exact(this.parsedObj.matcher); + } + } +}; +function decodeCall(call) { + if (!call) { + return void 0; + } + try { + const parsed = JSON.parse(call); + return parsed; + } catch { + return call; + } +} + +// node_modules/node-fetch/src/index.js +var import_node_http2 = __toESM(require("http"), 1); +var import_node_https = __toESM(require("https"), 1); +var import_node_zlib = __toESM(require("zlib"), 1); +var import_node_stream2 = __toESM(require("stream"), 1); +var import_node_buffer2 = require("buffer"); + +// ../../../node_modules/data-uri-to-buffer/dist/index.js +function dataUriToBuffer(uri) { + if (!/^data:/i.test(uri)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); + } + uri = uri.replace(/\r?\n/g, ""); + const firstComma = uri.indexOf(","); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError("malformed data: URI"); + } + const meta = uri.substring(5, firstComma).split(";"); + let charset = ""; + let base64 = false; + const type = meta[0] || "text/plain"; + let typeFull = type; + for (let i2 = 1; i2 < meta.length; i2++) { + if (meta[i2] === "base64") { + base64 = true; + } else if (meta[i2]) { + typeFull += `;${meta[i2]}`; + if (meta[i2].indexOf("charset=") === 0) { + charset = meta[i2].substring(8); + } + } + } + if (!meta[0] && !charset.length) { + typeFull += ";charset=US-ASCII"; + charset = "US-ASCII"; + } + const encoding = base64 ? "base64" : "ascii"; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + buffer.type = type; + buffer.typeFull = typeFull; + buffer.charset = charset; + return buffer; +} +var dist_default = dataUriToBuffer; + +// node_modules/node-fetch/src/body.js +var import_node_stream = __toESM(require("stream"), 1); +var import_node_util = require("util"); +var import_node_buffer = require("buffer"); +init_fetch_blob(); +init_esm_min(); + +// node_modules/node-fetch/src/errors/base.js +var FetchBaseError = class extends Error { + constructor(message, type) { + super(message); + Error.captureStackTrace(this, this.constructor); + this.type = type; + } + get name() { + return this.constructor.name; + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } +}; + +// node_modules/node-fetch/src/errors/fetch-error.js +var FetchError = class extends FetchBaseError { + /** + * @param {string} message - Error message for human + * @param {string} [type] - Error type for machine + * @param {SystemError} [systemError] - For Node.js system error + */ + constructor(message, type, systemError) { + super(message, type); + if (systemError) { + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } + } +}; + +// node_modules/node-fetch/src/utils/is.js +var NAME = Symbol.toStringTag; +var isURLSearchParameters = (object) => { + return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams"; +}; +var isBlob = (object) => { + return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]); +}; +var isAbortSignal = (object) => { + return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget"); +}; +var isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + return orig === dest || orig.endsWith(`.${dest}`); +}; +var isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + return orig === dest; +}; + +// node_modules/node-fetch/src/body.js +var pipeline = (0, import_node_util.promisify)(import_node_stream.default.pipeline); +var INTERNALS = Symbol("Body internals"); +var Body = class { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + if (body === null) { + body = null; + } else if (isURLSearchParameters(body)) { + body = import_node_buffer.Buffer.from(body.toString()); + } else if (isBlob(body)) { + } else if (import_node_buffer.Buffer.isBuffer(body)) { + } else if (import_node_util.types.isAnyArrayBuffer(body)) { + body = import_node_buffer.Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + body = import_node_buffer.Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof import_node_stream.default) { + } else if (body instanceof FormData) { + body = formDataToBlob(body); + boundary = body.type.split("=")[1]; + } else { + body = import_node_buffer.Buffer.from(String(body)); + } + let stream = body; + if (import_node_buffer.Buffer.isBuffer(body)) { + stream = import_node_stream.default.Readable.from(body); + } else if (isBlob(body)) { + stream = import_node_stream.default.Readable.from(body.stream()); + } + this[INTERNALS] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + if (body instanceof import_node_stream.default) { + body.on("error", (error_) => { + const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_); + this[INTERNALS].error = error; + }); + } + } + get body() { + return this[INTERNALS].stream; + } + get bodyUsed() { + return this[INTERNALS].disturbed; + } + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + async arrayBuffer() { + const { buffer, byteOffset, byteLength } = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + async formData() { + const ct = this.headers.get("content-type"); + if (ct.startsWith("application/x-www-form-urlencoded")) { + const formData = new FormData(); + const parameters = new URLSearchParams(await this.text()); + for (const [name, value] of parameters) { + formData.append(name, value); + } + return formData; + } + const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports)); + return toFormData2(this.body, ct); + } + /** + * Return raw response as Blob + * + * @return Promise + */ + async blob() { + const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || ""; + const buf = await this.arrayBuffer(); + return new fetch_blob_default([buf], { + type: ct + }); + } + /** + * Decode response as json + * + * @return Promise + */ + async json() { + const text = await this.text(); + return JSON.parse(text); + } + /** + * Decode response as text + * + * @return Promise + */ + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody(this); + } +}; +Body.prototype.buffer = (0, import_node_util.deprecate)(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer"); +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true }, + data: { get: (0, import_node_util.deprecate)( + () => { + }, + "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", + "https://github.com/node-fetch/node-fetch/issues/1000 (response)" + ) } +}); +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + data[INTERNALS].disturbed = true; + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + const { body } = data; + if (body === null) { + return import_node_buffer.Buffer.alloc(0); + } + if (!(body instanceof import_node_stream.default)) { + return import_node_buffer.Buffer.alloc(0); + } + const accum = []; + let accumBytes = 0; + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size"); + body.destroy(error); + throw error; + } + accumBytes += chunk.length; + accum.push(chunk); + } + } catch (error) { + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, "system", error); + throw error_; + } + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every((c) => typeof c === "string")) { + return import_node_buffer.Buffer.from(accum.join("")); + } + return import_node_buffer.Buffer.concat(accum, accumBytes); + } catch (error) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, "system", error); + } + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} +var clone = (instance, highWaterMark) => { + let p1; + let p2; + let { body } = instance[INTERNALS]; + if (instance.bodyUsed) { + throw new Error("cannot clone body after it is used"); + } + if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") { + p1 = new import_node_stream.PassThrough({ highWaterMark }); + p2 = new import_node_stream.PassThrough({ highWaterMark }); + body.pipe(p1); + body.pipe(p2); + instance[INTERNALS].stream = p1; + body = p2; + } + return body; +}; +var getNonSpecFormDataBoundary = (0, import_node_util.deprecate)( + (body) => body.getBoundary(), + "form-data doesn't follow the spec and requires special treatment. Use alternative package", + "https://github.com/node-fetch/node-fetch/issues/1167" +); +var extractContentType = (body, request2) => { + if (body === null) { + return null; + } + if (typeof body === "string") { + return "text/plain;charset=UTF-8"; + } + if (isURLSearchParameters(body)) { + return "application/x-www-form-urlencoded;charset=UTF-8"; + } + if (isBlob(body)) { + return body.type || null; + } + if (import_node_buffer.Buffer.isBuffer(body) || import_node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + if (body instanceof FormData) { + return `multipart/form-data; boundary=${request2[INTERNALS].boundary}`; + } + if (body && typeof body.getBoundary === "function") { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + if (body instanceof import_node_stream.default) { + return null; + } + return "text/plain;charset=UTF-8"; +}; +var getTotalBytes = (request2) => { + const { body } = request2[INTERNALS]; + if (body === null) { + return 0; + } + if (isBlob(body)) { + return body.size; + } + if (import_node_buffer.Buffer.isBuffer(body)) { + return body.length; + } + if (body && typeof body.getLengthSync === "function") { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + return null; +}; +var writeToStream = async (dest, { body }) => { + if (body === null) { + dest.end(); + } else { + await pipeline(body, dest); + } +}; + +// node_modules/node-fetch/src/headers.js +var import_node_util2 = require("util"); +var import_node_http = __toESM(require("http"), 1); +var validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_HTTP_TOKEN" }); + throw error; + } +}; +var validateHeaderValue = typeof import_node_http.default.validateHeaderValue === "function" ? import_node_http.default.validateHeaderValue : (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_CHAR" }); + throw error; + } +}; +var Headers = class extends URLSearchParams { + /** + * Headers class + * + * @constructor + * @param {HeadersInit} [init] - Response headers + */ + constructor(init) { + let result = []; + if (init instanceof Headers) { + const raw = init.raw(); + for (const [name, values] of Object.entries(raw)) { + result.push(...values.map((value) => [name, value])); + } + } else if (init == null) { + } else if (typeof init === "object" && !import_node_util2.types.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + if (method == null) { + result.push(...Object.entries(init)); + } else { + if (typeof method !== "function") { + throw new TypeError("Header pairs must be iterable"); + } + result = [...init].map((pair) => { + if (typeof pair !== "object" || import_node_util2.types.isBoxedPrimitive(pair)) { + throw new TypeError("Each header pair must be an iterable object"); + } + return [...pair]; + }).map((pair) => { + if (pair.length !== 2) { + throw new TypeError("Each header pair must be a name/value tuple"); + } + return [...pair]; + }); + } + } else { + throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)"); + } + result = result.length > 0 ? result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : void 0; + super(result); + return new Proxy(this, { + get(target, p, receiver) { + switch (p) { + case "append": + case "set": + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase(), + String(value) + ); + }; + case "delete": + case "has": + case "getAll": + return (name) => { + validateHeaderName(name); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase() + ); + }; + case "keys": + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + default: + return Reflect.get(target, p, receiver); + } + } + }); + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } + toString() { + return Object.prototype.toString.call(this); + } + get(name) { + const values = this.getAll(name); + if (values.length === 0) { + return null; + } + let value = values.join(", "); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + return value; + } + forEach(callback, thisArg = void 0) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } + } + *values() { + for (const name of this.keys()) { + yield this.get(name); + } + } + /** + * @type {() => IterableIterator<[string, string]>} + */ + *entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } + } + [Symbol.iterator]() { + return this.entries(); + } + /** + * Node-fetch non-spec method + * returning all headers and their values as array + * @returns {Record} + */ + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); + } + /** + * For better console.log(headers) and also to convert Headers into Node.js Request compatible format + */ + [Symbol.for("nodejs.util.inspect.custom")]() { + return [...this.keys()].reduce((result, key) => { + const values = this.getAll(key); + if (key === "host") { + result[key] = values[0]; + } else { + result[key] = values.length > 1 ? values : values[0]; + } + return result; + }, {}); + } +}; +Object.defineProperties( + Headers.prototype, + ["get", "entries", "forEach", "values"].reduce((result, property) => { + result[property] = { enumerable: true }; + return result; + }, {}) +); +function fromRawHeaders(headers = []) { + return new Headers( + headers.reduce((result, value, index, array) => { + if (index % 2 === 0) { + result.push(array.slice(index, index + 2)); + } + return result; + }, []).filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch { + return false; + } + }) + ); +} + +// node_modules/node-fetch/src/utils/is-redirect.js +var redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); +var isRedirect = (code) => { + return redirectStatus.has(code); +}; + +// node_modules/node-fetch/src/response.js +var INTERNALS2 = Symbol("Response internals"); +var Response = class extends Body { + constructor(body = null, options = {}) { + super(body, options); + const status = options.status != null ? options.status : 200; + const headers = new Headers(options.headers); + if (body !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append("Content-Type", contentType); + } + } + this[INTERNALS2] = { + type: "default", + url: options.url, + status, + statusText: options.statusText || "", + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + get type() { + return this[INTERNALS2].type; + } + get url() { + return this[INTERNALS2].url || ""; + } + get status() { + return this[INTERNALS2].status; + } + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300; + } + get redirected() { + return this[INTERNALS2].counter > 0; + } + get statusText() { + return this[INTERNALS2].statusText; + } + get headers() { + return this[INTERNALS2].headers; + } + get highWaterMark() { + return this[INTERNALS2].highWaterMark; + } + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); + } + /** + * @param {string} url The URL that the new response is to originate from. + * @param {number} status An optional status code for the response (e.g., 302.) + * @returns {Response} A Response object. + */ + static redirect(url2, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + return new Response(null, { + headers: { + location: new URL(url2).toString() + }, + status + }); + } + static error() { + const response = new Response(null, { status: 0, statusText: "" }); + response[INTERNALS2].type = "error"; + return response; + } + static json(data = void 0, init = {}) { + const body = JSON.stringify(data); + if (body === void 0) { + throw new TypeError("data is not JSON serializable"); + } + const headers = new Headers(init && init.headers); + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + return new Response(body, { + ...init, + headers + }); + } + get [Symbol.toStringTag]() { + return "Response"; + } +}; +Object.defineProperties(Response.prototype, { + type: { enumerable: true }, + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +// node_modules/node-fetch/src/request.js +var import_node_url = require("url"); +var import_node_util3 = require("util"); + +// node_modules/node-fetch/src/utils/get-search.js +var getSearch = (parsedURL) => { + if (parsedURL.search) { + return parsedURL.search; + } + const lastOffset = parsedURL.href.length - 1; + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : ""); + return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : ""; +}; + +// node_modules/node-fetch/src/utils/referrer.js +var import_node_net = require("net"); +function stripURLForUseAsAReferrer(url2, originOnly = false) { + if (url2 == null) { + return "no-referrer"; + } + url2 = new URL(url2); + if (/^(about|blob|data):$/.test(url2.protocol)) { + return "no-referrer"; + } + url2.username = ""; + url2.password = ""; + url2.hash = ""; + if (originOnly) { + url2.pathname = ""; + url2.search = ""; + } + return url2; +} +var ReferrerPolicy = /* @__PURE__ */ new Set([ + "", + "no-referrer", + "no-referrer-when-downgrade", + "same-origin", + "origin", + "strict-origin", + "origin-when-cross-origin", + "strict-origin-when-cross-origin", + "unsafe-url" +]); +var DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin"; +function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + return referrerPolicy; +} +function isOriginPotentiallyTrustworthy(url2) { + if (/^(http|ws)s:$/.test(url2.protocol)) { + return true; + } + const hostIp = url2.host.replace(/(^\[)|(]$)/g, ""); + const hostIPVersion = (0, import_node_net.isIP)(hostIp); + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + if (url2.host === "localhost" || url2.host.endsWith(".localhost")) { + return false; + } + if (url2.protocol === "file:") { + return true; + } + return false; +} +function isUrlPotentiallyTrustworthy(url2) { + if (/^about:(blank|srcdoc)$/.test(url2)) { + return true; + } + if (url2.protocol === "data:") { + return true; + } + if (/^(blob|filesystem):$/.test(url2.protocol)) { + return true; + } + return isOriginPotentiallyTrustworthy(url2); +} +function determineRequestsReferrer(request2, { referrerURLCallback, referrerOriginCallback } = {}) { + if (request2.referrer === "no-referrer" || request2.referrerPolicy === "") { + return null; + } + const policy = request2.referrerPolicy; + if (request2.referrer === "about:client") { + return "no-referrer"; + } + const referrerSource = request2.referrer; + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + const currentURL = new URL(request2.url); + switch (policy) { + case "no-referrer": + return "no-referrer"; + case "origin": + return referrerOrigin; + case "unsafe-url": + return referrerURL; + case "strict-origin": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin.toString(); + case "strict-origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin; + case "same-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return "no-referrer"; + case "origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return referrerOrigin; + case "no-referrer-when-downgrade": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerURL; + default: + throw new TypeError(`Invalid referrerPolicy: ${policy}`); + } +} +function parseReferrerPolicyFromHeader(headers) { + const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/); + let policy = ""; + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy = token; + } + } + return policy; +} + +// node_modules/node-fetch/src/request.js +var INTERNALS3 = Symbol("Request internals"); +var isRequest = (object) => { + return typeof object === "object" && typeof object[INTERNALS3] === "object"; +}; +var doBadDataWarn = (0, import_node_util3.deprecate)( + () => { + }, + ".data is not a valid RequestInit property, use .body instead", + "https://github.com/node-fetch/node-fetch/issues/1000 (request)" +); +var Request = class extends Body { + constructor(input, init = {}) { + let parsedURL; + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; + } + if (parsedURL.username !== "" || parsedURL.password !== "") { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); + } + let method = init.method || input.method || "GET"; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); + } + if (!isRequest(init) && "data" in init) { + doBadDataWarn(); + } + if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) { + throw new TypeError("Request with GET/HEAD method cannot have body"); + } + const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + super(inputBody, { + size: init.size || input.size || 0 + }); + const headers = new Headers(init.headers || input.headers || {}); + if (inputBody !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set("Content-Type", contentType); + } + } + let signal = isRequest(input) ? input.signal : null; + if ("signal" in init) { + signal = init.signal; + } + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget"); + } + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === "") { + referrer = "no-referrer"; + } else if (referrer) { + const parsedReferrer = new URL(referrer); + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer; + } else { + referrer = void 0; + } + this[INTERNALS3] = { + method, + redirect: init.redirect || input.redirect || "follow", + headers, + parsedURL, + signal, + referrer + }; + this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow; + this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ""; + } + /** @returns {string} */ + get method() { + return this[INTERNALS3].method; + } + /** @returns {string} */ + get url() { + return (0, import_node_url.format)(this[INTERNALS3].parsedURL); + } + /** @returns {Headers} */ + get headers() { + return this[INTERNALS3].headers; + } + get redirect() { + return this[INTERNALS3].redirect; + } + /** @returns {AbortSignal} */ + get signal() { + return this[INTERNALS3].signal; + } + // https://fetch.spec.whatwg.org/#dom-request-referrer + get referrer() { + if (this[INTERNALS3].referrer === "no-referrer") { + return ""; + } + if (this[INTERNALS3].referrer === "client") { + return "about:client"; + } + if (this[INTERNALS3].referrer) { + return this[INTERNALS3].referrer.toString(); + } + return void 0; + } + get referrerPolicy() { + return this[INTERNALS3].referrerPolicy; + } + set referrerPolicy(referrerPolicy) { + this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } + get [Symbol.toStringTag]() { + return "Request"; + } +}; +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true }, + referrer: { enumerable: true }, + referrerPolicy: { enumerable: true } +}); +var getNodeRequestOptions = (request2) => { + const { parsedURL } = request2[INTERNALS3]; + const headers = new Headers(request2[INTERNALS3].headers); + if (!headers.has("Accept")) { + headers.set("Accept", "*/*"); + } + let contentLengthValue = null; + if (request2.body === null && /^(post|put)$/i.test(request2.method)) { + contentLengthValue = "0"; + } + if (request2.body !== null) { + const totalBytes = getTotalBytes(request2); + if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set("Content-Length", contentLengthValue); + } + if (request2.referrerPolicy === "") { + request2.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + if (request2.referrer && request2.referrer !== "no-referrer") { + request2[INTERNALS3].referrer = determineRequestsReferrer(request2); + } else { + request2[INTERNALS3].referrer = "no-referrer"; + } + if (request2[INTERNALS3].referrer instanceof URL) { + headers.set("Referer", request2.referrer); + } + if (!headers.has("User-Agent")) { + headers.set("User-Agent", "node-fetch"); + } + if (request2.compress && !headers.has("Accept-Encoding")) { + headers.set("Accept-Encoding", "gzip, deflate, br"); + } + let { agent } = request2; + if (typeof agent === "function") { + agent = agent(parsedURL); + } + if (!headers.has("Connection") && !agent) { + headers.set("Connection", "close"); + } + const search = getSearch(parsedURL); + const options = { + // Overwrite search to retain trailing ? (issue #776) + path: parsedURL.pathname + search, + // The following options are not expressed in the URL + method: request2.method, + headers: headers[Symbol.for("nodejs.util.inspect.custom")](), + insecureHTTPParser: request2.insecureHTTPParser, + agent + }; + return { + /** @type {URL} */ + parsedURL, + options + }; +}; + +// node_modules/node-fetch/src/errors/abort-error.js +var AbortError = class extends FetchBaseError { + constructor(message, type = "aborted") { + super(message, type); + } +}; + +// node_modules/node-fetch/src/index.js +init_esm_min(); +init_from(); +var supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]); +async function fetch(url2, options_) { + return new Promise((resolve, reject) => { + const request2 = new Request(url2, options_); + const { parsedURL, options } = getNodeRequestOptions(request2); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url2}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`); + } + if (parsedURL.protocol === "data:") { + const data = dist_default(request2.url); + const response2 = new Response(data, { headers: { "Content-Type": data.typeFull } }); + resolve(response2); + return; + } + const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request; + const { signal } = request2; + let response = null; + const abort = () => { + const error = new AbortError("The operation was aborted."); + reject(error); + if (request2.body && request2.body instanceof import_node_stream2.default.Readable) { + request2.body.destroy(error); + } + if (!response || !response.body) { + return; + } + response.body.emit("error", error); + }; + if (signal && signal.aborted) { + abort(); + return; + } + const abortAndFinalize = () => { + abort(); + finalize(); + }; + const request_ = send(parsedURL.toString(), options); + if (signal) { + signal.addEventListener("abort", abortAndFinalize); + } + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener("abort", abortAndFinalize); + } + }; + request_.on("error", (error) => { + reject(new FetchError(`request to ${request2.url} failed, reason: ${error.message}`, "system", error)); + finalize(); + }); + fixResponseChunkedTransferBadEnding(request_, (error) => { + if (response && response.body) { + response.body.destroy(error); + } + }); + if (process.version < "v14") { + request_.on("socket", (s2) => { + let endedWithEventsCount; + s2.prependListener("end", () => { + endedWithEventsCount = s2._eventsCount; + }); + s2.prependListener("close", (hadError) => { + if (response && endedWithEventsCount < s2._eventsCount && !hadError) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + response.body.emit("error", error); + } + }); + }); + } + request_.on("response", (response_) => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + if (isRedirect(response_.statusCode)) { + const location = headers.get("Location"); + let locationURL = null; + try { + locationURL = location === null ? null : new URL(location, request2.url); + } catch { + if (request2.redirect !== "manual") { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect")); + finalize(); + return; + } + } + switch (request2.redirect) { + case "error": + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request2.url}`, "no-redirect")); + finalize(); + return; + case "manual": + break; + case "follow": { + if (locationURL === null) { + break; + } + if (request2.counter >= request2.follow) { + reject(new FetchError(`maximum redirect reached at: ${request2.url}`, "max-redirect")); + finalize(); + return; + } + const requestOptions = { + headers: new Headers(request2.headers), + follow: request2.follow, + counter: request2.counter + 1, + agent: request2.agent, + compress: request2.compress, + method: request2.method, + body: clone(request2), + signal: request2.signal, + size: request2.size, + referrer: request2.referrer, + referrerPolicy: request2.referrerPolicy + }; + if (!isDomainOrSubdomain(request2.url, locationURL) || !isSameProtocol(request2.url, locationURL)) { + for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) { + requestOptions.headers.delete(name); + } + } + if (response_.statusCode !== 303 && request2.body && options_.body instanceof import_node_stream2.default.Readable) { + reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect")); + finalize(); + return; + } + if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request2.method === "POST") { + requestOptions.method = "GET"; + requestOptions.body = void 0; + requestOptions.headers.delete("content-length"); + } + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + resolve(fetch(new Request(locationURL, requestOptions))); + finalize(); + return; + } + default: + return reject(new TypeError(`Redirect option '${request2.redirect}' is not a valid value of RequestRedirect`)); + } + } + if (signal) { + response_.once("end", () => { + signal.removeEventListener("abort", abortAndFinalize); + }); + } + let body = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + if (process.version < "v12.10") { + response_.on("aborted", abortAndFinalize); + } + const responseOptions = { + url: request2.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request2.size, + counter: request2.counter, + highWaterMark: request2.highWaterMark + }; + const codings = headers.get("Content-Encoding"); + if (!request2.compress || request2.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + const zlibOptions = { + flush: import_node_zlib.default.Z_SYNC_FLUSH, + finishFlush: import_node_zlib.default.Z_SYNC_FLUSH + }; + if (codings === "gzip" || codings === "x-gzip") { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createGunzip(zlibOptions), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + if (codings === "deflate" || codings === "x-deflate") { + const raw = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + raw.once("data", (chunk) => { + if ((chunk[0] & 15) === 8) { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflate(), (error) => { + if (error) { + reject(error); + } + }); + } else { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflateRaw(), (error) => { + if (error) { + reject(error); + } + }); + } + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once("end", () => { + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + if (codings === "br") { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + response = new Response(body, responseOptions); + resolve(response); + }); + writeToStream(request_, request2).catch(reject); + }); +} +function fixResponseChunkedTransferBadEnding(request2, errorCallback) { + const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n"); + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + request2.on("response", (response) => { + const { headers } = response; + isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"]; + }); + request2.on("socket", (socket) => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + errorCallback(error); + } + }; + const onData = (buf) => { + properLastChunkReceived = import_node_buffer2.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = import_node_buffer2.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && import_node_buffer2.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0; + } + previousChunk = buf; + }; + socket.prependListener("close", onSocketClose); + socket.on("data", onData); + request2.on("close", () => { + socket.removeListener("close", onSocketClose); + socket.removeListener("data", onData); + }); + }); +} + +// lib/assertions/providers/lambda-handler/http.ts +var HttpHandler = class extends CustomResourceHandler { + async processEvent(request2) { + console.log("request", request2); + const response = await fetch(request2.parameters.url, request2.parameters.fetchOptions); + const result = { + ok: response.ok, + status: response.status, + statusText: response.statusText, + headers: response.headers.raw() + }; + try { + const jsonResponse = await response.json(); + result.body = jsonResponse; + } catch (e2) { + result.body = {}; + } + return { + apiCallResponse: result + }; + } +}; + +// lib/assertions/providers/lambda-handler/utils.ts +function decode(object) { + return JSON.parse(JSON.stringify(object), (_k, v) => { + switch (v) { + case "TRUE:BOOLEAN": + return true; + case "FALSE:BOOLEAN": + return false; + default: + return v; + } + }); +} + +// lib/assertions/providers/lambda-handler/sdk.ts +function flatten(object) { + return Object.assign( + {}, + ...function _flatten(child, path = []) { + return [].concat(...Object.keys(child).map((key) => { + let childKey = Buffer.isBuffer(child[key]) ? child[key].toString("utf8") : child[key]; + if (typeof childKey === "string") { + childKey = isJsonString(childKey); + } + return typeof childKey === "object" && childKey !== null ? _flatten(childKey, path.concat([key])) : { [path.concat([key]).join(".")]: childKey }; + })); + }(object) + ); +} +var AwsApiCallHandler = class extends CustomResourceHandler { + async processEvent(request2) { + const AWS2 = require("aws-sdk"); + console.log(`AWS SDK VERSION: ${AWS2.VERSION}`); + if (!Object.prototype.hasOwnProperty.call(AWS2, request2.service)) { + throw Error(`Service ${request2.service} does not exist in AWS SDK version ${AWS2.VERSION}.`); + } + const service = new AWS2[request2.service](); + const response = await service[request2.api](request2.parameters && decode(request2.parameters)).promise(); + console.log(`SDK response received ${JSON.stringify(response)}`); + delete response.ResponseMetadata; + const respond = { + apiCallResponse: response + }; + const flatData = { + ...flatten(respond) + }; + let resp = respond; + if (request2.outputPaths) { + resp = filterKeys(flatData, request2.outputPaths); + } else if (request2.flattenResponse === "true") { + resp = flatData; + } + console.log(`Returning result ${JSON.stringify(resp)}`); + return resp; + } +}; +function filterKeys(object, searchStrings) { + return Object.entries(object).reduce((filteredObject, [key, value]) => { + for (const searchString of searchStrings) { + if (key.startsWith(`apiCallResponse.${searchString}`)) { + filteredObject[key] = value; + } + } + return filteredObject; + }, {}); +} +function isJsonString(value) { + try { + return JSON.parse(value); + } catch { + return value; + } +} + +// lib/assertions/providers/lambda-handler/types.ts +var ASSERT_RESOURCE_TYPE = "Custom::DeployAssert@AssertEquals"; +var SDK_RESOURCE_TYPE_PREFIX = "Custom::DeployAssert@SdkCall"; +var HTTP_RESOURCE_TYPE = "Custom::DeployAssert@HttpCall"; + +// lib/assertions/providers/lambda-handler/index.ts +async function handler(event, context) { + console.log(`Event: ${JSON.stringify({ ...event, ResponseURL: "..." })}`); + const provider = createResourceHandler(event, context); + try { + if (event.RequestType === "Delete") { + await provider.respond({ + status: "SUCCESS", + reason: "OK" + }); + return; + } + const result = await provider.handle(); + if ("stateMachineArn" in event.ResourceProperties) { + console.info('Found "stateMachineArn", waiter statemachine started'); + return; + } else if ("expected" in event.ResourceProperties) { + console.info('Found "expected", testing assertions'); + const actualPath = event.ResourceProperties.actualPath; + const actual = actualPath ? result[`apiCallResponse.${actualPath}`] : result.apiCallResponse; + const assertion = new AssertionHandler({ + ...event, + ResourceProperties: { + ServiceToken: event.ServiceToken, + actual, + expected: event.ResourceProperties.expected + } + }, context); + try { + const assertionResult = await assertion.handle(); + await provider.respond({ + status: "SUCCESS", + reason: "OK", + // return both the result of the API call _and_ the assertion results + data: { + ...assertionResult, + ...result + } + }); + return; + } catch (e2) { + await provider.respond({ + status: "FAILED", + reason: e2.message ?? "Internal Error" + }); + return; + } + } + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: result + }); + } catch (e2) { + await provider.respond({ + status: "FAILED", + reason: e2.message ?? "Internal Error" + }); + return; + } + return; +} +async function onTimeout(timeoutEvent) { + const isCompleteRequest = JSON.parse(JSON.parse(timeoutEvent.Cause).errorMessage); + const provider = createResourceHandler(isCompleteRequest, standardContext); + await provider.respond({ + status: "FAILED", + reason: "Operation timed out: " + JSON.stringify(isCompleteRequest) + }); +} +async function isComplete(event, context) { + console.log(`Event: ${JSON.stringify({ ...event, ResponseURL: "..." })}`); + const provider = createResourceHandler(event, context); + try { + const result = await provider.handleIsComplete(); + const actualPath = event.ResourceProperties.actualPath; + if (result) { + const actual = actualPath ? result[`apiCallResponse.${actualPath}`] : result.apiCallResponse; + if ("expected" in event.ResourceProperties) { + const assertion = new AssertionHandler({ + ...event, + ResourceProperties: { + ServiceToken: event.ServiceToken, + actual, + expected: event.ResourceProperties.expected + } + }, context); + const assertionResult = await assertion.handleIsComplete(); + if (!(assertionResult == null ? void 0 : assertionResult.failed)) { + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: { + ...assertionResult, + ...result + } + }); + return; + } else { + console.log(`Assertion Failed: ${JSON.stringify(assertionResult)}`); + throw new Error(JSON.stringify(event)); + } + } + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: result + }); + } else { + console.log("No result"); + throw new Error(JSON.stringify(event)); + } + return; + } catch (e2) { + console.log(e2); + throw new Error(JSON.stringify(event)); + } +} +function createResourceHandler(event, context) { + if (event.ResourceType.startsWith(SDK_RESOURCE_TYPE_PREFIX)) { + return new AwsApiCallHandler(event, context); + } else if (event.ResourceType.startsWith(ASSERT_RESOURCE_TYPE)) { + return new AssertionHandler(event, context); + } else if (event.ResourceType.startsWith(HTTP_RESOURCE_TYPE)) { + return new HttpHandler(event, context); + } else { + throw new Error(`Unsupported resource type "${event.ResourceType}`); + } +} +var standardContext = { + getRemainingTimeInMillis: () => 9e4 +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + handler, + isComplete, + onTimeout +}); +/*! Bundled license information: + +fetch-blob/index.js: + (*! fetch-blob. MIT License. Jimmy Wärting *) + +formdata-polyfill/esm.min.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting *) + +node-domexception/index.js: + (*! node-domexception. MIT License. Jimmy Wärting *) +*/ diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/cdk.out b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/cdk.out index 8ecc185e9dbee..f0b901e7c06e5 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/cdk.out +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/cdk.out @@ -1 +1 @@ -{"version":"21.0.0"} \ No newline at end of file +{"version":"32.0.0"} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/domainnamemappingtestDefaultTestDeployAssert4FFC8047.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/domainnamemappingtestDefaultTestDeployAssert4FFC8047.assets.json index 298b64e0e3328..505ed8e9821eb 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/domainnamemappingtestDefaultTestDeployAssert4FFC8047.assets.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/domainnamemappingtestDefaultTestDeployAssert4FFC8047.assets.json @@ -1,20 +1,20 @@ { - "version": "21.0.0", + "version": "32.0.0", "files": { - "456da4984f762c1c25e94bd5f2df6758d2b0884d0dae8ca59bb8f4e3de7c2136": { + "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231": { "source": { - "path": "asset.456da4984f762c1c25e94bd5f2df6758d2b0884d0dae8ca59bb8f4e3de7c2136.bundle", + "path": "asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle", "packaging": "zip" }, "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "456da4984f762c1c25e94bd5f2df6758d2b0884d0dae8ca59bb8f4e3de7c2136.zip", + "objectKey": "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.zip", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } }, - "ca221fe7d8415bb5d7851fa5f77af9fa55569243f4832c489ac239a1a9ccf4ca": { + "a964cf65aae2e23802c1975a0c39add8b0c2e59296daad40cc71353166b3685f": { "source": { "path": "domainnamemappingtestDefaultTestDeployAssert4FFC8047.template.json", "packaging": "file" @@ -22,7 +22,7 @@ "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "ca221fe7d8415bb5d7851fa5f77af9fa55569243f4832c489ac239a1a9ccf4ca.json", + "objectKey": "a964cf65aae2e23802c1975a0c39add8b0c2e59296daad40cc71353166b3685f.json", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/domainnamemappingtestDefaultTestDeployAssert4FFC8047.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/domainnamemappingtestDefaultTestDeployAssert4FFC8047.template.json index 2c342b9a4c8b9..86ce129307311 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/domainnamemappingtestDefaultTestDeployAssert4FFC8047.template.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/domainnamemappingtestDefaultTestDeployAssert4FFC8047.template.json @@ -1,7 +1,7 @@ { "Resources": { - "LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a": { - "Type": "Custom::DeployAssert@SdkCallLambdainvoke", + "HttpApiCall5c7406415c21459755238de5e3d1af86": { + "Type": "Custom::DeployAssert@HttpCall", "Properties": { "ServiceToken": { "Fn::GetAtt": [ @@ -9,47 +9,27 @@ "Arn" ] }, - "service": "Lambda", - "api": "invoke", - "expected": "{\"$ObjectLike\":{\"Payload\":{\"$StringLike\":\"201\"}}}", "parameters": { - "FunctionName": { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - }, - "Payload": { + "url": { "Fn::Join": [ "", [ - "{\"hostname\":\"", + "https://", { "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefIntegDomain624DF323D17B7540" }, - "\",\"path\":\"/orders/v1/items\"}" + "/orders/v1/items" ] ] - } + }, + "fetchOptions": {} }, - "flattenResponse": "false", - "salt": "1665514871380" + "expected": "{\"$ObjectLike\":{\"body\":{\"message\":\"Hello, world\"},\"ok\":true,\"status\":201}}", + "salt": "1687522738197" }, "UpdateReplacePolicy": "Delete", "DeletionPolicy": "Delete" }, - "LambdaInvoke6c82f4296e4da69e1d6905e3d20f761aInvokeF34C6427": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "FunctionName": { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - }, - "Principal": { - "Fn::GetAtt": [ - "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73", - "Arn" - ] - } - } - }, "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73": { "Type": "AWS::IAM::Role", "Properties": { @@ -69,176 +49,6 @@ { "Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" } - ], - "Policies": [ - { - "PolicyName": "Inline", - "PolicyDocument": { - "Version": "2012-10-17", - "Statement": [ - { - "Action": [ - "lambda:Invoke" - ], - "Effect": "Allow", - "Resource": [ - "*" - ] - }, - { - "Action": [ - "lambda:InvokeFunction" - ], - "Effect": "Allow", - "Resource": [ - { - "Fn::Join": [ - "", - [ - "arn:", - { - "Ref": "AWS::Partition" - }, - ":lambda:", - { - "Ref": "AWS::Region" - }, - ":", - { - "Ref": "AWS::AccountId" - }, - ":function:", - { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - } - ] - ] - } - ] - }, - { - "Action": [ - "lambda:Invoke" - ], - "Effect": "Allow", - "Resource": [ - "*" - ] - }, - { - "Action": [ - "lambda:InvokeFunction" - ], - "Effect": "Allow", - "Resource": [ - { - "Fn::Join": [ - "", - [ - "arn:", - { - "Ref": "AWS::Partition" - }, - ":lambda:", - { - "Ref": "AWS::Region" - }, - ":", - { - "Ref": "AWS::AccountId" - }, - ":function:", - { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - } - ] - ] - } - ] - }, - { - "Action": [ - "lambda:Invoke" - ], - "Effect": "Allow", - "Resource": [ - "*" - ] - }, - { - "Action": [ - "lambda:InvokeFunction" - ], - "Effect": "Allow", - "Resource": [ - { - "Fn::Join": [ - "", - [ - "arn:", - { - "Ref": "AWS::Partition" - }, - ":lambda:", - { - "Ref": "AWS::Region" - }, - ":", - { - "Ref": "AWS::AccountId" - }, - ":function:", - { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - } - ] - ] - } - ] - }, - { - "Action": [ - "lambda:Invoke" - ], - "Effect": "Allow", - "Resource": [ - "*" - ] - }, - { - "Action": [ - "lambda:InvokeFunction" - ], - "Effect": "Allow", - "Resource": [ - { - "Fn::Join": [ - "", - [ - "arn:", - { - "Ref": "AWS::Partition" - }, - ":lambda:", - { - "Ref": "AWS::Region" - }, - ":", - { - "Ref": "AWS::AccountId" - }, - ":function:", - { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - } - ] - ] - } - ] - } - ] - } - } ] } }, @@ -250,7 +60,7 @@ "S3Bucket": { "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" }, - "S3Key": "456da4984f762c1c25e94bd5f2df6758d2b0884d0dae8ca59bb8f4e3de7c2136.zip" + "S3Key": "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.zip" }, "Timeout": 120, "Handler": "index.handler", @@ -262,8 +72,8 @@ } } }, - "LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320": { - "Type": "Custom::DeployAssert@SdkCallLambdainvoke", + "HttpApiCall87249be5ff18205c5f4320c2baec9418": { + "Type": "Custom::DeployAssert@HttpCall", "Properties": { "ServiceToken": { "Fn::GetAtt": [ @@ -271,49 +81,29 @@ "Arn" ] }, - "service": "Lambda", - "api": "invoke", - "expected": "{\"$ObjectLike\":{\"Payload\":{\"$StringLike\":\"202\"}}}", "parameters": { - "FunctionName": { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - }, - "Payload": { + "url": { "Fn::Join": [ "", [ - "{\"hostname\":\"", + "https://", { "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefIntegDomain624DF323D17B7540" }, - "\",\"path\":\"/orders/v2/items\"}" + "/orders/v2/items" ] ] - } + }, + "fetchOptions": {} }, - "flattenResponse": "false", - "salt": "1665514871381" + "expected": "{\"$ObjectLike\":{\"body\":{\"message\":\"Hello, world\"},\"ok\":true,\"status\":202}}", + "salt": "1687522738198" }, "UpdateReplacePolicy": "Delete", "DeletionPolicy": "Delete" }, - "LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320InvokeC08B85F1": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "FunctionName": { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - }, - "Principal": { - "Fn::GetAtt": [ - "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73", - "Arn" - ] - } - } - }, - "LambdaInvokef718aff12f12e7e6e6dd823f91dfce23": { - "Type": "Custom::DeployAssert@SdkCallLambdainvoke", + "HttpApiCall39df1b9413ee8ef1155877d35e1a132f": { + "Type": "Custom::DeployAssert@HttpCall", "Properties": { "ServiceToken": { "Fn::GetAtt": [ @@ -321,49 +111,29 @@ "Arn" ] }, - "service": "Lambda", - "api": "invoke", - "expected": "{\"$ObjectLike\":{\"Payload\":{\"$StringLike\":\"201\"}}}", "parameters": { - "FunctionName": { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - }, - "Payload": { + "url": { "Fn::Join": [ "", [ - "{\"hostname\":\"", + "https://", { "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInteg2Domain70CCEA688A08551F" }, - "\",\"path\":\"/orders/items\"}" + "/orders/items" ] ] - } + }, + "fetchOptions": {} }, - "flattenResponse": "false", - "salt": "1665514871382" + "expected": "{\"$ObjectLike\":{\"body\":{\"message\":\"Hello, world\"},\"ok\":true,\"status\":201}}", + "salt": "1687522738198" }, "UpdateReplacePolicy": "Delete", "DeletionPolicy": "Delete" }, - "LambdaInvokef718aff12f12e7e6e6dd823f91dfce23Invoke0C7CC2F4": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "FunctionName": { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - }, - "Principal": { - "Fn::GetAtt": [ - "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73", - "Arn" - ] - } - } - }, - "LambdaInvoke2025c0c4c97e10064ec08312531cb316": { - "Type": "Custom::DeployAssert@SdkCallLambdainvoke", + "HttpApiCallbfb4c2986471eaae77943449a0ea25f6": { + "Type": "Custom::DeployAssert@HttpCall", "Properties": { "ServiceToken": { "Fn::GetAtt": [ @@ -371,77 +141,57 @@ "Arn" ] }, - "service": "Lambda", - "api": "invoke", - "expected": "{\"$ObjectLike\":{\"Payload\":{\"$StringLike\":\"202\"}}}", "parameters": { - "FunctionName": { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - }, - "Payload": { + "url": { "Fn::Join": [ "", [ - "{\"hostname\":\"", + "https://", { "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInteg2Domain70CCEA688A08551F" }, - "\",\"path\":\"/orders/v2/items\"}" + "/orders/v2/items" ] ] - } + }, + "fetchOptions": {} }, - "flattenResponse": "false", - "salt": "1665514871382" + "expected": "{\"$ObjectLike\":{\"body\":{\"message\":\"Hello, world\"},\"ok\":true,\"status\":202}}", + "salt": "1687522738198" }, "UpdateReplacePolicy": "Delete", "DeletionPolicy": "Delete" - }, - "LambdaInvoke2025c0c4c97e10064ec08312531cb316Invoke5ACCC8A3": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "FunctionName": { - "Fn::ImportValue": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - }, - "Principal": { - "Fn::GetAtt": [ - "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73", - "Arn" - ] - } - } } }, "Outputs": { - "AssertionResultsLambdaInvoke6c82f4296e4da69e1d6905e3d20f761a": { + "AssertionResultsHttpApiCall5c7406415c21459755238de5e3d1af86": { "Value": { "Fn::GetAtt": [ - "LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a", + "HttpApiCall5c7406415c21459755238de5e3d1af86", "assertion" ] } }, - "AssertionResultsLambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320": { + "AssertionResultsHttpApiCall87249be5ff18205c5f4320c2baec9418": { "Value": { "Fn::GetAtt": [ - "LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320", + "HttpApiCall87249be5ff18205c5f4320c2baec9418", "assertion" ] } }, - "AssertionResultsLambdaInvokef718aff12f12e7e6e6dd823f91dfce23": { + "AssertionResultsHttpApiCall39df1b9413ee8ef1155877d35e1a132f": { "Value": { "Fn::GetAtt": [ - "LambdaInvokef718aff12f12e7e6e6dd823f91dfce23", + "HttpApiCall39df1b9413ee8ef1155877d35e1a132f", "assertion" ] } }, - "AssertionResultsLambdaInvoke2025c0c4c97e10064ec08312531cb316": { + "AssertionResultsHttpApiCallbfb4c2986471eaae77943449a0ea25f6": { "Value": { "Fn::GetAtt": [ - "LambdaInvoke2025c0c4c97e10064ec08312531cb316", + "HttpApiCallbfb4c2986471eaae77943449a0ea25f6", "assertion" ] } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ-apigw-domain-name-mapping.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ-apigw-domain-name-mapping.assets.json index 4d6328721dcd0..ebdb5d0751dcf 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ-apigw-domain-name-mapping.assets.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ-apigw-domain-name-mapping.assets.json @@ -1,7 +1,7 @@ { - "version": "21.0.0", + "version": "32.0.0", "files": { - "732ce16bf00b2654f30bf4b983582705a052dc86d86378d872853ac7af91ba90": { + "f7ccec973eed5f351a2c2a708c1b11dea556de0ef8c090253df193046ac05e30": { "source": { "path": "integ-apigw-domain-name-mapping.template.json", "packaging": "file" @@ -9,7 +9,7 @@ "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "732ce16bf00b2654f30bf4b983582705a052dc86d86378d872853ac7af91ba90.json", + "objectKey": "f7ccec973eed5f351a2c2a708c1b11dea556de0ef8c090253df193046ac05e30.json", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ-apigw-domain-name-mapping.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ-apigw-domain-name-mapping.template.json index 06810e9960993..d172564a41fdd 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ-apigw-domain-name-mapping.template.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ-apigw-domain-name-mapping.template.json @@ -119,6 +119,125 @@ ] } }, + "IntegApi2IntegApi202F39817F4": { + "Type": "AWS::ApiGateway::RestApi", + "Properties": { + "EndpointConfiguration": { + "Types": [ + "REGIONAL" + ] + }, + "Name": "IntegApi202" + } + }, + "IntegApi2IntegApi202Deployment16A1A56Af8137e7222475e5a9ac210201aa96737": { + "Type": "AWS::ApiGateway::Deployment", + "Properties": { + "RestApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + }, + "Description": "Automatically created by the RestApi construct" + }, + "DependsOn": [ + "IntegApi2IntegApi202GETA6A9E1FD", + "IntegApi2IntegApi202itemsGET3C1B2802", + "IntegApi2IntegApi202items6625F7BA" + ] + }, + "IntegApi2IntegApi202DeploymentStageprod9500285C": { + "Type": "AWS::ApiGateway::Stage", + "Properties": { + "RestApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + }, + "DeploymentId": { + "Ref": "IntegApi2IntegApi202Deployment16A1A56Af8137e7222475e5a9ac210201aa96737" + }, + "StageName": "prod" + } + }, + "IntegApi2IntegApi202items6625F7BA": { + "Type": "AWS::ApiGateway::Resource", + "Properties": { + "ParentId": { + "Fn::GetAtt": [ + "IntegApi2IntegApi202F39817F4", + "RootResourceId" + ] + }, + "PathPart": "items", + "RestApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + } + } + }, + "IntegApi2IntegApi202itemsGET3C1B2802": { + "Type": "AWS::ApiGateway::Method", + "Properties": { + "HttpMethod": "GET", + "ResourceId": { + "Ref": "IntegApi2IntegApi202items6625F7BA" + }, + "RestApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + }, + "AuthorizationType": "NONE", + "Integration": { + "IntegrationResponses": [ + { + "ResponseTemplates": { + "application/json": "{\"message\":\"Hello, world\"}" + }, + "StatusCode": "202" + } + ], + "RequestTemplates": { + "application/json": "{ statusCode: 202 }" + }, + "Type": "MOCK" + }, + "MethodResponses": [ + { + "StatusCode": "202" + } + ] + } + }, + "IntegApi2IntegApi202GETA6A9E1FD": { + "Type": "AWS::ApiGateway::Method", + "Properties": { + "HttpMethod": "GET", + "ResourceId": { + "Fn::GetAtt": [ + "IntegApi2IntegApi202F39817F4", + "RootResourceId" + ] + }, + "RestApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + }, + "AuthorizationType": "NONE", + "Integration": { + "IntegrationResponses": [ + { + "ResponseTemplates": { + "application/json": "{\"message\":\"Hello, world\"}" + }, + "StatusCode": "202" + } + ], + "RequestTemplates": { + "application/json": "{ statusCode: 202 }" + }, + "Type": "MOCK" + }, + "MethodResponses": [ + { + "StatusCode": "202" + } + ] + } + }, "IntegDomain624DF323": { "Type": "AWS::ApiGateway::DomainName", "Properties": { @@ -191,6 +310,28 @@ "ApiMappingKey": "orders/v1" } }, + "IntegDomainRecord": { + "Type": "AWS::Route53::RecordSet", + "Properties": { + "Name": "*.example.com", + "Type": "A", + "AliasTarget": { + "DNSName": { + "Fn::GetAtt": [ + "IntegDomain624DF323", + "RegionalDomainName" + ] + }, + "HostedZoneId": { + "Fn::GetAtt": [ + "IntegDomain624DF323", + "RegionalHostedZoneId" + ] + } + }, + "HostedZoneId": "Z23ABC4XYZL05B" + } + }, "Integ2Domain70CCEA68": { "Type": "AWS::ApiGateway::DomainName", "Properties": { @@ -234,6 +375,28 @@ "ApiMappingKey": "orders/v2" } }, + "Integ2DomainRecord": { + "Type": "AWS::Route53::RecordSet", + "Properties": { + "Name": "another-*.example.com", + "Type": "A", + "AliasTarget": { + "DNSName": { + "Fn::GetAtt": [ + "Integ2Domain70CCEA68", + "RegionalDomainName" + ] + }, + "HostedZoneId": { + "Fn::GetAtt": [ + "Integ2Domain70CCEA68", + "RegionalHostedZoneId" + ] + } + }, + "HostedZoneId": "Z23ABC4XYZL05B" + } + }, "Integ3DomainE531FBAB": { "Type": "AWS::ApiGateway::DomainName", "Properties": { @@ -276,50 +439,6 @@ } } }, - "IntegDomainRecord": { - "Type": "AWS::Route53::RecordSet", - "Properties": { - "Name": "*.example.com", - "Type": "A", - "AliasTarget": { - "DNSName": { - "Fn::GetAtt": [ - "IntegDomain624DF323", - "RegionalDomainName" - ] - }, - "HostedZoneId": { - "Fn::GetAtt": [ - "IntegDomain624DF323", - "RegionalHostedZoneId" - ] - } - }, - "HostedZoneId": "Z23ABC4XYZL05B" - } - }, - "Integ2DomainRecord": { - "Type": "AWS::Route53::RecordSet", - "Properties": { - "Name": "another-*.example.com", - "Type": "A", - "AliasTarget": { - "DNSName": { - "Fn::GetAtt": [ - "Integ2Domain70CCEA68", - "RegionalDomainName" - ] - }, - "HostedZoneId": { - "Fn::GetAtt": [ - "Integ2Domain70CCEA68", - "RegionalHostedZoneId" - ] - } - }, - "HostedZoneId": "Z23ABC4XYZL05B" - } - }, "Integ3DomainRecord": { "Type": "AWS::Route53::RecordSet", "Properties": { @@ -341,175 +460,6 @@ }, "HostedZoneId": "Z23ABC4XYZL05B" } - }, - "IntegApi2IntegApi202F39817F4": { - "Type": "AWS::ApiGateway::RestApi", - "Properties": { - "EndpointConfiguration": { - "Types": [ - "REGIONAL" - ] - }, - "Name": "IntegApi202" - } - }, - "IntegApi2IntegApi202Deployment16A1A56Af8137e7222475e5a9ac210201aa96737": { - "Type": "AWS::ApiGateway::Deployment", - "Properties": { - "RestApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - }, - "Description": "Automatically created by the RestApi construct" - }, - "DependsOn": [ - "IntegApi2IntegApi202GETA6A9E1FD", - "IntegApi2IntegApi202itemsGET3C1B2802", - "IntegApi2IntegApi202items6625F7BA" - ] - }, - "IntegApi2IntegApi202DeploymentStageprod9500285C": { - "Type": "AWS::ApiGateway::Stage", - "Properties": { - "RestApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - }, - "DeploymentId": { - "Ref": "IntegApi2IntegApi202Deployment16A1A56Af8137e7222475e5a9ac210201aa96737" - }, - "StageName": "prod" - } - }, - "IntegApi2IntegApi202items6625F7BA": { - "Type": "AWS::ApiGateway::Resource", - "Properties": { - "ParentId": { - "Fn::GetAtt": [ - "IntegApi2IntegApi202F39817F4", - "RootResourceId" - ] - }, - "PathPart": "items", - "RestApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - } - } - }, - "IntegApi2IntegApi202itemsGET3C1B2802": { - "Type": "AWS::ApiGateway::Method", - "Properties": { - "HttpMethod": "GET", - "ResourceId": { - "Ref": "IntegApi2IntegApi202items6625F7BA" - }, - "RestApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - }, - "AuthorizationType": "NONE", - "Integration": { - "IntegrationResponses": [ - { - "ResponseTemplates": { - "application/json": "{\"message\":\"Hello, world\"}" - }, - "StatusCode": "202" - } - ], - "RequestTemplates": { - "application/json": "{ statusCode: 202 }" - }, - "Type": "MOCK" - }, - "MethodResponses": [ - { - "StatusCode": "202" - } - ] - } - }, - "IntegApi2IntegApi202GETA6A9E1FD": { - "Type": "AWS::ApiGateway::Method", - "Properties": { - "HttpMethod": "GET", - "ResourceId": { - "Fn::GetAtt": [ - "IntegApi2IntegApi202F39817F4", - "RootResourceId" - ] - }, - "RestApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - }, - "AuthorizationType": "NONE", - "Integration": { - "IntegrationResponses": [ - { - "ResponseTemplates": { - "application/json": "{\"message\":\"Hello, world\"}" - }, - "StatusCode": "202" - } - ], - "RequestTemplates": { - "application/json": "{ statusCode: 202 }" - }, - "Type": "MOCK" - }, - "MethodResponses": [ - { - "StatusCode": "202" - } - ] - } - }, - "InvokeApiServiceRoleFB17CD97": { - "Type": "AWS::IAM::Role", - "Properties": { - "AssumeRolePolicyDocument": { - "Statement": [ - { - "Action": "sts:AssumeRole", - "Effect": "Allow", - "Principal": { - "Service": "lambda.amazonaws.com" - } - } - ], - "Version": "2012-10-17" - }, - "ManagedPolicyArns": [ - { - "Fn::Join": [ - "", - [ - "arn:", - { - "Ref": "AWS::Partition" - }, - ":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - ] - ] - } - ] - } - }, - "InvokeApi313C8B49": { - "Type": "AWS::Lambda::Function", - "Properties": { - "Code": { - "ZipFile": "\nconst https = require('https');\nexports.handler = async function(event) {\n console.log(event);\n const options = {\n hostname: event.hostname,\n path: event.path,\n };\n let dataString = '';\n const response = await new Promise((resolve, reject) => {\n const req = https.get(options, (res) => {\n res.on('data', data => {\n dataString += data;\n })\n res.on('end', () => {\n resolve({\n statusCode: res.statusCode,\n body: dataString,\n });\n })\n });\n req.on('error', err => {\n reject({\n statusCode: 500,\n body: JSON.stringify({\n cause: 'Something went wrong',\n error: err,\n })\n });\n });\n req.end();\n });\n return response;\n}\n\n" - }, - "Role": { - "Fn::GetAtt": [ - "InvokeApiServiceRoleFB17CD97", - "Arn" - ] - }, - "Handler": "index.handler", - "Runtime": "nodejs16.x" - }, - "DependsOn": [ - "InvokeApiServiceRoleFB17CD97" - ] } }, "Outputs": { @@ -565,14 +515,6 @@ ] } }, - "ExportsOutputRefInvokeApi313C8B4949AC2AFC": { - "Value": { - "Ref": "InvokeApi313C8B49" - }, - "Export": { - "Name": "integ-apigw-domain-name-mapping:ExportsOutputRefInvokeApi313C8B4949AC2AFC" - } - }, "ExportsOutputRefIntegDomain624DF323D17B7540": { "Value": { "Ref": "IntegDomain624DF323" diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ.json index db70a8549af6b..c30eca177760f 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/integ.json @@ -1,6 +1,6 @@ { "enableLookups": true, - "version": "21.0.0", + "version": "32.0.0", "testCases": { "domain-name-mapping-test/DefaultTest": { "stacks": [ diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/manifest.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/manifest.json index 9a8e006b62584..6f116822dad92 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/manifest.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/manifest.json @@ -1,12 +1,6 @@ { - "version": "21.0.0", + "version": "32.0.0", "artifacts": { - "Tree": { - "type": "cdk:tree", - "properties": { - "file": "tree.json" - } - }, "integ-apigw-domain-name-mapping.assets": { "type": "cdk:asset-manifest", "properties": { @@ -23,7 +17,7 @@ "validateOnSynth": false, "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", - "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/732ce16bf00b2654f30bf4b983582705a052dc86d86378d872853ac7af91ba90.json", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/f7ccec973eed5f351a2c2a708c1b11dea556de0ef8c090253df193046ac05e30.json", "requiresBootstrapStackVersion": 6, "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", "additionalDependencies": [ @@ -81,148 +75,130 @@ "data": "IntegApi1IntegApi201GET725FD00E" } ], - "/integ-apigw-domain-name-mapping/IntegDomain/Resource": [ - { - "type": "aws:cdk:logicalId", - "data": "IntegDomain624DF323" - } - ], - "/integ-apigw-domain-name-mapping/IntegDomain/Map:--=>integapigwdomainnamemappingIntegApi1IntegApi201817D4F3E/Resource": [ - { - "type": "aws:cdk:logicalId", - "data": "IntegDomainMapintegapigwdomainnamemappingIntegApi1IntegApi201817D4F3E86701596" - } - ], - "/integ-apigw-domain-name-mapping/IntegDomain/Map:orders=>integapigwdomainnamemappingIntegApi1IntegApi201817D4F3E/Resource": [ - { - "type": "aws:cdk:logicalId", - "data": "IntegDomainMapordersintegapigwdomainnamemappingIntegApi1IntegApi201817D4F3E1F08DBEE" - } - ], - "/integ-apigw-domain-name-mapping/IntegDomain/Map:orders--v2=>integapigwdomainnamemappingIntegApi2IntegApi202DeploymentStageprodDA7FC3FE": [ + "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Resource": [ { "type": "aws:cdk:logicalId", - "data": "IntegDomainMapordersv2integapigwdomainnamemappingIntegApi2IntegApi202DeploymentStageprodDA7FC3FE3C3CDD8F" + "data": "IntegApi2IntegApi202F39817F4" } ], - "/integ-apigw-domain-name-mapping/IntegDomain/Map:orders--v1=>integapigwdomainnamemappingIntegApi1IntegApi201DeploymentStageprod556D5976": [ + "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Deployment/Resource": [ { "type": "aws:cdk:logicalId", - "data": "IntegDomainMapordersv1integapigwdomainnamemappingIntegApi1IntegApi201DeploymentStageprod556D59765598DA9A" + "data": "IntegApi2IntegApi202Deployment16A1A56Af8137e7222475e5a9ac210201aa96737" } ], - "/integ-apigw-domain-name-mapping/Integ2Domain/Resource": [ + "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/DeploymentStage.prod/Resource": [ { "type": "aws:cdk:logicalId", - "data": "Integ2Domain70CCEA68" + "data": "IntegApi2IntegApi202DeploymentStageprod9500285C" } ], - "/integ-apigw-domain-name-mapping/Integ2Domain/Map:orders=>integapigwdomainnamemappingIntegApi1IntegApi201817D4F3E/Resource": [ + "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Endpoint": [ { "type": "aws:cdk:logicalId", - "data": "Integ2DomainMapordersintegapigwdomainnamemappingIntegApi1IntegApi201817D4F3E604CCBD9" + "data": "IntegApi2IntegApi202Endpoint18343E9B" } ], - "/integ-apigw-domain-name-mapping/Integ2Domain/Map:orders--v2=>integapigwdomainnamemappingIntegApi2IntegApi202DeploymentStageprodDA7FC3FE": [ + "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/Resource": [ { "type": "aws:cdk:logicalId", - "data": "Integ2DomainMapordersv2integapigwdomainnamemappingIntegApi2IntegApi202DeploymentStageprodDA7FC3FECE78C5AD" + "data": "IntegApi2IntegApi202items6625F7BA" } ], - "/integ-apigw-domain-name-mapping/Integ3Domain/Resource": [ + "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/GET/Resource": [ { "type": "aws:cdk:logicalId", - "data": "Integ3DomainE531FBAB" + "data": "IntegApi2IntegApi202itemsGET3C1B2802" } ], - "/integ-apigw-domain-name-mapping/Integ3Domain/Map:--=>integapigwdomainnamemappingIntegApi1IntegApi201817D4F3E/Resource": [ + "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/GET/Resource": [ { "type": "aws:cdk:logicalId", - "data": "Integ3DomainMapintegapigwdomainnamemappingIntegApi1IntegApi201817D4F3EC2A223F3" + "data": "IntegApi2IntegApi202GETA6A9E1FD" } ], - "/integ-apigw-domain-name-mapping/Integ3Domain/Map:v2=>integapigwdomainnamemappingIntegApi2IntegApi20289438F2B/Resource": [ + "/integ-apigw-domain-name-mapping/IntegDomain/Resource": [ { "type": "aws:cdk:logicalId", - "data": "Integ3DomainMapv2integapigwdomainnamemappingIntegApi2IntegApi20289438F2BD839069D" + "data": "IntegDomain624DF323" } ], - "/integ-apigw-domain-name-mapping/IntegDomainRecord": [ + "/integ-apigw-domain-name-mapping/IntegDomain/Map:--=>integapigwdomainnamemappingIntegApi1IntegApi201817D4F3E/Resource": [ { "type": "aws:cdk:logicalId", - "data": "IntegDomainRecord" + "data": "IntegDomainMapintegapigwdomainnamemappingIntegApi1IntegApi201817D4F3E86701596" } ], - "/integ-apigw-domain-name-mapping/Integ2DomainRecord": [ + "/integ-apigw-domain-name-mapping/IntegDomain/Map:orders=>integapigwdomainnamemappingIntegApi1IntegApi201817D4F3E/Resource": [ { "type": "aws:cdk:logicalId", - "data": "Integ2DomainRecord" + "data": "IntegDomainMapordersintegapigwdomainnamemappingIntegApi1IntegApi201817D4F3E1F08DBEE" } ], - "/integ-apigw-domain-name-mapping/Integ3DomainRecord": [ + "/integ-apigw-domain-name-mapping/IntegDomain/Map:orders--v2=>integapigwdomainnamemappingIntegApi2IntegApi202DeploymentStageprodDA7FC3FE": [ { "type": "aws:cdk:logicalId", - "data": "Integ3DomainRecord" + "data": "IntegDomainMapordersv2integapigwdomainnamemappingIntegApi2IntegApi202DeploymentStageprodDA7FC3FE3C3CDD8F" } ], - "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Resource": [ + "/integ-apigw-domain-name-mapping/IntegDomain/Map:orders--v1=>integapigwdomainnamemappingIntegApi1IntegApi201DeploymentStageprod556D5976": [ { "type": "aws:cdk:logicalId", - "data": "IntegApi2IntegApi202F39817F4" + "data": "IntegDomainMapordersv1integapigwdomainnamemappingIntegApi1IntegApi201DeploymentStageprod556D59765598DA9A" } ], - "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Deployment/Resource": [ + "/integ-apigw-domain-name-mapping/IntegDomainRecord": [ { "type": "aws:cdk:logicalId", - "data": "IntegApi2IntegApi202Deployment16A1A56Af8137e7222475e5a9ac210201aa96737" + "data": "IntegDomainRecord" } ], - "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/DeploymentStage.prod/Resource": [ + "/integ-apigw-domain-name-mapping/Integ2Domain/Resource": [ { "type": "aws:cdk:logicalId", - "data": "IntegApi2IntegApi202DeploymentStageprod9500285C" + "data": "Integ2Domain70CCEA68" } ], - "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Endpoint": [ + "/integ-apigw-domain-name-mapping/Integ2Domain/Map:orders=>integapigwdomainnamemappingIntegApi1IntegApi201817D4F3E/Resource": [ { "type": "aws:cdk:logicalId", - "data": "IntegApi2IntegApi202Endpoint18343E9B" + "data": "Integ2DomainMapordersintegapigwdomainnamemappingIntegApi1IntegApi201817D4F3E604CCBD9" } ], - "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/Resource": [ + "/integ-apigw-domain-name-mapping/Integ2Domain/Map:orders--v2=>integapigwdomainnamemappingIntegApi2IntegApi202DeploymentStageprodDA7FC3FE": [ { "type": "aws:cdk:logicalId", - "data": "IntegApi2IntegApi202items6625F7BA" + "data": "Integ2DomainMapordersv2integapigwdomainnamemappingIntegApi2IntegApi202DeploymentStageprodDA7FC3FECE78C5AD" } ], - "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/GET/Resource": [ + "/integ-apigw-domain-name-mapping/Integ2DomainRecord": [ { "type": "aws:cdk:logicalId", - "data": "IntegApi2IntegApi202itemsGET3C1B2802" + "data": "Integ2DomainRecord" } ], - "/integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/GET/Resource": [ + "/integ-apigw-domain-name-mapping/Integ3Domain/Resource": [ { "type": "aws:cdk:logicalId", - "data": "IntegApi2IntegApi202GETA6A9E1FD" + "data": "Integ3DomainE531FBAB" } ], - "/integ-apigw-domain-name-mapping/InvokeApi/ServiceRole/Resource": [ + "/integ-apigw-domain-name-mapping/Integ3Domain/Map:--=>integapigwdomainnamemappingIntegApi1IntegApi201817D4F3E/Resource": [ { "type": "aws:cdk:logicalId", - "data": "InvokeApiServiceRoleFB17CD97" + "data": "Integ3DomainMapintegapigwdomainnamemappingIntegApi1IntegApi201817D4F3EC2A223F3" } ], - "/integ-apigw-domain-name-mapping/InvokeApi/Resource": [ + "/integ-apigw-domain-name-mapping/Integ3Domain/Map:v2=>integapigwdomainnamemappingIntegApi2IntegApi20289438F2B/Resource": [ { "type": "aws:cdk:logicalId", - "data": "InvokeApi313C8B49" + "data": "Integ3DomainMapv2integapigwdomainnamemappingIntegApi2IntegApi20289438F2BD839069D" } ], - "/integ-apigw-domain-name-mapping/Exports/Output{\"Ref\":\"InvokeApi313C8B49\"}": [ + "/integ-apigw-domain-name-mapping/Integ3DomainRecord": [ { "type": "aws:cdk:logicalId", - "data": "ExportsOutputRefInvokeApi313C8B4949AC2AFC" + "data": "Integ3DomainRecord" } ], "/integ-apigw-domain-name-mapping/Exports/Output{\"Ref\":\"IntegDomain624DF323\"}": [ @@ -248,15 +224,6 @@ "type": "aws:cdk:logicalId", "data": "CheckBootstrapVersion" } - ], - "Integ2DomainMapordersintegapigwdomainnamemappingIntegApi1IntegApi201DeploymentStageprod556D59769E7794A6": [ - { - "type": "aws:cdk:logicalId", - "data": "Integ2DomainMapordersintegapigwdomainnamemappingIntegApi1IntegApi201DeploymentStageprod556D59769E7794A6", - "trace": [ - "!!DESTRUCTIVE_CHANGES: WILL_DESTROY" - ] - } ] }, "displayName": "integ-apigw-domain-name-mapping" @@ -277,7 +244,7 @@ "validateOnSynth": false, "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", - "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/ca221fe7d8415bb5d7851fa5f77af9fa55569243f4832c489ac239a1a9ccf4ca.json", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/a964cf65aae2e23802c1975a0c39add8b0c2e59296daad40cc71353166b3685f.json", "requiresBootstrapStackVersion": 6, "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", "additionalDependencies": [ @@ -294,22 +261,16 @@ "domainnamemappingtestDefaultTestDeployAssert4FFC8047.assets" ], "metadata": { - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/Default/Default": [ - { - "type": "aws:cdk:logicalId", - "data": "LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a" - } - ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/Invoke": [ + "/domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall5c7406415c21459755238de5e3d1af86/Default/Default": [ { "type": "aws:cdk:logicalId", - "data": "LambdaInvoke6c82f4296e4da69e1d6905e3d20f761aInvokeF34C6427" + "data": "HttpApiCall5c7406415c21459755238de5e3d1af86" } ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/AssertionResults": [ + "/domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall5c7406415c21459755238de5e3d1af86/AssertionResults": [ { "type": "aws:cdk:logicalId", - "data": "AssertionResultsLambdaInvoke6c82f4296e4da69e1d6905e3d20f761a" + "data": "AssertionResultsHttpApiCall5c7406415c21459755238de5e3d1af86" } ], "/domain-name-mapping-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role": [ @@ -324,58 +285,40 @@ "data": "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F" } ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/Default/Default": [ - { - "type": "aws:cdk:logicalId", - "data": "LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320" - } - ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/Invoke": [ - { - "type": "aws:cdk:logicalId", - "data": "LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320InvokeC08B85F1" - } - ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/AssertionResults": [ - { - "type": "aws:cdk:logicalId", - "data": "AssertionResultsLambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320" - } - ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/Default/Default": [ + "/domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall87249be5ff18205c5f4320c2baec9418/Default/Default": [ { "type": "aws:cdk:logicalId", - "data": "LambdaInvokef718aff12f12e7e6e6dd823f91dfce23" + "data": "HttpApiCall87249be5ff18205c5f4320c2baec9418" } ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/Invoke": [ + "/domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall87249be5ff18205c5f4320c2baec9418/AssertionResults": [ { "type": "aws:cdk:logicalId", - "data": "LambdaInvokef718aff12f12e7e6e6dd823f91dfce23Invoke0C7CC2F4" + "data": "AssertionResultsHttpApiCall87249be5ff18205c5f4320c2baec9418" } ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/AssertionResults": [ + "/domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall39df1b9413ee8ef1155877d35e1a132f/Default/Default": [ { "type": "aws:cdk:logicalId", - "data": "AssertionResultsLambdaInvokef718aff12f12e7e6e6dd823f91dfce23" + "data": "HttpApiCall39df1b9413ee8ef1155877d35e1a132f" } ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/Default/Default": [ + "/domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall39df1b9413ee8ef1155877d35e1a132f/AssertionResults": [ { "type": "aws:cdk:logicalId", - "data": "LambdaInvoke2025c0c4c97e10064ec08312531cb316" + "data": "AssertionResultsHttpApiCall39df1b9413ee8ef1155877d35e1a132f" } ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/Invoke": [ + "/domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCallbfb4c2986471eaae77943449a0ea25f6/Default/Default": [ { "type": "aws:cdk:logicalId", - "data": "LambdaInvoke2025c0c4c97e10064ec08312531cb316Invoke5ACCC8A3" + "data": "HttpApiCallbfb4c2986471eaae77943449a0ea25f6" } ], - "/domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/AssertionResults": [ + "/domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCallbfb4c2986471eaae77943449a0ea25f6/AssertionResults": [ { "type": "aws:cdk:logicalId", - "data": "AssertionResultsLambdaInvoke2025c0c4c97e10064ec08312531cb316" + "data": "AssertionResultsHttpApiCallbfb4c2986471eaae77943449a0ea25f6" } ], "/domain-name-mapping-test/DefaultTest/DeployAssert/BootstrapVersion": [ @@ -392,6 +335,12 @@ ] }, "displayName": "domain-name-mapping-test/DefaultTest/DeployAssert" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } } } } \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/tree.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/tree.json index e8f305f9bd52c..0e2a31da27ac9 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/tree.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.js.snapshot/tree.json @@ -4,14 +4,6 @@ "id": "App", "path": "", "children": { - "Tree": { - "id": "Tree", - "path": "Tree", - "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.108" - } - }, "integ-apigw-domain-name-mapping": { "id": "integ-apigw-domain-name-mapping", "path": "integ-apigw-domain-name-mapping", @@ -20,7 +12,7 @@ "id": "Cert", "path": "integ-apigw-domain-name-mapping/Cert", "constructInfo": { - "fqn": "@aws-cdk/core.Resource", + "fqn": "aws-cdk-lib.Resource", "version": "0.0.0" } }, @@ -47,7 +39,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnRestApi", + "fqn": "aws-cdk-lib.aws_apigateway.CfnRestApi", "version": "0.0.0" } }, @@ -68,13 +60,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnDeployment", + "fqn": "aws-cdk-lib.aws_apigateway.CfnDeployment", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Deployment", + "fqn": "aws-cdk-lib.aws_apigateway.Deployment", "version": "0.0.0" } }, @@ -98,13 +90,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnStage", + "fqn": "aws-cdk-lib.aws_apigateway.CfnStage", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Stage", + "fqn": "aws-cdk-lib.aws_apigateway.Stage", "version": "0.0.0" } }, @@ -112,7 +104,7 @@ "id": "Endpoint", "path": "integ-apigw-domain-name-mapping/IntegApi1/IntegApi201/Endpoint", "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", + "fqn": "aws-cdk-lib.CfnOutput", "version": "0.0.0" } }, @@ -143,7 +135,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnResource", + "fqn": "aws-cdk-lib.aws_apigateway.CfnResource", "version": "0.0.0" } }, @@ -187,19 +179,19 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnMethod", + "fqn": "aws-cdk-lib.aws_apigateway.CfnMethod", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Method", + "fqn": "aws-cdk-lib.aws_apigateway.Method", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Resource", + "fqn": "aws-cdk-lib.aws_apigateway.Resource", "version": "0.0.0" } }, @@ -246,32 +238,282 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnMethod", + "fqn": "aws-cdk-lib.aws_apigateway.CfnMethod", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.Method", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.ResourceBase", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.RestApi", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "IntegApi2": { + "id": "IntegApi2", + "path": "integ-apigw-domain-name-mapping/IntegApi2", + "children": { + "IntegApi202": { + "id": "IntegApi202", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202", + "children": { + "Resource": { + "id": "Resource", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::ApiGateway::RestApi", + "aws:cdk:cloudformation:props": { + "endpointConfiguration": { + "types": [ + "REGIONAL" + ] + }, + "name": "IntegApi202" + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.CfnRestApi", + "version": "0.0.0" + } + }, + "Deployment": { + "id": "Deployment", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Deployment", + "children": { + "Resource": { + "id": "Resource", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Deployment/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::ApiGateway::Deployment", + "aws:cdk:cloudformation:props": { + "restApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + }, + "description": "Automatically created by the RestApi construct" + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.CfnDeployment", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.Deployment", + "version": "0.0.0" + } + }, + "DeploymentStage.prod": { + "id": "DeploymentStage.prod", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/DeploymentStage.prod", + "children": { + "Resource": { + "id": "Resource", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/DeploymentStage.prod/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::ApiGateway::Stage", + "aws:cdk:cloudformation:props": { + "restApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + }, + "deploymentId": { + "Ref": "IntegApi2IntegApi202Deployment16A1A56Af8137e7222475e5a9ac210201aa96737" + }, + "stageName": "prod" + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.CfnStage", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.Stage", + "version": "0.0.0" + } + }, + "Endpoint": { + "id": "Endpoint", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Endpoint", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnOutput", + "version": "0.0.0" + } + }, + "Default": { + "id": "Default", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default", + "children": { + "items": { + "id": "items", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items", + "children": { + "Resource": { + "id": "Resource", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::ApiGateway::Resource", + "aws:cdk:cloudformation:props": { + "parentId": { + "Fn::GetAtt": [ + "IntegApi2IntegApi202F39817F4", + "RootResourceId" + ] + }, + "pathPart": "items", + "restApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.CfnResource", + "version": "0.0.0" + } + }, + "GET": { + "id": "GET", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/GET", + "children": { + "Resource": { + "id": "Resource", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/GET/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::ApiGateway::Method", + "aws:cdk:cloudformation:props": { + "httpMethod": "GET", + "resourceId": { + "Ref": "IntegApi2IntegApi202items6625F7BA" + }, + "restApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + }, + "authorizationType": "NONE", + "integration": { + "type": "MOCK", + "requestTemplates": { + "application/json": "{ statusCode: 202 }" + }, + "integrationResponses": [ + { + "statusCode": "202", + "responseTemplates": { + "application/json": "{\"message\":\"Hello, world\"}" + } + } + ] + }, + "methodResponses": [ + { + "statusCode": "202" + } + ] + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.CfnMethod", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.Method", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.Resource", + "version": "0.0.0" + } + }, + "GET": { + "id": "GET", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/GET", + "children": { + "Resource": { + "id": "Resource", + "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/GET/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::ApiGateway::Method", + "aws:cdk:cloudformation:props": { + "httpMethod": "GET", + "resourceId": { + "Fn::GetAtt": [ + "IntegApi2IntegApi202F39817F4", + "RootResourceId" + ] + }, + "restApiId": { + "Ref": "IntegApi2IntegApi202F39817F4" + }, + "authorizationType": "NONE", + "integration": { + "type": "MOCK", + "requestTemplates": { + "application/json": "{ statusCode: 202 }" + }, + "integrationResponses": [ + { + "statusCode": "202", + "responseTemplates": { + "application/json": "{\"message\":\"Hello, world\"}" + } + } + ] + }, + "methodResponses": [ + { + "statusCode": "202" + } + ] + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_apigateway.CfnMethod", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Method", + "fqn": "aws-cdk-lib.aws_apigateway.Method", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.ResourceBase", + "fqn": "aws-cdk-lib.aws_apigateway.ResourceBase", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.RestApi", + "fqn": "aws-cdk-lib.aws_apigateway.RestApi", "version": "0.0.0" } } }, "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.108" + "version": "10.2.55" } }, "IntegDomain": { @@ -295,7 +537,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnDomainName", + "fqn": "aws-cdk-lib.aws_apigateway.CfnDomainName", "version": "0.0.0" } }, @@ -321,13 +563,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnBasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.CfnBasePathMapping", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.BasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.BasePathMapping", "version": "0.0.0" } }, @@ -354,13 +596,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnBasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.CfnBasePathMapping", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.BasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.BasePathMapping", "version": "0.0.0" } }, @@ -383,7 +625,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigatewayv2.CfnApiMapping", + "fqn": "aws-cdk-lib.aws_apigatewayv2.CfnApiMapping", "version": "0.0.0" } }, @@ -406,30 +648,60 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigatewayv2.CfnApiMapping", + "fqn": "aws-cdk-lib.aws_apigatewayv2.CfnApiMapping", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.DomainName", + "fqn": "aws-cdk-lib.aws_apigateway.DomainName", "version": "0.0.0" } }, - "Integ2Domain": { - "id": "Integ2Domain", - "path": "integ-apigw-domain-name-mapping/Integ2Domain", - "children": { - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/Integ2Domain/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::ApiGateway::DomainName", - "aws:cdk:cloudformation:props": { - "domainName": "another-*.example.com", - "endpointConfiguration": { - "types": [ - "REGIONAL" + "IntegDomainRecord": { + "id": "IntegDomainRecord", + "path": "integ-apigw-domain-name-mapping/IntegDomainRecord", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::Route53::RecordSet", + "aws:cdk:cloudformation:props": { + "name": "*.example.com", + "type": "A", + "aliasTarget": { + "hostedZoneId": { + "Fn::GetAtt": [ + "IntegDomain624DF323", + "RegionalHostedZoneId" + ] + }, + "dnsName": { + "Fn::GetAtt": [ + "IntegDomain624DF323", + "RegionalDomainName" + ] + } + }, + "hostedZoneId": "Z23ABC4XYZL05B" + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_route53.CfnRecordSet", + "version": "0.0.0" + } + }, + "Integ2Domain": { + "id": "Integ2Domain", + "path": "integ-apigw-domain-name-mapping/Integ2Domain", + "children": { + "Resource": { + "id": "Resource", + "path": "integ-apigw-domain-name-mapping/Integ2Domain/Resource", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::ApiGateway::DomainName", + "aws:cdk:cloudformation:props": { + "domainName": "another-*.example.com", + "endpointConfiguration": { + "types": [ + "REGIONAL" ] }, "regionalCertificateArn": "arn:aws:acm:test-region:12345678:certificate/86468209-a272-595d-b831-0efb6421265z", @@ -437,7 +709,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnDomainName", + "fqn": "aws-cdk-lib.aws_apigateway.CfnDomainName", "version": "0.0.0" } }, @@ -464,13 +736,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnBasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.CfnBasePathMapping", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.BasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.BasePathMapping", "version": "0.0.0" } }, @@ -493,13 +765,43 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigatewayv2.CfnApiMapping", + "fqn": "aws-cdk-lib.aws_apigatewayv2.CfnApiMapping", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.DomainName", + "fqn": "aws-cdk-lib.aws_apigateway.DomainName", + "version": "0.0.0" + } + }, + "Integ2DomainRecord": { + "id": "Integ2DomainRecord", + "path": "integ-apigw-domain-name-mapping/Integ2DomainRecord", + "attributes": { + "aws:cdk:cloudformation:type": "AWS::Route53::RecordSet", + "aws:cdk:cloudformation:props": { + "name": "another-*.example.com", + "type": "A", + "aliasTarget": { + "hostedZoneId": { + "Fn::GetAtt": [ + "Integ2Domain70CCEA68", + "RegionalHostedZoneId" + ] + }, + "dnsName": { + "Fn::GetAtt": [ + "Integ2Domain70CCEA68", + "RegionalDomainName" + ] + } + }, + "hostedZoneId": "Z23ABC4XYZL05B" + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_route53.CfnRecordSet", "version": "0.0.0" } }, @@ -524,7 +826,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnDomainName", + "fqn": "aws-cdk-lib.aws_apigateway.CfnDomainName", "version": "0.0.0" } }, @@ -550,13 +852,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnBasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.CfnBasePathMapping", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.BasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.BasePathMapping", "version": "0.0.0" } }, @@ -583,79 +885,19 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnBasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.CfnBasePathMapping", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.BasePathMapping", + "fqn": "aws-cdk-lib.aws_apigateway.BasePathMapping", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.DomainName", - "version": "0.0.0" - } - }, - "IntegDomainRecord": { - "id": "IntegDomainRecord", - "path": "integ-apigw-domain-name-mapping/IntegDomainRecord", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::Route53::RecordSet", - "aws:cdk:cloudformation:props": { - "name": "*.example.com", - "type": "A", - "aliasTarget": { - "hostedZoneId": { - "Fn::GetAtt": [ - "IntegDomain624DF323", - "RegionalHostedZoneId" - ] - }, - "dnsName": { - "Fn::GetAtt": [ - "IntegDomain624DF323", - "RegionalDomainName" - ] - } - }, - "hostedZoneId": "Z23ABC4XYZL05B" - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-route53.CfnRecordSet", - "version": "0.0.0" - } - }, - "Integ2DomainRecord": { - "id": "Integ2DomainRecord", - "path": "integ-apigw-domain-name-mapping/Integ2DomainRecord", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::Route53::RecordSet", - "aws:cdk:cloudformation:props": { - "name": "another-*.example.com", - "type": "A", - "aliasTarget": { - "hostedZoneId": { - "Fn::GetAtt": [ - "Integ2Domain70CCEA68", - "RegionalHostedZoneId" - ] - }, - "dnsName": { - "Fn::GetAtt": [ - "Integ2Domain70CCEA68", - "RegionalDomainName" - ] - } - }, - "hostedZoneId": "Z23ABC4XYZL05B" - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-route53.CfnRecordSet", + "fqn": "aws-cdk-lib.aws_apigateway.DomainName", "version": "0.0.0" } }, @@ -685,340 +927,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-route53.CfnRecordSet", - "version": "0.0.0" - } - }, - "IntegApi2": { - "id": "IntegApi2", - "path": "integ-apigw-domain-name-mapping/IntegApi2", - "children": { - "IntegApi202": { - "id": "IntegApi202", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202", - "children": { - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::ApiGateway::RestApi", - "aws:cdk:cloudformation:props": { - "endpointConfiguration": { - "types": [ - "REGIONAL" - ] - }, - "name": "IntegApi202" - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnRestApi", - "version": "0.0.0" - } - }, - "Deployment": { - "id": "Deployment", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Deployment", - "children": { - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Deployment/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::ApiGateway::Deployment", - "aws:cdk:cloudformation:props": { - "restApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - }, - "description": "Automatically created by the RestApi construct" - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnDeployment", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Deployment", - "version": "0.0.0" - } - }, - "DeploymentStage.prod": { - "id": "DeploymentStage.prod", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/DeploymentStage.prod", - "children": { - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/DeploymentStage.prod/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::ApiGateway::Stage", - "aws:cdk:cloudformation:props": { - "restApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - }, - "deploymentId": { - "Ref": "IntegApi2IntegApi202Deployment16A1A56Af8137e7222475e5a9ac210201aa96737" - }, - "stageName": "prod" - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnStage", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Stage", - "version": "0.0.0" - } - }, - "Endpoint": { - "id": "Endpoint", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Endpoint", - "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", - "version": "0.0.0" - } - }, - "Default": { - "id": "Default", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default", - "children": { - "items": { - "id": "items", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items", - "children": { - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::ApiGateway::Resource", - "aws:cdk:cloudformation:props": { - "parentId": { - "Fn::GetAtt": [ - "IntegApi2IntegApi202F39817F4", - "RootResourceId" - ] - }, - "pathPart": "items", - "restApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnResource", - "version": "0.0.0" - } - }, - "GET": { - "id": "GET", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/GET", - "children": { - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/items/GET/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::ApiGateway::Method", - "aws:cdk:cloudformation:props": { - "httpMethod": "GET", - "resourceId": { - "Ref": "IntegApi2IntegApi202items6625F7BA" - }, - "restApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - }, - "authorizationType": "NONE", - "integration": { - "type": "MOCK", - "requestTemplates": { - "application/json": "{ statusCode: 202 }" - }, - "integrationResponses": [ - { - "statusCode": "202", - "responseTemplates": { - "application/json": "{\"message\":\"Hello, world\"}" - } - } - ] - }, - "methodResponses": [ - { - "statusCode": "202" - } - ] - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnMethod", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Method", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Resource", - "version": "0.0.0" - } - }, - "GET": { - "id": "GET", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/GET", - "children": { - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/IntegApi2/IntegApi202/Default/GET/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::ApiGateway::Method", - "aws:cdk:cloudformation:props": { - "httpMethod": "GET", - "resourceId": { - "Fn::GetAtt": [ - "IntegApi2IntegApi202F39817F4", - "RootResourceId" - ] - }, - "restApiId": { - "Ref": "IntegApi2IntegApi202F39817F4" - }, - "authorizationType": "NONE", - "integration": { - "type": "MOCK", - "requestTemplates": { - "application/json": "{ statusCode: 202 }" - }, - "integrationResponses": [ - { - "statusCode": "202", - "responseTemplates": { - "application/json": "{\"message\":\"Hello, world\"}" - } - } - ] - }, - "methodResponses": [ - { - "statusCode": "202" - } - ] - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnMethod", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Method", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.ResourceBase", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.RestApi", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.108" - } - }, - "InvokeApi": { - "id": "InvokeApi", - "path": "integ-apigw-domain-name-mapping/InvokeApi", - "children": { - "ServiceRole": { - "id": "ServiceRole", - "path": "integ-apigw-domain-name-mapping/InvokeApi/ServiceRole", - "children": { - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/InvokeApi/ServiceRole/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::IAM::Role", - "aws:cdk:cloudformation:props": { - "assumeRolePolicyDocument": { - "Statement": [ - { - "Action": "sts:AssumeRole", - "Effect": "Allow", - "Principal": { - "Service": "lambda.amazonaws.com" - } - } - ], - "Version": "2012-10-17" - }, - "managedPolicyArns": [ - { - "Fn::Join": [ - "", - [ - "arn:", - { - "Ref": "AWS::Partition" - }, - ":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - ] - ] - } - ] - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-iam.CfnRole", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-iam.Role", - "version": "0.0.0" - } - }, - "Resource": { - "id": "Resource", - "path": "integ-apigw-domain-name-mapping/InvokeApi/Resource", - "attributes": { - "aws:cdk:cloudformation:type": "AWS::Lambda::Function", - "aws:cdk:cloudformation:props": { - "code": { - "zipFile": "\nconst https = require('https');\nexports.handler = async function(event) {\n console.log(event);\n const options = {\n hostname: event.hostname,\n path: event.path,\n };\n let dataString = '';\n const response = await new Promise((resolve, reject) => {\n const req = https.get(options, (res) => {\n res.on('data', data => {\n dataString += data;\n })\n res.on('end', () => {\n resolve({\n statusCode: res.statusCode,\n body: dataString,\n });\n })\n });\n req.on('error', err => {\n reject({\n statusCode: 500,\n body: JSON.stringify({\n cause: 'Something went wrong',\n error: err,\n })\n });\n });\n req.end();\n });\n return response;\n}\n\n" - }, - "role": { - "Fn::GetAtt": [ - "InvokeApiServiceRoleFB17CD97", - "Arn" - ] - }, - "handler": "index.handler", - "runtime": "nodejs16.x" - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.CfnFunction", - "version": "0.0.0" - } - } - }, - "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.Function", + "fqn": "aws-cdk-lib.aws_route53.CfnRecordSet", "version": "0.0.0" } }, @@ -1026,19 +935,11 @@ "id": "Exports", "path": "integ-apigw-domain-name-mapping/Exports", "children": { - "Output{\"Ref\":\"InvokeApi313C8B49\"}": { - "id": "Output{\"Ref\":\"InvokeApi313C8B49\"}", - "path": "integ-apigw-domain-name-mapping/Exports/Output{\"Ref\":\"InvokeApi313C8B49\"}", - "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", - "version": "0.0.0" - } - }, "Output{\"Ref\":\"IntegDomain624DF323\"}": { "id": "Output{\"Ref\":\"IntegDomain624DF323\"}", "path": "integ-apigw-domain-name-mapping/Exports/Output{\"Ref\":\"IntegDomain624DF323\"}", "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", + "fqn": "aws-cdk-lib.CfnOutput", "version": "0.0.0" } }, @@ -1046,19 +947,35 @@ "id": "Output{\"Ref\":\"Integ2Domain70CCEA68\"}", "path": "integ-apigw-domain-name-mapping/Exports/Output{\"Ref\":\"Integ2Domain70CCEA68\"}", "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", + "fqn": "aws-cdk-lib.CfnOutput", "version": "0.0.0" } } }, "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.108" + "version": "10.2.55" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "integ-apigw-domain-name-mapping/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "integ-apigw-domain-name-mapping/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/core.Stack", + "fqn": "aws-cdk-lib.Stack", "version": "0.0.0" } }, @@ -1075,73 +992,65 @@ "path": "domain-name-mapping-test/DefaultTest/Default", "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.108" + "version": "10.2.55" } }, "DeployAssert": { "id": "DeployAssert", "path": "domain-name-mapping-test/DefaultTest/DeployAssert", "children": { - "LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a": { - "id": "LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a", + "HttpApiCall5c7406415c21459755238de5e3d1af86": { + "id": "HttpApiCall5c7406415c21459755238de5e3d1af86", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall5c7406415c21459755238de5e3d1af86", "children": { - "SdkProvider": { - "id": "SdkProvider", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/SdkProvider", + "HttpProvider": { + "id": "HttpProvider", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall5c7406415c21459755238de5e3d1af86/HttpProvider", "children": { "AssertionsProvider": { "id": "AssertionsProvider", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/SdkProvider/AssertionsProvider", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall5c7406415c21459755238de5e3d1af86/HttpProvider/AssertionsProvider", "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.108" + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.AssertionsProvider", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } }, "Default": { "id": "Default", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/Default", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall5c7406415c21459755238de5e3d1af86/Default", "children": { "Default": { "id": "Default", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/Default/Default", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall5c7406415c21459755238de5e3d1af86/Default/Default", "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CfnResource", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/core.CustomResource", - "version": "0.0.0" - } - }, - "Invoke": { - "id": "Invoke", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/Invoke", - "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CustomResource", "version": "0.0.0" } }, "AssertionResults": { "id": "AssertionResults", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke6c82f4296e4da69e1d6905e3d20f761a/AssertionResults", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall5c7406415c21459755238de5e3d1af86/AssertionResults", "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", + "fqn": "aws-cdk-lib.CfnOutput", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.LambdaInvokeFunction", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } }, "SingletonFunction1488541a7b23466481b69b4408076b81": { @@ -1152,7 +1061,7 @@ "id": "Staging", "path": "domain-name-mapping-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Staging", "constructInfo": { - "fqn": "@aws-cdk/core.AssetStaging", + "fqn": "aws-cdk-lib.AssetStaging", "version": "0.0.0" } }, @@ -1160,7 +1069,7 @@ "id": "Role", "path": "domain-name-mapping-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role", "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CfnResource", "version": "0.0.0" } }, @@ -1168,223 +1077,223 @@ "id": "Handler", "path": "domain-name-mapping-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Handler", "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CfnResource", "version": "0.0.0" } } }, "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.108" + "version": "10.2.55" } }, - "LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320": { - "id": "LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320", + "HttpApiCall87249be5ff18205c5f4320c2baec9418": { + "id": "HttpApiCall87249be5ff18205c5f4320c2baec9418", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall87249be5ff18205c5f4320c2baec9418", "children": { - "SdkProvider": { - "id": "SdkProvider", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/SdkProvider", + "HttpProvider": { + "id": "HttpProvider", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall87249be5ff18205c5f4320c2baec9418/HttpProvider", "children": { "AssertionsProvider": { "id": "AssertionsProvider", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/SdkProvider/AssertionsProvider", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall87249be5ff18205c5f4320c2baec9418/HttpProvider/AssertionsProvider", "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.108" + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.AssertionsProvider", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } }, "Default": { "id": "Default", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/Default", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall87249be5ff18205c5f4320c2baec9418/Default", "children": { "Default": { "id": "Default", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/Default/Default", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall87249be5ff18205c5f4320c2baec9418/Default/Default", "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CfnResource", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/core.CustomResource", - "version": "0.0.0" - } - }, - "Invoke": { - "id": "Invoke", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/Invoke", - "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CustomResource", "version": "0.0.0" } }, "AssertionResults": { "id": "AssertionResults", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke4f2bfb0cc64af0ccca4a6e7b6c3de320/AssertionResults", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall87249be5ff18205c5f4320c2baec9418/AssertionResults", "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", + "fqn": "aws-cdk-lib.CfnOutput", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.LambdaInvokeFunction", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } }, - "LambdaInvokef718aff12f12e7e6e6dd823f91dfce23": { - "id": "LambdaInvokef718aff12f12e7e6e6dd823f91dfce23", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23", + "HttpApiCall39df1b9413ee8ef1155877d35e1a132f": { + "id": "HttpApiCall39df1b9413ee8ef1155877d35e1a132f", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall39df1b9413ee8ef1155877d35e1a132f", "children": { - "SdkProvider": { - "id": "SdkProvider", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/SdkProvider", + "HttpProvider": { + "id": "HttpProvider", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall39df1b9413ee8ef1155877d35e1a132f/HttpProvider", "children": { "AssertionsProvider": { "id": "AssertionsProvider", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/SdkProvider/AssertionsProvider", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall39df1b9413ee8ef1155877d35e1a132f/HttpProvider/AssertionsProvider", "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.108" + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.AssertionsProvider", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } }, "Default": { "id": "Default", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/Default", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall39df1b9413ee8ef1155877d35e1a132f/Default", "children": { "Default": { "id": "Default", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/Default/Default", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall39df1b9413ee8ef1155877d35e1a132f/Default/Default", "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CfnResource", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/core.CustomResource", - "version": "0.0.0" - } - }, - "Invoke": { - "id": "Invoke", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/Invoke", - "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CustomResource", "version": "0.0.0" } }, "AssertionResults": { "id": "AssertionResults", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvokef718aff12f12e7e6e6dd823f91dfce23/AssertionResults", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCall39df1b9413ee8ef1155877d35e1a132f/AssertionResults", "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", + "fqn": "aws-cdk-lib.CfnOutput", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.LambdaInvokeFunction", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } }, - "LambdaInvoke2025c0c4c97e10064ec08312531cb316": { - "id": "LambdaInvoke2025c0c4c97e10064ec08312531cb316", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316", + "HttpApiCallbfb4c2986471eaae77943449a0ea25f6": { + "id": "HttpApiCallbfb4c2986471eaae77943449a0ea25f6", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCallbfb4c2986471eaae77943449a0ea25f6", "children": { - "SdkProvider": { - "id": "SdkProvider", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/SdkProvider", + "HttpProvider": { + "id": "HttpProvider", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCallbfb4c2986471eaae77943449a0ea25f6/HttpProvider", "children": { "AssertionsProvider": { "id": "AssertionsProvider", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/SdkProvider/AssertionsProvider", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCallbfb4c2986471eaae77943449a0ea25f6/HttpProvider/AssertionsProvider", "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.108" + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.AssertionsProvider", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } }, "Default": { "id": "Default", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/Default", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCallbfb4c2986471eaae77943449a0ea25f6/Default", "children": { "Default": { "id": "Default", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/Default/Default", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCallbfb4c2986471eaae77943449a0ea25f6/Default/Default", "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CfnResource", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/core.CustomResource", - "version": "0.0.0" - } - }, - "Invoke": { - "id": "Invoke", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/Invoke", - "constructInfo": { - "fqn": "@aws-cdk/core.CfnResource", + "fqn": "aws-cdk-lib.CustomResource", "version": "0.0.0" } }, "AssertionResults": { "id": "AssertionResults", - "path": "domain-name-mapping-test/DefaultTest/DeployAssert/LambdaInvoke2025c0c4c97e10064ec08312531cb316/AssertionResults", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/HttpApiCallbfb4c2986471eaae77943449a0ea25f6/AssertionResults", "constructInfo": { - "fqn": "@aws-cdk/core.CfnOutput", + "fqn": "aws-cdk-lib.CfnOutput", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.LambdaInvokeFunction", + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "domain-name-mapping-test/DefaultTest/DeployAssert/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/core.Stack", + "fqn": "aws-cdk-lib.Stack", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.IntegTestCase", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.IntegTest", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "Tree": { + "id": "Tree", + "path": "Tree", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "@aws-cdk/core.App", + "fqn": "aws-cdk-lib.App", "version": "0.0.0" } } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.ts b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.ts index 29eb4b811df55..60bd2bbac9663 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.ts +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.domain-name.ts @@ -1,11 +1,9 @@ import { Certificate } from 'aws-cdk-lib/aws-certificatemanager'; -import { Function, Code, Runtime } from 'aws-cdk-lib/aws-lambda'; import { CfnRecordSet } from 'aws-cdk-lib/aws-route53'; import * as cdk from 'aws-cdk-lib'; import { IntegTest, ExpectedResult, - Match, } from '@aws-cdk/integ-tests-alpha'; import { Construct } from 'constructs'; import * as apigw from 'aws-cdk-lib/aws-apigateway'; @@ -185,85 +183,28 @@ const integ = new IntegTest(app, 'domain-name-mapping-test', { enableLookups: true, }); -const invoke = new Function(testCase, 'InvokeApi', { - code: Code.fromInline(` -const https = require('https'); -exports.handler = async function(event) { - console.log(event); - const options = { - hostname: event.hostname, - path: event.path, - }; - let dataString = ''; - const response = await new Promise((resolve, reject) => { - const req = https.get(options, (res) => { - res.on('data', data => { - dataString += data; - }) - res.on('end', () => { - resolve({ - statusCode: res.statusCode, - body: dataString, - }); - }) - }); - req.on('error', err => { - reject({ - statusCode: 500, - body: JSON.stringify({ - cause: 'Something went wrong', - error: err, - }) - }); - }); - req.end(); - }); - return response; -} - -`), - handler: 'index.handler', - runtime: Runtime.NODEJS_16_X, -}); - -const api1Invoke = integ.assertions.invokeFunction({ - functionName: invoke.functionName, - payload: JSON.stringify({ - hostname: domain.domainName, - path: '/orders/v1/items', - }), -}); +const api1Invoke = integ.assertions.httpApiCall(`https://${domain.domainName}/orders/v1/items`, { }); api1Invoke.expect(ExpectedResult.objectLike({ - Payload: Match.stringLikeRegexp('201'), + body: { message: 'Hello, world' }, + ok: true, + status: 201, })); -const api2Invoke = integ.assertions.invokeFunction({ - functionName: invoke.functionName, - payload: JSON.stringify({ - hostname: domain.domainName, - path: '/orders/v2/items', - }), -}); +const api2Invoke = integ.assertions.httpApiCall(`https://${domain.domainName}/orders/v2/items`, { }); api2Invoke.expect(ExpectedResult.objectLike({ - Payload: Match.stringLikeRegexp('202'), + body: { message: 'Hello, world' }, + ok: true, + status: 202, })); -const domain2api1Invoke = integ.assertions.invokeFunction({ - functionName: invoke.functionName, - payload: JSON.stringify({ - hostname: secondDomain.domainName, - path: '/orders/items', - }), -}); +const domain2api1Invoke = integ.assertions.httpApiCall(`https://${secondDomain.domainName}/orders/items`, { }); domain2api1Invoke.expect(ExpectedResult.objectLike({ - Payload: Match.stringLikeRegexp('201'), + body: { message: 'Hello, world' }, + ok: true, + status: 201, })); -const domain2api2Invoke = integ.assertions.invokeFunction({ - functionName: invoke.functionName, - payload: JSON.stringify({ - hostname: secondDomain.domainName, - path: '/orders/v2/items', - }), -}); +const domain2api2Invoke = integ.assertions.httpApiCall(`https://${secondDomain.domainName}/orders/v2/items`, { }); domain2api2Invoke.expect(ExpectedResult.objectLike({ - Payload: Match.stringLikeRegexp('202'), + body: { message: 'Hello, world' }, + ok: true, + status: 202, })); diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/LambdaApiIntegrationOptionsStack.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/LambdaApiIntegrationOptionsStack.assets.json index 3ef8665be717c..c493db7104e2a 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/LambdaApiIntegrationOptionsStack.assets.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/LambdaApiIntegrationOptionsStack.assets.json @@ -1,7 +1,7 @@ { - "version": "20.0.0", + "version": "32.0.0", "files": { - "d2917ea4195aa0183538531b99a1ccb6369a7a90926d79378d84278263b33b46": { + "4db5712a4ffeeb138b865a31a6cce9ec7becd96318f72baeb40d48a8b0d2a334": { "source": { "path": "LambdaApiIntegrationOptionsStack.template.json", "packaging": "file" @@ -9,7 +9,7 @@ "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "d2917ea4195aa0183538531b99a1ccb6369a7a90926d79378d84278263b33b46.json", + "objectKey": "4db5712a4ffeeb138b865a31a6cce9ec7becd96318f72baeb40d48a8b0d2a334.json", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/LambdaApiIntegrationOptionsStack.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/LambdaApiIntegrationOptionsStack.template.json index a113a5f480e55..858058ddfebf0 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/LambdaApiIntegrationOptionsStack.template.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/LambdaApiIntegrationOptionsStack.template.json @@ -35,7 +35,7 @@ "Type": "AWS::Lambda::Function", "Properties": { "Code": { - "ZipFile": "foo" + "ZipFile": "exports.handler = async function(event) {\n return {\n body: JSON.stringify({\n message: 'Hello',\n }),\n statusCode: 200,\n headers: { 'Content-Type': '*/*' }\n };\n }" }, "Role": { "Fn::GetAtt": [ @@ -44,7 +44,7 @@ ] }, "Handler": "index.handler", - "Runtime": "nodejs14.x" + "Runtime": "nodejs18.x" }, "DependsOn": [ "myfnServiceRole7822DC24" @@ -417,6 +417,22 @@ ] ] } + }, + "ExportsOutputReflambdarestapiF559E4F2E351BC88": { + "Value": { + "Ref": "lambdarestapiF559E4F2" + }, + "Export": { + "Name": "LambdaApiIntegrationOptionsStack:ExportsOutputReflambdarestapiF559E4F2E351BC88" + } + }, + "ExportsOutputReflambdarestapiDeploymentStageprodA05F84EA6A0E534F": { + "Value": { + "Ref": "lambdarestapiDeploymentStageprodA05F84EA" + }, + "Export": { + "Name": "LambdaApiIntegrationOptionsStack:ExportsOutputReflambdarestapiDeploymentStageprodA05F84EA6A0E534F" + } } }, "Parameters": { diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js new file mode 100644 index 0000000000000..c29f3db7d5483 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js @@ -0,0 +1,7272 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; + +// ../../aws-cdk-lib/assertions/lib/matcher.ts +var matcher_exports = {}; +__export(matcher_exports, { + MatchResult: () => MatchResult, + Matcher: () => Matcher +}); +function* range(n) { + for (let i2 = 0; i2 < n; i2++) { + yield i2; + } +} +function* enumFirst(xs) { + let first = true; + for (const x2 of xs) { + yield [first, x2]; + first = false; + } +} +var Matcher, MatchResult; +var init_matcher = __esm({ + "../../aws-cdk-lib/assertions/lib/matcher.ts"() { + "use strict"; + Matcher = class { + /** + * Check whether the provided object is a subtype of the `IMatcher`. + */ + static isMatcher(x2) { + return x2 && x2 instanceof Matcher; + } + }; + MatchResult = class { + constructor(target) { + this.failuresHere = /* @__PURE__ */ new Map(); + this.captures = /* @__PURE__ */ new Map(); + this.finalized = false; + this.innerMatchFailures = /* @__PURE__ */ new Map(); + this._hasFailed = false; + this._failCount = 0; + this._cost = 0; + this.target = target; + } + /** + * DEPRECATED + * @deprecated use recordFailure() + */ + push(matcher, path, message) { + return this.recordFailure({ matcher, path, message }); + } + /** + * Record a new failure into this result at a specific path. + */ + recordFailure(failure) { + const failKey = failure.path.join("."); + let list = this.failuresHere.get(failKey); + if (!list) { + list = []; + this.failuresHere.set(failKey, list); + } + this._failCount += 1; + this._cost += failure.cost ?? 1; + list.push(failure); + this._hasFailed = true; + return this; + } + /** Whether the match is a success */ + get isSuccess() { + return !this._hasFailed; + } + /** Does the result contain any failures. If not, the result is a success */ + hasFailed() { + return this._hasFailed; + } + /** The number of failures */ + get failCount() { + return this._failCount; + } + /** The cost of the failures so far */ + get failCost() { + return this._cost; + } + /** + * Compose the results of a previous match as a subtree. + * @param id the id of the parent tree. + */ + compose(id, inner) { + if (inner.hasFailed()) { + this._hasFailed = true; + this._failCount += inner.failCount; + this._cost += inner._cost; + this.innerMatchFailures.set(id, inner); + } + inner.captures.forEach((vals, capture) => { + vals.forEach((value) => this.recordCapture({ capture, value })); + }); + return this; + } + /** + * Prepare the result to be analyzed. + * This API *must* be called prior to analyzing these results. + */ + finished() { + if (this.finalized) { + return this; + } + if (this.failCount === 0) { + this.captures.forEach((vals, cap) => cap._captured.push(...vals)); + } + this.finalized = true; + return this; + } + /** + * Render the failed match in a presentable way + * + * Prefer using `renderMismatch` over this method. It is left for backwards + * compatibility for test suites that expect it, but `renderMismatch()` will + * produce better output. + */ + toHumanStrings() { + const failures = new Array(); + debugger; + recurse(this, []); + return failures.map((r2) => { + const loc = r2.path.length === 0 ? "" : ` at /${r2.path.join("/")}`; + return "" + r2.message + loc + ` (using ${r2.matcher.name} matcher)`; + }); + function recurse(x2, prefix) { + for (const fail of Array.from(x2.failuresHere.values()).flat()) { + failures.push({ + matcher: fail.matcher, + message: fail.message, + path: [...prefix, ...fail.path] + }); + } + for (const [key, inner] of x2.innerMatchFailures.entries()) { + recurse(inner, [...prefix, key]); + } + } + } + /** + * Do a deep render of the match result, showing the structure mismatches in context + */ + renderMismatch() { + if (!this.hasFailed()) { + return ""; + } + const parts = new Array(); + const indents = new Array(); + emitFailures(this, ""); + recurse(this); + return moveMarkersToFront(parts.join("").trimEnd()); + function emit(x2) { + if (x2 === void 0) { + debugger; + } + parts.push(x2.replace(/\n/g, ` +${indents.join("")}`)); + } + function emitFailures(r2, path, scrapSet) { + for (const fail of r2.failuresHere.get(path) ?? []) { + emit(`!! ${fail.message} +`); + } + scrapSet == null ? void 0 : scrapSet.delete(path); + } + function recurse(r2) { + const remainingFailures = new Set(Array.from(r2.failuresHere.keys()).filter((x2) => x2 !== "")); + if (Array.isArray(r2.target)) { + indents.push(" "); + emit("[\n"); + for (const [first, i2] of enumFirst(range(r2.target.length))) { + if (!first) { + emit(",\n"); + } + emitFailures(r2, `${i2}`, remainingFailures); + const innerMatcher = r2.innerMatchFailures.get(`${i2}`); + if (innerMatcher) { + emitFailures(innerMatcher, ""); + recurseComparingValues(innerMatcher, r2.target[i2]); + } else { + emit(renderAbridged(r2.target[i2])); + } + } + emitRemaining(); + indents.pop(); + emit("\n]"); + return; + } + if (r2.target && typeof r2.target === "object") { + indents.push(" "); + emit("{\n"); + const keys = Array.from(/* @__PURE__ */ new Set([ + ...Object.keys(r2.target), + ...Array.from(remainingFailures) + ])).sort(); + for (const [first, key] of enumFirst(keys)) { + if (!first) { + emit(",\n"); + } + emitFailures(r2, key, remainingFailures); + const innerMatcher = r2.innerMatchFailures.get(key); + if (innerMatcher) { + emitFailures(innerMatcher, ""); + emit(`${jsonify(key)}: `); + recurseComparingValues(innerMatcher, r2.target[key]); + } else { + emit(`${jsonify(key)}: `); + emit(renderAbridged(r2.target[key])); + } + } + emitRemaining(); + indents.pop(); + emit("\n}"); + return; + } + emitRemaining(); + emit(jsonify(r2.target)); + function emitRemaining() { + if (remainingFailures.size > 0) { + emit("\n"); + } + for (const key of remainingFailures) { + emitFailures(r2, key); + } + } + } + function recurseComparingValues(inner, actualValue) { + if (inner.target === actualValue) { + return recurse(inner); + } + emit(renderAbridged(actualValue)); + emit(" <*> "); + recurse(inner); + } + function renderAbridged(x2) { + if (Array.isArray(x2)) { + switch (x2.length) { + case 0: + return "[]"; + case 1: + return `[ ${renderAbridged(x2[0])} ]`; + case 2: + if (x2.every((e2) => ["number", "boolean", "string"].includes(typeof e2))) { + return `[ ${x2.map(renderAbridged).join(", ")} ]`; + } + return "[ ... ]"; + default: + return "[ ... ]"; + } + } + if (x2 && typeof x2 === "object") { + const keys = Object.keys(x2); + switch (keys.length) { + case 0: + return "{}"; + case 1: + return `{ ${JSON.stringify(keys[0])}: ${renderAbridged(x2[keys[0]])} }`; + default: + return "{ ... }"; + } + } + return jsonify(x2); + } + function jsonify(x2) { + return JSON.stringify(x2) ?? "undefined"; + } + function moveMarkersToFront(x2) { + const re = /^(\s+)!!/gm; + return x2.replace(re, (_, spaces) => `!!${spaces.substring(0, spaces.length - 2)}`); + } + } + /** + * Record a capture against in this match result. + */ + recordCapture(options) { + let values = this.captures.get(options.capture); + if (values === void 0) { + values = []; + } + values.push(options.value); + this.captures.set(options.capture, values); + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/matchers/absent.ts +var AbsentMatch; +var init_absent = __esm({ + "../../aws-cdk-lib/assertions/lib/private/matchers/absent.ts"() { + "use strict"; + init_matcher(); + AbsentMatch = class extends Matcher { + constructor(name) { + super(); + this.name = name; + } + test(actual) { + const result = new MatchResult(actual); + if (actual !== void 0) { + result.recordFailure({ + matcher: this, + path: [], + message: `Received ${actual}, but key should be absent` + }); + } + return result; + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/sorting.ts +function sortKeyComparator(keyFn) { + return (a, b) => { + const ak = keyFn(a); + const bk = keyFn(b); + for (let i2 = 0; i2 < ak.length && i2 < bk.length; i2++) { + const av = ak[i2]; + const bv = bk[i2]; + let diff = 0; + if (typeof av === "number" && typeof bv === "number") { + diff = av - bv; + } else if (typeof av === "string" && typeof bv === "string") { + diff = av.localeCompare(bv); + } + if (diff !== 0) { + return diff; + } + } + return bk.length - ak.length; + }; +} +var init_sorting = __esm({ + "../../aws-cdk-lib/assertions/lib/private/sorting.ts"() { + "use strict"; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/sparse-matrix.ts +var SparseMatrix; +var init_sparse_matrix = __esm({ + "../../aws-cdk-lib/assertions/lib/private/sparse-matrix.ts"() { + "use strict"; + SparseMatrix = class { + constructor() { + this.matrix = /* @__PURE__ */ new Map(); + } + get(row, col) { + var _a4; + return (_a4 = this.matrix.get(row)) == null ? void 0 : _a4.get(col); + } + row(row) { + var _a4; + return Array.from(((_a4 = this.matrix.get(row)) == null ? void 0 : _a4.entries()) ?? []); + } + set(row, col, value) { + let r2 = this.matrix.get(row); + if (!r2) { + r2 = /* @__PURE__ */ new Map(); + this.matrix.set(row, r2); + } + r2.set(col, value); + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/type.ts +function getType(obj) { + return Array.isArray(obj) ? "array" : typeof obj; +} +var init_type = __esm({ + "../../aws-cdk-lib/assertions/lib/private/type.ts"() { + "use strict"; + } +}); + +// ../../aws-cdk-lib/assertions/lib/match.ts +var match_exports = {}; +__export(match_exports, { + Match: () => Match +}); +var Match, LiteralMatch, ArrayMatch, ObjectMatch, SerializedJson, NotMatch, AnyMatch, StringLikeRegexpMatch; +var init_match = __esm({ + "../../aws-cdk-lib/assertions/lib/match.ts"() { + "use strict"; + init_matcher(); + init_absent(); + init_sorting(); + init_sparse_matrix(); + init_type(); + Match = class { + /** + * Use this matcher in the place of a field's value, if the field must not be present. + */ + static absent() { + return new AbsentMatch("absent"); + } + /** + * Matches the specified pattern with the array found in the same relative path of the target. + * The set of elements (or matchers) must be in the same order as would be found. + * @param pattern the pattern to match + */ + static arrayWith(pattern) { + return new ArrayMatch("arrayWith", pattern); + } + /** + * Matches the specified pattern with the array found in the same relative path of the target. + * The set of elements (or matchers) must match exactly and in order. + * @param pattern the pattern to match + */ + static arrayEquals(pattern) { + return new ArrayMatch("arrayEquals", pattern, { subsequence: false }); + } + /** + * Deep exact matching of the specified pattern to the target. + * @param pattern the pattern to match + */ + static exact(pattern) { + return new LiteralMatch("exact", pattern, { partialObjects: false }); + } + /** + * Matches the specified pattern to an object found in the same relative path of the target. + * The keys and their values (or matchers) must be present in the target but the target can be a superset. + * @param pattern the pattern to match + */ + static objectLike(pattern) { + return new ObjectMatch("objectLike", pattern); + } + /** + * Matches the specified pattern to an object found in the same relative path of the target. + * The keys and their values (or matchers) must match exactly with the target. + * @param pattern the pattern to match + */ + static objectEquals(pattern) { + return new ObjectMatch("objectEquals", pattern, { partial: false }); + } + /** + * Matches any target which does NOT follow the specified pattern. + * @param pattern the pattern to NOT match + */ + static not(pattern) { + return new NotMatch("not", pattern); + } + /** + * Matches any string-encoded JSON and applies the specified pattern after parsing it. + * @param pattern the pattern to match after parsing the encoded JSON. + */ + static serializedJson(pattern) { + return new SerializedJson("serializedJson", pattern); + } + /** + * Matches any non-null value at the target. + */ + static anyValue() { + return new AnyMatch("anyValue"); + } + /** + * Matches targets according to a regular expression + */ + static stringLikeRegexp(pattern) { + return new StringLikeRegexpMatch("stringLikeRegexp", pattern); + } + }; + LiteralMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.partialObjects = options.partialObjects ?? false; + if (Matcher.isMatcher(this.pattern)) { + throw new Error("LiteralMatch cannot directly contain another matcher. Remove the top-level matcher or nest it more deeply."); + } + } + test(actual) { + if (Array.isArray(this.pattern)) { + return new ArrayMatch(this.name, this.pattern, { subsequence: false, partialObjects: this.partialObjects }).test(actual); + } + if (typeof this.pattern === "object") { + return new ObjectMatch(this.name, this.pattern, { partial: this.partialObjects }).test(actual); + } + const result = new MatchResult(actual); + if (typeof this.pattern !== typeof actual) { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected type ${typeof this.pattern} but received ${getType(actual)}` + }); + return result; + } + if (actual !== this.pattern) { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected ${this.pattern} but received ${actual}` + }); + } + return result; + } + }; + ArrayMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.subsequence = options.subsequence ?? true; + this.partialObjects = options.partialObjects ?? false; + } + test(actual) { + if (!Array.isArray(actual)) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected type array but received ${getType(actual)}` + }); + } + return this.subsequence ? this.testSubsequence(actual) : this.testFullArray(actual); + } + testFullArray(actual) { + const result = new MatchResult(actual); + let i2 = 0; + for (; i2 < this.pattern.length && i2 < actual.length; i2++) { + const patternElement = this.pattern[i2]; + const matcher = Matcher.isMatcher(patternElement) ? patternElement : new LiteralMatch(this.name, patternElement, { partialObjects: this.partialObjects }); + const innerResult = matcher.test(actual[i2]); + result.compose(`${i2}`, innerResult); + } + if (i2 < this.pattern.length) { + result.recordFailure({ + matcher: this, + message: `Not enough elements in array (expecting ${this.pattern.length}, got ${actual.length})`, + path: [`${i2}`] + }); + } + if (i2 < actual.length) { + result.recordFailure({ + matcher: this, + message: `Too many elements in array (expecting ${this.pattern.length}, got ${actual.length})`, + path: [`${i2}`] + }); + } + return result; + } + testSubsequence(actual) { + const result = new MatchResult(actual); + let patternIdx = 0; + let actualIdx = 0; + const matches = new SparseMatrix(); + while (patternIdx < this.pattern.length && actualIdx < actual.length) { + const patternElement = this.pattern[patternIdx]; + const matcher = Matcher.isMatcher(patternElement) ? patternElement : new LiteralMatch(this.name, patternElement, { partialObjects: this.partialObjects }); + const matcherName = matcher.name; + if (matcherName == "absent" || matcherName == "anyValue") { + throw new Error(`The Matcher ${matcherName}() cannot be nested within arrayWith()`); + } + const innerResult = matcher.test(actual[actualIdx]); + matches.set(patternIdx, actualIdx, innerResult); + actualIdx++; + if (innerResult.isSuccess) { + result.compose(`${actualIdx}`, innerResult); + patternIdx++; + } + } + if (patternIdx < this.pattern.length) { + for (let spi = 0; spi < patternIdx; spi++) { + const foundMatch = matches.row(spi).find(([, r2]) => r2.isSuccess); + if (!foundMatch) { + continue; + } + const [index] = foundMatch; + result.compose(`${index}`, new MatchResult(actual[index]).recordFailure({ + matcher: this, + message: `arrayWith pattern ${spi} matched here`, + path: [], + cost: 0 + // This is an informational message so it would be unfair to assign it cost + })); + } + const failedMatches = matches.row(patternIdx); + failedMatches.sort(sortKeyComparator(([i2, r2]) => [r2.failCost, i2])); + if (failedMatches.length > 0) { + const [index, innerResult] = failedMatches[0]; + result.recordFailure({ + matcher: this, + message: `Could not match arrayWith pattern ${patternIdx}. This is the closest match`, + path: [`${index}`], + cost: 0 + // Informational message + }); + result.compose(`${index}`, innerResult); + } else { + result.recordFailure({ + matcher: this, + message: `Could not match arrayWith pattern ${patternIdx}. No more elements to try`, + path: [`${actual.length}`] + }); + } + } + return result; + } + }; + ObjectMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.partial = options.partial ?? true; + } + test(actual) { + if (typeof actual !== "object" || Array.isArray(actual)) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected type object but received ${getType(actual)}` + }); + } + const result = new MatchResult(actual); + if (!this.partial) { + for (const a of Object.keys(actual)) { + if (!(a in this.pattern)) { + result.recordFailure({ + matcher: this, + path: [a], + message: `Unexpected key ${a}` + }); + } + } + } + for (const [patternKey, patternVal] of Object.entries(this.pattern)) { + if (!(patternKey in actual) && !(patternVal instanceof AbsentMatch)) { + result.recordFailure({ + matcher: this, + path: [patternKey], + message: `Missing key '${patternKey}'` + }); + continue; + } + const matcher = Matcher.isMatcher(patternVal) ? patternVal : new LiteralMatch(this.name, patternVal, { partialObjects: this.partial }); + const inner = matcher.test(actual[patternKey]); + result.compose(patternKey, inner); + } + return result; + } + }; + SerializedJson = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + if (getType(actual) !== "string") { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected JSON as a string but found ${getType(actual)}` + }); + } + let parsed; + try { + parsed = JSON.parse(actual); + } catch (err) { + if (err instanceof SyntaxError) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Invalid JSON string: ${actual}` + }); + } else { + throw err; + } + } + const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); + const innerResult = matcher.test(parsed); + if (innerResult.hasFailed()) { + innerResult.recordFailure({ + matcher: this, + path: [], + message: "Encoded JSON value does not match" + }); + } + return innerResult; + } + }; + NotMatch = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); + const innerResult = matcher.test(actual); + const result = new MatchResult(actual); + if (innerResult.failCount === 0) { + result.recordFailure({ + matcher: this, + path: [], + message: `Found unexpected match: ${JSON.stringify(actual, void 0, 2)}` + }); + } + return result; + } + }; + AnyMatch = class extends Matcher { + constructor(name) { + super(); + this.name = name; + } + test(actual) { + const result = new MatchResult(actual); + if (actual == null) { + result.recordFailure({ + matcher: this, + path: [], + message: "Expected a value but found none" + }); + } + return result; + } + }; + StringLikeRegexpMatch = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const result = new MatchResult(actual); + const regex = new RegExp(this.pattern, "gm"); + if (typeof actual !== "string") { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected a string, but got '${typeof actual}'` + }); + } + if (!regex.test(actual)) { + result.recordFailure({ + matcher: this, + path: [], + message: `String '${actual}' did not match pattern '${this.pattern}'` + }); + } + return result; + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/helpers-internal/index.js +var require_helpers_internal = __commonJS({ + "../../aws-cdk-lib/assertions/lib/helpers-internal/index.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + var desc = Object.getOwnPropertyDescriptor(m2, k); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + o[k2] = m2[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p in m2) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m2, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar((init_match(), __toCommonJS(match_exports)), exports); + __exportStar((init_matcher(), __toCommonJS(matcher_exports)), exports); + } +}); + +// ../../../node_modules/web-streams-polyfill/dist/ponyfill.es2018.js +var require_ponyfill_es2018 = __commonJS({ + "../../../node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports, module2) { + (function(global2, factory) { + typeof exports === "object" && typeof module2 !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); + })(exports, function(exports2) { + "use strict"; + const SymbolPolyfill = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol : (description) => `Symbol(${description})`; + function noop2() { + return void 0; + } + function getGlobals() { + if (typeof self !== "undefined") { + return self; + } else if (typeof window !== "undefined") { + return window; + } else if (typeof global !== "undefined") { + return global; + } + return void 0; + } + const globals = getGlobals(); + function typeIsObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + const rethrowAssertionErrorRejection = noop2; + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, void 0, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === "function") { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(void 0); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F2, V, args) { + if (typeof F2 !== "function") { + throw new TypeError("Argument is not a function"); + } + return Function.prototype.apply.call(F2, V, args); + } + function promiseCall(F2, V, args) { + try { + return promiseResolvedWith(reflectCall(F2, V, args)); + } catch (value) { + return promiseRejectedWith(value); + } + } + const QUEUE_MAX_ARRAY_SIZE = 16384; + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + this._front = { + _elements: [], + _next: void 0 + }; + this._back = this._front; + this._cursor = 0; + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: void 0 + }; + } + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + elements[oldCursor] = void 0; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i2 = this._cursor; + let node = this._front; + let elements = node._elements; + while (i2 !== elements.length || node._next !== void 0) { + if (i2 === elements.length) { + node = node._next; + elements = node._elements; + i2 = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i2]); + ++i2; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === "readable") { + defaultReaderClosedPromiseInitialize(reader); + } else if (stream._state === "closed") { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === "readable") { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = void 0; + reader._ownerReadableStream = void 0; + } + function readerLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released reader"); + } + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = void 0; + reader._closedPromise_reject = void 0; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === void 0) { + return; + } + reader._closedPromise_resolve(void 0); + reader._closedPromise_resolve = void 0; + reader._closedPromise_reject = void 0; + } + const AbortSteps = SymbolPolyfill("[[AbortSteps]]"); + const ErrorSteps = SymbolPolyfill("[[ErrorSteps]]"); + const CancelSteps = SymbolPolyfill("[[CancelSteps]]"); + const PullSteps = SymbolPolyfill("[[PullSteps]]"); + const NumberIsFinite = Number.isFinite || function(x2) { + return typeof x2 === "number" && isFinite(x2); + }; + const MathTrunc = Math.trunc || function(v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + function isDictionary(x2) { + return typeof x2 === "object" || typeof x2 === "function"; + } + function assertDictionary(obj, context) { + if (obj !== void 0 && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertFunction(x2, context) { + if (typeof x2 !== "function") { + throw new TypeError(`${context} is not a function.`); + } + } + function isObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + function assertObject(x2, context) { + if (!isObject(x2)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x2, position, context) { + if (x2 === void 0) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x2, field, context) { + if (x2 === void 0) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x2) { + return x2 === 0 ? 0 : x2; + } + function integerPart(x2) { + return censorNegativeZero(MathTrunc(x2)); + } + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x2 = Number(value); + x2 = censorNegativeZero(x2); + if (!NumberIsFinite(x2)) { + throw new TypeError(`${context} is not a finite number`); + } + x2 = integerPart(x2); + if (x2 < lowerBound || x2 > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x2) || x2 === 0) { + return 0; + } + return x2; + } + function assertReadableStream(x2, context) { + if (!IsReadableStream(x2)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === void 0) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = void 0) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("read")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: void 0, done: true }), + _errorSteps: (e2) => rejectPromise(e2) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === void 0) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamDefaultReader", + configurable: true + }); + } + function IsReadableStreamDefaultReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readRequests")) { + return false; + } + return x2 instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "closed") { + readRequest._closeSteps(); + } else if (stream._state === "errored") { + readRequest._errorSteps(stream._storedError); + } else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { + }).prototype); + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = void 0; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: void 0, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("iterate")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => { + this._ongoingPromise = void 0; + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = void 0; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: void 0, done: true }); + }, + _errorSteps: (reason) => { + this._ongoingPromise = void 0; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("finish iterating")); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== void 0) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_asyncIteratorImpl")) { + return false; + } + try { + return x2._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; + } catch (_a4) { + return false; + } + } + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + const NumberIsNaN = Number.isNaN || function(x2) { + return x2 !== x2; + }; + function CreateArrayFromList(elements) { + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + function TransferArrayBuffer(O) { + return O; + } + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function IsNonNegativeNumber(v) { + if (typeof v !== "number") { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError("Size must be a finite, non-NaN, non-negative number."); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("view"); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respond"); + } + assertRequiredArgument(bytesWritten, 1, "respond"); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter"); + if (this._associatedReadableByteStreamController === void 0) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(this._view.buffer)) + ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respondWithNewView"); + } + assertRequiredArgument(view, 1, "respondWithNewView"); + if (!ArrayBuffer.isView(view)) { + throw new TypeError("You can only respond with array buffer views"); + } + if (this._associatedReadableByteStreamController === void 0) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(view.buffer)) + ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamBYOBRequest", + configurable: true + }); + } + class ReadableByteStreamController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("byobRequest"); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("desiredSize"); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("close"); + } + if (this._closeRequested) { + throw new TypeError("The stream has already been closed; do not close it again!"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("enqueue"); + } + assertRequiredArgument(chunk, 1, "enqueue"); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError("chunk must be an array buffer view"); + } + if (chunk.byteLength === 0) { + throw new TypeError("chunk must have non-zero byteLength"); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError("stream is closed or draining"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e2 = void 0) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("error"); + } + ReadableByteStreamControllerError(this, e2); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== void 0) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: "default" + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableByteStreamController", + configurable: true + }); + } + function IsReadableByteStreamController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableByteStream")) { + return false; + } + return x2 instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_associatedReadableByteStreamController")) { + return false; + } + return x2 instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, (e2) => { + ReadableByteStreamControllerError(controller, e2); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === "closed") { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === "default") { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = void 0; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + const buffer = TransferArrayBuffer(view.buffer); + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: "byob" + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === "closed") { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e2); + readIntoRequest._errorSteps(e2); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + ReadableByteStreamControllerRespondInClosedState(controller); + } else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = void 0; + controller._cancelAlgorithm = void 0; + } + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e2); + throw e2; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) + ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } else if (ReadableStreamHasBYOBReader(stream)) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e2) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e2); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (bytesWritten !== 0) { + throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream"); + } + } else { + if (bytesWritten === 0) { + throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream"); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError("bytesWritten out of range"); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (view.byteLength !== 0) { + throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream"); + } + } else { + if (view.byteLength === 0) { + throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError("The region specified by view does not match byobRequest"); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError("The buffer of view has different capacity than byobRequest"); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError("The region specified by view is larger than byobRequest"); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + controller._queue = controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, (r2) => { + ReadableByteStreamControllerError(controller, r2); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => void 0; + let pullAlgorithm = () => promiseResolvedWith(void 0); + let cancelAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingByteSource.start !== void 0) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== void 0) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== void 0) { + cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError("autoAllocateChunkSize must be greater than 0"); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request2, controller, view) { + request2._associatedReadableByteStreamController = controller; + request2._view = view; + } + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === void 0) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = void 0) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("read")); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError("view must be an array buffer view")); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError("view must have non-zero byteLength")); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) + ; + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }), + _errorSteps: (e2) => rejectPromise(e2) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === void 0) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamBYOBReader", + configurable: true + }); + } + function IsReadableStreamBYOBReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readIntoRequests")) { + return false; + } + return x2 instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "errored") { + readIntoRequest._errorSteps(stream._storedError); + } else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === void 0) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError("Invalid highWaterMark"); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark), + size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return (chunk) => convertUnrestrictedDouble(fn(chunk)); + } + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function assertWritableStream(x2, context) { + if (!IsWritableStream(x2)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + function isAbortSignal2(value) { + if (typeof value !== "object" || value === null) { + return false; + } + try { + return typeof value.aborted === "boolean"; + } catch (_a4) { + return false; + } + } + const supportsAbortController = typeof AbortController === "function"; + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return void 0; + } + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === void 0) { + rawUnderlyingSink = null; + } else { + assertObject(rawUnderlyingSink, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter"); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== void 0) { + throw new RangeError("Invalid type is specified"); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("locked"); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = void 0) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("abort")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer")); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("close")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer")); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("getWriter"); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStream", + configurable: true + }); + } + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = "writable"; + stream._storedError = void 0; + stream._writer = void 0; + stream._writableStreamController = void 0; + stream._writeRequests = new SimpleQueue(); + stream._inFlightWriteRequest = void 0; + stream._closeRequest = void 0; + stream._inFlightCloseRequest = void 0; + stream._pendingAbortRequest = void 0; + stream._backpressure = false; + } + function IsWritableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_writableStreamController")) { + return false; + } + return x2 instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === void 0) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a4; + if (stream._state === "closed" || stream._state === "errored") { + return promiseResolvedWith(void 0); + } + stream._writableStreamController._abortReason = reason; + (_a4 = stream._writableStreamController._abortController) === null || _a4 === void 0 ? void 0 : _a4.abort(); + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseResolvedWith(void 0); + } + if (stream._pendingAbortRequest !== void 0) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === "erroring") { + wasAlreadyErroring = true; + reason = void 0; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: void 0, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== void 0 && stream._backpressure && state === "writable") { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === "writable") { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = "erroring"; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== void 0) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = "errored"; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach((writeRequest) => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === void 0) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = void 0; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(void 0); + stream._inFlightWriteRequest = void 0; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = void 0; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(void 0); + stream._inFlightCloseRequest = void 0; + const state = stream._state; + if (state === "erroring") { + stream._storedError = void 0; + if (stream._pendingAbortRequest !== void 0) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = void 0; + } + } + stream._state = "closed"; + const writer = stream._writer; + if (writer !== void 0) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = void 0; + if (stream._pendingAbortRequest !== void 0) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = void 0; + } + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = void 0; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== void 0) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = void 0; + } + const writer = stream._writer; + if (writer !== void 0) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== void 0 && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter"); + assertWritableStream(stream, "First parameter"); + if (IsWritableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive writing by another writer"); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === "writable") { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } else if (state === "erroring") { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } else if (state === "closed") { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("desiredSize"); + } + if (this._ownerWritableStream === void 0) { + throw defaultWriterLockException("desiredSize"); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("ready")); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = void 0) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("abort")); + } + if (this._ownerWritableStream === void 0) { + return promiseRejectedWith(defaultWriterLockException("abort")); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("close")); + } + const stream = this._ownerWritableStream; + if (stream === void 0) { + return promiseRejectedWith(defaultWriterLockException("close")); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("releaseLock"); + } + const stream = this._ownerWritableStream; + if (stream === void 0) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = void 0) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("write")); + } + if (this._ownerWritableStream === void 0) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStreamDefaultWriter", + configurable: true + }); + } + function IsWritableStreamDefaultWriter(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_ownerWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultWriter; + } + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseResolvedWith(void 0); + } + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === "pending") { + defaultWriterClosedPromiseReject(writer, error); + } else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === "pending") { + defaultWriterReadyPromiseReject(writer, error); + } else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === "errored" || state === "erroring") { + return null; + } + if (state === "closed") { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = void 0; + writer._ownerWritableStream = void 0; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + const state = stream._state; + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to")); + } + if (state === "erroring") { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + class WritableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("abortReason"); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("signal"); + } + if (this._abortController === void 0) { + throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported"); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e2 = void 0) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("error"); + } + const state = this._controlledWritableStream._state; + if (state !== "writable") { + return; + } + WritableStreamDefaultControllerError(this, e2); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStreamDefaultController", + configurable: true + }); + } + function IsWritableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + controller._queue = void 0; + controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._abortReason = void 0; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, (r2) => { + controller._started = true; + WritableStreamDealWithRejection(stream, r2); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => void 0; + let writeAlgorithm = () => promiseResolvedWith(void 0); + let closeAlgorithm = () => promiseResolvedWith(void 0); + let abortAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingSink.start !== void 0) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== void 0) { + writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== void 0) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== void 0) { + abortAlgorithm = (reason) => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = void 0; + controller._closeAlgorithm = void 0; + controller._abortAlgorithm = void 0; + controller._strategySizeAlgorithm = void 0; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== void 0) { + return; + } + const state = stream._state; + if (state === "erroring") { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === "writable") { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, (reason) => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, (reason) => { + if (stream._state === "writable") { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released writer"); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = "pending"; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = void 0; + writer._closedPromise_reject = void 0; + writer._closedPromiseState = "rejected"; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === void 0) { + return; + } + writer._closedPromise_resolve(void 0); + writer._closedPromise_resolve = void 0; + writer._closedPromise_reject = void 0; + writer._closedPromiseState = "resolved"; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = "pending"; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = void 0; + writer._readyPromise_reject = void 0; + writer._readyPromiseState = "rejected"; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === void 0) { + return; + } + writer._readyPromise_resolve(void 0); + writer._readyPromise_resolve = void 0; + writer._readyPromise_reject = void 0; + writer._readyPromiseState = "fulfilled"; + } + const NativeDOMException = typeof DOMException !== "undefined" ? DOMException : void 0; + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === "function" || typeof ctor === "object")) { + return false; + } + try { + new ctor(); + return true; + } catch (_a4) { + return false; + } + } + function createDOMExceptionPolyfill() { + const ctor = function DOMException3(message, name) { + this.message = message || ""; + this.name = name || "Error"; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true }); + return ctor; + } + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + let currentWrite = promiseResolvedWith(void 0); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== void 0) { + abortAlgorithm = () => { + const error = new DOMException$1("Aborted", "AbortError"); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === "writable") { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(void 0); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === "readable") { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(void 0); + }); + } + shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener("abort", abortAlgorithm); + } + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } else { + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: (chunk) => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + isOrBecomesErrored(source, reader._closedPromise, (storedError) => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + }); + isOrBecomesErrored(dest, writer._closedPromise, (storedError) => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + }); + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } else { + shutdown(); + } + }); + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") { + const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it"); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === "errored") { + action(stream._storedError); + } else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === "closed") { + action(); + } else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== void 0) { + signal.removeEventListener("abort", abortAlgorithm); + } + if (isError) { + reject(error); + } else { + resolve(void 0); + } + } + }); + } + class ReadableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("desiredSize"); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("close"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits close"); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = void 0) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("enqueue"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits enqueue"); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e2 = void 0) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("error"); + } + ReadableStreamDefaultControllerError(this, e2); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamDefaultController", + configurable: true + }); + } + function IsReadableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableStream")) { + return false; + } + return x2 instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, (e2) => { + ReadableStreamDefaultControllerError(controller, e2); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = void 0; + controller._cancelAlgorithm = void 0; + controller._strategySizeAlgorithm = void 0; + } + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e2) { + const stream = controller._controlledReadableStream; + if (stream._state !== "readable") { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e2); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === "readable") { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = void 0; + controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, (r2) => { + ReadableStreamDefaultControllerError(controller, r2); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => void 0; + let pullAlgorithm = () => promiseResolvedWith(void 0); + let cancelAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingSource.start !== void 0) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== void 0) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== void 0) { + cancelAlgorithm = (reason) => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(void 0); + } + reading = true; + const readRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(void 0); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r2) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r2); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, (r2) => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r2); + ReadableByteStreamControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: (chunk) => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== void 0) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(void 0); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(void 0); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(void 0); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(void 0); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== "bytes") { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== "byob") { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== void 0) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal2(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, "readable", "ReadableWritablePair"); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, "writable", "ReadableWritablePair"); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + class ReadableStream2 { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === void 0) { + rawUnderlyingSource = null; + } else { + assertObject(rawUnderlyingSource, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter"); + InitializeReadableStream(this); + if (underlyingSource.type === "bytes") { + if (strategy.size !== void 0) { + throw new RangeError("The strategy for a byte stream cannot have a size function"); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("locked"); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = void 0) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("cancel")); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader")); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = void 0) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("getReader"); + } + const options = convertReaderOptions(rawOptions, "First parameter"); + if (options.mode === void 0) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("pipeThrough"); + } + assertRequiredArgument(rawTransform, 1, "pipeThrough"); + const transform = convertReadableWritablePair(rawTransform, "First parameter"); + const options = convertPipeOptions(rawOptions, "Second parameter"); + if (IsReadableStreamLocked(this)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream"); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream"); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("pipeTo")); + } + if (destination === void 0) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, "Second parameter"); + } catch (e2) { + return promiseRejectedWith(e2); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("tee"); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = void 0) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("values"); + } + const options = convertIteratorOptions(rawOptions, "First parameter"); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream2.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStream", + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === "symbol") { + Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream2.prototype.values, + writable: true, + configurable: true + }); + } + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = "readable"; + stream._reader = void 0; + stream._storedError = void 0; + stream._disturbed = false; + } + function IsReadableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readableStreamController")) { + return false; + } + return x2 instanceof ReadableStream2; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === void 0) { + return false; + } + return true; + } + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === "closed") { + return promiseResolvedWith(void 0); + } + if (stream._state === "errored") { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._closeSteps(void 0); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop2); + } + function ReadableStreamClose(stream) { + stream._state = "closed"; + const reader = stream._reader; + if (reader === void 0) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach((readRequest) => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e2) { + stream._state = "errored"; + stream._storedError = e2; + const reader = stream._reader; + if (reader === void 0) { + return; + } + defaultReaderClosedPromiseReject(reader, e2); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach((readRequest) => { + readRequest._errorSteps(e2); + }); + reader._readRequests = new SimpleQueue(); + } else { + reader._readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._errorSteps(e2); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit"); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, "name", { + value: "size", + configurable: true + }); + } catch (_a4) { + } + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("highWaterMark"); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("size"); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: "ByteLengthQueuingStrategy", + configurable: true + }); + } + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_byteLengthQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof ByteLengthQueuingStrategy; + } + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, "name", { + value: "size", + configurable: true + }); + } catch (_a4) { + } + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "CountQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("highWaterMark"); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("size"); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: "CountQueuingStrategy", + configurable: true + }); + } + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_countQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof CountQueuingStrategy; + } + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === void 0) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter"); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter"); + const transformer = convertTransformer(rawTransformer, "First parameter"); + if (transformer.readableType !== void 0) { + throw new RangeError("Invalid readableType specified"); + } + if (transformer.writableType !== void 0) { + throw new RangeError("Invalid writableType specified"); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise((resolve) => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== void 0) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } else { + startPromise_resolve(void 0); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("readable"); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("writable"); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: "TransformStream", + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(void 0); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + stream._backpressure = void 0; + stream._backpressureChangePromise = void 0; + stream._backpressureChangePromise_resolve = void 0; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = void 0; + } + function IsTransformStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_transformStreamController")) { + return false; + } + return x2 instanceof TransformStream; + } + function TransformStreamError(stream, e2) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e2); + TransformStreamErrorWritableAndUnblockWrite(stream, e2); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e2) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e2); + if (stream._backpressure) { + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + if (stream._backpressureChangePromise !== void 0) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise((resolve) => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + class TransformStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("desiredSize"); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = void 0) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("enqueue"); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = void 0) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("error"); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("terminate"); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "TransformStreamDefaultController", + configurable: true + }); + } + function IsTransformStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledTransformStream")) { + return false; + } + return x2 instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(void 0); + } catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(void 0); + if (transformer.transform !== void 0) { + transformAlgorithm = (chunk) => transformer.transform(chunk, controller); + } + if (transformer.flush !== void 0) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = void 0; + controller._flushAlgorithm = void 0; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError("Readable side is not in a state that permits enqueue"); + } + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } catch (e2) { + TransformStreamErrorWritableAndUnblockWrite(stream, e2); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e2) { + TransformStreamError(controller._controlledTransformStream, e2); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, void 0, (r2) => { + TransformStreamError(controller._controlledTransformStream, r2); + throw r2; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError("TransformStream terminated"); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === "erroring") { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + TransformStreamError(stream, reason); + return promiseResolvedWith(void 0); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + return transformPromiseWith(flushPromise, () => { + if (readable._state === "errored") { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, (r2) => { + TransformStreamError(stream, r2); + throw readable._storedError; + }); + } + function TransformStreamDefaultSourcePullAlgorithm(stream) { + TransformStreamSetBackpressure(stream, false); + return stream._backpressureChangePromise; + } + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + exports2.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports2.CountQueuingStrategy = CountQueuingStrategy; + exports2.ReadableByteStreamController = ReadableByteStreamController; + exports2.ReadableStream = ReadableStream2; + exports2.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports2.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports2.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports2.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports2.TransformStream = TransformStream; + exports2.TransformStreamDefaultController = TransformStreamDefaultController; + exports2.WritableStream = WritableStream; + exports2.WritableStreamDefaultController = WritableStreamDefaultController; + exports2.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + Object.defineProperty(exports2, "__esModule", { value: true }); + }); + } +}); + +// ../../../node_modules/fetch-blob/streams.cjs +var require_streams = __commonJS({ + "../../../node_modules/fetch-blob/streams.cjs"() { + var POOL_SIZE2 = 65536; + if (!globalThis.ReadableStream) { + try { + const process2 = require("process"); + const { emitWarning } = process2; + try { + process2.emitWarning = () => { + }; + Object.assign(globalThis, require("stream/web")); + process2.emitWarning = emitWarning; + } catch (error) { + process2.emitWarning = emitWarning; + throw error; + } + } catch (error) { + Object.assign(globalThis, require_ponyfill_es2018()); + } + } + try { + const { Blob: Blob2 } = require("buffer"); + if (Blob2 && !Blob2.prototype.stream) { + Blob2.prototype.stream = function name(params) { + let position = 0; + const blob = this; + return new ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + ctrl.enqueue(new Uint8Array(buffer)); + if (position === blob.size) { + ctrl.close(); + } + } + }); + }; + } + } catch (error) { + } + } +}); + +// ../../../node_modules/fetch-blob/index.js +async function* toIterator(parts, clone2 = true) { + for (const part of parts) { + if ("stream" in part) { + yield* ( + /** @type {AsyncIterableIterator} */ + part.stream() + ); + } else if (ArrayBuffer.isView(part)) { + if (clone2) { + let position = part.byteOffset; + const end = part.byteOffset + part.byteLength; + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); + } + } else { + yield part; + } + } else { + let position = 0, b = ( + /** @type {Blob} */ + part + ); + while (position !== b.size) { + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); + } + } + } +} +var import_streams, POOL_SIZE, _parts, _type, _size, _endings, _a, _Blob, Blob, fetch_blob_default; +var init_fetch_blob = __esm({ + "../../../node_modules/fetch-blob/index.js"() { + import_streams = __toESM(require_streams(), 1); + POOL_SIZE = 65536; + _Blob = (_a = class { + /** + * The Blob() constructor returns a new Blob object. The content + * of the blob consists of the concatenation of the values given + * in the parameter array. + * + * @param {*} blobParts + * @param {{ type?: string, endings?: string }} [options] + */ + constructor(blobParts = [], options = {}) { + /** @type {Array.<(Blob|Uint8Array)>} */ + __privateAdd(this, _parts, []); + __privateAdd(this, _type, ""); + __privateAdd(this, _size, 0); + __privateAdd(this, _endings, "transparent"); + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence."); + } + if (typeof blobParts[Symbol.iterator] !== "function") { + throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property."); + } + if (typeof options !== "object" && typeof options !== "function") { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); + } + if (options === null) + options = {}; + const encoder = new TextEncoder(); + for (const element of blobParts) { + let part; + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)); + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)); + } else if (element instanceof _a) { + part = element; + } else { + part = encoder.encode(`${element}`); + } + __privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size)); + __privateGet(this, _parts).push(part); + } + __privateSet(this, _endings, `${options.endings === void 0 ? "transparent" : options.endings}`); + const type = options.type === void 0 ? "" : String(options.type); + __privateSet(this, _type, /^[\x20-\x7E]*$/.test(type) ? type : ""); + } + /** + * The Blob interface's size property returns the + * size of the Blob in bytes. + */ + get size() { + return __privateGet(this, _size); + } + /** + * The type property of a Blob object returns the MIME type of the file. + */ + get type() { + return __privateGet(this, _type); + } + /** + * The text() method in the Blob interface returns a Promise + * that resolves with a string containing the contents of + * the blob, interpreted as UTF-8. + * + * @return {Promise} + */ + async text() { + const decoder = new TextDecoder(); + let str = ""; + for await (const part of toIterator(__privateGet(this, _parts), false)) { + str += decoder.decode(part, { stream: true }); + } + str += decoder.decode(); + return str; + } + /** + * The arrayBuffer() method in the Blob interface returns a + * Promise that resolves with the contents of the blob as + * binary data contained in an ArrayBuffer. + * + * @return {Promise} + */ + async arrayBuffer() { + const data = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of toIterator(__privateGet(this, _parts), false)) { + data.set(chunk, offset); + offset += chunk.length; + } + return data.buffer; + } + stream() { + const it = toIterator(__privateGet(this, _parts), true); + return new globalThis.ReadableStream({ + // @ts-ignore + type: "bytes", + async pull(ctrl) { + const chunk = await it.next(); + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value); + }, + async cancel() { + await it.return(); + } + }); + } + /** + * The Blob interface's slice() method creates and returns a + * new Blob object which contains data from a subset of the + * blob on which it's called. + * + * @param {number} [start] + * @param {number} [end] + * @param {string} [type] + */ + slice(start = 0, end = this.size, type = "") { + const { size } = this; + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size); + const span = Math.max(relativeEnd - relativeStart, 0); + const parts = __privateGet(this, _parts); + const blobParts = []; + let added = 0; + for (const part of parts) { + if (added >= span) { + break; + } + const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && size2 <= relativeStart) { + relativeStart -= size2; + relativeEnd -= size2; + } else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.byteLength; + } else { + chunk = part.slice(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.size; + } + relativeEnd -= size2; + blobParts.push(chunk); + relativeStart = 0; + } + } + const blob = new _a([], { type: String(type).toLowerCase() }); + __privateSet(blob, _size, span); + __privateSet(blob, _parts, blobParts); + return blob; + } + get [Symbol.toStringTag]() { + return "Blob"; + } + static [Symbol.hasInstance](object) { + return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]); + } + }, _parts = new WeakMap(), _type = new WeakMap(), _size = new WeakMap(), _endings = new WeakMap(), _a); + Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } + }); + Blob = _Blob; + fetch_blob_default = Blob; + } +}); + +// ../../../node_modules/fetch-blob/file.js +var _lastModified, _name, _a2, _File, File, file_default; +var init_file = __esm({ + "../../../node_modules/fetch-blob/file.js"() { + init_fetch_blob(); + _File = (_a2 = class extends fetch_blob_default { + /** + * @param {*[]} fileBits + * @param {string} fileName + * @param {{lastModified?: number, type?: string}} options + */ + // @ts-ignore + constructor(fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`); + } + super(fileBits, options); + __privateAdd(this, _lastModified, 0); + __privateAdd(this, _name, ""); + if (options === null) + options = {}; + const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + __privateSet(this, _lastModified, lastModified); + } + __privateSet(this, _name, String(fileName)); + } + get name() { + return __privateGet(this, _name); + } + get lastModified() { + return __privateGet(this, _lastModified); + } + get [Symbol.toStringTag]() { + return "File"; + } + static [Symbol.hasInstance](object) { + return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]); + } + }, _lastModified = new WeakMap(), _name = new WeakMap(), _a2); + File = _File; + file_default = File; + } +}); + +// ../../../node_modules/formdata-polyfill/esm.min.js +function formDataToBlob(F2, B = fetch_blob_default) { + var b = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c = [], p = `--${b}\r +Content-Disposition: form-data; name="`; + F2.forEach((v, n) => typeof v == "string" ? c.push(p + e(n) + `"\r +\r +${v.replace(/\r(?!\n)|(? (a += "", /^(Blob|File)$/.test(b && b[t]) ? [(c = c !== void 0 ? c + "" : b[t] == "File" ? b.name : "blob", a), b.name !== c || b[t] == "blob" ? new file_default([b], c, b) : b] : [a, b + ""]); + e = (c, f3) => (f3 ? c : c.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); + x = (n, a, e2) => { + if (a.length < e2) { + throw new TypeError(`Failed to execute '${n}' on 'FormData': ${e2} arguments required, but only ${a.length} present.`); + } + }; + FormData = (_a3 = class { + constructor(...a) { + __privateAdd(this, _d, []); + if (a.length) + throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`); + } + get [t]() { + return "FormData"; + } + [i]() { + return this.entries(); + } + static [h](o) { + return o && typeof o === "object" && o[t] === "FormData" && !m.some((m2) => typeof o[m2] != "function"); + } + append(...a) { + x("append", arguments, 2); + __privateGet(this, _d).push(f(...a)); + } + delete(a) { + x("delete", arguments, 1); + a += ""; + __privateSet(this, _d, __privateGet(this, _d).filter(([b]) => b !== a)); + } + get(a) { + x("get", arguments, 1); + a += ""; + for (var b = __privateGet(this, _d), l = b.length, c = 0; c < l; c++) + if (b[c][0] === a) + return b[c][1]; + return null; + } + getAll(a, b) { + x("getAll", arguments, 1); + b = []; + a += ""; + __privateGet(this, _d).forEach((c) => c[0] === a && b.push(c[1])); + return b; + } + has(a) { + x("has", arguments, 1); + a += ""; + return __privateGet(this, _d).some((b) => b[0] === a); + } + forEach(a, b) { + x("forEach", arguments, 1); + for (var [c, d] of this) + a.call(b, d, c, this); + } + set(...a) { + x("set", arguments, 2); + var b = [], c = true; + a = f(...a); + __privateGet(this, _d).forEach((d) => { + d[0] === a[0] ? c && (c = !b.push(a)) : b.push(d); + }); + c && b.push(a); + __privateSet(this, _d, b); + } + *entries() { + yield* __privateGet(this, _d); + } + *keys() { + for (var [a] of this) + yield a; + } + *values() { + for (var [, a] of this) + yield a; + } + }, _d = new WeakMap(), _a3); + } +}); + +// ../../../node_modules/node-domexception/index.js +var require_node_domexception = __commonJS({ + "../../../node_modules/node-domexception/index.js"(exports, module2) { + if (!globalThis.DOMException) { + try { + const { MessageChannel } = require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer(); + port.postMessage(ab, [ab, ab]); + } catch (err) { + err.constructor.name === "DOMException" && (globalThis.DOMException = err.constructor); + } + } + module2.exports = globalThis.DOMException; + } +}); + +// ../../../node_modules/fetch-blob/from.js +var import_node_fs, import_node_domexception, stat, _path, _start, _BlobDataItem, BlobDataItem; +var init_from = __esm({ + "../../../node_modules/fetch-blob/from.js"() { + import_node_fs = require("fs"); + import_node_domexception = __toESM(require_node_domexception(), 1); + init_file(); + init_fetch_blob(); + ({ stat } = import_node_fs.promises); + _BlobDataItem = class { + constructor(options) { + __privateAdd(this, _path, void 0); + __privateAdd(this, _start, void 0); + __privateSet(this, _path, options.path); + __privateSet(this, _start, options.start); + this.size = options.size; + this.lastModified = options.lastModified; + } + /** + * Slicing arguments is first validated and formatted + * to not be out of range by Blob.prototype.slice + */ + slice(start, end) { + return new _BlobDataItem({ + path: __privateGet(this, _path), + lastModified: this.lastModified, + size: end - start, + start: __privateGet(this, _start) + start + }); + } + async *stream() { + const { mtimeMs } = await stat(__privateGet(this, _path)); + if (mtimeMs > this.lastModified) { + throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError"); + } + yield* (0, import_node_fs.createReadStream)(__privateGet(this, _path), { + start: __privateGet(this, _start), + end: __privateGet(this, _start) + this.size - 1 + }); + } + get [Symbol.toStringTag]() { + return "Blob"; + } + }; + BlobDataItem = _BlobDataItem; + _path = new WeakMap(); + _start = new WeakMap(); + } +}); + +// node_modules/node-fetch/src/utils/multipart-parser.js +var multipart_parser_exports = {}; +__export(multipart_parser_exports, { + toFormData: () => toFormData +}); +function _fileName(headerValue) { + const m2 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m2) { + return; + } + const match = m2[2] || m2[3] || ""; + let filename = match.slice(match.lastIndexOf("\\") + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m3, code) => { + return String.fromCharCode(code); + }); + return filename; +} +async function toFormData(Body2, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError("Failed to fetch"); + } + const m2 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (!m2) { + throw new TypeError("no or bad content-type header, no multipart boundary"); + } + const parser = new MultipartParser(m2[1] || m2[2]); + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData(); + const onPartData = (ui8a) => { + entryValue += decoder.decode(ui8a, { stream: true }); + }; + const appendToFile = (ui8a) => { + entryChunks.push(ui8a); + }; + const appendFileToFormData = () => { + const file = new file_default(entryChunks, filename, { type: contentType }); + formData.append(entryName, file); + }; + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + const decoder = new TextDecoder("utf-8"); + decoder.decode(); + parser.onPartBegin = function() { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + headerField = ""; + headerValue = ""; + entryValue = ""; + entryName = ""; + contentType = ""; + filename = null; + entryChunks.length = 0; + }; + parser.onHeaderField = function(ui8a) { + headerField += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderValue = function(ui8a) { + headerValue += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderEnd = function() { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + if (headerField === "content-disposition") { + const m3 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + if (m3) { + entryName = m3[2] || m3[3] || ""; + } + filename = _fileName(headerValue); + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === "content-type") { + contentType = headerValue; + } + headerValue = ""; + headerField = ""; + }; + for await (const chunk of Body2) { + parser.write(chunk); + } + parser.end(); + return formData; +} +var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser; +var init_multipart_parser = __esm({ + "node_modules/node-fetch/src/utils/multipart-parser.js"() { + init_from(); + init_esm_min(); + s = 0; + S = { + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + END: s++ + }; + f2 = 1; + F = { + PART_BOUNDARY: f2, + LAST_BOUNDARY: f2 *= 2 + }; + LF = 10; + CR = 13; + SPACE = 32; + HYPHEN = 45; + COLON = 58; + A = 97; + Z = 122; + lower = (c) => c | 32; + noop = () => { + }; + MultipartParser = class { + /** + * @param {string} boundary + */ + constructor(boundary) { + this.index = 0; + this.flags = 0; + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + this.boundaryChars = {}; + boundary = "\r\n--" + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i2 = 0; i2 < boundary.length; i2++) { + ui8a[i2] = boundary.charCodeAt(i2); + this.boundaryChars[ui8a[i2]] = true; + } + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + /** + * @param {Uint8Array} data + */ + write(data) { + let i2 = 0; + const length_ = data.length; + let previousIndex = this.index; + let { lookbehind, boundary, boundaryChars, index, state, flags } = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + const mark = (name) => { + this[name + "Mark"] = i2; + }; + const clear = (name) => { + delete this[name + "Mark"]; + }; + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === void 0 || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + const dataCallback = (name, clear2) => { + const markSymbol = name + "Mark"; + if (!(markSymbol in this)) { + return; + } + if (clear2) { + callback(name, this[markSymbol], i2, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + for (i2 = 0; i2 < length_; i2++) { + c = data[i2]; + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + } else { + return; + } + break; + } + if (c !== boundary[index + 2]) { + index = -2; + } + if (c === boundary[index + 2]) { + index++; + } + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark("onHeaderField"); + index = 0; + case S.HEADER_FIELD: + if (c === CR) { + clear("onHeaderField"); + state = S.HEADERS_ALMOST_DONE; + break; + } + index++; + if (c === HYPHEN) { + break; + } + if (c === COLON) { + if (index === 1) { + return; + } + dataCallback("onHeaderField", true); + state = S.HEADER_VALUE_START; + break; + } + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + mark("onHeaderValue"); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if (c === CR) { + dataCallback("onHeaderValue", true); + callback("onHeaderEnd"); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + callback("onHeadersEnd"); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark("onPartData"); + case S.PART_DATA: + previousIndex = index; + if (index === 0) { + i2 += boundaryEnd; + while (i2 < bufferLength && !(data[i2] in boundaryChars)) { + i2 += boundaryLength; + } + i2 -= boundaryEnd; + c = data[i2]; + } + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback("onPartData", true); + } + index++; + } else { + index = 0; + } + } else if (index === boundary.length) { + index++; + if (c === CR) { + flags |= F.PART_BOUNDARY; + } else if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 === boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c === LF) { + flags &= ~F.PART_BOUNDARY; + callback("onPartEnd"); + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback("onPartEnd"); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + if (index > 0) { + lookbehind[index - 1] = c; + } else if (previousIndex > 0) { + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback("onPartData", 0, previousIndex, _lookbehind); + previousIndex = 0; + mark("onPartData"); + i2--; + } + break; + case S.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } + } + dataCallback("onHeaderField"); + dataCallback("onHeaderValue"); + dataCallback("onPartData"); + this.index = index; + this.state = state; + this.flags = flags; + } + end() { + if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error("MultipartParser.end(): stream ended unexpectedly"); + } + } + }; + } +}); + +// lib/assertions/providers/lambda-handler/index.ts +var lambda_handler_exports = {}; +__export(lambda_handler_exports, { + handler: () => handler, + isComplete: () => isComplete, + onTimeout: () => onTimeout +}); +module.exports = __toCommonJS(lambda_handler_exports); + +// lib/assertions/providers/lambda-handler/assertion.ts +var import_helpers_internal = __toESM(require_helpers_internal()); + +// lib/assertions/providers/lambda-handler/base.ts +var https = __toESM(require("https")); +var url = __toESM(require("url")); +var AWS = __toESM(require("aws-sdk")); +var CustomResourceHandler = class { + constructor(event, context) { + this.event = event; + this.context = context; + this.timedOut = false; + this.timeout = setTimeout(async () => { + await this.respond({ + status: "FAILED", + reason: "Lambda Function Timeout", + data: this.context.logStreamName + }); + this.timedOut = true; + }, context.getRemainingTimeInMillis() - 1200); + this.event = event; + this.physicalResourceId = extractPhysicalResourceId(event); + } + /** + * Handles executing the custom resource event. If `stateMachineArn` is present + * in the props then trigger the waiter statemachine + */ + async handle() { + try { + if ("stateMachineArn" in this.event.ResourceProperties) { + const req = { + stateMachineArn: this.event.ResourceProperties.stateMachineArn, + name: this.event.RequestId, + input: JSON.stringify(this.event) + }; + await this.startExecution(req); + return; + } else { + const response = await this.processEvent(this.event.ResourceProperties); + return response; + } + } catch (e2) { + console.log(e2); + throw e2; + } finally { + clearTimeout(this.timeout); + } + } + /** + * Handle async requests from the waiter state machine + */ + async handleIsComplete() { + try { + const result = await this.processEvent(this.event.ResourceProperties); + return result; + } catch (e2) { + console.log(e2); + return; + } finally { + clearTimeout(this.timeout); + } + } + /** + * Start a step function state machine which will wait for the request + * to be successful. + */ + async startExecution(req) { + try { + const sfn = new AWS.StepFunctions(); + await sfn.startExecution(req).promise(); + } finally { + clearTimeout(this.timeout); + } + } + respond(response) { + if (this.timedOut) { + return; + } + const cfResponse = { + Status: response.status, + Reason: response.reason, + PhysicalResourceId: this.physicalResourceId, + StackId: this.event.StackId, + RequestId: this.event.RequestId, + LogicalResourceId: this.event.LogicalResourceId, + NoEcho: false, + Data: response.data + }; + const responseBody = JSON.stringify(cfResponse); + console.log("Responding to CloudFormation", responseBody); + const parsedUrl = url.parse(this.event.ResponseURL); + const requestOptions = { + hostname: parsedUrl.hostname, + path: parsedUrl.path, + method: "PUT", + headers: { + "content-type": "", + "content-length": Buffer.byteLength(responseBody, "utf8") + } + }; + return new Promise((resolve, reject) => { + try { + const request2 = https.request(requestOptions, resolve); + request2.on("error", reject); + request2.write(responseBody); + request2.end(); + } catch (e2) { + reject(e2); + } finally { + clearTimeout(this.timeout); + } + }); + } +}; +function extractPhysicalResourceId(event) { + switch (event.RequestType) { + case "Create": + return event.LogicalResourceId; + case "Update": + case "Delete": + return event.PhysicalResourceId; + } +} + +// lib/assertions/providers/lambda-handler/assertion.ts +var AssertionHandler = class extends CustomResourceHandler { + async processEvent(request2) { + let actual = decodeCall(request2.actual); + const expected = decodeCall(request2.expected); + let result; + const matcher = new MatchCreator(expected).getMatcher(); + console.log(`Testing equality between ${JSON.stringify(request2.actual)} and ${JSON.stringify(request2.expected)}`); + const matchResult = matcher.test(actual); + matchResult.finished(); + if (matchResult.hasFailed()) { + result = { + failed: true, + assertion: JSON.stringify({ + status: "fail", + message: matchResult.renderMismatch() + }) + }; + if (request2.failDeployment) { + throw new Error(result.assertion); + } + } else { + result = { + assertion: JSON.stringify({ + status: "success" + }) + }; + } + return result; + } +}; +var MatchCreator = class { + constructor(obj) { + this.parsedObj = { + matcher: obj + }; + } + /** + * Return a Matcher that can be tested against the actual results. + * This will convert the encoded matchers into their corresponding + * assertions matcher. + * + * For example: + * + * ExpectedResult.objectLike({ + * Messages: [{ + * Body: Match.objectLike({ + * Elements: Match.arrayWith([{ Asdf: 3 }]), + * Payload: Match.serializedJson({ key: 'value' }), + * }), + * }], + * }); + * + * Will be encoded as: + * { + * $ObjectLike: { + * Messages: [{ + * Body: { + * $ObjectLike: { + * Elements: { + * $ArrayWith: [{ Asdf: 3 }], + * }, + * Payload: { + * $SerializedJson: { key: 'value' } + * } + * }, + * }, + * }], + * }, + * } + * + * Which can then be parsed by this function. For each key (recursively) + * the parser will check if the value has one of the encoded matchers as a key + * and if so, it will set the value as the Matcher. So, + * + * { + * Body: { + * $ObjectLike: { + * Elements: { + * $ArrayWith: [{ Asdf: 3 }], + * }, + * Payload: { + * $SerializedJson: { key: 'value' } + * } + * }, + * }, + * } + * + * Will be converted to + * { + * Body: Match.objectLike({ + * Elements: Match.arrayWith([{ Asdf: 3 }]), + * Payload: Match.serializedJson({ key: 'value' }), + * }), + * } + */ + getMatcher() { + try { + const final = JSON.parse(JSON.stringify(this.parsedObj), function(_k, v) { + const nested = Object.keys(v)[0]; + switch (nested) { + case "$ArrayWith": + return import_helpers_internal.Match.arrayWith(v[nested]); + case "$ObjectLike": + return import_helpers_internal.Match.objectLike(v[nested]); + case "$StringLike": + return import_helpers_internal.Match.stringLikeRegexp(v[nested]); + case "$SerializedJson": + return import_helpers_internal.Match.serializedJson(v[nested]); + default: + return v; + } + }); + if (import_helpers_internal.Matcher.isMatcher(final.matcher)) { + return final.matcher; + } + return import_helpers_internal.Match.exact(final.matcher); + } catch { + return import_helpers_internal.Match.exact(this.parsedObj.matcher); + } + } +}; +function decodeCall(call) { + if (!call) { + return void 0; + } + try { + const parsed = JSON.parse(call); + return parsed; + } catch { + return call; + } +} + +// node_modules/node-fetch/src/index.js +var import_node_http2 = __toESM(require("http"), 1); +var import_node_https = __toESM(require("https"), 1); +var import_node_zlib = __toESM(require("zlib"), 1); +var import_node_stream2 = __toESM(require("stream"), 1); +var import_node_buffer2 = require("buffer"); + +// ../../../node_modules/data-uri-to-buffer/dist/index.js +function dataUriToBuffer(uri) { + if (!/^data:/i.test(uri)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); + } + uri = uri.replace(/\r?\n/g, ""); + const firstComma = uri.indexOf(","); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError("malformed data: URI"); + } + const meta = uri.substring(5, firstComma).split(";"); + let charset = ""; + let base64 = false; + const type = meta[0] || "text/plain"; + let typeFull = type; + for (let i2 = 1; i2 < meta.length; i2++) { + if (meta[i2] === "base64") { + base64 = true; + } else if (meta[i2]) { + typeFull += `;${meta[i2]}`; + if (meta[i2].indexOf("charset=") === 0) { + charset = meta[i2].substring(8); + } + } + } + if (!meta[0] && !charset.length) { + typeFull += ";charset=US-ASCII"; + charset = "US-ASCII"; + } + const encoding = base64 ? "base64" : "ascii"; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + buffer.type = type; + buffer.typeFull = typeFull; + buffer.charset = charset; + return buffer; +} +var dist_default = dataUriToBuffer; + +// node_modules/node-fetch/src/body.js +var import_node_stream = __toESM(require("stream"), 1); +var import_node_util = require("util"); +var import_node_buffer = require("buffer"); +init_fetch_blob(); +init_esm_min(); + +// node_modules/node-fetch/src/errors/base.js +var FetchBaseError = class extends Error { + constructor(message, type) { + super(message); + Error.captureStackTrace(this, this.constructor); + this.type = type; + } + get name() { + return this.constructor.name; + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } +}; + +// node_modules/node-fetch/src/errors/fetch-error.js +var FetchError = class extends FetchBaseError { + /** + * @param {string} message - Error message for human + * @param {string} [type] - Error type for machine + * @param {SystemError} [systemError] - For Node.js system error + */ + constructor(message, type, systemError) { + super(message, type); + if (systemError) { + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } + } +}; + +// node_modules/node-fetch/src/utils/is.js +var NAME = Symbol.toStringTag; +var isURLSearchParameters = (object) => { + return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams"; +}; +var isBlob = (object) => { + return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]); +}; +var isAbortSignal = (object) => { + return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget"); +}; +var isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + return orig === dest || orig.endsWith(`.${dest}`); +}; +var isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + return orig === dest; +}; + +// node_modules/node-fetch/src/body.js +var pipeline = (0, import_node_util.promisify)(import_node_stream.default.pipeline); +var INTERNALS = Symbol("Body internals"); +var Body = class { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + if (body === null) { + body = null; + } else if (isURLSearchParameters(body)) { + body = import_node_buffer.Buffer.from(body.toString()); + } else if (isBlob(body)) { + } else if (import_node_buffer.Buffer.isBuffer(body)) { + } else if (import_node_util.types.isAnyArrayBuffer(body)) { + body = import_node_buffer.Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + body = import_node_buffer.Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof import_node_stream.default) { + } else if (body instanceof FormData) { + body = formDataToBlob(body); + boundary = body.type.split("=")[1]; + } else { + body = import_node_buffer.Buffer.from(String(body)); + } + let stream = body; + if (import_node_buffer.Buffer.isBuffer(body)) { + stream = import_node_stream.default.Readable.from(body); + } else if (isBlob(body)) { + stream = import_node_stream.default.Readable.from(body.stream()); + } + this[INTERNALS] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + if (body instanceof import_node_stream.default) { + body.on("error", (error_) => { + const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_); + this[INTERNALS].error = error; + }); + } + } + get body() { + return this[INTERNALS].stream; + } + get bodyUsed() { + return this[INTERNALS].disturbed; + } + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + async arrayBuffer() { + const { buffer, byteOffset, byteLength } = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + async formData() { + const ct = this.headers.get("content-type"); + if (ct.startsWith("application/x-www-form-urlencoded")) { + const formData = new FormData(); + const parameters = new URLSearchParams(await this.text()); + for (const [name, value] of parameters) { + formData.append(name, value); + } + return formData; + } + const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports)); + return toFormData2(this.body, ct); + } + /** + * Return raw response as Blob + * + * @return Promise + */ + async blob() { + const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || ""; + const buf = await this.arrayBuffer(); + return new fetch_blob_default([buf], { + type: ct + }); + } + /** + * Decode response as json + * + * @return Promise + */ + async json() { + const text = await this.text(); + return JSON.parse(text); + } + /** + * Decode response as text + * + * @return Promise + */ + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody(this); + } +}; +Body.prototype.buffer = (0, import_node_util.deprecate)(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer"); +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true }, + data: { get: (0, import_node_util.deprecate)( + () => { + }, + "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", + "https://github.com/node-fetch/node-fetch/issues/1000 (response)" + ) } +}); +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + data[INTERNALS].disturbed = true; + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + const { body } = data; + if (body === null) { + return import_node_buffer.Buffer.alloc(0); + } + if (!(body instanceof import_node_stream.default)) { + return import_node_buffer.Buffer.alloc(0); + } + const accum = []; + let accumBytes = 0; + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size"); + body.destroy(error); + throw error; + } + accumBytes += chunk.length; + accum.push(chunk); + } + } catch (error) { + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, "system", error); + throw error_; + } + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every((c) => typeof c === "string")) { + return import_node_buffer.Buffer.from(accum.join("")); + } + return import_node_buffer.Buffer.concat(accum, accumBytes); + } catch (error) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, "system", error); + } + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} +var clone = (instance, highWaterMark) => { + let p1; + let p2; + let { body } = instance[INTERNALS]; + if (instance.bodyUsed) { + throw new Error("cannot clone body after it is used"); + } + if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") { + p1 = new import_node_stream.PassThrough({ highWaterMark }); + p2 = new import_node_stream.PassThrough({ highWaterMark }); + body.pipe(p1); + body.pipe(p2); + instance[INTERNALS].stream = p1; + body = p2; + } + return body; +}; +var getNonSpecFormDataBoundary = (0, import_node_util.deprecate)( + (body) => body.getBoundary(), + "form-data doesn't follow the spec and requires special treatment. Use alternative package", + "https://github.com/node-fetch/node-fetch/issues/1167" +); +var extractContentType = (body, request2) => { + if (body === null) { + return null; + } + if (typeof body === "string") { + return "text/plain;charset=UTF-8"; + } + if (isURLSearchParameters(body)) { + return "application/x-www-form-urlencoded;charset=UTF-8"; + } + if (isBlob(body)) { + return body.type || null; + } + if (import_node_buffer.Buffer.isBuffer(body) || import_node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + if (body instanceof FormData) { + return `multipart/form-data; boundary=${request2[INTERNALS].boundary}`; + } + if (body && typeof body.getBoundary === "function") { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + if (body instanceof import_node_stream.default) { + return null; + } + return "text/plain;charset=UTF-8"; +}; +var getTotalBytes = (request2) => { + const { body } = request2[INTERNALS]; + if (body === null) { + return 0; + } + if (isBlob(body)) { + return body.size; + } + if (import_node_buffer.Buffer.isBuffer(body)) { + return body.length; + } + if (body && typeof body.getLengthSync === "function") { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + return null; +}; +var writeToStream = async (dest, { body }) => { + if (body === null) { + dest.end(); + } else { + await pipeline(body, dest); + } +}; + +// node_modules/node-fetch/src/headers.js +var import_node_util2 = require("util"); +var import_node_http = __toESM(require("http"), 1); +var validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_HTTP_TOKEN" }); + throw error; + } +}; +var validateHeaderValue = typeof import_node_http.default.validateHeaderValue === "function" ? import_node_http.default.validateHeaderValue : (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_CHAR" }); + throw error; + } +}; +var Headers = class extends URLSearchParams { + /** + * Headers class + * + * @constructor + * @param {HeadersInit} [init] - Response headers + */ + constructor(init) { + let result = []; + if (init instanceof Headers) { + const raw = init.raw(); + for (const [name, values] of Object.entries(raw)) { + result.push(...values.map((value) => [name, value])); + } + } else if (init == null) { + } else if (typeof init === "object" && !import_node_util2.types.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + if (method == null) { + result.push(...Object.entries(init)); + } else { + if (typeof method !== "function") { + throw new TypeError("Header pairs must be iterable"); + } + result = [...init].map((pair) => { + if (typeof pair !== "object" || import_node_util2.types.isBoxedPrimitive(pair)) { + throw new TypeError("Each header pair must be an iterable object"); + } + return [...pair]; + }).map((pair) => { + if (pair.length !== 2) { + throw new TypeError("Each header pair must be a name/value tuple"); + } + return [...pair]; + }); + } + } else { + throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)"); + } + result = result.length > 0 ? result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : void 0; + super(result); + return new Proxy(this, { + get(target, p, receiver) { + switch (p) { + case "append": + case "set": + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase(), + String(value) + ); + }; + case "delete": + case "has": + case "getAll": + return (name) => { + validateHeaderName(name); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase() + ); + }; + case "keys": + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + default: + return Reflect.get(target, p, receiver); + } + } + }); + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } + toString() { + return Object.prototype.toString.call(this); + } + get(name) { + const values = this.getAll(name); + if (values.length === 0) { + return null; + } + let value = values.join(", "); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + return value; + } + forEach(callback, thisArg = void 0) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } + } + *values() { + for (const name of this.keys()) { + yield this.get(name); + } + } + /** + * @type {() => IterableIterator<[string, string]>} + */ + *entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } + } + [Symbol.iterator]() { + return this.entries(); + } + /** + * Node-fetch non-spec method + * returning all headers and their values as array + * @returns {Record} + */ + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); + } + /** + * For better console.log(headers) and also to convert Headers into Node.js Request compatible format + */ + [Symbol.for("nodejs.util.inspect.custom")]() { + return [...this.keys()].reduce((result, key) => { + const values = this.getAll(key); + if (key === "host") { + result[key] = values[0]; + } else { + result[key] = values.length > 1 ? values : values[0]; + } + return result; + }, {}); + } +}; +Object.defineProperties( + Headers.prototype, + ["get", "entries", "forEach", "values"].reduce((result, property) => { + result[property] = { enumerable: true }; + return result; + }, {}) +); +function fromRawHeaders(headers = []) { + return new Headers( + headers.reduce((result, value, index, array) => { + if (index % 2 === 0) { + result.push(array.slice(index, index + 2)); + } + return result; + }, []).filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch { + return false; + } + }) + ); +} + +// node_modules/node-fetch/src/utils/is-redirect.js +var redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); +var isRedirect = (code) => { + return redirectStatus.has(code); +}; + +// node_modules/node-fetch/src/response.js +var INTERNALS2 = Symbol("Response internals"); +var Response = class extends Body { + constructor(body = null, options = {}) { + super(body, options); + const status = options.status != null ? options.status : 200; + const headers = new Headers(options.headers); + if (body !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append("Content-Type", contentType); + } + } + this[INTERNALS2] = { + type: "default", + url: options.url, + status, + statusText: options.statusText || "", + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + get type() { + return this[INTERNALS2].type; + } + get url() { + return this[INTERNALS2].url || ""; + } + get status() { + return this[INTERNALS2].status; + } + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300; + } + get redirected() { + return this[INTERNALS2].counter > 0; + } + get statusText() { + return this[INTERNALS2].statusText; + } + get headers() { + return this[INTERNALS2].headers; + } + get highWaterMark() { + return this[INTERNALS2].highWaterMark; + } + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); + } + /** + * @param {string} url The URL that the new response is to originate from. + * @param {number} status An optional status code for the response (e.g., 302.) + * @returns {Response} A Response object. + */ + static redirect(url2, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + return new Response(null, { + headers: { + location: new URL(url2).toString() + }, + status + }); + } + static error() { + const response = new Response(null, { status: 0, statusText: "" }); + response[INTERNALS2].type = "error"; + return response; + } + static json(data = void 0, init = {}) { + const body = JSON.stringify(data); + if (body === void 0) { + throw new TypeError("data is not JSON serializable"); + } + const headers = new Headers(init && init.headers); + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + return new Response(body, { + ...init, + headers + }); + } + get [Symbol.toStringTag]() { + return "Response"; + } +}; +Object.defineProperties(Response.prototype, { + type: { enumerable: true }, + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +// node_modules/node-fetch/src/request.js +var import_node_url = require("url"); +var import_node_util3 = require("util"); + +// node_modules/node-fetch/src/utils/get-search.js +var getSearch = (parsedURL) => { + if (parsedURL.search) { + return parsedURL.search; + } + const lastOffset = parsedURL.href.length - 1; + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : ""); + return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : ""; +}; + +// node_modules/node-fetch/src/utils/referrer.js +var import_node_net = require("net"); +function stripURLForUseAsAReferrer(url2, originOnly = false) { + if (url2 == null) { + return "no-referrer"; + } + url2 = new URL(url2); + if (/^(about|blob|data):$/.test(url2.protocol)) { + return "no-referrer"; + } + url2.username = ""; + url2.password = ""; + url2.hash = ""; + if (originOnly) { + url2.pathname = ""; + url2.search = ""; + } + return url2; +} +var ReferrerPolicy = /* @__PURE__ */ new Set([ + "", + "no-referrer", + "no-referrer-when-downgrade", + "same-origin", + "origin", + "strict-origin", + "origin-when-cross-origin", + "strict-origin-when-cross-origin", + "unsafe-url" +]); +var DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin"; +function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + return referrerPolicy; +} +function isOriginPotentiallyTrustworthy(url2) { + if (/^(http|ws)s:$/.test(url2.protocol)) { + return true; + } + const hostIp = url2.host.replace(/(^\[)|(]$)/g, ""); + const hostIPVersion = (0, import_node_net.isIP)(hostIp); + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + if (url2.host === "localhost" || url2.host.endsWith(".localhost")) { + return false; + } + if (url2.protocol === "file:") { + return true; + } + return false; +} +function isUrlPotentiallyTrustworthy(url2) { + if (/^about:(blank|srcdoc)$/.test(url2)) { + return true; + } + if (url2.protocol === "data:") { + return true; + } + if (/^(blob|filesystem):$/.test(url2.protocol)) { + return true; + } + return isOriginPotentiallyTrustworthy(url2); +} +function determineRequestsReferrer(request2, { referrerURLCallback, referrerOriginCallback } = {}) { + if (request2.referrer === "no-referrer" || request2.referrerPolicy === "") { + return null; + } + const policy = request2.referrerPolicy; + if (request2.referrer === "about:client") { + return "no-referrer"; + } + const referrerSource = request2.referrer; + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + const currentURL = new URL(request2.url); + switch (policy) { + case "no-referrer": + return "no-referrer"; + case "origin": + return referrerOrigin; + case "unsafe-url": + return referrerURL; + case "strict-origin": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin.toString(); + case "strict-origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin; + case "same-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return "no-referrer"; + case "origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return referrerOrigin; + case "no-referrer-when-downgrade": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerURL; + default: + throw new TypeError(`Invalid referrerPolicy: ${policy}`); + } +} +function parseReferrerPolicyFromHeader(headers) { + const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/); + let policy = ""; + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy = token; + } + } + return policy; +} + +// node_modules/node-fetch/src/request.js +var INTERNALS3 = Symbol("Request internals"); +var isRequest = (object) => { + return typeof object === "object" && typeof object[INTERNALS3] === "object"; +}; +var doBadDataWarn = (0, import_node_util3.deprecate)( + () => { + }, + ".data is not a valid RequestInit property, use .body instead", + "https://github.com/node-fetch/node-fetch/issues/1000 (request)" +); +var Request = class extends Body { + constructor(input, init = {}) { + let parsedURL; + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; + } + if (parsedURL.username !== "" || parsedURL.password !== "") { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); + } + let method = init.method || input.method || "GET"; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); + } + if (!isRequest(init) && "data" in init) { + doBadDataWarn(); + } + if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) { + throw new TypeError("Request with GET/HEAD method cannot have body"); + } + const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + super(inputBody, { + size: init.size || input.size || 0 + }); + const headers = new Headers(init.headers || input.headers || {}); + if (inputBody !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set("Content-Type", contentType); + } + } + let signal = isRequest(input) ? input.signal : null; + if ("signal" in init) { + signal = init.signal; + } + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget"); + } + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === "") { + referrer = "no-referrer"; + } else if (referrer) { + const parsedReferrer = new URL(referrer); + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer; + } else { + referrer = void 0; + } + this[INTERNALS3] = { + method, + redirect: init.redirect || input.redirect || "follow", + headers, + parsedURL, + signal, + referrer + }; + this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow; + this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ""; + } + /** @returns {string} */ + get method() { + return this[INTERNALS3].method; + } + /** @returns {string} */ + get url() { + return (0, import_node_url.format)(this[INTERNALS3].parsedURL); + } + /** @returns {Headers} */ + get headers() { + return this[INTERNALS3].headers; + } + get redirect() { + return this[INTERNALS3].redirect; + } + /** @returns {AbortSignal} */ + get signal() { + return this[INTERNALS3].signal; + } + // https://fetch.spec.whatwg.org/#dom-request-referrer + get referrer() { + if (this[INTERNALS3].referrer === "no-referrer") { + return ""; + } + if (this[INTERNALS3].referrer === "client") { + return "about:client"; + } + if (this[INTERNALS3].referrer) { + return this[INTERNALS3].referrer.toString(); + } + return void 0; + } + get referrerPolicy() { + return this[INTERNALS3].referrerPolicy; + } + set referrerPolicy(referrerPolicy) { + this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } + get [Symbol.toStringTag]() { + return "Request"; + } +}; +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true }, + referrer: { enumerable: true }, + referrerPolicy: { enumerable: true } +}); +var getNodeRequestOptions = (request2) => { + const { parsedURL } = request2[INTERNALS3]; + const headers = new Headers(request2[INTERNALS3].headers); + if (!headers.has("Accept")) { + headers.set("Accept", "*/*"); + } + let contentLengthValue = null; + if (request2.body === null && /^(post|put)$/i.test(request2.method)) { + contentLengthValue = "0"; + } + if (request2.body !== null) { + const totalBytes = getTotalBytes(request2); + if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set("Content-Length", contentLengthValue); + } + if (request2.referrerPolicy === "") { + request2.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + if (request2.referrer && request2.referrer !== "no-referrer") { + request2[INTERNALS3].referrer = determineRequestsReferrer(request2); + } else { + request2[INTERNALS3].referrer = "no-referrer"; + } + if (request2[INTERNALS3].referrer instanceof URL) { + headers.set("Referer", request2.referrer); + } + if (!headers.has("User-Agent")) { + headers.set("User-Agent", "node-fetch"); + } + if (request2.compress && !headers.has("Accept-Encoding")) { + headers.set("Accept-Encoding", "gzip, deflate, br"); + } + let { agent } = request2; + if (typeof agent === "function") { + agent = agent(parsedURL); + } + if (!headers.has("Connection") && !agent) { + headers.set("Connection", "close"); + } + const search = getSearch(parsedURL); + const options = { + // Overwrite search to retain trailing ? (issue #776) + path: parsedURL.pathname + search, + // The following options are not expressed in the URL + method: request2.method, + headers: headers[Symbol.for("nodejs.util.inspect.custom")](), + insecureHTTPParser: request2.insecureHTTPParser, + agent + }; + return { + /** @type {URL} */ + parsedURL, + options + }; +}; + +// node_modules/node-fetch/src/errors/abort-error.js +var AbortError = class extends FetchBaseError { + constructor(message, type = "aborted") { + super(message, type); + } +}; + +// node_modules/node-fetch/src/index.js +init_esm_min(); +init_from(); +var supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]); +async function fetch(url2, options_) { + return new Promise((resolve, reject) => { + const request2 = new Request(url2, options_); + const { parsedURL, options } = getNodeRequestOptions(request2); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url2}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`); + } + if (parsedURL.protocol === "data:") { + const data = dist_default(request2.url); + const response2 = new Response(data, { headers: { "Content-Type": data.typeFull } }); + resolve(response2); + return; + } + const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request; + const { signal } = request2; + let response = null; + const abort = () => { + const error = new AbortError("The operation was aborted."); + reject(error); + if (request2.body && request2.body instanceof import_node_stream2.default.Readable) { + request2.body.destroy(error); + } + if (!response || !response.body) { + return; + } + response.body.emit("error", error); + }; + if (signal && signal.aborted) { + abort(); + return; + } + const abortAndFinalize = () => { + abort(); + finalize(); + }; + const request_ = send(parsedURL.toString(), options); + if (signal) { + signal.addEventListener("abort", abortAndFinalize); + } + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener("abort", abortAndFinalize); + } + }; + request_.on("error", (error) => { + reject(new FetchError(`request to ${request2.url} failed, reason: ${error.message}`, "system", error)); + finalize(); + }); + fixResponseChunkedTransferBadEnding(request_, (error) => { + if (response && response.body) { + response.body.destroy(error); + } + }); + if (process.version < "v14") { + request_.on("socket", (s2) => { + let endedWithEventsCount; + s2.prependListener("end", () => { + endedWithEventsCount = s2._eventsCount; + }); + s2.prependListener("close", (hadError) => { + if (response && endedWithEventsCount < s2._eventsCount && !hadError) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + response.body.emit("error", error); + } + }); + }); + } + request_.on("response", (response_) => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + if (isRedirect(response_.statusCode)) { + const location = headers.get("Location"); + let locationURL = null; + try { + locationURL = location === null ? null : new URL(location, request2.url); + } catch { + if (request2.redirect !== "manual") { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect")); + finalize(); + return; + } + } + switch (request2.redirect) { + case "error": + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request2.url}`, "no-redirect")); + finalize(); + return; + case "manual": + break; + case "follow": { + if (locationURL === null) { + break; + } + if (request2.counter >= request2.follow) { + reject(new FetchError(`maximum redirect reached at: ${request2.url}`, "max-redirect")); + finalize(); + return; + } + const requestOptions = { + headers: new Headers(request2.headers), + follow: request2.follow, + counter: request2.counter + 1, + agent: request2.agent, + compress: request2.compress, + method: request2.method, + body: clone(request2), + signal: request2.signal, + size: request2.size, + referrer: request2.referrer, + referrerPolicy: request2.referrerPolicy + }; + if (!isDomainOrSubdomain(request2.url, locationURL) || !isSameProtocol(request2.url, locationURL)) { + for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) { + requestOptions.headers.delete(name); + } + } + if (response_.statusCode !== 303 && request2.body && options_.body instanceof import_node_stream2.default.Readable) { + reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect")); + finalize(); + return; + } + if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request2.method === "POST") { + requestOptions.method = "GET"; + requestOptions.body = void 0; + requestOptions.headers.delete("content-length"); + } + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + resolve(fetch(new Request(locationURL, requestOptions))); + finalize(); + return; + } + default: + return reject(new TypeError(`Redirect option '${request2.redirect}' is not a valid value of RequestRedirect`)); + } + } + if (signal) { + response_.once("end", () => { + signal.removeEventListener("abort", abortAndFinalize); + }); + } + let body = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + if (process.version < "v12.10") { + response_.on("aborted", abortAndFinalize); + } + const responseOptions = { + url: request2.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request2.size, + counter: request2.counter, + highWaterMark: request2.highWaterMark + }; + const codings = headers.get("Content-Encoding"); + if (!request2.compress || request2.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + const zlibOptions = { + flush: import_node_zlib.default.Z_SYNC_FLUSH, + finishFlush: import_node_zlib.default.Z_SYNC_FLUSH + }; + if (codings === "gzip" || codings === "x-gzip") { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createGunzip(zlibOptions), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + if (codings === "deflate" || codings === "x-deflate") { + const raw = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + raw.once("data", (chunk) => { + if ((chunk[0] & 15) === 8) { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflate(), (error) => { + if (error) { + reject(error); + } + }); + } else { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflateRaw(), (error) => { + if (error) { + reject(error); + } + }); + } + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once("end", () => { + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + if (codings === "br") { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + response = new Response(body, responseOptions); + resolve(response); + }); + writeToStream(request_, request2).catch(reject); + }); +} +function fixResponseChunkedTransferBadEnding(request2, errorCallback) { + const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n"); + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + request2.on("response", (response) => { + const { headers } = response; + isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"]; + }); + request2.on("socket", (socket) => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + errorCallback(error); + } + }; + const onData = (buf) => { + properLastChunkReceived = import_node_buffer2.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = import_node_buffer2.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && import_node_buffer2.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0; + } + previousChunk = buf; + }; + socket.prependListener("close", onSocketClose); + socket.on("data", onData); + request2.on("close", () => { + socket.removeListener("close", onSocketClose); + socket.removeListener("data", onData); + }); + }); +} + +// lib/assertions/providers/lambda-handler/http.ts +var HttpHandler = class extends CustomResourceHandler { + async processEvent(request2) { + console.log("request", request2); + const response = await fetch(request2.parameters.url, request2.parameters.fetchOptions); + const result = { + ok: response.ok, + status: response.status, + statusText: response.statusText, + headers: response.headers.raw() + }; + try { + const jsonResponse = await response.json(); + result.body = jsonResponse; + } catch (e2) { + result.body = {}; + } + return { + apiCallResponse: result + }; + } +}; + +// lib/assertions/providers/lambda-handler/utils.ts +function decode(object) { + return JSON.parse(JSON.stringify(object), (_k, v) => { + switch (v) { + case "TRUE:BOOLEAN": + return true; + case "FALSE:BOOLEAN": + return false; + default: + return v; + } + }); +} + +// lib/assertions/providers/lambda-handler/sdk.ts +function flatten(object) { + return Object.assign( + {}, + ...function _flatten(child, path = []) { + return [].concat(...Object.keys(child).map((key) => { + let childKey = Buffer.isBuffer(child[key]) ? child[key].toString("utf8") : child[key]; + if (typeof childKey === "string") { + childKey = isJsonString(childKey); + } + return typeof childKey === "object" && childKey !== null ? _flatten(childKey, path.concat([key])) : { [path.concat([key]).join(".")]: childKey }; + })); + }(object) + ); +} +var AwsApiCallHandler = class extends CustomResourceHandler { + async processEvent(request2) { + const AWS2 = require("aws-sdk"); + console.log(`AWS SDK VERSION: ${AWS2.VERSION}`); + if (!Object.prototype.hasOwnProperty.call(AWS2, request2.service)) { + throw Error(`Service ${request2.service} does not exist in AWS SDK version ${AWS2.VERSION}.`); + } + const service = new AWS2[request2.service](); + const response = await service[request2.api](request2.parameters && decode(request2.parameters)).promise(); + console.log(`SDK response received ${JSON.stringify(response)}`); + delete response.ResponseMetadata; + const respond = { + apiCallResponse: response + }; + const flatData = { + ...flatten(respond) + }; + let resp = respond; + if (request2.outputPaths) { + resp = filterKeys(flatData, request2.outputPaths); + } else if (request2.flattenResponse === "true") { + resp = flatData; + } + console.log(`Returning result ${JSON.stringify(resp)}`); + return resp; + } +}; +function filterKeys(object, searchStrings) { + return Object.entries(object).reduce((filteredObject, [key, value]) => { + for (const searchString of searchStrings) { + if (key.startsWith(`apiCallResponse.${searchString}`)) { + filteredObject[key] = value; + } + } + return filteredObject; + }, {}); +} +function isJsonString(value) { + try { + return JSON.parse(value); + } catch { + return value; + } +} + +// lib/assertions/providers/lambda-handler/types.ts +var ASSERT_RESOURCE_TYPE = "Custom::DeployAssert@AssertEquals"; +var SDK_RESOURCE_TYPE_PREFIX = "Custom::DeployAssert@SdkCall"; +var HTTP_RESOURCE_TYPE = "Custom::DeployAssert@HttpCall"; + +// lib/assertions/providers/lambda-handler/index.ts +async function handler(event, context) { + console.log(`Event: ${JSON.stringify({ ...event, ResponseURL: "..." })}`); + const provider = createResourceHandler(event, context); + try { + if (event.RequestType === "Delete") { + await provider.respond({ + status: "SUCCESS", + reason: "OK" + }); + return; + } + const result = await provider.handle(); + if ("stateMachineArn" in event.ResourceProperties) { + console.info('Found "stateMachineArn", waiter statemachine started'); + return; + } else if ("expected" in event.ResourceProperties) { + console.info('Found "expected", testing assertions'); + const actualPath = event.ResourceProperties.actualPath; + const actual = actualPath ? result[`apiCallResponse.${actualPath}`] : result.apiCallResponse; + const assertion = new AssertionHandler({ + ...event, + ResourceProperties: { + ServiceToken: event.ServiceToken, + actual, + expected: event.ResourceProperties.expected + } + }, context); + try { + const assertionResult = await assertion.handle(); + await provider.respond({ + status: "SUCCESS", + reason: "OK", + // return both the result of the API call _and_ the assertion results + data: { + ...assertionResult, + ...result + } + }); + return; + } catch (e2) { + await provider.respond({ + status: "FAILED", + reason: e2.message ?? "Internal Error" + }); + return; + } + } + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: result + }); + } catch (e2) { + await provider.respond({ + status: "FAILED", + reason: e2.message ?? "Internal Error" + }); + return; + } + return; +} +async function onTimeout(timeoutEvent) { + const isCompleteRequest = JSON.parse(JSON.parse(timeoutEvent.Cause).errorMessage); + const provider = createResourceHandler(isCompleteRequest, standardContext); + await provider.respond({ + status: "FAILED", + reason: "Operation timed out: " + JSON.stringify(isCompleteRequest) + }); +} +async function isComplete(event, context) { + console.log(`Event: ${JSON.stringify({ ...event, ResponseURL: "..." })}`); + const provider = createResourceHandler(event, context); + try { + const result = await provider.handleIsComplete(); + const actualPath = event.ResourceProperties.actualPath; + if (result) { + const actual = actualPath ? result[`apiCallResponse.${actualPath}`] : result.apiCallResponse; + if ("expected" in event.ResourceProperties) { + const assertion = new AssertionHandler({ + ...event, + ResourceProperties: { + ServiceToken: event.ServiceToken, + actual, + expected: event.ResourceProperties.expected + } + }, context); + const assertionResult = await assertion.handleIsComplete(); + if (!(assertionResult == null ? void 0 : assertionResult.failed)) { + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: { + ...assertionResult, + ...result + } + }); + return; + } else { + console.log(`Assertion Failed: ${JSON.stringify(assertionResult)}`); + throw new Error(JSON.stringify(event)); + } + } + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: result + }); + } else { + console.log("No result"); + throw new Error(JSON.stringify(event)); + } + return; + } catch (e2) { + console.log(e2); + throw new Error(JSON.stringify(event)); + } +} +function createResourceHandler(event, context) { + if (event.ResourceType.startsWith(SDK_RESOURCE_TYPE_PREFIX)) { + return new AwsApiCallHandler(event, context); + } else if (event.ResourceType.startsWith(ASSERT_RESOURCE_TYPE)) { + return new AssertionHandler(event, context); + } else if (event.ResourceType.startsWith(HTTP_RESOURCE_TYPE)) { + return new HttpHandler(event, context); + } else { + throw new Error(`Unsupported resource type "${event.ResourceType}`); + } +} +var standardContext = { + getRemainingTimeInMillis: () => 9e4 +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + handler, + isComplete, + onTimeout +}); +/*! Bundled license information: + +fetch-blob/index.js: + (*! fetch-blob. MIT License. Jimmy Wärting *) + +formdata-polyfill/esm.min.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting *) + +node-domexception/index.js: + (*! node-domexception. MIT License. Jimmy Wärting *) +*/ diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/cdk.out b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/cdk.out index 588d7b269d34f..f0b901e7c06e5 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/cdk.out +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/cdk.out @@ -1 +1 @@ -{"version":"20.0.0"} \ No newline at end of file +{"version":"32.0.0"} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/integ.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/integ.json index 088b891368fca..1898a3ce9ca39 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/integ.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/integ.json @@ -1,11 +1,12 @@ { - "version": "20.0.0", + "version": "32.0.0", "testCases": { "lambda-integration/DefaultTest": { "stacks": [ "LambdaApiIntegrationOptionsStack" ], - "assertionStack": "lambda-integration/DefaultTest/DeployAssert" + "assertionStack": "lambda-integration/DefaultTest/DeployAssert", + "assertionStackName": "lambdaintegrationDefaultTestDeployAssertAC2ED705" } } } \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/lambdaintegrationDefaultTestDeployAssertAC2ED705.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/lambdaintegrationDefaultTestDeployAssertAC2ED705.assets.json index 25acd2a4dfa20..8d46be6ae698f 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/lambdaintegrationDefaultTestDeployAssertAC2ED705.assets.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/lambdaintegrationDefaultTestDeployAssertAC2ED705.assets.json @@ -1,7 +1,20 @@ { - "version": "20.0.0", + "version": "32.0.0", "files": { - "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22": { + "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231": { + "source": { + "path": "asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle", + "packaging": "zip" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.zip", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + }, + "04f640bbe2d03b033525be6dbfd8cf75729dbf9720bc91e37045a300847a8104": { "source": { "path": "lambdaintegrationDefaultTestDeployAssertAC2ED705.template.json", "packaging": "file" @@ -9,7 +22,7 @@ "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "objectKey": "04f640bbe2d03b033525be6dbfd8cf75729dbf9720bc91e37045a300847a8104.json", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/lambdaintegrationDefaultTestDeployAssertAC2ED705.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/lambdaintegrationDefaultTestDeployAssertAC2ED705.template.json index ad9d0fb73d1dd..7516f9e5e934a 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/lambdaintegrationDefaultTestDeployAssertAC2ED705.template.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/lambdaintegrationDefaultTestDeployAssertAC2ED705.template.json @@ -1,4 +1,99 @@ { + "Resources": { + "HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1": { + "Type": "Custom::DeployAssert@HttpCall", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F", + "Arn" + ] + }, + "parameters": { + "url": { + "Fn::Join": [ + "", + [ + "https://", + { + "Fn::ImportValue": "LambdaApiIntegrationOptionsStack:ExportsOutputReflambdarestapiF559E4F2E351BC88" + }, + ".execute-api.", + { + "Ref": "AWS::Region" + }, + ".", + { + "Ref": "AWS::URLSuffix" + }, + "/", + { + "Fn::ImportValue": "LambdaApiIntegrationOptionsStack:ExportsOutputReflambdarestapiDeploymentStageprodA05F84EA6A0E534F" + }, + "/" + ] + ] + } + }, + "expected": "{\"$ObjectLike\":{\"body\":{\"message\":\"Hello\"}}}", + "salt": "1687520682509" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ] + }, + "ManagedPolicyArns": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + } + ] + } + }, + "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Runtime": "nodejs14.x", + "Code": { + "S3Bucket": { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + }, + "S3Key": "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.zip" + }, + "Timeout": 120, + "Handler": "index.handler", + "Role": { + "Fn::GetAtt": [ + "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73", + "Arn" + ] + } + } + } + }, + "Outputs": { + "AssertionResultsHttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1": { + "Value": { + "Fn::GetAtt": [ + "HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1", + "assertion" + ] + } + } + }, "Parameters": { "BootstrapVersion": { "Type": "AWS::SSM::Parameter::Value", diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/manifest.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/manifest.json index 4d396ab3bfa14..3da17346e8fcb 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/manifest.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/manifest.json @@ -1,12 +1,6 @@ { - "version": "20.0.0", + "version": "32.0.0", "artifacts": { - "Tree": { - "type": "cdk:tree", - "properties": { - "file": "tree.json" - } - }, "LambdaApiIntegrationOptionsStack.assets": { "type": "cdk:asset-manifest", "properties": { @@ -23,7 +17,7 @@ "validateOnSynth": false, "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", - "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/d2917ea4195aa0183538531b99a1ccb6369a7a90926d79378d84278263b33b46.json", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/4db5712a4ffeeb138b865a31a6cce9ec7becd96318f72baeb40d48a8b0d2a334.json", "requiresBootstrapStackVersion": 6, "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", "additionalDependencies": [ @@ -129,6 +123,18 @@ "data": "lambdarestapiANYB9BB3FB2" } ], + "/LambdaApiIntegrationOptionsStack/Exports/Output{\"Ref\":\"lambdarestapiF559E4F2\"}": [ + { + "type": "aws:cdk:logicalId", + "data": "ExportsOutputReflambdarestapiF559E4F2E351BC88" + } + ], + "/LambdaApiIntegrationOptionsStack/Exports/Output{\"Ref\":\"lambdarestapiDeploymentStageprodA05F84EA\"}": [ + { + "type": "aws:cdk:logicalId", + "data": "ExportsOutputReflambdarestapiDeploymentStageprodA05F84EA6A0E534F" + } + ], "/LambdaApiIntegrationOptionsStack/BootstrapVersion": [ { "type": "aws:cdk:logicalId", @@ -160,7 +166,7 @@ "validateOnSynth": false, "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", - "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/21fbb51d7b23f6a6c262b46a9caee79d744a3ac019fd45422d988b96d44b2a22.json", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/04f640bbe2d03b033525be6dbfd8cf75729dbf9720bc91e37045a300847a8104.json", "requiresBootstrapStackVersion": 6, "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", "additionalDependencies": [ @@ -173,9 +179,34 @@ } }, "dependencies": [ + "LambdaApiIntegrationOptionsStack", "lambdaintegrationDefaultTestDeployAssertAC2ED705.assets" ], "metadata": { + "/lambda-integration/DefaultTest/DeployAssert/HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1/Default/Default": [ + { + "type": "aws:cdk:logicalId", + "data": "HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1" + } + ], + "/lambda-integration/DefaultTest/DeployAssert/HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1/AssertionResults": [ + { + "type": "aws:cdk:logicalId", + "data": "AssertionResultsHttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1" + } + ], + "/lambda-integration/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role": [ + { + "type": "aws:cdk:logicalId", + "data": "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73" + } + ], + "/lambda-integration/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Handler": [ + { + "type": "aws:cdk:logicalId", + "data": "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F" + } + ], "/lambda-integration/DefaultTest/DeployAssert/BootstrapVersion": [ { "type": "aws:cdk:logicalId", @@ -190,6 +221,12 @@ ] }, "displayName": "lambda-integration/DefaultTest/DeployAssert" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } } } } \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/tree.json b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/tree.json index b467dc1dc66f1..bb5d4baf9d949 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/tree.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.js.snapshot/tree.json @@ -4,14 +4,6 @@ "id": "App", "path": "", "children": { - "Tree": { - "id": "Tree", - "path": "Tree", - "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" - } - }, "LambdaApiIntegrationOptionsStack": { "id": "LambdaApiIntegrationOptionsStack", "path": "LambdaApiIntegrationOptionsStack", @@ -24,6 +16,14 @@ "id": "ServiceRole", "path": "LambdaApiIntegrationOptionsStack/myfn/ServiceRole", "children": { + "ImportServiceRole": { + "id": "ImportServiceRole", + "path": "LambdaApiIntegrationOptionsStack/myfn/ServiceRole/ImportServiceRole", + "constructInfo": { + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" + } + }, "Resource": { "id": "Resource", "path": "LambdaApiIntegrationOptionsStack/myfn/ServiceRole/Resource", @@ -59,13 +59,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-iam.CfnRole", + "fqn": "aws-cdk-lib.aws_iam.CfnRole", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-iam.Role", + "fqn": "aws-cdk-lib.aws_iam.Role", "version": "0.0.0" } }, @@ -76,7 +76,7 @@ "aws:cdk:cloudformation:type": "AWS::Lambda::Function", "aws:cdk:cloudformation:props": { "code": { - "zipFile": "foo" + "zipFile": "exports.handler = async function(event) {\n return {\n body: JSON.stringify({\n message: 'Hello',\n }),\n statusCode: 200,\n headers: { 'Content-Type': '*/*' }\n };\n }" }, "role": { "Fn::GetAtt": [ @@ -85,17 +85,17 @@ ] }, "handler": "index.handler", - "runtime": "nodejs14.x" + "runtime": "nodejs18.x" } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.CfnFunction", + "fqn": "aws-cdk-lib.aws_lambda.CfnFunction", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.Function", + "fqn": "aws-cdk-lib.aws_lambda.Function", "version": "0.0.0" } }, @@ -113,7 +113,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnRestApi", + "fqn": "aws-cdk-lib.aws_apigateway.CfnRestApi", "version": "0.0.0" } }, @@ -121,6 +121,14 @@ "id": "CloudWatchRole", "path": "LambdaApiIntegrationOptionsStack/lambdarestapi/CloudWatchRole", "children": { + "ImportCloudWatchRole": { + "id": "ImportCloudWatchRole", + "path": "LambdaApiIntegrationOptionsStack/lambdarestapi/CloudWatchRole/ImportCloudWatchRole", + "constructInfo": { + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" + } + }, "Resource": { "id": "Resource", "path": "LambdaApiIntegrationOptionsStack/lambdarestapi/CloudWatchRole/Resource", @@ -156,13 +164,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-iam.CfnRole", + "fqn": "aws-cdk-lib.aws_iam.CfnRole", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-iam.Role", + "fqn": "aws-cdk-lib.aws_iam.Role", "version": "0.0.0" } }, @@ -181,7 +189,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnAccount", + "fqn": "aws-cdk-lib.aws_apigateway.CfnAccount", "version": "0.0.0" } }, @@ -202,13 +210,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnDeployment", + "fqn": "aws-cdk-lib.aws_apigateway.CfnDeployment", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Deployment", + "fqn": "aws-cdk-lib.aws_apigateway.Deployment", "version": "0.0.0" } }, @@ -232,13 +240,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnStage", + "fqn": "aws-cdk-lib.aws_apigateway.CfnStage", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Stage", + "fqn": "aws-cdk-lib.aws_apigateway.Stage", "version": "0.0.0" } }, @@ -246,8 +254,8 @@ "id": "Endpoint", "path": "LambdaApiIntegrationOptionsStack/lambdarestapi/Endpoint", "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.CfnOutput", + "version": "0.0.0" } }, "Default": { @@ -277,7 +285,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnResource", + "fqn": "aws-cdk-lib.aws_apigateway.CfnResource", "version": "0.0.0" } }, @@ -330,7 +338,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.CfnPermission", + "fqn": "aws-cdk-lib.aws_lambda.CfnPermission", "version": "0.0.0" } }, @@ -375,7 +383,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.CfnPermission", + "fqn": "aws-cdk-lib.aws_lambda.CfnPermission", "version": "0.0.0" } }, @@ -424,19 +432,19 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnMethod", + "fqn": "aws-cdk-lib.aws_apigateway.CfnMethod", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Method", + "fqn": "aws-cdk-lib.aws_apigateway.Method", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.ProxyResource", + "fqn": "aws-cdk-lib.aws_apigateway.ProxyResource", "version": "0.0.0" } }, @@ -489,7 +497,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.CfnPermission", + "fqn": "aws-cdk-lib.aws_lambda.CfnPermission", "version": "0.0.0" } }, @@ -534,7 +542,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.CfnPermission", + "fqn": "aws-cdk-lib.aws_lambda.CfnPermission", "version": "0.0.0" } }, @@ -586,32 +594,74 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.CfnMethod", + "fqn": "aws-cdk-lib.aws_apigateway.CfnMethod", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.Method", + "fqn": "aws-cdk-lib.aws_apigateway.Method", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.ResourceBase", + "fqn": "aws-cdk-lib.aws_apigateway.ResourceBase", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-apigateway.LambdaRestApi", + "fqn": "aws-cdk-lib.aws_apigateway.LambdaRestApi", + "version": "0.0.0" + } + }, + "Exports": { + "id": "Exports", + "path": "LambdaApiIntegrationOptionsStack/Exports", + "children": { + "Output{\"Ref\":\"lambdarestapiF559E4F2\"}": { + "id": "Output{\"Ref\":\"lambdarestapiF559E4F2\"}", + "path": "LambdaApiIntegrationOptionsStack/Exports/Output{\"Ref\":\"lambdarestapiF559E4F2\"}", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnOutput", + "version": "0.0.0" + } + }, + "Output{\"Ref\":\"lambdarestapiDeploymentStageprodA05F84EA\"}": { + "id": "Output{\"Ref\":\"lambdarestapiDeploymentStageprodA05F84EA\"}", + "path": "LambdaApiIntegrationOptionsStack/Exports/Output{\"Ref\":\"lambdarestapiDeploymentStageprodA05F84EA\"}", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnOutput", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "LambdaApiIntegrationOptionsStack/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "LambdaApiIntegrationOptionsStack/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" } }, "lambda-integration": { @@ -627,33 +677,147 @@ "path": "lambda-integration/DefaultTest/Default", "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.85" + "version": "10.2.55" } }, "DeployAssert": { "id": "DeployAssert", "path": "lambda-integration/DefaultTest/DeployAssert", + "children": { + "HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1": { + "id": "HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1", + "path": "lambda-integration/DefaultTest/DeployAssert/HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1", + "children": { + "HttpProvider": { + "id": "HttpProvider", + "path": "lambda-integration/DefaultTest/DeployAssert/HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1/HttpProvider", + "children": { + "AssertionsProvider": { + "id": "AssertionsProvider", + "path": "lambda-integration/DefaultTest/DeployAssert/HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1/HttpProvider/AssertionsProvider", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "Default": { + "id": "Default", + "path": "lambda-integration/DefaultTest/DeployAssert/HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1/Default", + "children": { + "Default": { + "id": "Default", + "path": "lambda-integration/DefaultTest/DeployAssert/HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1/Default/Default", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.CustomResource", + "version": "0.0.0" + } + }, + "AssertionResults": { + "id": "AssertionResults", + "path": "lambda-integration/DefaultTest/DeployAssert/HttpApiCallc5e2beec0ed716e95fd6628a8bb7c2f1/AssertionResults", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnOutput", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "SingletonFunction1488541a7b23466481b69b4408076b81": { + "id": "SingletonFunction1488541a7b23466481b69b4408076b81", + "path": "lambda-integration/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81", + "children": { + "Staging": { + "id": "Staging", + "path": "lambda-integration/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Staging", + "constructInfo": { + "fqn": "aws-cdk-lib.AssetStaging", + "version": "0.0.0" + } + }, + "Role": { + "id": "Role", + "path": "lambda-integration/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + }, + "Handler": { + "id": "Handler", + "path": "lambda-integration/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Handler", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "lambda-integration/DefaultTest/DeployAssert/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "lambda-integration/DefaultTest/DeployAssert/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.IntegTestCase", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "@aws-cdk/integ-tests.IntegTest", - "version": "0.0.0" + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "Tree": { + "id": "Tree", + "path": "Tree", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.App", + "version": "0.0.0" } } } \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.ts b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.ts index 135383b70ad2b..e1887952f663f 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.ts +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-apigateway/test/integ.lambda-api.ts @@ -1,20 +1,29 @@ import { Code, Function, Runtime } from 'aws-cdk-lib/aws-lambda'; import { App, Duration, Stack } from 'aws-cdk-lib'; -import { IntegTest } from '@aws-cdk/integ-tests-alpha'; +import { ExpectedResult, IntegTest } from '@aws-cdk/integ-tests-alpha'; import { Construct } from 'constructs'; import { LambdaRestApi } from 'aws-cdk-lib/aws-apigateway'; class LambdaApiIntegrationOptionsStack extends Stack { + public readonly api: LambdaRestApi; constructor(scope: Construct) { super(scope, 'LambdaApiIntegrationOptionsStack'); const fn = new Function(this, 'myfn', { - code: Code.fromInline('foo'), - runtime: Runtime.NODEJS_14_X, + code: Code.fromInline(`exports.handler = async function(event) { + return { + body: JSON.stringify({ + message: 'Hello', + }), + statusCode: 200, + headers: { 'Content-Type': '*/*' } + }; + }`), + runtime: Runtime.NODEJS_18_X, handler: 'index.handler', }); - new LambdaRestApi(this, 'lambdarestapi', { + this.api = new LambdaRestApi(this, 'lambdarestapi', { handler: fn, cloudWatchRole: true, integrationOptions: { @@ -26,6 +35,11 @@ class LambdaApiIntegrationOptionsStack extends Stack { const app = new App(); const testCase = new LambdaApiIntegrationOptionsStack(app); -new IntegTest(app, 'lambda-integration', { +const integ = new IntegTest(app, 'lambda-integration', { testCases: [testCase], }); + +const call = integ.assertions.httpApiCall(testCase.api.deploymentStage.urlForPath('/')); +call.expect(ExpectedResult.objectLike({ + body: { message: 'Hello' }, +})); diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/TestStack.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/TestStack.assets.json index d5645f413d371..0e9170652da16 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/TestStack.assets.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/TestStack.assets.json @@ -1,7 +1,7 @@ { - "version": "20.0.0", + "version": "32.0.0", "files": { - "09fed6843eb7543b7a99153262d1d26031e96a708c160488de552fbeb33dc7df": { + "fbba15e6e00a4b1f0763788fc913facda96a647e18b1894398dc3cb12296dd41": { "source": { "path": "TestStack.template.json", "packaging": "file" @@ -9,7 +9,7 @@ "destinations": { "current_account-current_region": { "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", - "objectKey": "09fed6843eb7543b7a99153262d1d26031e96a708c160488de552fbeb33dc7df.json", + "objectKey": "fbba15e6e00a4b1f0763788fc913facda96a647e18b1894398dc3cb12296dd41.json", "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" } } diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/TestStack.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/TestStack.template.json index 72ba45b71a12b..931870dc8f9a4 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/TestStack.template.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/TestStack.template.json @@ -489,7 +489,7 @@ "Type": "AWS::Lambda::Function", "Properties": { "Code": { - "ZipFile": "\ndef handler(event, context):\n return {\n \"isBase64Encoded\": False,\n \"statusCode\": 200,\n \"statusDescription\": \"200 OK\",\n \"headers\": {\n \"Set-cookie\": \"cookies\",\n \"Content-Type\": \"application/json\"\n },\n \"body\": \"Hello from Lambda\"\n }\n " + "ZipFile": "\nimport json\ndef handler(event, context):\n return {\n \"isBase64Encoded\": False,\n \"statusCode\": 200,\n \"statusDescription\": \"200 OK\",\n \"headers\": {\n \"Set-cookie\": \"cookies\",\n \"Content-Type\": \"application/json\"\n },\n \"body\": json.dumps({ \"message\": \"Hello from Lambda\" })\n }\n " }, "Role": { "Fn::GetAtt": [ @@ -518,6 +518,19 @@ } } }, + "Outputs": { + "ExportsOutputFnGetAttLB8A12904CDNSName5EFD7323": { + "Value": { + "Fn::GetAtt": [ + "LB8A12904C", + "DNSName" + ] + }, + "Export": { + "Name": "TestStack:ExportsOutputFnGetAttLB8A12904CDNSName5EFD7323" + } + } + }, "Parameters": { "BootstrapVersion": { "Type": "AWS::SSM::Parameter::Value", diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js new file mode 100644 index 0000000000000..c29f3db7d5483 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle/index.js @@ -0,0 +1,7272 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; + +// ../../aws-cdk-lib/assertions/lib/matcher.ts +var matcher_exports = {}; +__export(matcher_exports, { + MatchResult: () => MatchResult, + Matcher: () => Matcher +}); +function* range(n) { + for (let i2 = 0; i2 < n; i2++) { + yield i2; + } +} +function* enumFirst(xs) { + let first = true; + for (const x2 of xs) { + yield [first, x2]; + first = false; + } +} +var Matcher, MatchResult; +var init_matcher = __esm({ + "../../aws-cdk-lib/assertions/lib/matcher.ts"() { + "use strict"; + Matcher = class { + /** + * Check whether the provided object is a subtype of the `IMatcher`. + */ + static isMatcher(x2) { + return x2 && x2 instanceof Matcher; + } + }; + MatchResult = class { + constructor(target) { + this.failuresHere = /* @__PURE__ */ new Map(); + this.captures = /* @__PURE__ */ new Map(); + this.finalized = false; + this.innerMatchFailures = /* @__PURE__ */ new Map(); + this._hasFailed = false; + this._failCount = 0; + this._cost = 0; + this.target = target; + } + /** + * DEPRECATED + * @deprecated use recordFailure() + */ + push(matcher, path, message) { + return this.recordFailure({ matcher, path, message }); + } + /** + * Record a new failure into this result at a specific path. + */ + recordFailure(failure) { + const failKey = failure.path.join("."); + let list = this.failuresHere.get(failKey); + if (!list) { + list = []; + this.failuresHere.set(failKey, list); + } + this._failCount += 1; + this._cost += failure.cost ?? 1; + list.push(failure); + this._hasFailed = true; + return this; + } + /** Whether the match is a success */ + get isSuccess() { + return !this._hasFailed; + } + /** Does the result contain any failures. If not, the result is a success */ + hasFailed() { + return this._hasFailed; + } + /** The number of failures */ + get failCount() { + return this._failCount; + } + /** The cost of the failures so far */ + get failCost() { + return this._cost; + } + /** + * Compose the results of a previous match as a subtree. + * @param id the id of the parent tree. + */ + compose(id, inner) { + if (inner.hasFailed()) { + this._hasFailed = true; + this._failCount += inner.failCount; + this._cost += inner._cost; + this.innerMatchFailures.set(id, inner); + } + inner.captures.forEach((vals, capture) => { + vals.forEach((value) => this.recordCapture({ capture, value })); + }); + return this; + } + /** + * Prepare the result to be analyzed. + * This API *must* be called prior to analyzing these results. + */ + finished() { + if (this.finalized) { + return this; + } + if (this.failCount === 0) { + this.captures.forEach((vals, cap) => cap._captured.push(...vals)); + } + this.finalized = true; + return this; + } + /** + * Render the failed match in a presentable way + * + * Prefer using `renderMismatch` over this method. It is left for backwards + * compatibility for test suites that expect it, but `renderMismatch()` will + * produce better output. + */ + toHumanStrings() { + const failures = new Array(); + debugger; + recurse(this, []); + return failures.map((r2) => { + const loc = r2.path.length === 0 ? "" : ` at /${r2.path.join("/")}`; + return "" + r2.message + loc + ` (using ${r2.matcher.name} matcher)`; + }); + function recurse(x2, prefix) { + for (const fail of Array.from(x2.failuresHere.values()).flat()) { + failures.push({ + matcher: fail.matcher, + message: fail.message, + path: [...prefix, ...fail.path] + }); + } + for (const [key, inner] of x2.innerMatchFailures.entries()) { + recurse(inner, [...prefix, key]); + } + } + } + /** + * Do a deep render of the match result, showing the structure mismatches in context + */ + renderMismatch() { + if (!this.hasFailed()) { + return ""; + } + const parts = new Array(); + const indents = new Array(); + emitFailures(this, ""); + recurse(this); + return moveMarkersToFront(parts.join("").trimEnd()); + function emit(x2) { + if (x2 === void 0) { + debugger; + } + parts.push(x2.replace(/\n/g, ` +${indents.join("")}`)); + } + function emitFailures(r2, path, scrapSet) { + for (const fail of r2.failuresHere.get(path) ?? []) { + emit(`!! ${fail.message} +`); + } + scrapSet == null ? void 0 : scrapSet.delete(path); + } + function recurse(r2) { + const remainingFailures = new Set(Array.from(r2.failuresHere.keys()).filter((x2) => x2 !== "")); + if (Array.isArray(r2.target)) { + indents.push(" "); + emit("[\n"); + for (const [first, i2] of enumFirst(range(r2.target.length))) { + if (!first) { + emit(",\n"); + } + emitFailures(r2, `${i2}`, remainingFailures); + const innerMatcher = r2.innerMatchFailures.get(`${i2}`); + if (innerMatcher) { + emitFailures(innerMatcher, ""); + recurseComparingValues(innerMatcher, r2.target[i2]); + } else { + emit(renderAbridged(r2.target[i2])); + } + } + emitRemaining(); + indents.pop(); + emit("\n]"); + return; + } + if (r2.target && typeof r2.target === "object") { + indents.push(" "); + emit("{\n"); + const keys = Array.from(/* @__PURE__ */ new Set([ + ...Object.keys(r2.target), + ...Array.from(remainingFailures) + ])).sort(); + for (const [first, key] of enumFirst(keys)) { + if (!first) { + emit(",\n"); + } + emitFailures(r2, key, remainingFailures); + const innerMatcher = r2.innerMatchFailures.get(key); + if (innerMatcher) { + emitFailures(innerMatcher, ""); + emit(`${jsonify(key)}: `); + recurseComparingValues(innerMatcher, r2.target[key]); + } else { + emit(`${jsonify(key)}: `); + emit(renderAbridged(r2.target[key])); + } + } + emitRemaining(); + indents.pop(); + emit("\n}"); + return; + } + emitRemaining(); + emit(jsonify(r2.target)); + function emitRemaining() { + if (remainingFailures.size > 0) { + emit("\n"); + } + for (const key of remainingFailures) { + emitFailures(r2, key); + } + } + } + function recurseComparingValues(inner, actualValue) { + if (inner.target === actualValue) { + return recurse(inner); + } + emit(renderAbridged(actualValue)); + emit(" <*> "); + recurse(inner); + } + function renderAbridged(x2) { + if (Array.isArray(x2)) { + switch (x2.length) { + case 0: + return "[]"; + case 1: + return `[ ${renderAbridged(x2[0])} ]`; + case 2: + if (x2.every((e2) => ["number", "boolean", "string"].includes(typeof e2))) { + return `[ ${x2.map(renderAbridged).join(", ")} ]`; + } + return "[ ... ]"; + default: + return "[ ... ]"; + } + } + if (x2 && typeof x2 === "object") { + const keys = Object.keys(x2); + switch (keys.length) { + case 0: + return "{}"; + case 1: + return `{ ${JSON.stringify(keys[0])}: ${renderAbridged(x2[keys[0]])} }`; + default: + return "{ ... }"; + } + } + return jsonify(x2); + } + function jsonify(x2) { + return JSON.stringify(x2) ?? "undefined"; + } + function moveMarkersToFront(x2) { + const re = /^(\s+)!!/gm; + return x2.replace(re, (_, spaces) => `!!${spaces.substring(0, spaces.length - 2)}`); + } + } + /** + * Record a capture against in this match result. + */ + recordCapture(options) { + let values = this.captures.get(options.capture); + if (values === void 0) { + values = []; + } + values.push(options.value); + this.captures.set(options.capture, values); + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/matchers/absent.ts +var AbsentMatch; +var init_absent = __esm({ + "../../aws-cdk-lib/assertions/lib/private/matchers/absent.ts"() { + "use strict"; + init_matcher(); + AbsentMatch = class extends Matcher { + constructor(name) { + super(); + this.name = name; + } + test(actual) { + const result = new MatchResult(actual); + if (actual !== void 0) { + result.recordFailure({ + matcher: this, + path: [], + message: `Received ${actual}, but key should be absent` + }); + } + return result; + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/sorting.ts +function sortKeyComparator(keyFn) { + return (a, b) => { + const ak = keyFn(a); + const bk = keyFn(b); + for (let i2 = 0; i2 < ak.length && i2 < bk.length; i2++) { + const av = ak[i2]; + const bv = bk[i2]; + let diff = 0; + if (typeof av === "number" && typeof bv === "number") { + diff = av - bv; + } else if (typeof av === "string" && typeof bv === "string") { + diff = av.localeCompare(bv); + } + if (diff !== 0) { + return diff; + } + } + return bk.length - ak.length; + }; +} +var init_sorting = __esm({ + "../../aws-cdk-lib/assertions/lib/private/sorting.ts"() { + "use strict"; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/sparse-matrix.ts +var SparseMatrix; +var init_sparse_matrix = __esm({ + "../../aws-cdk-lib/assertions/lib/private/sparse-matrix.ts"() { + "use strict"; + SparseMatrix = class { + constructor() { + this.matrix = /* @__PURE__ */ new Map(); + } + get(row, col) { + var _a4; + return (_a4 = this.matrix.get(row)) == null ? void 0 : _a4.get(col); + } + row(row) { + var _a4; + return Array.from(((_a4 = this.matrix.get(row)) == null ? void 0 : _a4.entries()) ?? []); + } + set(row, col, value) { + let r2 = this.matrix.get(row); + if (!r2) { + r2 = /* @__PURE__ */ new Map(); + this.matrix.set(row, r2); + } + r2.set(col, value); + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/private/type.ts +function getType(obj) { + return Array.isArray(obj) ? "array" : typeof obj; +} +var init_type = __esm({ + "../../aws-cdk-lib/assertions/lib/private/type.ts"() { + "use strict"; + } +}); + +// ../../aws-cdk-lib/assertions/lib/match.ts +var match_exports = {}; +__export(match_exports, { + Match: () => Match +}); +var Match, LiteralMatch, ArrayMatch, ObjectMatch, SerializedJson, NotMatch, AnyMatch, StringLikeRegexpMatch; +var init_match = __esm({ + "../../aws-cdk-lib/assertions/lib/match.ts"() { + "use strict"; + init_matcher(); + init_absent(); + init_sorting(); + init_sparse_matrix(); + init_type(); + Match = class { + /** + * Use this matcher in the place of a field's value, if the field must not be present. + */ + static absent() { + return new AbsentMatch("absent"); + } + /** + * Matches the specified pattern with the array found in the same relative path of the target. + * The set of elements (or matchers) must be in the same order as would be found. + * @param pattern the pattern to match + */ + static arrayWith(pattern) { + return new ArrayMatch("arrayWith", pattern); + } + /** + * Matches the specified pattern with the array found in the same relative path of the target. + * The set of elements (or matchers) must match exactly and in order. + * @param pattern the pattern to match + */ + static arrayEquals(pattern) { + return new ArrayMatch("arrayEquals", pattern, { subsequence: false }); + } + /** + * Deep exact matching of the specified pattern to the target. + * @param pattern the pattern to match + */ + static exact(pattern) { + return new LiteralMatch("exact", pattern, { partialObjects: false }); + } + /** + * Matches the specified pattern to an object found in the same relative path of the target. + * The keys and their values (or matchers) must be present in the target but the target can be a superset. + * @param pattern the pattern to match + */ + static objectLike(pattern) { + return new ObjectMatch("objectLike", pattern); + } + /** + * Matches the specified pattern to an object found in the same relative path of the target. + * The keys and their values (or matchers) must match exactly with the target. + * @param pattern the pattern to match + */ + static objectEquals(pattern) { + return new ObjectMatch("objectEquals", pattern, { partial: false }); + } + /** + * Matches any target which does NOT follow the specified pattern. + * @param pattern the pattern to NOT match + */ + static not(pattern) { + return new NotMatch("not", pattern); + } + /** + * Matches any string-encoded JSON and applies the specified pattern after parsing it. + * @param pattern the pattern to match after parsing the encoded JSON. + */ + static serializedJson(pattern) { + return new SerializedJson("serializedJson", pattern); + } + /** + * Matches any non-null value at the target. + */ + static anyValue() { + return new AnyMatch("anyValue"); + } + /** + * Matches targets according to a regular expression + */ + static stringLikeRegexp(pattern) { + return new StringLikeRegexpMatch("stringLikeRegexp", pattern); + } + }; + LiteralMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.partialObjects = options.partialObjects ?? false; + if (Matcher.isMatcher(this.pattern)) { + throw new Error("LiteralMatch cannot directly contain another matcher. Remove the top-level matcher or nest it more deeply."); + } + } + test(actual) { + if (Array.isArray(this.pattern)) { + return new ArrayMatch(this.name, this.pattern, { subsequence: false, partialObjects: this.partialObjects }).test(actual); + } + if (typeof this.pattern === "object") { + return new ObjectMatch(this.name, this.pattern, { partial: this.partialObjects }).test(actual); + } + const result = new MatchResult(actual); + if (typeof this.pattern !== typeof actual) { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected type ${typeof this.pattern} but received ${getType(actual)}` + }); + return result; + } + if (actual !== this.pattern) { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected ${this.pattern} but received ${actual}` + }); + } + return result; + } + }; + ArrayMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.subsequence = options.subsequence ?? true; + this.partialObjects = options.partialObjects ?? false; + } + test(actual) { + if (!Array.isArray(actual)) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected type array but received ${getType(actual)}` + }); + } + return this.subsequence ? this.testSubsequence(actual) : this.testFullArray(actual); + } + testFullArray(actual) { + const result = new MatchResult(actual); + let i2 = 0; + for (; i2 < this.pattern.length && i2 < actual.length; i2++) { + const patternElement = this.pattern[i2]; + const matcher = Matcher.isMatcher(patternElement) ? patternElement : new LiteralMatch(this.name, patternElement, { partialObjects: this.partialObjects }); + const innerResult = matcher.test(actual[i2]); + result.compose(`${i2}`, innerResult); + } + if (i2 < this.pattern.length) { + result.recordFailure({ + matcher: this, + message: `Not enough elements in array (expecting ${this.pattern.length}, got ${actual.length})`, + path: [`${i2}`] + }); + } + if (i2 < actual.length) { + result.recordFailure({ + matcher: this, + message: `Too many elements in array (expecting ${this.pattern.length}, got ${actual.length})`, + path: [`${i2}`] + }); + } + return result; + } + testSubsequence(actual) { + const result = new MatchResult(actual); + let patternIdx = 0; + let actualIdx = 0; + const matches = new SparseMatrix(); + while (patternIdx < this.pattern.length && actualIdx < actual.length) { + const patternElement = this.pattern[patternIdx]; + const matcher = Matcher.isMatcher(patternElement) ? patternElement : new LiteralMatch(this.name, patternElement, { partialObjects: this.partialObjects }); + const matcherName = matcher.name; + if (matcherName == "absent" || matcherName == "anyValue") { + throw new Error(`The Matcher ${matcherName}() cannot be nested within arrayWith()`); + } + const innerResult = matcher.test(actual[actualIdx]); + matches.set(patternIdx, actualIdx, innerResult); + actualIdx++; + if (innerResult.isSuccess) { + result.compose(`${actualIdx}`, innerResult); + patternIdx++; + } + } + if (patternIdx < this.pattern.length) { + for (let spi = 0; spi < patternIdx; spi++) { + const foundMatch = matches.row(spi).find(([, r2]) => r2.isSuccess); + if (!foundMatch) { + continue; + } + const [index] = foundMatch; + result.compose(`${index}`, new MatchResult(actual[index]).recordFailure({ + matcher: this, + message: `arrayWith pattern ${spi} matched here`, + path: [], + cost: 0 + // This is an informational message so it would be unfair to assign it cost + })); + } + const failedMatches = matches.row(patternIdx); + failedMatches.sort(sortKeyComparator(([i2, r2]) => [r2.failCost, i2])); + if (failedMatches.length > 0) { + const [index, innerResult] = failedMatches[0]; + result.recordFailure({ + matcher: this, + message: `Could not match arrayWith pattern ${patternIdx}. This is the closest match`, + path: [`${index}`], + cost: 0 + // Informational message + }); + result.compose(`${index}`, innerResult); + } else { + result.recordFailure({ + matcher: this, + message: `Could not match arrayWith pattern ${patternIdx}. No more elements to try`, + path: [`${actual.length}`] + }); + } + } + return result; + } + }; + ObjectMatch = class extends Matcher { + constructor(name, pattern, options = {}) { + super(); + this.name = name; + this.pattern = pattern; + this.partial = options.partial ?? true; + } + test(actual) { + if (typeof actual !== "object" || Array.isArray(actual)) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected type object but received ${getType(actual)}` + }); + } + const result = new MatchResult(actual); + if (!this.partial) { + for (const a of Object.keys(actual)) { + if (!(a in this.pattern)) { + result.recordFailure({ + matcher: this, + path: [a], + message: `Unexpected key ${a}` + }); + } + } + } + for (const [patternKey, patternVal] of Object.entries(this.pattern)) { + if (!(patternKey in actual) && !(patternVal instanceof AbsentMatch)) { + result.recordFailure({ + matcher: this, + path: [patternKey], + message: `Missing key '${patternKey}'` + }); + continue; + } + const matcher = Matcher.isMatcher(patternVal) ? patternVal : new LiteralMatch(this.name, patternVal, { partialObjects: this.partial }); + const inner = matcher.test(actual[patternKey]); + result.compose(patternKey, inner); + } + return result; + } + }; + SerializedJson = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + if (getType(actual) !== "string") { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Expected JSON as a string but found ${getType(actual)}` + }); + } + let parsed; + try { + parsed = JSON.parse(actual); + } catch (err) { + if (err instanceof SyntaxError) { + return new MatchResult(actual).recordFailure({ + matcher: this, + path: [], + message: `Invalid JSON string: ${actual}` + }); + } else { + throw err; + } + } + const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); + const innerResult = matcher.test(parsed); + if (innerResult.hasFailed()) { + innerResult.recordFailure({ + matcher: this, + path: [], + message: "Encoded JSON value does not match" + }); + } + return innerResult; + } + }; + NotMatch = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const matcher = Matcher.isMatcher(this.pattern) ? this.pattern : new LiteralMatch(this.name, this.pattern); + const innerResult = matcher.test(actual); + const result = new MatchResult(actual); + if (innerResult.failCount === 0) { + result.recordFailure({ + matcher: this, + path: [], + message: `Found unexpected match: ${JSON.stringify(actual, void 0, 2)}` + }); + } + return result; + } + }; + AnyMatch = class extends Matcher { + constructor(name) { + super(); + this.name = name; + } + test(actual) { + const result = new MatchResult(actual); + if (actual == null) { + result.recordFailure({ + matcher: this, + path: [], + message: "Expected a value but found none" + }); + } + return result; + } + }; + StringLikeRegexpMatch = class extends Matcher { + constructor(name, pattern) { + super(); + this.name = name; + this.pattern = pattern; + } + test(actual) { + const result = new MatchResult(actual); + const regex = new RegExp(this.pattern, "gm"); + if (typeof actual !== "string") { + result.recordFailure({ + matcher: this, + path: [], + message: `Expected a string, but got '${typeof actual}'` + }); + } + if (!regex.test(actual)) { + result.recordFailure({ + matcher: this, + path: [], + message: `String '${actual}' did not match pattern '${this.pattern}'` + }); + } + return result; + } + }; + } +}); + +// ../../aws-cdk-lib/assertions/lib/helpers-internal/index.js +var require_helpers_internal = __commonJS({ + "../../aws-cdk-lib/assertions/lib/helpers-internal/index.js"(exports) { + "use strict"; + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + var desc = Object.getOwnPropertyDescriptor(m2, k); + if (!desc || ("get" in desc ? !m2.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m2[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m2, k, k2) { + if (k2 === void 0) + k2 = k; + o[k2] = m2[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m2, exports2) { + for (var p in m2) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m2, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar((init_match(), __toCommonJS(match_exports)), exports); + __exportStar((init_matcher(), __toCommonJS(matcher_exports)), exports); + } +}); + +// ../../../node_modules/web-streams-polyfill/dist/ponyfill.es2018.js +var require_ponyfill_es2018 = __commonJS({ + "../../../node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports, module2) { + (function(global2, factory) { + typeof exports === "object" && typeof module2 !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); + })(exports, function(exports2) { + "use strict"; + const SymbolPolyfill = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol : (description) => `Symbol(${description})`; + function noop2() { + return void 0; + } + function getGlobals() { + if (typeof self !== "undefined") { + return self; + } else if (typeof window !== "undefined") { + return window; + } else if (typeof global !== "undefined") { + return global; + } + return void 0; + } + const globals = getGlobals(); + function typeIsObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + const rethrowAssertionErrorRejection = noop2; + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, void 0, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === "function") { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(void 0); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F2, V, args) { + if (typeof F2 !== "function") { + throw new TypeError("Argument is not a function"); + } + return Function.prototype.apply.call(F2, V, args); + } + function promiseCall(F2, V, args) { + try { + return promiseResolvedWith(reflectCall(F2, V, args)); + } catch (value) { + return promiseRejectedWith(value); + } + } + const QUEUE_MAX_ARRAY_SIZE = 16384; + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + this._front = { + _elements: [], + _next: void 0 + }; + this._back = this._front; + this._cursor = 0; + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: void 0 + }; + } + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + elements[oldCursor] = void 0; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i2 = this._cursor; + let node = this._front; + let elements = node._elements; + while (i2 !== elements.length || node._next !== void 0) { + if (i2 === elements.length) { + node = node._next; + elements = node._elements; + i2 = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i2]); + ++i2; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === "readable") { + defaultReaderClosedPromiseInitialize(reader); + } else if (stream._state === "closed") { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === "readable") { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = void 0; + reader._ownerReadableStream = void 0; + } + function readerLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released reader"); + } + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = void 0; + reader._closedPromise_reject = void 0; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === void 0) { + return; + } + reader._closedPromise_resolve(void 0); + reader._closedPromise_resolve = void 0; + reader._closedPromise_reject = void 0; + } + const AbortSteps = SymbolPolyfill("[[AbortSteps]]"); + const ErrorSteps = SymbolPolyfill("[[ErrorSteps]]"); + const CancelSteps = SymbolPolyfill("[[CancelSteps]]"); + const PullSteps = SymbolPolyfill("[[PullSteps]]"); + const NumberIsFinite = Number.isFinite || function(x2) { + return typeof x2 === "number" && isFinite(x2); + }; + const MathTrunc = Math.trunc || function(v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + function isDictionary(x2) { + return typeof x2 === "object" || typeof x2 === "function"; + } + function assertDictionary(obj, context) { + if (obj !== void 0 && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertFunction(x2, context) { + if (typeof x2 !== "function") { + throw new TypeError(`${context} is not a function.`); + } + } + function isObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + function assertObject(x2, context) { + if (!isObject(x2)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x2, position, context) { + if (x2 === void 0) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x2, field, context) { + if (x2 === void 0) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x2) { + return x2 === 0 ? 0 : x2; + } + function integerPart(x2) { + return censorNegativeZero(MathTrunc(x2)); + } + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x2 = Number(value); + x2 = censorNegativeZero(x2); + if (!NumberIsFinite(x2)) { + throw new TypeError(`${context} is not a finite number`); + } + x2 = integerPart(x2); + if (x2 < lowerBound || x2 > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x2) || x2 === 0) { + return 0; + } + return x2; + } + function assertReadableStream(x2, context) { + if (!IsReadableStream(x2)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === void 0) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = void 0) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("read")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: void 0, done: true }), + _errorSteps: (e2) => rejectPromise(e2) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === void 0) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamDefaultReader", + configurable: true + }); + } + function IsReadableStreamDefaultReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readRequests")) { + return false; + } + return x2 instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "closed") { + readRequest._closeSteps(); + } else if (stream._state === "errored") { + readRequest._errorSteps(stream._storedError); + } else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { + }).prototype); + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = void 0; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: void 0, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("iterate")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => { + this._ongoingPromise = void 0; + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = void 0; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: void 0, done: true }); + }, + _errorSteps: (reason) => { + this._ongoingPromise = void 0; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("finish iterating")); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== void 0) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_asyncIteratorImpl")) { + return false; + } + try { + return x2._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; + } catch (_a4) { + return false; + } + } + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + const NumberIsNaN = Number.isNaN || function(x2) { + return x2 !== x2; + }; + function CreateArrayFromList(elements) { + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + function TransferArrayBuffer(O) { + return O; + } + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function IsNonNegativeNumber(v) { + if (typeof v !== "number") { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError("Size must be a finite, non-NaN, non-negative number."); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("view"); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respond"); + } + assertRequiredArgument(bytesWritten, 1, "respond"); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter"); + if (this._associatedReadableByteStreamController === void 0) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(this._view.buffer)) + ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respondWithNewView"); + } + assertRequiredArgument(view, 1, "respondWithNewView"); + if (!ArrayBuffer.isView(view)) { + throw new TypeError("You can only respond with array buffer views"); + } + if (this._associatedReadableByteStreamController === void 0) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(view.buffer)) + ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamBYOBRequest", + configurable: true + }); + } + class ReadableByteStreamController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("byobRequest"); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("desiredSize"); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("close"); + } + if (this._closeRequested) { + throw new TypeError("The stream has already been closed; do not close it again!"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("enqueue"); + } + assertRequiredArgument(chunk, 1, "enqueue"); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError("chunk must be an array buffer view"); + } + if (chunk.byteLength === 0) { + throw new TypeError("chunk must have non-zero byteLength"); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError("stream is closed or draining"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e2 = void 0) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("error"); + } + ReadableByteStreamControllerError(this, e2); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== void 0) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: "default" + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableByteStreamController", + configurable: true + }); + } + function IsReadableByteStreamController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableByteStream")) { + return false; + } + return x2 instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_associatedReadableByteStreamController")) { + return false; + } + return x2 instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, (e2) => { + ReadableByteStreamControllerError(controller, e2); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === "closed") { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === "default") { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = void 0; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + const buffer = TransferArrayBuffer(view.buffer); + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: "byob" + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === "closed") { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e2); + readIntoRequest._errorSteps(e2); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + ReadableByteStreamControllerRespondInClosedState(controller); + } else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = void 0; + controller._cancelAlgorithm = void 0; + } + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e2); + throw e2; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) + ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } else if (ReadableStreamHasBYOBReader(stream)) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e2) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e2); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (bytesWritten !== 0) { + throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream"); + } + } else { + if (bytesWritten === 0) { + throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream"); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError("bytesWritten out of range"); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (view.byteLength !== 0) { + throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream"); + } + } else { + if (view.byteLength === 0) { + throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError("The region specified by view does not match byobRequest"); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError("The buffer of view has different capacity than byobRequest"); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError("The region specified by view is larger than byobRequest"); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + controller._queue = controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, (r2) => { + ReadableByteStreamControllerError(controller, r2); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => void 0; + let pullAlgorithm = () => promiseResolvedWith(void 0); + let cancelAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingByteSource.start !== void 0) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== void 0) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== void 0) { + cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError("autoAllocateChunkSize must be greater than 0"); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request2, controller, view) { + request2._associatedReadableByteStreamController = controller; + request2._view = view; + } + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === void 0) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = void 0) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("read")); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError("view must be an array buffer view")); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError("view must have non-zero byteLength")); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) + ; + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }), + _errorSteps: (e2) => rejectPromise(e2) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === void 0) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamBYOBReader", + configurable: true + }); + } + function IsReadableStreamBYOBReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readIntoRequests")) { + return false; + } + return x2 instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "errored") { + readIntoRequest._errorSteps(stream._storedError); + } else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === void 0) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError("Invalid highWaterMark"); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark), + size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return (chunk) => convertUnrestrictedDouble(fn(chunk)); + } + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function assertWritableStream(x2, context) { + if (!IsWritableStream(x2)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + function isAbortSignal2(value) { + if (typeof value !== "object" || value === null) { + return false; + } + try { + return typeof value.aborted === "boolean"; + } catch (_a4) { + return false; + } + } + const supportsAbortController = typeof AbortController === "function"; + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return void 0; + } + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === void 0) { + rawUnderlyingSink = null; + } else { + assertObject(rawUnderlyingSink, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter"); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== void 0) { + throw new RangeError("Invalid type is specified"); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("locked"); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = void 0) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("abort")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer")); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("close")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer")); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("getWriter"); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStream", + configurable: true + }); + } + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = "writable"; + stream._storedError = void 0; + stream._writer = void 0; + stream._writableStreamController = void 0; + stream._writeRequests = new SimpleQueue(); + stream._inFlightWriteRequest = void 0; + stream._closeRequest = void 0; + stream._inFlightCloseRequest = void 0; + stream._pendingAbortRequest = void 0; + stream._backpressure = false; + } + function IsWritableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_writableStreamController")) { + return false; + } + return x2 instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === void 0) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a4; + if (stream._state === "closed" || stream._state === "errored") { + return promiseResolvedWith(void 0); + } + stream._writableStreamController._abortReason = reason; + (_a4 = stream._writableStreamController._abortController) === null || _a4 === void 0 ? void 0 : _a4.abort(); + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseResolvedWith(void 0); + } + if (stream._pendingAbortRequest !== void 0) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === "erroring") { + wasAlreadyErroring = true; + reason = void 0; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: void 0, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== void 0 && stream._backpressure && state === "writable") { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === "writable") { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = "erroring"; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== void 0) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = "errored"; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach((writeRequest) => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === void 0) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = void 0; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(void 0); + stream._inFlightWriteRequest = void 0; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = void 0; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(void 0); + stream._inFlightCloseRequest = void 0; + const state = stream._state; + if (state === "erroring") { + stream._storedError = void 0; + if (stream._pendingAbortRequest !== void 0) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = void 0; + } + } + stream._state = "closed"; + const writer = stream._writer; + if (writer !== void 0) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = void 0; + if (stream._pendingAbortRequest !== void 0) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = void 0; + } + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = void 0; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== void 0) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = void 0; + } + const writer = stream._writer; + if (writer !== void 0) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== void 0 && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter"); + assertWritableStream(stream, "First parameter"); + if (IsWritableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive writing by another writer"); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === "writable") { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } else if (state === "erroring") { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } else if (state === "closed") { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("closed")); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("desiredSize"); + } + if (this._ownerWritableStream === void 0) { + throw defaultWriterLockException("desiredSize"); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("ready")); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = void 0) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("abort")); + } + if (this._ownerWritableStream === void 0) { + return promiseRejectedWith(defaultWriterLockException("abort")); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("close")); + } + const stream = this._ownerWritableStream; + if (stream === void 0) { + return promiseRejectedWith(defaultWriterLockException("close")); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("releaseLock"); + } + const stream = this._ownerWritableStream; + if (stream === void 0) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = void 0) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("write")); + } + if (this._ownerWritableStream === void 0) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStreamDefaultWriter", + configurable: true + }); + } + function IsWritableStreamDefaultWriter(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_ownerWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultWriter; + } + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseResolvedWith(void 0); + } + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === "pending") { + defaultWriterClosedPromiseReject(writer, error); + } else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === "pending") { + defaultWriterReadyPromiseReject(writer, error); + } else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === "errored" || state === "erroring") { + return null; + } + if (state === "closed") { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = void 0; + writer._ownerWritableStream = void 0; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + const state = stream._state; + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to")); + } + if (state === "erroring") { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + class WritableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("abortReason"); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("signal"); + } + if (this._abortController === void 0) { + throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported"); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e2 = void 0) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("error"); + } + const state = this._controlledWritableStream._state; + if (state !== "writable") { + return; + } + WritableStreamDefaultControllerError(this, e2); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStreamDefaultController", + configurable: true + }); + } + function IsWritableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + controller._queue = void 0; + controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._abortReason = void 0; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, (r2) => { + controller._started = true; + WritableStreamDealWithRejection(stream, r2); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => void 0; + let writeAlgorithm = () => promiseResolvedWith(void 0); + let closeAlgorithm = () => promiseResolvedWith(void 0); + let abortAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingSink.start !== void 0) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== void 0) { + writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== void 0) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== void 0) { + abortAlgorithm = (reason) => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = void 0; + controller._closeAlgorithm = void 0; + controller._abortAlgorithm = void 0; + controller._strategySizeAlgorithm = void 0; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== void 0) { + return; + } + const state = stream._state; + if (state === "erroring") { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === "writable") { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, (reason) => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, (reason) => { + if (stream._state === "writable") { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released writer"); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = "pending"; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = void 0; + writer._closedPromise_reject = void 0; + writer._closedPromiseState = "rejected"; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === void 0) { + return; + } + writer._closedPromise_resolve(void 0); + writer._closedPromise_resolve = void 0; + writer._closedPromise_reject = void 0; + writer._closedPromiseState = "resolved"; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = "pending"; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = void 0; + writer._readyPromise_reject = void 0; + writer._readyPromiseState = "rejected"; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === void 0) { + return; + } + writer._readyPromise_resolve(void 0); + writer._readyPromise_resolve = void 0; + writer._readyPromise_reject = void 0; + writer._readyPromiseState = "fulfilled"; + } + const NativeDOMException = typeof DOMException !== "undefined" ? DOMException : void 0; + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === "function" || typeof ctor === "object")) { + return false; + } + try { + new ctor(); + return true; + } catch (_a4) { + return false; + } + } + function createDOMExceptionPolyfill() { + const ctor = function DOMException3(message, name) { + this.message = message || ""; + this.name = name || "Error"; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true }); + return ctor; + } + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + let currentWrite = promiseResolvedWith(void 0); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== void 0) { + abortAlgorithm = () => { + const error = new DOMException$1("Aborted", "AbortError"); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === "writable") { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(void 0); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === "readable") { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(void 0); + }); + } + shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener("abort", abortAlgorithm); + } + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } else { + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: (chunk) => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + isOrBecomesErrored(source, reader._closedPromise, (storedError) => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + }); + isOrBecomesErrored(dest, writer._closedPromise, (storedError) => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + }); + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } else { + shutdown(); + } + }); + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") { + const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it"); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === "errored") { + action(stream._storedError); + } else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === "closed") { + action(); + } else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== void 0) { + signal.removeEventListener("abort", abortAlgorithm); + } + if (isError) { + reject(error); + } else { + resolve(void 0); + } + } + }); + } + class ReadableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("desiredSize"); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("close"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits close"); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = void 0) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("enqueue"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits enqueue"); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e2 = void 0) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("error"); + } + ReadableStreamDefaultControllerError(this, e2); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamDefaultController", + configurable: true + }); + } + function IsReadableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableStream")) { + return false; + } + return x2 instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, (e2) => { + ReadableStreamDefaultControllerError(controller, e2); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = void 0; + controller._cancelAlgorithm = void 0; + controller._strategySizeAlgorithm = void 0; + } + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e2) { + const stream = controller._controlledReadableStream; + if (stream._state !== "readable") { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e2); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === "readable") { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = void 0; + controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, (r2) => { + ReadableStreamDefaultControllerError(controller, r2); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => void 0; + let pullAlgorithm = () => promiseResolvedWith(void 0); + let cancelAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingSource.start !== void 0) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== void 0) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== void 0) { + cancelAlgorithm = (reason) => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(void 0); + } + reading = true; + const readRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(void 0); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r2) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r2); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, (r2) => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r2); + ReadableByteStreamControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: (chunk) => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== void 0) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(void 0); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(void 0); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(void 0); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(void 0); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== "bytes") { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== "byob") { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== void 0) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal2(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, "readable", "ReadableWritablePair"); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, "writable", "ReadableWritablePair"); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + class ReadableStream2 { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === void 0) { + rawUnderlyingSource = null; + } else { + assertObject(rawUnderlyingSource, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter"); + InitializeReadableStream(this); + if (underlyingSource.type === "bytes") { + if (strategy.size !== void 0) { + throw new RangeError("The strategy for a byte stream cannot have a size function"); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("locked"); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = void 0) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("cancel")); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader")); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = void 0) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("getReader"); + } + const options = convertReaderOptions(rawOptions, "First parameter"); + if (options.mode === void 0) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("pipeThrough"); + } + assertRequiredArgument(rawTransform, 1, "pipeThrough"); + const transform = convertReadableWritablePair(rawTransform, "First parameter"); + const options = convertPipeOptions(rawOptions, "Second parameter"); + if (IsReadableStreamLocked(this)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream"); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream"); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("pipeTo")); + } + if (destination === void 0) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, "Second parameter"); + } catch (e2) { + return promiseRejectedWith(e2); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("tee"); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = void 0) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("values"); + } + const options = convertIteratorOptions(rawOptions, "First parameter"); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream2.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStream", + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === "symbol") { + Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream2.prototype.values, + writable: true, + configurable: true + }); + } + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = "readable"; + stream._reader = void 0; + stream._storedError = void 0; + stream._disturbed = false; + } + function IsReadableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readableStreamController")) { + return false; + } + return x2 instanceof ReadableStream2; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === void 0) { + return false; + } + return true; + } + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === "closed") { + return promiseResolvedWith(void 0); + } + if (stream._state === "errored") { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._closeSteps(void 0); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop2); + } + function ReadableStreamClose(stream) { + stream._state = "closed"; + const reader = stream._reader; + if (reader === void 0) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach((readRequest) => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e2) { + stream._state = "errored"; + stream._storedError = e2; + const reader = stream._reader; + if (reader === void 0) { + return; + } + defaultReaderClosedPromiseReject(reader, e2); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach((readRequest) => { + readRequest._errorSteps(e2); + }); + reader._readRequests = new SimpleQueue(); + } else { + reader._readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._errorSteps(e2); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit"); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, "name", { + value: "size", + configurable: true + }); + } catch (_a4) { + } + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("highWaterMark"); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("size"); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: "ByteLengthQueuingStrategy", + configurable: true + }); + } + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_byteLengthQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof ByteLengthQueuingStrategy; + } + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, "name", { + value: "size", + configurable: true + }); + } catch (_a4) { + } + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "CountQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("highWaterMark"); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("size"); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: "CountQueuingStrategy", + configurable: true + }); + } + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_countQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof CountQueuingStrategy; + } + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === void 0) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter"); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter"); + const transformer = convertTransformer(rawTransformer, "First parameter"); + if (transformer.readableType !== void 0) { + throw new RangeError("Invalid readableType specified"); + } + if (transformer.writableType !== void 0) { + throw new RangeError("Invalid writableType specified"); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise((resolve) => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== void 0) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } else { + startPromise_resolve(void 0); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("readable"); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("writable"); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: "TransformStream", + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(void 0); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + stream._backpressure = void 0; + stream._backpressureChangePromise = void 0; + stream._backpressureChangePromise_resolve = void 0; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = void 0; + } + function IsTransformStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_transformStreamController")) { + return false; + } + return x2 instanceof TransformStream; + } + function TransformStreamError(stream, e2) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e2); + TransformStreamErrorWritableAndUnblockWrite(stream, e2); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e2) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e2); + if (stream._backpressure) { + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + if (stream._backpressureChangePromise !== void 0) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise((resolve) => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + class TransformStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("desiredSize"); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = void 0) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("enqueue"); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = void 0) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("error"); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("terminate"); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "TransformStreamDefaultController", + configurable: true + }); + } + function IsTransformStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledTransformStream")) { + return false; + } + return x2 instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(void 0); + } catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(void 0); + if (transformer.transform !== void 0) { + transformAlgorithm = (chunk) => transformer.transform(chunk, controller); + } + if (transformer.flush !== void 0) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = void 0; + controller._flushAlgorithm = void 0; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError("Readable side is not in a state that permits enqueue"); + } + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } catch (e2) { + TransformStreamErrorWritableAndUnblockWrite(stream, e2); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e2) { + TransformStreamError(controller._controlledTransformStream, e2); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, void 0, (r2) => { + TransformStreamError(controller._controlledTransformStream, r2); + throw r2; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError("TransformStream terminated"); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === "erroring") { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + TransformStreamError(stream, reason); + return promiseResolvedWith(void 0); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + return transformPromiseWith(flushPromise, () => { + if (readable._state === "errored") { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, (r2) => { + TransformStreamError(stream, r2); + throw readable._storedError; + }); + } + function TransformStreamDefaultSourcePullAlgorithm(stream) { + TransformStreamSetBackpressure(stream, false); + return stream._backpressureChangePromise; + } + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + exports2.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports2.CountQueuingStrategy = CountQueuingStrategy; + exports2.ReadableByteStreamController = ReadableByteStreamController; + exports2.ReadableStream = ReadableStream2; + exports2.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports2.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports2.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports2.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports2.TransformStream = TransformStream; + exports2.TransformStreamDefaultController = TransformStreamDefaultController; + exports2.WritableStream = WritableStream; + exports2.WritableStreamDefaultController = WritableStreamDefaultController; + exports2.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + Object.defineProperty(exports2, "__esModule", { value: true }); + }); + } +}); + +// ../../../node_modules/fetch-blob/streams.cjs +var require_streams = __commonJS({ + "../../../node_modules/fetch-blob/streams.cjs"() { + var POOL_SIZE2 = 65536; + if (!globalThis.ReadableStream) { + try { + const process2 = require("process"); + const { emitWarning } = process2; + try { + process2.emitWarning = () => { + }; + Object.assign(globalThis, require("stream/web")); + process2.emitWarning = emitWarning; + } catch (error) { + process2.emitWarning = emitWarning; + throw error; + } + } catch (error) { + Object.assign(globalThis, require_ponyfill_es2018()); + } + } + try { + const { Blob: Blob2 } = require("buffer"); + if (Blob2 && !Blob2.prototype.stream) { + Blob2.prototype.stream = function name(params) { + let position = 0; + const blob = this; + return new ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + ctrl.enqueue(new Uint8Array(buffer)); + if (position === blob.size) { + ctrl.close(); + } + } + }); + }; + } + } catch (error) { + } + } +}); + +// ../../../node_modules/fetch-blob/index.js +async function* toIterator(parts, clone2 = true) { + for (const part of parts) { + if ("stream" in part) { + yield* ( + /** @type {AsyncIterableIterator} */ + part.stream() + ); + } else if (ArrayBuffer.isView(part)) { + if (clone2) { + let position = part.byteOffset; + const end = part.byteOffset + part.byteLength; + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); + } + } else { + yield part; + } + } else { + let position = 0, b = ( + /** @type {Blob} */ + part + ); + while (position !== b.size) { + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); + } + } + } +} +var import_streams, POOL_SIZE, _parts, _type, _size, _endings, _a, _Blob, Blob, fetch_blob_default; +var init_fetch_blob = __esm({ + "../../../node_modules/fetch-blob/index.js"() { + import_streams = __toESM(require_streams(), 1); + POOL_SIZE = 65536; + _Blob = (_a = class { + /** + * The Blob() constructor returns a new Blob object. The content + * of the blob consists of the concatenation of the values given + * in the parameter array. + * + * @param {*} blobParts + * @param {{ type?: string, endings?: string }} [options] + */ + constructor(blobParts = [], options = {}) { + /** @type {Array.<(Blob|Uint8Array)>} */ + __privateAdd(this, _parts, []); + __privateAdd(this, _type, ""); + __privateAdd(this, _size, 0); + __privateAdd(this, _endings, "transparent"); + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence."); + } + if (typeof blobParts[Symbol.iterator] !== "function") { + throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property."); + } + if (typeof options !== "object" && typeof options !== "function") { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); + } + if (options === null) + options = {}; + const encoder = new TextEncoder(); + for (const element of blobParts) { + let part; + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)); + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)); + } else if (element instanceof _a) { + part = element; + } else { + part = encoder.encode(`${element}`); + } + __privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size)); + __privateGet(this, _parts).push(part); + } + __privateSet(this, _endings, `${options.endings === void 0 ? "transparent" : options.endings}`); + const type = options.type === void 0 ? "" : String(options.type); + __privateSet(this, _type, /^[\x20-\x7E]*$/.test(type) ? type : ""); + } + /** + * The Blob interface's size property returns the + * size of the Blob in bytes. + */ + get size() { + return __privateGet(this, _size); + } + /** + * The type property of a Blob object returns the MIME type of the file. + */ + get type() { + return __privateGet(this, _type); + } + /** + * The text() method in the Blob interface returns a Promise + * that resolves with a string containing the contents of + * the blob, interpreted as UTF-8. + * + * @return {Promise} + */ + async text() { + const decoder = new TextDecoder(); + let str = ""; + for await (const part of toIterator(__privateGet(this, _parts), false)) { + str += decoder.decode(part, { stream: true }); + } + str += decoder.decode(); + return str; + } + /** + * The arrayBuffer() method in the Blob interface returns a + * Promise that resolves with the contents of the blob as + * binary data contained in an ArrayBuffer. + * + * @return {Promise} + */ + async arrayBuffer() { + const data = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of toIterator(__privateGet(this, _parts), false)) { + data.set(chunk, offset); + offset += chunk.length; + } + return data.buffer; + } + stream() { + const it = toIterator(__privateGet(this, _parts), true); + return new globalThis.ReadableStream({ + // @ts-ignore + type: "bytes", + async pull(ctrl) { + const chunk = await it.next(); + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value); + }, + async cancel() { + await it.return(); + } + }); + } + /** + * The Blob interface's slice() method creates and returns a + * new Blob object which contains data from a subset of the + * blob on which it's called. + * + * @param {number} [start] + * @param {number} [end] + * @param {string} [type] + */ + slice(start = 0, end = this.size, type = "") { + const { size } = this; + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size); + const span = Math.max(relativeEnd - relativeStart, 0); + const parts = __privateGet(this, _parts); + const blobParts = []; + let added = 0; + for (const part of parts) { + if (added >= span) { + break; + } + const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && size2 <= relativeStart) { + relativeStart -= size2; + relativeEnd -= size2; + } else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.byteLength; + } else { + chunk = part.slice(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.size; + } + relativeEnd -= size2; + blobParts.push(chunk); + relativeStart = 0; + } + } + const blob = new _a([], { type: String(type).toLowerCase() }); + __privateSet(blob, _size, span); + __privateSet(blob, _parts, blobParts); + return blob; + } + get [Symbol.toStringTag]() { + return "Blob"; + } + static [Symbol.hasInstance](object) { + return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]); + } + }, _parts = new WeakMap(), _type = new WeakMap(), _size = new WeakMap(), _endings = new WeakMap(), _a); + Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } + }); + Blob = _Blob; + fetch_blob_default = Blob; + } +}); + +// ../../../node_modules/fetch-blob/file.js +var _lastModified, _name, _a2, _File, File, file_default; +var init_file = __esm({ + "../../../node_modules/fetch-blob/file.js"() { + init_fetch_blob(); + _File = (_a2 = class extends fetch_blob_default { + /** + * @param {*[]} fileBits + * @param {string} fileName + * @param {{lastModified?: number, type?: string}} options + */ + // @ts-ignore + constructor(fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`); + } + super(fileBits, options); + __privateAdd(this, _lastModified, 0); + __privateAdd(this, _name, ""); + if (options === null) + options = {}; + const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + __privateSet(this, _lastModified, lastModified); + } + __privateSet(this, _name, String(fileName)); + } + get name() { + return __privateGet(this, _name); + } + get lastModified() { + return __privateGet(this, _lastModified); + } + get [Symbol.toStringTag]() { + return "File"; + } + static [Symbol.hasInstance](object) { + return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]); + } + }, _lastModified = new WeakMap(), _name = new WeakMap(), _a2); + File = _File; + file_default = File; + } +}); + +// ../../../node_modules/formdata-polyfill/esm.min.js +function formDataToBlob(F2, B = fetch_blob_default) { + var b = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c = [], p = `--${b}\r +Content-Disposition: form-data; name="`; + F2.forEach((v, n) => typeof v == "string" ? c.push(p + e(n) + `"\r +\r +${v.replace(/\r(?!\n)|(? (a += "", /^(Blob|File)$/.test(b && b[t]) ? [(c = c !== void 0 ? c + "" : b[t] == "File" ? b.name : "blob", a), b.name !== c || b[t] == "blob" ? new file_default([b], c, b) : b] : [a, b + ""]); + e = (c, f3) => (f3 ? c : c.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); + x = (n, a, e2) => { + if (a.length < e2) { + throw new TypeError(`Failed to execute '${n}' on 'FormData': ${e2} arguments required, but only ${a.length} present.`); + } + }; + FormData = (_a3 = class { + constructor(...a) { + __privateAdd(this, _d, []); + if (a.length) + throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`); + } + get [t]() { + return "FormData"; + } + [i]() { + return this.entries(); + } + static [h](o) { + return o && typeof o === "object" && o[t] === "FormData" && !m.some((m2) => typeof o[m2] != "function"); + } + append(...a) { + x("append", arguments, 2); + __privateGet(this, _d).push(f(...a)); + } + delete(a) { + x("delete", arguments, 1); + a += ""; + __privateSet(this, _d, __privateGet(this, _d).filter(([b]) => b !== a)); + } + get(a) { + x("get", arguments, 1); + a += ""; + for (var b = __privateGet(this, _d), l = b.length, c = 0; c < l; c++) + if (b[c][0] === a) + return b[c][1]; + return null; + } + getAll(a, b) { + x("getAll", arguments, 1); + b = []; + a += ""; + __privateGet(this, _d).forEach((c) => c[0] === a && b.push(c[1])); + return b; + } + has(a) { + x("has", arguments, 1); + a += ""; + return __privateGet(this, _d).some((b) => b[0] === a); + } + forEach(a, b) { + x("forEach", arguments, 1); + for (var [c, d] of this) + a.call(b, d, c, this); + } + set(...a) { + x("set", arguments, 2); + var b = [], c = true; + a = f(...a); + __privateGet(this, _d).forEach((d) => { + d[0] === a[0] ? c && (c = !b.push(a)) : b.push(d); + }); + c && b.push(a); + __privateSet(this, _d, b); + } + *entries() { + yield* __privateGet(this, _d); + } + *keys() { + for (var [a] of this) + yield a; + } + *values() { + for (var [, a] of this) + yield a; + } + }, _d = new WeakMap(), _a3); + } +}); + +// ../../../node_modules/node-domexception/index.js +var require_node_domexception = __commonJS({ + "../../../node_modules/node-domexception/index.js"(exports, module2) { + if (!globalThis.DOMException) { + try { + const { MessageChannel } = require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer(); + port.postMessage(ab, [ab, ab]); + } catch (err) { + err.constructor.name === "DOMException" && (globalThis.DOMException = err.constructor); + } + } + module2.exports = globalThis.DOMException; + } +}); + +// ../../../node_modules/fetch-blob/from.js +var import_node_fs, import_node_domexception, stat, _path, _start, _BlobDataItem, BlobDataItem; +var init_from = __esm({ + "../../../node_modules/fetch-blob/from.js"() { + import_node_fs = require("fs"); + import_node_domexception = __toESM(require_node_domexception(), 1); + init_file(); + init_fetch_blob(); + ({ stat } = import_node_fs.promises); + _BlobDataItem = class { + constructor(options) { + __privateAdd(this, _path, void 0); + __privateAdd(this, _start, void 0); + __privateSet(this, _path, options.path); + __privateSet(this, _start, options.start); + this.size = options.size; + this.lastModified = options.lastModified; + } + /** + * Slicing arguments is first validated and formatted + * to not be out of range by Blob.prototype.slice + */ + slice(start, end) { + return new _BlobDataItem({ + path: __privateGet(this, _path), + lastModified: this.lastModified, + size: end - start, + start: __privateGet(this, _start) + start + }); + } + async *stream() { + const { mtimeMs } = await stat(__privateGet(this, _path)); + if (mtimeMs > this.lastModified) { + throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError"); + } + yield* (0, import_node_fs.createReadStream)(__privateGet(this, _path), { + start: __privateGet(this, _start), + end: __privateGet(this, _start) + this.size - 1 + }); + } + get [Symbol.toStringTag]() { + return "Blob"; + } + }; + BlobDataItem = _BlobDataItem; + _path = new WeakMap(); + _start = new WeakMap(); + } +}); + +// node_modules/node-fetch/src/utils/multipart-parser.js +var multipart_parser_exports = {}; +__export(multipart_parser_exports, { + toFormData: () => toFormData +}); +function _fileName(headerValue) { + const m2 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m2) { + return; + } + const match = m2[2] || m2[3] || ""; + let filename = match.slice(match.lastIndexOf("\\") + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m3, code) => { + return String.fromCharCode(code); + }); + return filename; +} +async function toFormData(Body2, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError("Failed to fetch"); + } + const m2 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (!m2) { + throw new TypeError("no or bad content-type header, no multipart boundary"); + } + const parser = new MultipartParser(m2[1] || m2[2]); + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData(); + const onPartData = (ui8a) => { + entryValue += decoder.decode(ui8a, { stream: true }); + }; + const appendToFile = (ui8a) => { + entryChunks.push(ui8a); + }; + const appendFileToFormData = () => { + const file = new file_default(entryChunks, filename, { type: contentType }); + formData.append(entryName, file); + }; + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + const decoder = new TextDecoder("utf-8"); + decoder.decode(); + parser.onPartBegin = function() { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + headerField = ""; + headerValue = ""; + entryValue = ""; + entryName = ""; + contentType = ""; + filename = null; + entryChunks.length = 0; + }; + parser.onHeaderField = function(ui8a) { + headerField += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderValue = function(ui8a) { + headerValue += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderEnd = function() { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + if (headerField === "content-disposition") { + const m3 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + if (m3) { + entryName = m3[2] || m3[3] || ""; + } + filename = _fileName(headerValue); + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === "content-type") { + contentType = headerValue; + } + headerValue = ""; + headerField = ""; + }; + for await (const chunk of Body2) { + parser.write(chunk); + } + parser.end(); + return formData; +} +var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser; +var init_multipart_parser = __esm({ + "node_modules/node-fetch/src/utils/multipart-parser.js"() { + init_from(); + init_esm_min(); + s = 0; + S = { + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + END: s++ + }; + f2 = 1; + F = { + PART_BOUNDARY: f2, + LAST_BOUNDARY: f2 *= 2 + }; + LF = 10; + CR = 13; + SPACE = 32; + HYPHEN = 45; + COLON = 58; + A = 97; + Z = 122; + lower = (c) => c | 32; + noop = () => { + }; + MultipartParser = class { + /** + * @param {string} boundary + */ + constructor(boundary) { + this.index = 0; + this.flags = 0; + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + this.boundaryChars = {}; + boundary = "\r\n--" + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i2 = 0; i2 < boundary.length; i2++) { + ui8a[i2] = boundary.charCodeAt(i2); + this.boundaryChars[ui8a[i2]] = true; + } + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + /** + * @param {Uint8Array} data + */ + write(data) { + let i2 = 0; + const length_ = data.length; + let previousIndex = this.index; + let { lookbehind, boundary, boundaryChars, index, state, flags } = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + const mark = (name) => { + this[name + "Mark"] = i2; + }; + const clear = (name) => { + delete this[name + "Mark"]; + }; + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === void 0 || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + const dataCallback = (name, clear2) => { + const markSymbol = name + "Mark"; + if (!(markSymbol in this)) { + return; + } + if (clear2) { + callback(name, this[markSymbol], i2, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + for (i2 = 0; i2 < length_; i2++) { + c = data[i2]; + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + } else { + return; + } + break; + } + if (c !== boundary[index + 2]) { + index = -2; + } + if (c === boundary[index + 2]) { + index++; + } + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark("onHeaderField"); + index = 0; + case S.HEADER_FIELD: + if (c === CR) { + clear("onHeaderField"); + state = S.HEADERS_ALMOST_DONE; + break; + } + index++; + if (c === HYPHEN) { + break; + } + if (c === COLON) { + if (index === 1) { + return; + } + dataCallback("onHeaderField", true); + state = S.HEADER_VALUE_START; + break; + } + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + mark("onHeaderValue"); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if (c === CR) { + dataCallback("onHeaderValue", true); + callback("onHeaderEnd"); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + callback("onHeadersEnd"); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark("onPartData"); + case S.PART_DATA: + previousIndex = index; + if (index === 0) { + i2 += boundaryEnd; + while (i2 < bufferLength && !(data[i2] in boundaryChars)) { + i2 += boundaryLength; + } + i2 -= boundaryEnd; + c = data[i2]; + } + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback("onPartData", true); + } + index++; + } else { + index = 0; + } + } else if (index === boundary.length) { + index++; + if (c === CR) { + flags |= F.PART_BOUNDARY; + } else if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 === boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c === LF) { + flags &= ~F.PART_BOUNDARY; + callback("onPartEnd"); + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback("onPartEnd"); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + if (index > 0) { + lookbehind[index - 1] = c; + } else if (previousIndex > 0) { + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback("onPartData", 0, previousIndex, _lookbehind); + previousIndex = 0; + mark("onPartData"); + i2--; + } + break; + case S.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } + } + dataCallback("onHeaderField"); + dataCallback("onHeaderValue"); + dataCallback("onPartData"); + this.index = index; + this.state = state; + this.flags = flags; + } + end() { + if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error("MultipartParser.end(): stream ended unexpectedly"); + } + } + }; + } +}); + +// lib/assertions/providers/lambda-handler/index.ts +var lambda_handler_exports = {}; +__export(lambda_handler_exports, { + handler: () => handler, + isComplete: () => isComplete, + onTimeout: () => onTimeout +}); +module.exports = __toCommonJS(lambda_handler_exports); + +// lib/assertions/providers/lambda-handler/assertion.ts +var import_helpers_internal = __toESM(require_helpers_internal()); + +// lib/assertions/providers/lambda-handler/base.ts +var https = __toESM(require("https")); +var url = __toESM(require("url")); +var AWS = __toESM(require("aws-sdk")); +var CustomResourceHandler = class { + constructor(event, context) { + this.event = event; + this.context = context; + this.timedOut = false; + this.timeout = setTimeout(async () => { + await this.respond({ + status: "FAILED", + reason: "Lambda Function Timeout", + data: this.context.logStreamName + }); + this.timedOut = true; + }, context.getRemainingTimeInMillis() - 1200); + this.event = event; + this.physicalResourceId = extractPhysicalResourceId(event); + } + /** + * Handles executing the custom resource event. If `stateMachineArn` is present + * in the props then trigger the waiter statemachine + */ + async handle() { + try { + if ("stateMachineArn" in this.event.ResourceProperties) { + const req = { + stateMachineArn: this.event.ResourceProperties.stateMachineArn, + name: this.event.RequestId, + input: JSON.stringify(this.event) + }; + await this.startExecution(req); + return; + } else { + const response = await this.processEvent(this.event.ResourceProperties); + return response; + } + } catch (e2) { + console.log(e2); + throw e2; + } finally { + clearTimeout(this.timeout); + } + } + /** + * Handle async requests from the waiter state machine + */ + async handleIsComplete() { + try { + const result = await this.processEvent(this.event.ResourceProperties); + return result; + } catch (e2) { + console.log(e2); + return; + } finally { + clearTimeout(this.timeout); + } + } + /** + * Start a step function state machine which will wait for the request + * to be successful. + */ + async startExecution(req) { + try { + const sfn = new AWS.StepFunctions(); + await sfn.startExecution(req).promise(); + } finally { + clearTimeout(this.timeout); + } + } + respond(response) { + if (this.timedOut) { + return; + } + const cfResponse = { + Status: response.status, + Reason: response.reason, + PhysicalResourceId: this.physicalResourceId, + StackId: this.event.StackId, + RequestId: this.event.RequestId, + LogicalResourceId: this.event.LogicalResourceId, + NoEcho: false, + Data: response.data + }; + const responseBody = JSON.stringify(cfResponse); + console.log("Responding to CloudFormation", responseBody); + const parsedUrl = url.parse(this.event.ResponseURL); + const requestOptions = { + hostname: parsedUrl.hostname, + path: parsedUrl.path, + method: "PUT", + headers: { + "content-type": "", + "content-length": Buffer.byteLength(responseBody, "utf8") + } + }; + return new Promise((resolve, reject) => { + try { + const request2 = https.request(requestOptions, resolve); + request2.on("error", reject); + request2.write(responseBody); + request2.end(); + } catch (e2) { + reject(e2); + } finally { + clearTimeout(this.timeout); + } + }); + } +}; +function extractPhysicalResourceId(event) { + switch (event.RequestType) { + case "Create": + return event.LogicalResourceId; + case "Update": + case "Delete": + return event.PhysicalResourceId; + } +} + +// lib/assertions/providers/lambda-handler/assertion.ts +var AssertionHandler = class extends CustomResourceHandler { + async processEvent(request2) { + let actual = decodeCall(request2.actual); + const expected = decodeCall(request2.expected); + let result; + const matcher = new MatchCreator(expected).getMatcher(); + console.log(`Testing equality between ${JSON.stringify(request2.actual)} and ${JSON.stringify(request2.expected)}`); + const matchResult = matcher.test(actual); + matchResult.finished(); + if (matchResult.hasFailed()) { + result = { + failed: true, + assertion: JSON.stringify({ + status: "fail", + message: matchResult.renderMismatch() + }) + }; + if (request2.failDeployment) { + throw new Error(result.assertion); + } + } else { + result = { + assertion: JSON.stringify({ + status: "success" + }) + }; + } + return result; + } +}; +var MatchCreator = class { + constructor(obj) { + this.parsedObj = { + matcher: obj + }; + } + /** + * Return a Matcher that can be tested against the actual results. + * This will convert the encoded matchers into their corresponding + * assertions matcher. + * + * For example: + * + * ExpectedResult.objectLike({ + * Messages: [{ + * Body: Match.objectLike({ + * Elements: Match.arrayWith([{ Asdf: 3 }]), + * Payload: Match.serializedJson({ key: 'value' }), + * }), + * }], + * }); + * + * Will be encoded as: + * { + * $ObjectLike: { + * Messages: [{ + * Body: { + * $ObjectLike: { + * Elements: { + * $ArrayWith: [{ Asdf: 3 }], + * }, + * Payload: { + * $SerializedJson: { key: 'value' } + * } + * }, + * }, + * }], + * }, + * } + * + * Which can then be parsed by this function. For each key (recursively) + * the parser will check if the value has one of the encoded matchers as a key + * and if so, it will set the value as the Matcher. So, + * + * { + * Body: { + * $ObjectLike: { + * Elements: { + * $ArrayWith: [{ Asdf: 3 }], + * }, + * Payload: { + * $SerializedJson: { key: 'value' } + * } + * }, + * }, + * } + * + * Will be converted to + * { + * Body: Match.objectLike({ + * Elements: Match.arrayWith([{ Asdf: 3 }]), + * Payload: Match.serializedJson({ key: 'value' }), + * }), + * } + */ + getMatcher() { + try { + const final = JSON.parse(JSON.stringify(this.parsedObj), function(_k, v) { + const nested = Object.keys(v)[0]; + switch (nested) { + case "$ArrayWith": + return import_helpers_internal.Match.arrayWith(v[nested]); + case "$ObjectLike": + return import_helpers_internal.Match.objectLike(v[nested]); + case "$StringLike": + return import_helpers_internal.Match.stringLikeRegexp(v[nested]); + case "$SerializedJson": + return import_helpers_internal.Match.serializedJson(v[nested]); + default: + return v; + } + }); + if (import_helpers_internal.Matcher.isMatcher(final.matcher)) { + return final.matcher; + } + return import_helpers_internal.Match.exact(final.matcher); + } catch { + return import_helpers_internal.Match.exact(this.parsedObj.matcher); + } + } +}; +function decodeCall(call) { + if (!call) { + return void 0; + } + try { + const parsed = JSON.parse(call); + return parsed; + } catch { + return call; + } +} + +// node_modules/node-fetch/src/index.js +var import_node_http2 = __toESM(require("http"), 1); +var import_node_https = __toESM(require("https"), 1); +var import_node_zlib = __toESM(require("zlib"), 1); +var import_node_stream2 = __toESM(require("stream"), 1); +var import_node_buffer2 = require("buffer"); + +// ../../../node_modules/data-uri-to-buffer/dist/index.js +function dataUriToBuffer(uri) { + if (!/^data:/i.test(uri)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); + } + uri = uri.replace(/\r?\n/g, ""); + const firstComma = uri.indexOf(","); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError("malformed data: URI"); + } + const meta = uri.substring(5, firstComma).split(";"); + let charset = ""; + let base64 = false; + const type = meta[0] || "text/plain"; + let typeFull = type; + for (let i2 = 1; i2 < meta.length; i2++) { + if (meta[i2] === "base64") { + base64 = true; + } else if (meta[i2]) { + typeFull += `;${meta[i2]}`; + if (meta[i2].indexOf("charset=") === 0) { + charset = meta[i2].substring(8); + } + } + } + if (!meta[0] && !charset.length) { + typeFull += ";charset=US-ASCII"; + charset = "US-ASCII"; + } + const encoding = base64 ? "base64" : "ascii"; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + buffer.type = type; + buffer.typeFull = typeFull; + buffer.charset = charset; + return buffer; +} +var dist_default = dataUriToBuffer; + +// node_modules/node-fetch/src/body.js +var import_node_stream = __toESM(require("stream"), 1); +var import_node_util = require("util"); +var import_node_buffer = require("buffer"); +init_fetch_blob(); +init_esm_min(); + +// node_modules/node-fetch/src/errors/base.js +var FetchBaseError = class extends Error { + constructor(message, type) { + super(message); + Error.captureStackTrace(this, this.constructor); + this.type = type; + } + get name() { + return this.constructor.name; + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } +}; + +// node_modules/node-fetch/src/errors/fetch-error.js +var FetchError = class extends FetchBaseError { + /** + * @param {string} message - Error message for human + * @param {string} [type] - Error type for machine + * @param {SystemError} [systemError] - For Node.js system error + */ + constructor(message, type, systemError) { + super(message, type); + if (systemError) { + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } + } +}; + +// node_modules/node-fetch/src/utils/is.js +var NAME = Symbol.toStringTag; +var isURLSearchParameters = (object) => { + return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams"; +}; +var isBlob = (object) => { + return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]); +}; +var isAbortSignal = (object) => { + return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget"); +}; +var isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + return orig === dest || orig.endsWith(`.${dest}`); +}; +var isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + return orig === dest; +}; + +// node_modules/node-fetch/src/body.js +var pipeline = (0, import_node_util.promisify)(import_node_stream.default.pipeline); +var INTERNALS = Symbol("Body internals"); +var Body = class { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + if (body === null) { + body = null; + } else if (isURLSearchParameters(body)) { + body = import_node_buffer.Buffer.from(body.toString()); + } else if (isBlob(body)) { + } else if (import_node_buffer.Buffer.isBuffer(body)) { + } else if (import_node_util.types.isAnyArrayBuffer(body)) { + body = import_node_buffer.Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + body = import_node_buffer.Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof import_node_stream.default) { + } else if (body instanceof FormData) { + body = formDataToBlob(body); + boundary = body.type.split("=")[1]; + } else { + body = import_node_buffer.Buffer.from(String(body)); + } + let stream = body; + if (import_node_buffer.Buffer.isBuffer(body)) { + stream = import_node_stream.default.Readable.from(body); + } else if (isBlob(body)) { + stream = import_node_stream.default.Readable.from(body.stream()); + } + this[INTERNALS] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + if (body instanceof import_node_stream.default) { + body.on("error", (error_) => { + const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_); + this[INTERNALS].error = error; + }); + } + } + get body() { + return this[INTERNALS].stream; + } + get bodyUsed() { + return this[INTERNALS].disturbed; + } + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + async arrayBuffer() { + const { buffer, byteOffset, byteLength } = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + async formData() { + const ct = this.headers.get("content-type"); + if (ct.startsWith("application/x-www-form-urlencoded")) { + const formData = new FormData(); + const parameters = new URLSearchParams(await this.text()); + for (const [name, value] of parameters) { + formData.append(name, value); + } + return formData; + } + const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports)); + return toFormData2(this.body, ct); + } + /** + * Return raw response as Blob + * + * @return Promise + */ + async blob() { + const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || ""; + const buf = await this.arrayBuffer(); + return new fetch_blob_default([buf], { + type: ct + }); + } + /** + * Decode response as json + * + * @return Promise + */ + async json() { + const text = await this.text(); + return JSON.parse(text); + } + /** + * Decode response as text + * + * @return Promise + */ + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody(this); + } +}; +Body.prototype.buffer = (0, import_node_util.deprecate)(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer"); +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true }, + data: { get: (0, import_node_util.deprecate)( + () => { + }, + "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", + "https://github.com/node-fetch/node-fetch/issues/1000 (response)" + ) } +}); +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + data[INTERNALS].disturbed = true; + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + const { body } = data; + if (body === null) { + return import_node_buffer.Buffer.alloc(0); + } + if (!(body instanceof import_node_stream.default)) { + return import_node_buffer.Buffer.alloc(0); + } + const accum = []; + let accumBytes = 0; + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size"); + body.destroy(error); + throw error; + } + accumBytes += chunk.length; + accum.push(chunk); + } + } catch (error) { + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, "system", error); + throw error_; + } + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every((c) => typeof c === "string")) { + return import_node_buffer.Buffer.from(accum.join("")); + } + return import_node_buffer.Buffer.concat(accum, accumBytes); + } catch (error) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, "system", error); + } + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} +var clone = (instance, highWaterMark) => { + let p1; + let p2; + let { body } = instance[INTERNALS]; + if (instance.bodyUsed) { + throw new Error("cannot clone body after it is used"); + } + if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") { + p1 = new import_node_stream.PassThrough({ highWaterMark }); + p2 = new import_node_stream.PassThrough({ highWaterMark }); + body.pipe(p1); + body.pipe(p2); + instance[INTERNALS].stream = p1; + body = p2; + } + return body; +}; +var getNonSpecFormDataBoundary = (0, import_node_util.deprecate)( + (body) => body.getBoundary(), + "form-data doesn't follow the spec and requires special treatment. Use alternative package", + "https://github.com/node-fetch/node-fetch/issues/1167" +); +var extractContentType = (body, request2) => { + if (body === null) { + return null; + } + if (typeof body === "string") { + return "text/plain;charset=UTF-8"; + } + if (isURLSearchParameters(body)) { + return "application/x-www-form-urlencoded;charset=UTF-8"; + } + if (isBlob(body)) { + return body.type || null; + } + if (import_node_buffer.Buffer.isBuffer(body) || import_node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + if (body instanceof FormData) { + return `multipart/form-data; boundary=${request2[INTERNALS].boundary}`; + } + if (body && typeof body.getBoundary === "function") { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + if (body instanceof import_node_stream.default) { + return null; + } + return "text/plain;charset=UTF-8"; +}; +var getTotalBytes = (request2) => { + const { body } = request2[INTERNALS]; + if (body === null) { + return 0; + } + if (isBlob(body)) { + return body.size; + } + if (import_node_buffer.Buffer.isBuffer(body)) { + return body.length; + } + if (body && typeof body.getLengthSync === "function") { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + return null; +}; +var writeToStream = async (dest, { body }) => { + if (body === null) { + dest.end(); + } else { + await pipeline(body, dest); + } +}; + +// node_modules/node-fetch/src/headers.js +var import_node_util2 = require("util"); +var import_node_http = __toESM(require("http"), 1); +var validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_HTTP_TOKEN" }); + throw error; + } +}; +var validateHeaderValue = typeof import_node_http.default.validateHeaderValue === "function" ? import_node_http.default.validateHeaderValue : (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_CHAR" }); + throw error; + } +}; +var Headers = class extends URLSearchParams { + /** + * Headers class + * + * @constructor + * @param {HeadersInit} [init] - Response headers + */ + constructor(init) { + let result = []; + if (init instanceof Headers) { + const raw = init.raw(); + for (const [name, values] of Object.entries(raw)) { + result.push(...values.map((value) => [name, value])); + } + } else if (init == null) { + } else if (typeof init === "object" && !import_node_util2.types.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + if (method == null) { + result.push(...Object.entries(init)); + } else { + if (typeof method !== "function") { + throw new TypeError("Header pairs must be iterable"); + } + result = [...init].map((pair) => { + if (typeof pair !== "object" || import_node_util2.types.isBoxedPrimitive(pair)) { + throw new TypeError("Each header pair must be an iterable object"); + } + return [...pair]; + }).map((pair) => { + if (pair.length !== 2) { + throw new TypeError("Each header pair must be a name/value tuple"); + } + return [...pair]; + }); + } + } else { + throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)"); + } + result = result.length > 0 ? result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : void 0; + super(result); + return new Proxy(this, { + get(target, p, receiver) { + switch (p) { + case "append": + case "set": + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase(), + String(value) + ); + }; + case "delete": + case "has": + case "getAll": + return (name) => { + validateHeaderName(name); + return URLSearchParams.prototype[p].call( + target, + String(name).toLowerCase() + ); + }; + case "keys": + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + default: + return Reflect.get(target, p, receiver); + } + } + }); + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } + toString() { + return Object.prototype.toString.call(this); + } + get(name) { + const values = this.getAll(name); + if (values.length === 0) { + return null; + } + let value = values.join(", "); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + return value; + } + forEach(callback, thisArg = void 0) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } + } + *values() { + for (const name of this.keys()) { + yield this.get(name); + } + } + /** + * @type {() => IterableIterator<[string, string]>} + */ + *entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } + } + [Symbol.iterator]() { + return this.entries(); + } + /** + * Node-fetch non-spec method + * returning all headers and their values as array + * @returns {Record} + */ + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); + } + /** + * For better console.log(headers) and also to convert Headers into Node.js Request compatible format + */ + [Symbol.for("nodejs.util.inspect.custom")]() { + return [...this.keys()].reduce((result, key) => { + const values = this.getAll(key); + if (key === "host") { + result[key] = values[0]; + } else { + result[key] = values.length > 1 ? values : values[0]; + } + return result; + }, {}); + } +}; +Object.defineProperties( + Headers.prototype, + ["get", "entries", "forEach", "values"].reduce((result, property) => { + result[property] = { enumerable: true }; + return result; + }, {}) +); +function fromRawHeaders(headers = []) { + return new Headers( + headers.reduce((result, value, index, array) => { + if (index % 2 === 0) { + result.push(array.slice(index, index + 2)); + } + return result; + }, []).filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch { + return false; + } + }) + ); +} + +// node_modules/node-fetch/src/utils/is-redirect.js +var redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); +var isRedirect = (code) => { + return redirectStatus.has(code); +}; + +// node_modules/node-fetch/src/response.js +var INTERNALS2 = Symbol("Response internals"); +var Response = class extends Body { + constructor(body = null, options = {}) { + super(body, options); + const status = options.status != null ? options.status : 200; + const headers = new Headers(options.headers); + if (body !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append("Content-Type", contentType); + } + } + this[INTERNALS2] = { + type: "default", + url: options.url, + status, + statusText: options.statusText || "", + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + get type() { + return this[INTERNALS2].type; + } + get url() { + return this[INTERNALS2].url || ""; + } + get status() { + return this[INTERNALS2].status; + } + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300; + } + get redirected() { + return this[INTERNALS2].counter > 0; + } + get statusText() { + return this[INTERNALS2].statusText; + } + get headers() { + return this[INTERNALS2].headers; + } + get highWaterMark() { + return this[INTERNALS2].highWaterMark; + } + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); + } + /** + * @param {string} url The URL that the new response is to originate from. + * @param {number} status An optional status code for the response (e.g., 302.) + * @returns {Response} A Response object. + */ + static redirect(url2, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + return new Response(null, { + headers: { + location: new URL(url2).toString() + }, + status + }); + } + static error() { + const response = new Response(null, { status: 0, statusText: "" }); + response[INTERNALS2].type = "error"; + return response; + } + static json(data = void 0, init = {}) { + const body = JSON.stringify(data); + if (body === void 0) { + throw new TypeError("data is not JSON serializable"); + } + const headers = new Headers(init && init.headers); + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + return new Response(body, { + ...init, + headers + }); + } + get [Symbol.toStringTag]() { + return "Response"; + } +}; +Object.defineProperties(Response.prototype, { + type: { enumerable: true }, + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +// node_modules/node-fetch/src/request.js +var import_node_url = require("url"); +var import_node_util3 = require("util"); + +// node_modules/node-fetch/src/utils/get-search.js +var getSearch = (parsedURL) => { + if (parsedURL.search) { + return parsedURL.search; + } + const lastOffset = parsedURL.href.length - 1; + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : ""); + return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : ""; +}; + +// node_modules/node-fetch/src/utils/referrer.js +var import_node_net = require("net"); +function stripURLForUseAsAReferrer(url2, originOnly = false) { + if (url2 == null) { + return "no-referrer"; + } + url2 = new URL(url2); + if (/^(about|blob|data):$/.test(url2.protocol)) { + return "no-referrer"; + } + url2.username = ""; + url2.password = ""; + url2.hash = ""; + if (originOnly) { + url2.pathname = ""; + url2.search = ""; + } + return url2; +} +var ReferrerPolicy = /* @__PURE__ */ new Set([ + "", + "no-referrer", + "no-referrer-when-downgrade", + "same-origin", + "origin", + "strict-origin", + "origin-when-cross-origin", + "strict-origin-when-cross-origin", + "unsafe-url" +]); +var DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin"; +function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + return referrerPolicy; +} +function isOriginPotentiallyTrustworthy(url2) { + if (/^(http|ws)s:$/.test(url2.protocol)) { + return true; + } + const hostIp = url2.host.replace(/(^\[)|(]$)/g, ""); + const hostIPVersion = (0, import_node_net.isIP)(hostIp); + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + if (url2.host === "localhost" || url2.host.endsWith(".localhost")) { + return false; + } + if (url2.protocol === "file:") { + return true; + } + return false; +} +function isUrlPotentiallyTrustworthy(url2) { + if (/^about:(blank|srcdoc)$/.test(url2)) { + return true; + } + if (url2.protocol === "data:") { + return true; + } + if (/^(blob|filesystem):$/.test(url2.protocol)) { + return true; + } + return isOriginPotentiallyTrustworthy(url2); +} +function determineRequestsReferrer(request2, { referrerURLCallback, referrerOriginCallback } = {}) { + if (request2.referrer === "no-referrer" || request2.referrerPolicy === "") { + return null; + } + const policy = request2.referrerPolicy; + if (request2.referrer === "about:client") { + return "no-referrer"; + } + const referrerSource = request2.referrer; + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + const currentURL = new URL(request2.url); + switch (policy) { + case "no-referrer": + return "no-referrer"; + case "origin": + return referrerOrigin; + case "unsafe-url": + return referrerURL; + case "strict-origin": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin.toString(); + case "strict-origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin; + case "same-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return "no-referrer"; + case "origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return referrerOrigin; + case "no-referrer-when-downgrade": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerURL; + default: + throw new TypeError(`Invalid referrerPolicy: ${policy}`); + } +} +function parseReferrerPolicyFromHeader(headers) { + const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/); + let policy = ""; + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy = token; + } + } + return policy; +} + +// node_modules/node-fetch/src/request.js +var INTERNALS3 = Symbol("Request internals"); +var isRequest = (object) => { + return typeof object === "object" && typeof object[INTERNALS3] === "object"; +}; +var doBadDataWarn = (0, import_node_util3.deprecate)( + () => { + }, + ".data is not a valid RequestInit property, use .body instead", + "https://github.com/node-fetch/node-fetch/issues/1000 (request)" +); +var Request = class extends Body { + constructor(input, init = {}) { + let parsedURL; + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; + } + if (parsedURL.username !== "" || parsedURL.password !== "") { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); + } + let method = init.method || input.method || "GET"; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); + } + if (!isRequest(init) && "data" in init) { + doBadDataWarn(); + } + if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) { + throw new TypeError("Request with GET/HEAD method cannot have body"); + } + const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + super(inputBody, { + size: init.size || input.size || 0 + }); + const headers = new Headers(init.headers || input.headers || {}); + if (inputBody !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set("Content-Type", contentType); + } + } + let signal = isRequest(input) ? input.signal : null; + if ("signal" in init) { + signal = init.signal; + } + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget"); + } + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === "") { + referrer = "no-referrer"; + } else if (referrer) { + const parsedReferrer = new URL(referrer); + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer; + } else { + referrer = void 0; + } + this[INTERNALS3] = { + method, + redirect: init.redirect || input.redirect || "follow", + headers, + parsedURL, + signal, + referrer + }; + this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow; + this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ""; + } + /** @returns {string} */ + get method() { + return this[INTERNALS3].method; + } + /** @returns {string} */ + get url() { + return (0, import_node_url.format)(this[INTERNALS3].parsedURL); + } + /** @returns {Headers} */ + get headers() { + return this[INTERNALS3].headers; + } + get redirect() { + return this[INTERNALS3].redirect; + } + /** @returns {AbortSignal} */ + get signal() { + return this[INTERNALS3].signal; + } + // https://fetch.spec.whatwg.org/#dom-request-referrer + get referrer() { + if (this[INTERNALS3].referrer === "no-referrer") { + return ""; + } + if (this[INTERNALS3].referrer === "client") { + return "about:client"; + } + if (this[INTERNALS3].referrer) { + return this[INTERNALS3].referrer.toString(); + } + return void 0; + } + get referrerPolicy() { + return this[INTERNALS3].referrerPolicy; + } + set referrerPolicy(referrerPolicy) { + this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } + get [Symbol.toStringTag]() { + return "Request"; + } +}; +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true }, + referrer: { enumerable: true }, + referrerPolicy: { enumerable: true } +}); +var getNodeRequestOptions = (request2) => { + const { parsedURL } = request2[INTERNALS3]; + const headers = new Headers(request2[INTERNALS3].headers); + if (!headers.has("Accept")) { + headers.set("Accept", "*/*"); + } + let contentLengthValue = null; + if (request2.body === null && /^(post|put)$/i.test(request2.method)) { + contentLengthValue = "0"; + } + if (request2.body !== null) { + const totalBytes = getTotalBytes(request2); + if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set("Content-Length", contentLengthValue); + } + if (request2.referrerPolicy === "") { + request2.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + if (request2.referrer && request2.referrer !== "no-referrer") { + request2[INTERNALS3].referrer = determineRequestsReferrer(request2); + } else { + request2[INTERNALS3].referrer = "no-referrer"; + } + if (request2[INTERNALS3].referrer instanceof URL) { + headers.set("Referer", request2.referrer); + } + if (!headers.has("User-Agent")) { + headers.set("User-Agent", "node-fetch"); + } + if (request2.compress && !headers.has("Accept-Encoding")) { + headers.set("Accept-Encoding", "gzip, deflate, br"); + } + let { agent } = request2; + if (typeof agent === "function") { + agent = agent(parsedURL); + } + if (!headers.has("Connection") && !agent) { + headers.set("Connection", "close"); + } + const search = getSearch(parsedURL); + const options = { + // Overwrite search to retain trailing ? (issue #776) + path: parsedURL.pathname + search, + // The following options are not expressed in the URL + method: request2.method, + headers: headers[Symbol.for("nodejs.util.inspect.custom")](), + insecureHTTPParser: request2.insecureHTTPParser, + agent + }; + return { + /** @type {URL} */ + parsedURL, + options + }; +}; + +// node_modules/node-fetch/src/errors/abort-error.js +var AbortError = class extends FetchBaseError { + constructor(message, type = "aborted") { + super(message, type); + } +}; + +// node_modules/node-fetch/src/index.js +init_esm_min(); +init_from(); +var supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]); +async function fetch(url2, options_) { + return new Promise((resolve, reject) => { + const request2 = new Request(url2, options_); + const { parsedURL, options } = getNodeRequestOptions(request2); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url2}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`); + } + if (parsedURL.protocol === "data:") { + const data = dist_default(request2.url); + const response2 = new Response(data, { headers: { "Content-Type": data.typeFull } }); + resolve(response2); + return; + } + const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request; + const { signal } = request2; + let response = null; + const abort = () => { + const error = new AbortError("The operation was aborted."); + reject(error); + if (request2.body && request2.body instanceof import_node_stream2.default.Readable) { + request2.body.destroy(error); + } + if (!response || !response.body) { + return; + } + response.body.emit("error", error); + }; + if (signal && signal.aborted) { + abort(); + return; + } + const abortAndFinalize = () => { + abort(); + finalize(); + }; + const request_ = send(parsedURL.toString(), options); + if (signal) { + signal.addEventListener("abort", abortAndFinalize); + } + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener("abort", abortAndFinalize); + } + }; + request_.on("error", (error) => { + reject(new FetchError(`request to ${request2.url} failed, reason: ${error.message}`, "system", error)); + finalize(); + }); + fixResponseChunkedTransferBadEnding(request_, (error) => { + if (response && response.body) { + response.body.destroy(error); + } + }); + if (process.version < "v14") { + request_.on("socket", (s2) => { + let endedWithEventsCount; + s2.prependListener("end", () => { + endedWithEventsCount = s2._eventsCount; + }); + s2.prependListener("close", (hadError) => { + if (response && endedWithEventsCount < s2._eventsCount && !hadError) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + response.body.emit("error", error); + } + }); + }); + } + request_.on("response", (response_) => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + if (isRedirect(response_.statusCode)) { + const location = headers.get("Location"); + let locationURL = null; + try { + locationURL = location === null ? null : new URL(location, request2.url); + } catch { + if (request2.redirect !== "manual") { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect")); + finalize(); + return; + } + } + switch (request2.redirect) { + case "error": + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request2.url}`, "no-redirect")); + finalize(); + return; + case "manual": + break; + case "follow": { + if (locationURL === null) { + break; + } + if (request2.counter >= request2.follow) { + reject(new FetchError(`maximum redirect reached at: ${request2.url}`, "max-redirect")); + finalize(); + return; + } + const requestOptions = { + headers: new Headers(request2.headers), + follow: request2.follow, + counter: request2.counter + 1, + agent: request2.agent, + compress: request2.compress, + method: request2.method, + body: clone(request2), + signal: request2.signal, + size: request2.size, + referrer: request2.referrer, + referrerPolicy: request2.referrerPolicy + }; + if (!isDomainOrSubdomain(request2.url, locationURL) || !isSameProtocol(request2.url, locationURL)) { + for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) { + requestOptions.headers.delete(name); + } + } + if (response_.statusCode !== 303 && request2.body && options_.body instanceof import_node_stream2.default.Readable) { + reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect")); + finalize(); + return; + } + if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request2.method === "POST") { + requestOptions.method = "GET"; + requestOptions.body = void 0; + requestOptions.headers.delete("content-length"); + } + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + resolve(fetch(new Request(locationURL, requestOptions))); + finalize(); + return; + } + default: + return reject(new TypeError(`Redirect option '${request2.redirect}' is not a valid value of RequestRedirect`)); + } + } + if (signal) { + response_.once("end", () => { + signal.removeEventListener("abort", abortAndFinalize); + }); + } + let body = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + if (process.version < "v12.10") { + response_.on("aborted", abortAndFinalize); + } + const responseOptions = { + url: request2.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request2.size, + counter: request2.counter, + highWaterMark: request2.highWaterMark + }; + const codings = headers.get("Content-Encoding"); + if (!request2.compress || request2.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + const zlibOptions = { + flush: import_node_zlib.default.Z_SYNC_FLUSH, + finishFlush: import_node_zlib.default.Z_SYNC_FLUSH + }; + if (codings === "gzip" || codings === "x-gzip") { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createGunzip(zlibOptions), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + if (codings === "deflate" || codings === "x-deflate") { + const raw = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + raw.once("data", (chunk) => { + if ((chunk[0] & 15) === 8) { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflate(), (error) => { + if (error) { + reject(error); + } + }); + } else { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflateRaw(), (error) => { + if (error) { + reject(error); + } + }); + } + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once("end", () => { + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + if (codings === "br") { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + response = new Response(body, responseOptions); + resolve(response); + }); + writeToStream(request_, request2).catch(reject); + }); +} +function fixResponseChunkedTransferBadEnding(request2, errorCallback) { + const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n"); + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + request2.on("response", (response) => { + const { headers } = response; + isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"]; + }); + request2.on("socket", (socket) => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + errorCallback(error); + } + }; + const onData = (buf) => { + properLastChunkReceived = import_node_buffer2.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = import_node_buffer2.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && import_node_buffer2.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0; + } + previousChunk = buf; + }; + socket.prependListener("close", onSocketClose); + socket.on("data", onData); + request2.on("close", () => { + socket.removeListener("close", onSocketClose); + socket.removeListener("data", onData); + }); + }); +} + +// lib/assertions/providers/lambda-handler/http.ts +var HttpHandler = class extends CustomResourceHandler { + async processEvent(request2) { + console.log("request", request2); + const response = await fetch(request2.parameters.url, request2.parameters.fetchOptions); + const result = { + ok: response.ok, + status: response.status, + statusText: response.statusText, + headers: response.headers.raw() + }; + try { + const jsonResponse = await response.json(); + result.body = jsonResponse; + } catch (e2) { + result.body = {}; + } + return { + apiCallResponse: result + }; + } +}; + +// lib/assertions/providers/lambda-handler/utils.ts +function decode(object) { + return JSON.parse(JSON.stringify(object), (_k, v) => { + switch (v) { + case "TRUE:BOOLEAN": + return true; + case "FALSE:BOOLEAN": + return false; + default: + return v; + } + }); +} + +// lib/assertions/providers/lambda-handler/sdk.ts +function flatten(object) { + return Object.assign( + {}, + ...function _flatten(child, path = []) { + return [].concat(...Object.keys(child).map((key) => { + let childKey = Buffer.isBuffer(child[key]) ? child[key].toString("utf8") : child[key]; + if (typeof childKey === "string") { + childKey = isJsonString(childKey); + } + return typeof childKey === "object" && childKey !== null ? _flatten(childKey, path.concat([key])) : { [path.concat([key]).join(".")]: childKey }; + })); + }(object) + ); +} +var AwsApiCallHandler = class extends CustomResourceHandler { + async processEvent(request2) { + const AWS2 = require("aws-sdk"); + console.log(`AWS SDK VERSION: ${AWS2.VERSION}`); + if (!Object.prototype.hasOwnProperty.call(AWS2, request2.service)) { + throw Error(`Service ${request2.service} does not exist in AWS SDK version ${AWS2.VERSION}.`); + } + const service = new AWS2[request2.service](); + const response = await service[request2.api](request2.parameters && decode(request2.parameters)).promise(); + console.log(`SDK response received ${JSON.stringify(response)}`); + delete response.ResponseMetadata; + const respond = { + apiCallResponse: response + }; + const flatData = { + ...flatten(respond) + }; + let resp = respond; + if (request2.outputPaths) { + resp = filterKeys(flatData, request2.outputPaths); + } else if (request2.flattenResponse === "true") { + resp = flatData; + } + console.log(`Returning result ${JSON.stringify(resp)}`); + return resp; + } +}; +function filterKeys(object, searchStrings) { + return Object.entries(object).reduce((filteredObject, [key, value]) => { + for (const searchString of searchStrings) { + if (key.startsWith(`apiCallResponse.${searchString}`)) { + filteredObject[key] = value; + } + } + return filteredObject; + }, {}); +} +function isJsonString(value) { + try { + return JSON.parse(value); + } catch { + return value; + } +} + +// lib/assertions/providers/lambda-handler/types.ts +var ASSERT_RESOURCE_TYPE = "Custom::DeployAssert@AssertEquals"; +var SDK_RESOURCE_TYPE_PREFIX = "Custom::DeployAssert@SdkCall"; +var HTTP_RESOURCE_TYPE = "Custom::DeployAssert@HttpCall"; + +// lib/assertions/providers/lambda-handler/index.ts +async function handler(event, context) { + console.log(`Event: ${JSON.stringify({ ...event, ResponseURL: "..." })}`); + const provider = createResourceHandler(event, context); + try { + if (event.RequestType === "Delete") { + await provider.respond({ + status: "SUCCESS", + reason: "OK" + }); + return; + } + const result = await provider.handle(); + if ("stateMachineArn" in event.ResourceProperties) { + console.info('Found "stateMachineArn", waiter statemachine started'); + return; + } else if ("expected" in event.ResourceProperties) { + console.info('Found "expected", testing assertions'); + const actualPath = event.ResourceProperties.actualPath; + const actual = actualPath ? result[`apiCallResponse.${actualPath}`] : result.apiCallResponse; + const assertion = new AssertionHandler({ + ...event, + ResourceProperties: { + ServiceToken: event.ServiceToken, + actual, + expected: event.ResourceProperties.expected + } + }, context); + try { + const assertionResult = await assertion.handle(); + await provider.respond({ + status: "SUCCESS", + reason: "OK", + // return both the result of the API call _and_ the assertion results + data: { + ...assertionResult, + ...result + } + }); + return; + } catch (e2) { + await provider.respond({ + status: "FAILED", + reason: e2.message ?? "Internal Error" + }); + return; + } + } + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: result + }); + } catch (e2) { + await provider.respond({ + status: "FAILED", + reason: e2.message ?? "Internal Error" + }); + return; + } + return; +} +async function onTimeout(timeoutEvent) { + const isCompleteRequest = JSON.parse(JSON.parse(timeoutEvent.Cause).errorMessage); + const provider = createResourceHandler(isCompleteRequest, standardContext); + await provider.respond({ + status: "FAILED", + reason: "Operation timed out: " + JSON.stringify(isCompleteRequest) + }); +} +async function isComplete(event, context) { + console.log(`Event: ${JSON.stringify({ ...event, ResponseURL: "..." })}`); + const provider = createResourceHandler(event, context); + try { + const result = await provider.handleIsComplete(); + const actualPath = event.ResourceProperties.actualPath; + if (result) { + const actual = actualPath ? result[`apiCallResponse.${actualPath}`] : result.apiCallResponse; + if ("expected" in event.ResourceProperties) { + const assertion = new AssertionHandler({ + ...event, + ResourceProperties: { + ServiceToken: event.ServiceToken, + actual, + expected: event.ResourceProperties.expected + } + }, context); + const assertionResult = await assertion.handleIsComplete(); + if (!(assertionResult == null ? void 0 : assertionResult.failed)) { + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: { + ...assertionResult, + ...result + } + }); + return; + } else { + console.log(`Assertion Failed: ${JSON.stringify(assertionResult)}`); + throw new Error(JSON.stringify(event)); + } + } + await provider.respond({ + status: "SUCCESS", + reason: "OK", + data: result + }); + } else { + console.log("No result"); + throw new Error(JSON.stringify(event)); + } + return; + } catch (e2) { + console.log(e2); + throw new Error(JSON.stringify(event)); + } +} +function createResourceHandler(event, context) { + if (event.ResourceType.startsWith(SDK_RESOURCE_TYPE_PREFIX)) { + return new AwsApiCallHandler(event, context); + } else if (event.ResourceType.startsWith(ASSERT_RESOURCE_TYPE)) { + return new AssertionHandler(event, context); + } else if (event.ResourceType.startsWith(HTTP_RESOURCE_TYPE)) { + return new HttpHandler(event, context); + } else { + throw new Error(`Unsupported resource type "${event.ResourceType}`); + } +} +var standardContext = { + getRemainingTimeInMillis: () => 9e4 +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + handler, + isComplete, + onTimeout +}); +/*! Bundled license information: + +fetch-blob/index.js: + (*! fetch-blob. MIT License. Jimmy Wärting *) + +formdata-polyfill/esm.min.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting *) + +node-domexception/index.js: + (*! node-domexception. MIT License. Jimmy Wärting *) +*/ diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/cdk.out b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/cdk.out index 588d7b269d34f..f0b901e7c06e5 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/cdk.out +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/cdk.out @@ -1 +1 @@ -{"version":"20.0.0"} \ No newline at end of file +{"version":"32.0.0"} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integ.json b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integ.json index e978390ab7297..01eb9a81329a0 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integ.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integ.json @@ -1,14 +1,12 @@ { - "version": "20.0.0", + "version": "32.0.0", "testCases": { - "integ.lambda-target": { + "integ-test/DefaultTest": { "stacks": [ "TestStack" ], - "diffAssets": false, - "stackUpdateWorkflow": true + "assertionStack": "integ-test/DefaultTest/DeployAssert", + "assertionStackName": "integtestDefaultTestDeployAssert24D5C536" } - }, - "synthContext": {}, - "enableLookups": false + } } \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integtestDefaultTestDeployAssert24D5C536.assets.json b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integtestDefaultTestDeployAssert24D5C536.assets.json new file mode 100644 index 0000000000000..3125df543a015 --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integtestDefaultTestDeployAssert24D5C536.assets.json @@ -0,0 +1,32 @@ +{ + "version": "32.0.0", + "files": { + "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231": { + "source": { + "path": "asset.939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.bundle", + "packaging": "zip" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.zip", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + }, + "eb51d743b276434c505b3725a847d37044c5671a063019cfd1b3a2bd3d3fca7f": { + "source": { + "path": "integtestDefaultTestDeployAssert24D5C536.template.json", + "packaging": "file" + }, + "destinations": { + "current_account-current_region": { + "bucketName": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}", + "objectKey": "eb51d743b276434c505b3725a847d37044c5671a063019cfd1b3a2bd3d3fca7f.json", + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-file-publishing-role-${AWS::AccountId}-${AWS::Region}" + } + } + } + }, + "dockerImages": {} +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integtestDefaultTestDeployAssert24D5C536.template.json b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integtestDefaultTestDeployAssert24D5C536.template.json new file mode 100644 index 0000000000000..306b69f5ca8fc --- /dev/null +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/integtestDefaultTestDeployAssert24D5C536.template.json @@ -0,0 +1,119 @@ +{ + "Resources": { + "HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed": { + "Type": "Custom::DeployAssert@HttpCall", + "Properties": { + "ServiceToken": { + "Fn::GetAtt": [ + "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F", + "Arn" + ] + }, + "parameters": { + "url": { + "Fn::Join": [ + "", + [ + "http://", + { + "Fn::ImportValue": "TestStack:ExportsOutputFnGetAttLB8A12904CDNSName5EFD7323" + } + ] + ] + }, + "fetchOptions": {} + }, + "expected": "{\"$ObjectLike\":{\"status\":200,\"headers\":{\"content-type\":[\"application/json\"]},\"body\":{\"message\":\"Hello from Lambda\"}}}", + "salt": "1687525536356" + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete" + }, + "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + } + ] + }, + "ManagedPolicyArns": [ + { + "Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + } + ] + } + }, + "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Runtime": "nodejs14.x", + "Code": { + "S3Bucket": { + "Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}" + }, + "S3Key": "939278de4f3903a6b4bdb449b0e6f69208d04d53be21684b360f6410e8416231.zip" + }, + "Timeout": 120, + "Handler": "index.handler", + "Role": { + "Fn::GetAtt": [ + "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73", + "Arn" + ] + } + } + } + }, + "Outputs": { + "AssertionResultsHttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed": { + "Value": { + "Fn::GetAtt": [ + "HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed", + "assertion" + ] + } + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": { + "Fn::Not": [ + { + "Fn::Contains": [ + [ + "1", + "2", + "3", + "4", + "5" + ], + { + "Ref": "BootstrapVersion" + } + ] + } + ] + }, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/manifest.json b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/manifest.json index f385a756c5143..b1a282378d5c4 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/manifest.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/manifest.json @@ -1,12 +1,6 @@ { - "version": "20.0.0", + "version": "32.0.0", "artifacts": { - "Tree": { - "type": "cdk:tree", - "properties": { - "file": "tree.json" - } - }, "TestStack.assets": { "type": "cdk:asset-manifest", "properties": { @@ -23,7 +17,7 @@ "validateOnSynth": false, "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", - "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/09fed6843eb7543b7a99153262d1d26031e96a708c160488de552fbeb33dc7df.json", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/fbba15e6e00a4b1f0763788fc913facda96a647e18b1894398dc3cb12296dd41.json", "requiresBootstrapStackVersion": 6, "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", "additionalDependencies": [ @@ -207,6 +201,12 @@ "data": "FunInvoke2UTWxhlfyqbT5FTn5jvgbLgjFfJwzswGk55DU1HY1CA1AAFB" } ], + "/TestStack/Exports/Output{\"Fn::GetAtt\":[\"LB8A12904C\",\"DNSName\"]}": [ + { + "type": "aws:cdk:logicalId", + "data": "ExportsOutputFnGetAttLB8A12904CDNSName5EFD7323" + } + ], "/TestStack/BootstrapVersion": [ { "type": "aws:cdk:logicalId", @@ -221,6 +221,84 @@ ] }, "displayName": "TestStack" + }, + "integtestDefaultTestDeployAssert24D5C536.assets": { + "type": "cdk:asset-manifest", + "properties": { + "file": "integtestDefaultTestDeployAssert24D5C536.assets.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "integtestDefaultTestDeployAssert24D5C536": { + "type": "aws:cloudformation:stack", + "environment": "aws://unknown-account/unknown-region", + "properties": { + "templateFile": "integtestDefaultTestDeployAssert24D5C536.template.json", + "validateOnSynth": false, + "assumeRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-deploy-role-${AWS::AccountId}-${AWS::Region}", + "cloudFormationExecutionRoleArn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-cfn-exec-role-${AWS::AccountId}-${AWS::Region}", + "stackTemplateAssetObjectUrl": "s3://cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}/eb51d743b276434c505b3725a847d37044c5671a063019cfd1b3a2bd3d3fca7f.json", + "requiresBootstrapStackVersion": 6, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version", + "additionalDependencies": [ + "integtestDefaultTestDeployAssert24D5C536.assets" + ], + "lookupRole": { + "arn": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/cdk-hnb659fds-lookup-role-${AWS::AccountId}-${AWS::Region}", + "requiresBootstrapStackVersion": 8, + "bootstrapStackVersionSsmParameter": "/cdk-bootstrap/hnb659fds/version" + } + }, + "dependencies": [ + "TestStack", + "integtestDefaultTestDeployAssert24D5C536.assets" + ], + "metadata": { + "/integ-test/DefaultTest/DeployAssert/HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed/Default/Default": [ + { + "type": "aws:cdk:logicalId", + "data": "HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed" + } + ], + "/integ-test/DefaultTest/DeployAssert/HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed/AssertionResults": [ + { + "type": "aws:cdk:logicalId", + "data": "AssertionResultsHttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed" + } + ], + "/integ-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role": [ + { + "type": "aws:cdk:logicalId", + "data": "SingletonFunction1488541a7b23466481b69b4408076b81Role37ABCE73" + } + ], + "/integ-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Handler": [ + { + "type": "aws:cdk:logicalId", + "data": "SingletonFunction1488541a7b23466481b69b4408076b81HandlerCD40AE9F" + } + ], + "/integ-test/DefaultTest/DeployAssert/BootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "BootstrapVersion" + } + ], + "/integ-test/DefaultTest/DeployAssert/CheckBootstrapVersion": [ + { + "type": "aws:cdk:logicalId", + "data": "CheckBootstrapVersion" + } + ] + }, + "displayName": "integ-test/DefaultTest/DeployAssert" + }, + "Tree": { + "type": "cdk:tree", + "properties": { + "file": "tree.json" + } } } } \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/tree.json b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/tree.json index 56e04e12da313..279e94afefa9b 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/tree.json +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.js.snapshot/tree.json @@ -4,14 +4,6 @@ "id": "App", "path": "", "children": { - "Tree": { - "id": "Tree", - "path": "Tree", - "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" - } - }, "TestStack": { "id": "TestStack", "path": "TestStack", @@ -39,7 +31,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnVPC", + "fqn": "aws-cdk-lib.aws_ec2.CfnVPC", "version": "0.0.0" } }, @@ -83,7 +75,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSubnet", + "fqn": "aws-cdk-lib.aws_ec2.CfnSubnet", "version": "0.0.0" } }, @@ -91,8 +83,8 @@ "id": "Acl", "path": "TestStack/Stack/PublicSubnet1/Acl", "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" } }, "RouteTable": { @@ -113,7 +105,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnRouteTable", + "fqn": "aws-cdk-lib.aws_ec2.CfnRouteTable", "version": "0.0.0" } }, @@ -132,7 +124,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSubnetRouteTableAssociation", + "fqn": "aws-cdk-lib.aws_ec2.CfnSubnetRouteTableAssociation", "version": "0.0.0" } }, @@ -152,7 +144,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnRoute", + "fqn": "aws-cdk-lib.aws_ec2.CfnRoute", "version": "0.0.0" } }, @@ -172,7 +164,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnEIP", + "fqn": "aws-cdk-lib.aws_ec2.CfnEIP", "version": "0.0.0" } }, @@ -200,13 +192,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnNatGateway", + "fqn": "aws-cdk-lib.aws_ec2.CfnNatGateway", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.PublicSubnet", + "fqn": "aws-cdk-lib.aws_ec2.PublicSubnet", "version": "0.0.0" } }, @@ -250,7 +242,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSubnet", + "fqn": "aws-cdk-lib.aws_ec2.CfnSubnet", "version": "0.0.0" } }, @@ -258,8 +250,8 @@ "id": "Acl", "path": "TestStack/Stack/PublicSubnet2/Acl", "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" } }, "RouteTable": { @@ -280,7 +272,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnRouteTable", + "fqn": "aws-cdk-lib.aws_ec2.CfnRouteTable", "version": "0.0.0" } }, @@ -299,7 +291,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSubnetRouteTableAssociation", + "fqn": "aws-cdk-lib.aws_ec2.CfnSubnetRouteTableAssociation", "version": "0.0.0" } }, @@ -319,13 +311,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnRoute", + "fqn": "aws-cdk-lib.aws_ec2.CfnRoute", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.PublicSubnet", + "fqn": "aws-cdk-lib.aws_ec2.PublicSubnet", "version": "0.0.0" } }, @@ -369,7 +361,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSubnet", + "fqn": "aws-cdk-lib.aws_ec2.CfnSubnet", "version": "0.0.0" } }, @@ -377,8 +369,8 @@ "id": "Acl", "path": "TestStack/Stack/PrivateSubnet1/Acl", "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" } }, "RouteTable": { @@ -399,7 +391,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnRouteTable", + "fqn": "aws-cdk-lib.aws_ec2.CfnRouteTable", "version": "0.0.0" } }, @@ -418,7 +410,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSubnetRouteTableAssociation", + "fqn": "aws-cdk-lib.aws_ec2.CfnSubnetRouteTableAssociation", "version": "0.0.0" } }, @@ -438,13 +430,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnRoute", + "fqn": "aws-cdk-lib.aws_ec2.CfnRoute", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.PrivateSubnet", + "fqn": "aws-cdk-lib.aws_ec2.PrivateSubnet", "version": "0.0.0" } }, @@ -488,7 +480,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSubnet", + "fqn": "aws-cdk-lib.aws_ec2.CfnSubnet", "version": "0.0.0" } }, @@ -496,8 +488,8 @@ "id": "Acl", "path": "TestStack/Stack/PrivateSubnet2/Acl", "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" } }, "RouteTable": { @@ -518,7 +510,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnRouteTable", + "fqn": "aws-cdk-lib.aws_ec2.CfnRouteTable", "version": "0.0.0" } }, @@ -537,7 +529,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSubnetRouteTableAssociation", + "fqn": "aws-cdk-lib.aws_ec2.CfnSubnetRouteTableAssociation", "version": "0.0.0" } }, @@ -557,13 +549,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnRoute", + "fqn": "aws-cdk-lib.aws_ec2.CfnRoute", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.PrivateSubnet", + "fqn": "aws-cdk-lib.aws_ec2.PrivateSubnet", "version": "0.0.0" } }, @@ -582,7 +574,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnInternetGateway", + "fqn": "aws-cdk-lib.aws_ec2.CfnInternetGateway", "version": "0.0.0" } }, @@ -601,13 +593,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnVPCGatewayAttachment", + "fqn": "aws-cdk-lib.aws_ec2.CfnVPCGatewayAttachment", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.Vpc", + "fqn": "aws-cdk-lib.aws_ec2.Vpc", "version": "0.0.0" } }, @@ -648,7 +640,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-elasticloadbalancingv2.CfnLoadBalancer", + "fqn": "aws-cdk-lib.aws_elasticloadbalancingv2.CfnLoadBalancer", "version": "0.0.0" } }, @@ -687,13 +679,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.CfnSecurityGroup", + "fqn": "aws-cdk-lib.aws_ec2.CfnSecurityGroup", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-ec2.SecurityGroup", + "fqn": "aws-cdk-lib.aws_ec2.SecurityGroup", "version": "0.0.0" } }, @@ -723,7 +715,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-elasticloadbalancingv2.CfnListener", + "fqn": "aws-cdk-lib.aws_elasticloadbalancingv2.CfnListener", "version": "0.0.0" } }, @@ -751,25 +743,25 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-elasticloadbalancingv2.CfnTargetGroup", + "fqn": "aws-cdk-lib.aws_elasticloadbalancingv2.CfnTargetGroup", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-elasticloadbalancingv2.ApplicationTargetGroup", + "fqn": "aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationTargetGroup", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-elasticloadbalancingv2.ApplicationListener", + "fqn": "aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationListener", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-elasticloadbalancingv2.ApplicationLoadBalancer", + "fqn": "aws-cdk-lib.aws_elasticloadbalancingv2.ApplicationLoadBalancer", "version": "0.0.0" } }, @@ -781,6 +773,14 @@ "id": "ServiceRole", "path": "TestStack/Fun/ServiceRole", "children": { + "ImportServiceRole": { + "id": "ImportServiceRole", + "path": "TestStack/Fun/ServiceRole/ImportServiceRole", + "constructInfo": { + "fqn": "aws-cdk-lib.Resource", + "version": "0.0.0" + } + }, "Resource": { "id": "Resource", "path": "TestStack/Fun/ServiceRole/Resource", @@ -816,13 +816,13 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-iam.CfnRole", + "fqn": "aws-cdk-lib.aws_iam.CfnRole", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-iam.Role", + "fqn": "aws-cdk-lib.aws_iam.Role", "version": "0.0.0" } }, @@ -833,7 +833,7 @@ "aws:cdk:cloudformation:type": "AWS::Lambda::Function", "aws:cdk:cloudformation:props": { "code": { - "zipFile": "\ndef handler(event, context):\n return {\n \"isBase64Encoded\": False,\n \"statusCode\": 200,\n \"statusDescription\": \"200 OK\",\n \"headers\": {\n \"Set-cookie\": \"cookies\",\n \"Content-Type\": \"application/json\"\n },\n \"body\": \"Hello from Lambda\"\n }\n " + "zipFile": "\nimport json\ndef handler(event, context):\n return {\n \"isBase64Encoded\": False,\n \"statusCode\": 200,\n \"statusDescription\": \"200 OK\",\n \"headers\": {\n \"Set-cookie\": \"cookies\",\n \"Content-Type\": \"application/json\"\n },\n \"body\": json.dumps({ \"message\": \"Hello from Lambda\" })\n }\n " }, "role": { "Fn::GetAtt": [ @@ -846,7 +846,7 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.CfnFunction", + "fqn": "aws-cdk-lib.aws_lambda.CfnFunction", "version": "0.0.0" } }, @@ -867,26 +867,210 @@ } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.CfnPermission", + "fqn": "aws-cdk-lib.aws_lambda.CfnPermission", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.aws_lambda.Function", + "version": "0.0.0" + } + }, + "Exports": { + "id": "Exports", + "path": "TestStack/Exports", + "children": { + "Output{\"Fn::GetAtt\":[\"LB8A12904C\",\"DNSName\"]}": { + "id": "Output{\"Fn::GetAtt\":[\"LB8A12904C\",\"DNSName\"]}", + "path": "TestStack/Exports/Output{\"Fn::GetAtt\":[\"LB8A12904C\",\"DNSName\"]}", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnOutput", "version": "0.0.0" } } }, "constructInfo": { - "fqn": "@aws-cdk/aws-lambda.Function", + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "TestStack/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "TestStack/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", "version": "0.0.0" } } }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + }, + "integ-test": { + "id": "integ-test", + "path": "integ-test", + "children": { + "DefaultTest": { + "id": "DefaultTest", + "path": "integ-test/DefaultTest", + "children": { + "Default": { + "id": "Default", + "path": "integ-test/DefaultTest/Default", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "DeployAssert": { + "id": "DeployAssert", + "path": "integ-test/DefaultTest/DeployAssert", + "children": { + "HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed": { + "id": "HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed", + "path": "integ-test/DefaultTest/DeployAssert/HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed", + "children": { + "HttpProvider": { + "id": "HttpProvider", + "path": "integ-test/DefaultTest/DeployAssert/HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed/HttpProvider", + "children": { + "AssertionsProvider": { + "id": "AssertionsProvider", + "path": "integ-test/DefaultTest/DeployAssert/HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed/HttpProvider/AssertionsProvider", + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "Default": { + "id": "Default", + "path": "integ-test/DefaultTest/DeployAssert/HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed/Default", + "children": { + "Default": { + "id": "Default", + "path": "integ-test/DefaultTest/DeployAssert/HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed/Default/Default", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.CustomResource", + "version": "0.0.0" + } + }, + "AssertionResults": { + "id": "AssertionResults", + "path": "integ-test/DefaultTest/DeployAssert/HttpApiCalle3f6a93bca1f1b655dbed0f0a1ca02ed/AssertionResults", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnOutput", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "SingletonFunction1488541a7b23466481b69b4408076b81": { + "id": "SingletonFunction1488541a7b23466481b69b4408076b81", + "path": "integ-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81", + "children": { + "Staging": { + "id": "Staging", + "path": "integ-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Staging", + "constructInfo": { + "fqn": "aws-cdk-lib.AssetStaging", + "version": "0.0.0" + } + }, + "Role": { + "id": "Role", + "path": "integ-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Role", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + }, + "Handler": { + "id": "Handler", + "path": "integ-test/DefaultTest/DeployAssert/SingletonFunction1488541a7b23466481b69b4408076b81/Handler", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnResource", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "BootstrapVersion": { + "id": "BootstrapVersion", + "path": "integ-test/DefaultTest/DeployAssert/BootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnParameter", + "version": "0.0.0" + } + }, + "CheckBootstrapVersion": { + "id": "CheckBootstrapVersion", + "path": "integ-test/DefaultTest/DeployAssert/CheckBootstrapVersion", + "constructInfo": { + "fqn": "aws-cdk-lib.CfnRule", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "aws-cdk-lib.Stack", + "version": "0.0.0" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + } + }, + "constructInfo": { + "fqn": "constructs.Construct", + "version": "10.2.55" + } + }, + "Tree": { + "id": "Tree", + "path": "Tree", "constructInfo": { "fqn": "constructs.Construct", - "version": "10.1.85" + "version": "10.2.55" } } }, "constructInfo": { - "fqn": "constructs.Construct", - "version": "10.1.85" + "fqn": "aws-cdk-lib.App", + "version": "0.0.0" } } } \ No newline at end of file diff --git a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.ts b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.ts index 733155643bbd6..b0a242cfe6ad8 100644 --- a/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.ts +++ b/packages/@aws-cdk-testing/framework-integ/test/aws-elasticloadbalancingv2-targets/test/integ.lambda-target.ts @@ -4,18 +4,21 @@ import * as lambda from 'aws-cdk-lib/aws-lambda'; import { App, Stack } from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as targets from 'aws-cdk-lib/aws-elasticloadbalancingv2-targets'; +import { ExpectedResult, IntegTest } from '@aws-cdk/integ-tests-alpha'; class TestStack extends Stack { + public readonly lb: elbv2.IApplicationLoadBalancer; constructor(scope: Construct, id: string) { super(scope, id); const vpc = new ec2.Vpc(this, 'Stack', { maxAzs: 2, natGateways: 1, restrictDefaultSecurityGroup: false }); - const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { vpc, internetFacing: true }); - const listener = lb.addListener('Listener', { port: 80 }); + this.lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { vpc, internetFacing: true }); + const listener = this.lb.addListener('Listener', { port: 80 }); const fn = new lambda.Function(this, 'Fun', { code: lambda.Code.fromInline(` +import json def handler(event, context): return { "isBase64Encoded": False, @@ -25,7 +28,7 @@ def handler(event, context): "Set-cookie": "cookies", "Content-Type": "application/json" }, - "body": "Hello from Lambda" + "body": json.dumps({ "message": "Hello from Lambda" }) } `), runtime: lambda.Runtime.PYTHON_3_9, @@ -39,5 +42,16 @@ def handler(event, context): } const app = new App(); -new TestStack(app, 'TestStack'); -app.synth(); +const testCase = new TestStack(app, 'TestStack'); +const integ = new IntegTest(app, 'integ-test', { + testCases: [testCase], +}); + +const call = integ.assertions.httpApiCall(`http://${testCase.lb.loadBalancerDnsName}`, { }); +call.expect(ExpectedResult.objectLike({ + status: 200, + headers: { + 'content-type': ['application/json'], + }, + body: { message: 'Hello from Lambda' }, +})); diff --git a/packages/@aws-cdk/integ-tests-alpha/README.md b/packages/@aws-cdk/integ-tests-alpha/README.md index c6e3a89d49fc2..eaa086c78fe89 100644 --- a/packages/@aws-cdk/integ-tests-alpha/README.md +++ b/packages/@aws-cdk/integ-tests-alpha/README.md @@ -241,12 +241,43 @@ integ.assertions.expect( In the above example an assertion is created that will trigger a user defined `CustomResource` and assert that the `data` attribute is equal to `{ foo: 'bar' }`. -### AwsApiCall +### API Calls A common method to retrieve the "actual" results to compare with what is expected is to make an -AWS API call to receive some data. This library does this by utilizing CloudFormation custom resources +API call to receive some data. This library does this by utilizing CloudFormation custom resources which means that CloudFormation will call out to a Lambda Function which will -use the AWS JavaScript SDK to make the API call. +make the API call. + +#### HttpApiCall + +Using the `HttpApiCall` will use the +[node-fetch](https://github.com/node-fetch/node-fetch) JavaScript library to +make the HTTP call. + +This can be done by using the class directory (in the case of a normal deployment): + +```ts +declare const stack: Stack; + +new HttpApiCall(stack, 'MyAsssertion', { + url: 'https://example-api.com/abc', +}); +``` + +Or by using the `httpApiCall` method on `DeployAssert` (when writing integration tests): + +```ts +declare const app: App; +declare const stack: Stack; +const integ = new IntegTest(app, 'Integ', { + testCases: [stack], +}); +integ.assertions.httpApiCall('https://example-api.com/abc'); +``` + +#### AwsApiCall + +Using the `AwsApiCall` construct will use the AWS JavaScript SDK to make the API call. This can be done by using the class directory (in the case of a normal deployment): diff --git a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/http-call.ts b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/http-call.ts new file mode 100644 index 0000000000000..41e3bdf0e2a88 --- /dev/null +++ b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/http-call.ts @@ -0,0 +1,68 @@ +import { Aspects, CfnOutput, CustomResource, Lazy, Token } from 'aws-cdk-lib'; +import { Construct, IConstruct } from 'constructs'; +import { ApiCallBase, IApiCall } from './api-call-base'; +import { ExpectedResult } from './common'; +import { AssertionsProvider, HttpRequestParameters, HTTP_RESOURCE_TYPE } from './providers'; +import { WaiterStateMachine, WaiterStateMachineOptions } from './waiter-state-machine'; + +/** + * Options for creating an HttpApiCall provider + */ +export interface HttpCallProps extends HttpRequestParameters { } +/** + * Construct that creates a custom resource that will perform + * an HTTP API Call + */ +export class HttpApiCall extends ApiCallBase { + protected readonly apiCallResource: CustomResource; + public readonly provider: AssertionsProvider; + + constructor(scope: Construct, id: string, props: HttpCallProps) { + super(scope, id); + + let name = ''; + if (!Token.isUnresolved(props.url)) { + const url = new URL(props.url); + name = `${url.hostname}${url.pathname}`.replace(/\/|\.|:/g, ''); + } + this.provider = new AssertionsProvider(this, 'HttpProvider'); + this.apiCallResource = new CustomResource(this, 'Default', { + serviceToken: this.provider.serviceToken, + properties: { + parameters: props, + expected: Lazy.any({ produce: () => this.expectedResult }), + stateMachineArn: Lazy.string({ produce: () => this.stateMachineArn }), + salt: Date.now().toString(), + }, + resourceType: `${HTTP_RESOURCE_TYPE}${name}`.substring(0, 60), + }); + + // Needed so that all the policies set up by the provider should be available before the custom resource is provisioned. + this.apiCallResource.node.addDependency(this.provider); + Aspects.of(this).add({ + visit(node: IConstruct) { + if (node instanceof HttpApiCall) { + if (node.expectedResult) { + const result = node.apiCallResource.getAttString('assertion'); + + new CfnOutput(node, 'AssertionResults', { + value: result, + }).overrideLogicalId(`AssertionResults${id}`); + } + } + }, + }); + } + + public assertAtPath(_path: string, _expected: ExpectedResult): IApiCall { + return this; + } + public waitForAssertions(options?: WaiterStateMachineOptions | undefined): IApiCall { + const waiter = new WaiterStateMachine(this, 'WaitFor', { + ...options, + }); + this.stateMachineArn = waiter.stateMachineArn; + this.provider.addPolicyStatementFromSdkCall('states', 'StartExecution'); + return this; + }; +} diff --git a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/index.ts b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/index.ts index fdb65ff0d2b9c..209f95eed0693 100644 --- a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/index.ts +++ b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/index.ts @@ -6,3 +6,4 @@ export * from './common'; export * from './match'; export * from './api-call-base'; export * from './waiter-state-machine'; +export * from './http-call'; diff --git a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/private/deploy-assert.ts b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/private/deploy-assert.ts index 4610a6c0a03a0..e0bac3df6a8c5 100644 --- a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/private/deploy-assert.ts +++ b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/private/deploy-assert.ts @@ -1,9 +1,11 @@ -import { Stack } from 'aws-cdk-lib/core'; +import { Stack, Token } from 'aws-cdk-lib/core'; import { Construct, IConstruct, Node } from 'constructs'; import { IApiCall } from '../api-call-base'; import { EqualsAssertion } from '../assertions'; import { ActualResult, ExpectedResult } from '../common'; +import { HttpApiCall as HttpApiCall } from '../http-call'; import { md5hash } from '../private/hash'; +import { FetchOptions } from '../providers'; import { AwsApiCall, LambdaInvokeFunction, LambdaInvokeFunctionProps } from '../sdk'; import { IDeployAssert } from '../types'; @@ -71,6 +73,26 @@ export class DeployAssert extends Construct implements IDeployAssert { }); } + public httpApiCall(url: string, options?: FetchOptions): IApiCall { + let hash = ''; + try { + hash = md5hash(this.scope.resolve({ + url, + options, + })); + } catch {} + + let append = ''; + if (!Token.isUnresolved(url)) { + const parsedUrl = new URL(url); + append = `${parsedUrl.hostname}${parsedUrl.pathname}`; + } + return new HttpApiCall(this.scope, `HttpApiCall${append}${hash}`, { + url, + fetchOptions: options, + }); + } + public invokeFunction(props: LambdaInvokeFunctionProps): IApiCall { const hash = md5hash(this.scope.resolve(props)); return new LambdaInvokeFunction(this.scope, `LambdaInvoke${hash}`, props); diff --git a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/http.ts b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/http.ts new file mode 100644 index 0000000000000..386c56cf1d96e --- /dev/null +++ b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/http.ts @@ -0,0 +1,28 @@ +/* eslint-disable no-console */ +// eslint-disable-next-line import/no-extraneous-dependencies +import fetch, { Response } from 'node-fetch'; +// TODO: can use builtin fetch on node18 +import { CustomResourceHandler } from './base'; +import { HttpRequest, HttpResponseWrapper } from './types'; + +export class HttpHandler extends CustomResourceHandler { + protected async processEvent(request: HttpRequest): Promise { + console.log('request', request); + const response: Response = await fetch(request.parameters.url, request.parameters.fetchOptions); + const result: any = { + ok: response.ok, + status: response.status, + statusText: response.statusText, + headers: response.headers.raw(), + }; + try { + const jsonResponse = await response.json(); + result.body = jsonResponse; + } catch (e) { + result.body = {}; + } + return { + apiCallResponse: result, + }; + } +} diff --git a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/index.ts b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/index.ts index 464dcbe537622..976baed2c133d 100644 --- a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/index.ts +++ b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/index.ts @@ -1,5 +1,6 @@ /* eslint-disable no-console */ import { AssertionHandler } from './assertion'; +import { HttpHandler } from './http'; import { AwsApiCallHandler } from './sdk'; import * as types from './types'; @@ -147,6 +148,8 @@ function createResourceHandler(event: AWSLambda.CloudFormationCustomResourceEven return new AwsApiCallHandler(event, context); } else if (event.ResourceType.startsWith(types.ASSERT_RESOURCE_TYPE)) { return new AssertionHandler(event, context); + } else if (event.ResourceType.startsWith(types.HTTP_RESOURCE_TYPE)) { + return new HttpHandler(event, context); } else { throw new Error(`Unsupported resource type "${event.ResourceType}`); } diff --git a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/types.ts b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/types.ts index 096731c804f23..40c0e3f3565d5 100644 --- a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/types.ts +++ b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/providers/lambda-handler/types.ts @@ -3,6 +3,104 @@ export const ASSERT_RESOURCE_TYPE = 'Custom::DeployAssert@AssertEquals'; export const SDK_RESOURCE_TYPE_PREFIX = 'Custom::DeployAssert@SdkCall'; +export const HTTP_RESOURCE_TYPE = 'Custom::DeployAssert@HttpCall'; + +export interface HttpRequestParameters { + /** + * The url to fetch + */ + readonly url: string; + + /** + * Options for fetch + */ + readonly fetchOptions?: FetchOptions; +} + +/** + * Request to the HttpCall resource + */ +export interface HttpRequest { + /** + * Parameters from the custom resource + */ + readonly parameters: HttpRequestParameters; +} + +/** + * Options to pass to the JavaScript fetch api + */ +export interface FetchOptions { + /** + * Request body + * + * @default - no body + */ + readonly body?: string; + + /** + * Optional port + * + * @default default port for protocol + */ + readonly port?: number; + + /** + * HTTP method + * + * @default GET + */ + readonly method?: string; + + /** + * Optional request headers + * + * @default no headers + */ + readonly headers?: { [key: string]: string }; +} + +/** + * Response from the HttpCall resource + */ +export interface HttpResponseWrapper { + /** + * The Response from the fetch request + */ + readonly apiCallResponse: HttpResponse; +} + +/** + * Response from fetch + */ +export interface HttpResponse { + /** + * Indicates whether the response was successful + * + * status range 200-299 + */ + readonly ok?: boolean; + + /** + * Status code of the response + */ + readonly status?: number; + + /** + * The status message corresponding to the status code + */ + readonly statusText?: string; + + /** + * The response as JSON + */ + readonly responseJson?: { [key: string]: any }; + + /** + * Headers associated with the response + */ + readonly headers?: { [name: string]: any }; +} /** * A AWS JavaScript SDK V2 request diff --git a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/types.ts b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/types.ts index 81b3f1ec37250..e1a5843a9f3be 100644 --- a/packages/@aws-cdk/integ-tests-alpha/lib/assertions/types.ts +++ b/packages/@aws-cdk/integ-tests-alpha/lib/assertions/types.ts @@ -1,5 +1,6 @@ import { IApiCall } from './api-call-base'; import { ExpectedResult, ActualResult } from './common'; +import { FetchOptions } from './providers'; import { LambdaInvokeFunctionProps } from './sdk'; /** @@ -44,6 +45,19 @@ export interface IDeployAssert { */ invokeFunction(props: LambdaInvokeFunctionProps): IApiCall; + /** + * Make an HTTP call to the provided endpoint + * + * @example + * declare const app: App; + * declare const integ: IntegTest; + * const call = integ.assertions.httpApiCall('https://example.com/test'); + * call.expect(ExpectedResult.objectLike({ + * Message: 'Hello World!', + * })); + */ + httpApiCall(url: string, options?: FetchOptions): IApiCall; + /** * Assert that the ExpectedResult is equal * to the ActualResult diff --git a/packages/@aws-cdk/integ-tests-alpha/package.json b/packages/@aws-cdk/integ-tests-alpha/package.json index 71c4566de8fe0..1e4c65200db6a 100644 --- a/packages/@aws-cdk/integ-tests-alpha/package.json +++ b/packages/@aws-cdk/integ-tests-alpha/package.json @@ -77,6 +77,8 @@ "nock": "^13.3.1", "sinon": "^9.2.4", "aws-cdk-lib": "0.0.0", + "node-fetch": "^2.6.11", + "@types/node-fetch": "^2.6.2", "constructs": "^10.0.0" }, "dependencies": {}, diff --git a/packages/@aws-cdk/integ-tests-alpha/rosetta/default.ts-fixture b/packages/@aws-cdk/integ-tests-alpha/rosetta/default.ts-fixture index 9ae8a2ab04d7d..c2ae7dd6cd955 100644 --- a/packages/@aws-cdk/integ-tests-alpha/rosetta/default.ts-fixture +++ b/packages/@aws-cdk/integ-tests-alpha/rosetta/default.ts-fixture @@ -13,6 +13,7 @@ import { LambdaInvokeFunction, Match, AssertionsProvider, + HttpApiCall, } from '@aws-cdk/integ-tests-alpha'; import { Construct } from 'constructs'; import { diff --git a/packages/@aws-cdk/integ-tests-alpha/test/assertions/deploy-assert.test.ts b/packages/@aws-cdk/integ-tests-alpha/test/assertions/deploy-assert.test.ts index 4e2f149c9cbb5..fedf4f7a59704 100644 --- a/packages/@aws-cdk/integ-tests-alpha/test/assertions/deploy-assert.test.ts +++ b/packages/@aws-cdk/integ-tests-alpha/test/assertions/deploy-assert.test.ts @@ -1,4 +1,4 @@ -import { Template } from 'aws-cdk-lib/assertions'; +import { Match, Template } from 'aws-cdk-lib/assertions'; import { App, CustomResource, Stack } from 'aws-cdk-lib'; import { ActualResult, ExpectedResult, InvocationType, LogType } from '../../lib/assertions'; import { DeployAssert } from '../../lib/assertions/private/deploy-assert'; @@ -162,6 +162,102 @@ describe('DeployAssert', () => { template.resourceCountIs(truncatedType, 1); }); }); + + describe('httpApiCall', () => { + test('default', () => { + // GIVEN + const app = new App(); + const deplossert = new DeployAssert(app); + + // WHEN + deplossert.httpApiCall('https://example.com/test/123'); + + // THEN + Template.fromStack(deplossert.scope).templateMatches(Match.objectLike({ + Resources: Match.objectLike({ + HttpApiCallexamplecomtest1235ffa3a1b41e83da401e71706d1d9bc9a: { + Type: 'Custom::DeployAssert@HttpCallexamplecomtest123', + Properties: Match.objectLike({ + parameters: { + url: 'https://example.com/test/123', + }, + }), + }, + }), + })); + }); + + test('multiple calls can be configured', () => { + // GIVEN + const app = new App(); + + // WHEN + const deplossert = new DeployAssert(app); + deplossert.httpApiCall('https://example.com/test/123'); + deplossert.httpApiCall('https://example.com/test/789'); + + // THEN + const template = Template.fromStack(deplossert.scope); + template.resourceCountIs('AWS::Lambda::Function', 1); + template.resourceCountIs('Custom::DeployAssert@HttpCallexamplecomtest123', 1); + template.resourceCountIs('Custom::DeployAssert@HttpCallexamplecomtest789', 1); + }); + + test('call with fetch options', () => { + // GIVEN + const app = new App(); + + // WHEN + const deplossert = new DeployAssert(app); + deplossert.httpApiCall('https://example.com/test/123', { + body: JSON.stringify({ param: 'value' }), + headers: { + header1: 'value/value1', + }, + method: 'POST', + port: 8443, + }); + + // THEN + const template = Template.fromStack(deplossert.scope); + template.templateMatches(Match.objectLike({ + Resources: Match.objectLike({ + HttpApiCallexamplecomtest1234ed1aca271c61baebedbb58ac2be8cea: { + Type: 'Custom::DeployAssert@HttpCallexamplecomtest123', + Properties: Match.objectLike({ + parameters: { + url: 'https://example.com/test/123', + fetchOptions: { + body: JSON.stringify({ param: 'value' }), + headers: { header1: 'value/value1' }, + method: 'POST', + port: 8443, + }, + }, + }), + }, + }), + })); + template.resourceCountIs('AWS::Lambda::Function', 1); + }); + + test('custom resource type length is truncated when greater than 60 characters', () => { + // GIVEN + const app = new App(); + + // WHEN + const deplossert = new DeployAssert(app); + deplossert.httpApiCall('https://example.com/TheQuickBrownFoxJumpsOverTheLazyDog'); + + // THEN + const truncatedType = 'Custom::DeployAssert@HttpCallexamplecomTheQuickBrownFoxJumps'; + expect(truncatedType.length).toEqual(60); + + const template = Template.fromStack(deplossert.scope); + template.resourceCountIs('AWS::Lambda::Function', 1); + template.resourceCountIs(truncatedType, 1); + }); + }); }); describe('User provided assertions stack', () => { diff --git a/packages/@aws-cdk/integ-tests-alpha/test/assertions/providers/lambda-handler/http.test.ts b/packages/@aws-cdk/integ-tests-alpha/test/assertions/providers/lambda-handler/http.test.ts new file mode 100644 index 0000000000000..121114d135e16 --- /dev/null +++ b/packages/@aws-cdk/integ-tests-alpha/test/assertions/providers/lambda-handler/http.test.ts @@ -0,0 +1,107 @@ +import { HttpHandler } from '../../../../lib/assertions/providers/lambda-handler/http'; +import * as fetch from 'node-fetch'; +import { HttpRequest, HttpResponseWrapper } from '../../../../lib'; + +let fetchMock = jest.fn(); +jest.mock('node-fetch'); +const { Response } = jest.requireActual('node-fetch'); + +function httpHandler() { + const context: any = { + getRemainingTimeInMillis: () => 50000, + }; + return new HttpHandler({} as any, context); +} + +beforeAll(() => { + jest.useFakeTimers(); + jest.spyOn(console, 'log').mockImplementation(() => { return true; }); +}); + +afterAll(() => { + jest.useRealTimers(); + jest.restoreAllMocks(); +}); + +beforeEach(() => { + fetchMock = (fetch as any).mockResolvedValue( + new Response( + JSON.stringify({ key: 'value' }), + { status: 200, statusText: 'OK', ok: true }), + ); +}); + +describe('HttpHandler', () => { + test('default', async () => { + // GIVEN + const handler = httpHandler() as any; + const request: HttpRequest = { + parameters: { + url: 'url', + }, + }; + + // WHEN + const response: HttpResponseWrapper = await handler.processEvent(request); + + // THEN + expect(response.apiCallResponse).toEqual({ + ok: true, + body: { + key: 'value', + }, + headers: { + 'Content-Type': [ + 'text/plain;charset=UTF-8', + ], + }, + status: 200, + statusText: 'OK', + }); + expect(fetchMock).toHaveBeenCalledWith('url', undefined); + }); + + test('with fetch options', async () => { + // GIVEN + const handler = httpHandler() as any; + const request: HttpRequest = { + parameters: { + url: 'url', + fetchOptions: { + body: JSON.stringify({ param: 'value1' }), + method: 'POST', + port: 8443, + headers: { + 'Content-Type': 'application/json', + }, + }, + }, + }; + + // WHEN + const response: HttpResponseWrapper = await handler.processEvent(request); + + // THEN + expect(response.apiCallResponse).toEqual({ + ok: true, + body: { + key: 'value', + }, + headers: { + 'Content-Type': [ + 'text/plain;charset=UTF-8', + ], + }, + status: 200, + statusText: 'OK', + }); + expect(fetchMock).toHaveBeenCalledWith('url', { + body: JSON.stringify({ param: 'value1' }), + method: 'POST', + port: 8443, + headers: { + 'Content-Type': 'application/json', + }, + }); + }); +}); diff --git a/yarn.lock b/yarn.lock index f67a447b95287..0a6fa88cf8398 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2967,6 +2967,14 @@ resolved "https://registry.npmjs.org/@types/mockery/-/mockery-1.4.30.tgz#25f07fa7340371c7ee0fb9239511a34e0a19d5b7" integrity sha512-uv53RrNdhbkV/3VmVCtfImfYCWC3GTTRn3R11Whni3EJ+gb178tkZBVNj2edLY5CMrB749dQi+SJkg87jsN8UQ== +"@types/node-fetch@^2.6.2": + version "2.6.4" + resolved "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.4.tgz#1bc3a26de814f6bf466b25aeb1473fa1afe6a660" + integrity sha512-1ZX9fcN4Rvkvgv4E6PAY5WXUFWFcRWxZa3EW83UjycOB9ljJCedb2CupIP4RZMEwF/M3eTcCihbBRgwtGbg5Rg== + dependencies: + "@types/node" "*" + form-data "^3.0.0" + "@types/node@*": version "20.3.1" resolved "https://registry.npmjs.org/@types/node/-/node-20.3.1.tgz#e8a83f1aa8b649377bb1fb5d7bac5cb90e784dfe" @@ -6144,6 +6152,15 @@ form-data-encoder@^2.1.2: resolved "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-2.1.4.tgz#261ea35d2a70d48d30ec7a9603130fa5515e9cd5" integrity sha512-yDYSgNMraqvnxiEXO4hi88+YZxaHC6QKzb5N84iRCTDeRO7ZALpir/lVmf/uXUhnwUr2O4HU8s/n6x+yNjQkHw== +form-data@^3.0.0: + version "3.0.1" + resolved "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f" + integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg== + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.8" + mime-types "^2.1.12" + form-data@^4.0.0: version "4.0.0" resolved "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" @@ -9258,7 +9275,7 @@ node-fetch@2.6.7: dependencies: whatwg-url "^5.0.0" -node-fetch@^2.6.7: +node-fetch@^2.6.11, node-fetch@^2.6.7: version "2.6.11" resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.11.tgz#cde7fc71deef3131ef80a738919f999e6edfff25" integrity sha512-4I6pdBY1EthSqDmJkiNk3JIT8cswwR9nfeW/cPdUagJYEQG7R95WRH74wpz7ma8Gh/9dI9FP+OU+0E4FvtA55w==