@flowrunner/cli 0.1.7-dev.1 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/ai-docs/instructions/service-code-format/01-service-structure.md +1 -1
  2. package/ai-docs/instructions/service-code-format/11-output-model.md +1 -2
  3. package/dist/cli.js +1 -2
  4. package/dist/cli.js.map +2 -2
  5. package/dist/index.js +0 -1
  6. package/dist/index.js.map +2 -2
  7. package/dist/types/flow-extension-runner/src/v2/model/model-types.d.ts +0 -1
  8. package/dist/types/flow-extension-runner/src/v2/types.d.ts +1 -1
  9. package/dist/types/shared/src/scheme/flowrunner/custom-elements.d.ts +0 -4
  10. package/dist/types/shared/src/scheme/shared-extensions/base.d.ts +0 -1
  11. package/dist/types/shared/src/scheme/shared-extensions/custom-extensions.d.ts +0 -5
  12. package/dist/types/shared/src/scheme/shared-extensions/extension.d.ts +0 -4
  13. package/dist/types/shared/src/scheme/shared-extensions/resolve.d.ts +0 -3
  14. package/dist/types/shared/src/scheme/shared-extensions/search.d.ts +0 -2
  15. package/dist/types/shared/src/scheme/shared-extensions/service-info.d.ts +0 -1
  16. package/package.json +1 -1
  17. package/runtime/index.js +0 -1
  18. package/runtime/index.js.map +2 -2
  19. package/runtime/types/flow-extension-runner/src/v2/model/model-types.d.ts +0 -1
  20. package/runtime/types/flow-extension-runner/src/v2/types.d.ts +1 -1
  21. package/runtime/types/shared/src/scheme/flowrunner/custom-elements.d.ts +0 -4
  22. package/runtime/types/shared/src/scheme/shared-extensions/base.d.ts +0 -1
  23. package/runtime/types/shared/src/scheme/shared-extensions/custom-extensions.d.ts +0 -5
  24. package/runtime/types/shared/src/scheme/shared-extensions/extension.d.ts +0 -4
  25. package/runtime/types/shared/src/scheme/shared-extensions/resolve.d.ts +0 -3
  26. package/runtime/types/shared/src/scheme/shared-extensions/search.d.ts +0 -2
  27. package/runtime/types/shared/src/scheme/shared-extensions/service-info.d.ts +0 -1
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../node_modules/backendless-request/lib/utils.js", "../../../node_modules/backendless-request/lib/error.js", "../../../node_modules/backendless-request/lib/client-node.js", "../../../node_modules/backendless-request/lib/event-emitter.js", "../../../node_modules/backendless-request/lib/qs.js", "../../../node_modules/backendless-request/lib/request.js", "../../../node_modules/backendless-request/lib/client-browser.js", "../../../node_modules/backendless-request/lib/index.js", "../node_modules/adm-zip/util/constants.js", "../node_modules/adm-zip/util/errors.js", "../node_modules/adm-zip/util/utils.js", "../node_modules/adm-zip/util/fattr.js", "../node_modules/adm-zip/util/decoder.js", "../node_modules/adm-zip/util/index.js", "../node_modules/adm-zip/headers/entryHeader.js", "../node_modules/adm-zip/headers/mainHeader.js", "../node_modules/adm-zip/headers/index.js", "../node_modules/adm-zip/methods/deflater.js", "../node_modules/adm-zip/methods/inflater.js", "../node_modules/adm-zip/methods/zipcrypto.js", "../node_modules/adm-zip/methods/index.js", "../node_modules/adm-zip/zipEntry.js", "../node_modules/adm-zip/zipFile.js", "../node_modules/adm-zip/adm-zip.js", "../src/index.ts", "../src/constants/packaging.ts", "../src/constants/project.ts", "../src/constants/providers.ts", "../src/constants/server.ts", "../src/constants/testing.ts", "../src/errors.ts", "../src/operations/deploy/index.ts", "../src/api/console-client.ts", "../src/project/config.ts", "../src/project/token.ts", "../src/project/auth.ts", "../src/operations/types.ts", "../src/operations/deploy/discover-services.ts", "../../../flow-extension-runner/src/namespace.ts", "../../../flow-extension-runner/src/errors/base.ts", "../../../flow-extension-runner/src/errors/codes.ts", "../../../flow-extension-runner/src/errors/errors.ts", "../../../flow-extension-runner/src/v2/loaders/loader-owner.ts", "../../../flow-extension-runner/src/v2/params/schema/assert-object-schema.ts", "../../../flow-extension-runner/src/v2/params/widget-types.ts", "../../../flow-extension-runner/src/v2/params/schema/introspect.ts", "../../../flow-extension-runner/src/v2/params/schema/assert-supported-schema.ts", "../../../flow-extension-runner/src/v2/params/schema/dates.ts", "../../../flow-extension-runner/src/v2/params/schema/labels.ts", "../../../flow-extension-runner/src/v2/params/schema/field-plan.ts", "../../../flow-extension-runner/src/v2/params/schema/coerce.ts", "../../../flow-extension-runner/src/v2/params/schema/defaults.ts", "../../../flow-extension-runner/src/v2/params/schema/messages.ts", "../../../flow-extension-runner/src/v2/params/schema/normalize.ts", "../../../flow-extension-runner/src/v2/params/schema/parse.ts", "../../../flow-extension-runner/src/v2/params/params.ts", "../../../flow-extension-runner/src/v2/params/config-params.ts", "../../../flow-extension-runner/src/v2/params/method-params.ts", "../../../flow-extension-runner/src/v2/params/zod.ts", "../../../flow-extension-runner/src/v2/params/files-options.ts", "../../../flow-extension-runner/src/v2/params/json/values.ts", "../../../flow-extension-runner/src/v2/params/json/checks.ts", "../../../flow-extension-runner/src/v2/params/json/types.ts", "../../../flow-extension-runner/src/v2/params/json/decode.ts", "../../../flow-extension-runner/src/v2/params/json/encode.ts", "../../../flow-extension-runner/src/v2/context/method-input.ts", "../../../flow-extension-runner/src/v2/method.ts", "../../../flow-extension-runner/src/common/constants.ts", "../../../flow-extension-runner/src/v2/model/field-mapper.ts", "../../../flow-extension-runner/src/v2/model/method-model.ts", "../../../flow-extension-runner/src/v2/model/params-model.ts", "../../../flow-extension-runner/src/v2/result.ts", "../../../flow-extension-runner/src/v2/actions/action-method.ts", "../../../flow-extension-runner/src/common/context-files.ts", "../../../flow-extension-runner/src/v2/context/logger.ts", "../../../flow-extension-runner/src/v2/context/proxies.ts", "../../../flow-extension-runner/src/v2/context/execution-context.ts", "../../../flow-extension-runner/src/v2/dictionaries/payload-schema.ts", "../../../flow-extension-runner/src/v2/dictionaries/dictionary-method.ts", "../../../flow-extension-runner/src/v2/loaders/payload-schema.ts", "../../../flow-extension-runner/src/v2/loaders/loader-method.ts", "../../../flow-extension-runner/src/v2/oauth/oauth2.ts", "../../../flow-extension-runner/src/v2/oauth/method-names.ts", "../../../flow-extension-runner/src/v2/oauth/system-params.ts", "../../../flow-extension-runner/src/v2/polling-triggers/method-names.ts", "../../../flow-extension-runner/src/v2/polling-triggers/system-params.ts", "../../../flow-extension-runner/src/v2/polling-triggers/polling-triggers.ts", "../../../flow-extension-runner/src/v2/path.ts", "../../../flow-extension-runner/src/v2/polling-triggers/mechanisms.ts", "../../../flow-extension-runner/src/v2/polling-triggers/trigger-method.ts", "../../../flow-extension-runner/src/v2/realtime-triggers/method-names.ts", "../../../flow-extension-runner/src/v2/realtime-triggers/system-params.ts", "../../../flow-extension-runner/src/v2/realtime-triggers/verify.ts", "../../../flow-extension-runner/src/v2/realtime-triggers/realtime-setup.ts", "../../../flow-extension-runner/src/v2/realtime-triggers/trigger-method.ts", "../../../flow-extension-runner/src/v2/system-method.ts", "../../../flow-extension-runner/src/v2/extension.ts", "../../../flow-extension-runner/src/v2/registry.ts", "../../../flow-extension-runner/src/v2/create-extension.ts", "../../../flow-extension-runner/src/v2/crypto.ts", "../../../flow-extension-runner/src/common/config.ts", "../../../flow-extension-runner/src/v1/config.ts", "../../../flow-extension-runner/src/v1/namespace.ts", "../../../flow-extension-runner/src/v1/service.ts", "../../../flow-extension-runner/src/v2/index.ts", "../../../flow-extension-runner/src/index.ts", "../../../jsdoc-parser/src/custom-type-defs/files.ts", "../../../jsdoc-parser/src/lib.ts", "../../../jsdoc-parser/src/index.ts", "../src/operations/deploy/hash.ts", "../src/operations/deploy/public-files.ts", "../src/operations/deploy/select.ts", "../src/operations/deploy/zip.ts", "../src/operations/init/index.ts", "../src/templates/package-root.ts", "../src/utils/invocation.ts", "../src/operations/server-target.ts", "../src/operations/init/create-service.ts", "../src/templates/registry.ts", "../src/templates/manifest.ts", "../src/templates/paths.ts", "../src/templates/scaffold.ts", "../src/templates/render.ts", "../src/operations/init/answers.ts", "../src/operations/init/testing.ts", "../src/operations/init-claude/index.ts", "../src/operations/init-claude/segment.ts", "../src/server/index.ts", "../src/server/pages.ts", "../src/server/routes/callback.ts", "../src/utils/open-browser.ts", "../src/operations/login.ts", "../src/operations/logout.ts", "../src/operations/pull/index.ts", "../src/operations/pull/extract.ts", "../src/operations/use-server.ts"],
4
- "sourcesContent": ["\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.blobToFormPart = blobToFormPart;\nexports.castArray = void 0;\nexports.decodeBytes = decodeBytes;\nexports.ensureEncoding = ensureEncoding;\nexports.getFormData = getFormData;\nexports.isWebFormData = exports.isStream = exports.isObject = exports.isNodeJS = exports.isFormData = exports.isBytes = exports.isBrowser = exports.isBlob = void 0;\nexports.normalizeFormPart = normalizeFormPart;\nexports.normalizeTrailingSlashInPath = normalizeTrailingSlashInPath;\nexports.setFormData = setFormData;\nexports.toBytes = toBytes;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\n/**\n * Casts `value` as an array if it's not one.\n * Equivalent to lodash/castArray\n */\nvar castArray = exports.castArray = function castArray(value) {\n return Array.isArray(value) ? value : [value];\n};\nvar isObject = exports.isObject = function isObject(value) {\n return null != value && _typeof(value) === 'object';\n};\nvar isFormData = exports.isFormData = function isFormData(value) {\n if (!value) {\n return false;\n }\n var FormData = getFormData();\n if (value instanceof FormData) {\n return true;\n }\n return value && value.constructor && value.constructor.toString().trim().indexOf('function FormData') === 0;\n};\nvar isStream = exports.isStream = function isStream(value) {\n var stream = require('stream');\n return value instanceof stream.Stream;\n};\nvar isNodeJS = exports.isNodeJS = function isNodeJS() {\n return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n};\nvar isBrowser = exports.isBrowser = function isBrowser() {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n};\nvar CustomFormData = null;\nfunction getFormData() {\n if (CustomFormData) {\n return CustomFormData;\n }\n return isNodeJS() || typeof FormData === 'undefined' ? require('form-data') : FormData;\n}\nfunction setFormData(value) {\n CustomFormData = value;\n}\n\n// @ : / # ? = $ & +\nvar SAFE_CHAR_CODES = ['%40', '%3A', '%2F', '%23', '%3F', '%3D', '%24', '%26', '%2B'];\nfunction safeEscape(str, charCodes) {\n var _char = charCodes[0];\n if (_char) {\n var tokens = str.split(_char).map(function (p) {\n return safeEscape(p, charCodes.slice(1));\n });\n return tokens.join(_char);\n }\n return encodeURI(str);\n}\nfunction ensureComponentEncoding(uriComponent) {\n if (uriComponent === decodeURI(uriComponent)) {\n return safeEscape(uriComponent, [].concat(SAFE_CHAR_CODES));\n }\n return uriComponent;\n}\nfunction encodePath(path) {\n return path.split('/').map(ensureComponentEncoding).join('/');\n}\nfunction ensureEncoding(path) {\n try {\n var url = new URL(path);\n return url.origin + encodePath(normalizeTrailingSlashInPath(path, url)) + url.search;\n } catch (_unused) {\n return encodePath(path);\n }\n}\nfunction normalizeTrailingSlashInPath(originPath, _ref) {\n var pathname = _ref.pathname;\n if (originPath.includes('?')) {\n originPath = originPath.split('?')[0];\n }\n var keepTrailingSlash = originPath.endsWith('/');\n return !keepTrailingSlash && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;\n}\nvar isBytes = exports.isBytes = function isBytes(value) {\n return typeof Uint8Array !== 'undefined' && value instanceof Uint8Array;\n};\n\n/**\n * Normalizes a raw response body to bytes.\n *\n * A Buffer is a Uint8Array, so the check a caller needs is `instanceof Uint8Array` in both\n * environments, and the value we already have is handed back as is - no copy, these are file\n * payloads and a single one is routinely tens of MB.\n *\n * Everything else can only come from an empty response or from a replaced `Request.send`,\n * both of them cheap to convert. Anything that is not convertible is a broken contract and\n * throws rather than silently uploading wrong bytes.\n *\n * @param {*} value\n * @returns {Buffer|Uint8Array}\n */\nfunction toBytes(value) {\n if (isBytes(value)) {\n return value;\n }\n var hasBuffer = typeof Buffer !== 'undefined' && typeof Buffer.from === 'function';\n if (value === undefined || value === null || value === '') {\n return hasBuffer ? Buffer.alloc(0) : new Uint8Array(0);\n }\n if (typeof value === 'string') {\n return hasBuffer ? Buffer.from(value, 'utf8') : new TextEncoder().encode(value);\n }\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return hasBuffer ? Buffer.from(value) : new Uint8Array(value);\n }\n throw new Error('The response body can not be represented as bytes, ' + \"received \".concat(value === null ? 'null' : _typeof(value), \". \") + 'This happens when \"Request.send\" is replaced with an implementation ' + 'that does not return the raw body for a request made with \"toBuffer()\".');\n}\n\n/**\n * Decodes bytes to utf8 text, anything which is not bytes is passed through.\n *\n * Used for the error body of a raw request: a browser gets it as a Uint8Array, because\n * `responseType` is set for the whole response, and `String()` on a Uint8Array joins the byte\n * values with commas instead of decoding them\n *\n * @param {*} value\n * @returns {*}\n */\nfunction decodeBytes(value) {\n if (!isBytes(value)) {\n return value;\n }\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return value.toString('utf8');\n }\n if (typeof TextDecoder !== 'undefined') {\n return new TextDecoder('utf8').decode(value);\n }\n return value;\n}\n\n/**\n * A Blob or a File, duck typed so that an instance coming from another realm is recognized too\n */\nvar isBlob = exports.isBlob = function isBlob(value) {\n return !!value && _typeof(value) === 'object' && typeof value.stream === 'function' && typeof value.arrayBuffer === 'function' && typeof value.size === 'number';\n};\n\n/**\n * The FormData of the WHATWG spec - the Node 18+ global one, or the browser one.\n *\n * The `form-data` npm package, which is what `Request.FormData` is in Node js, is a different\n * class with a different API and it is recognized by `isFormData`\n */\nvar isWebFormData = exports.isWebFormData = function isWebFormData(value) {\n return !!value && typeof value.append === 'function' && typeof value.getAll === 'function' && typeof value.forEach === 'function' && typeof value.getHeaders !== 'function';\n};\n\n/**\n * Turns a Blob or a File into something the `form-data` package can stream.\n *\n * The package accepts a Buffer or a stream and treats any other object as stream like, which\n * makes it throw \"source.on is not a function\" from inside `combined-stream` at append time.\n * A web stream is not that either, `Readable.fromWeb` bridges the two.\n *\n * `knownLength` is what keeps `form.getLength()` synchronous and the content-length header\n * correct, and the filename follows what a browser sends for a nameless Blob\n *\n * @param {Blob|File} blob\n * @returns {{ value: Object, options: Object }}\n */\nfunction blobToFormPart(blob) {\n var _require = require('stream'),\n Readable = _require.Readable;\n if (typeof Readable.fromWeb !== 'function') {\n throw new Error('A Blob can only be added to a form on Node 18 or newer, ' + 'pass a Buffer or a stream instead.');\n }\n var options = {\n knownLength: blob.size,\n filename: blob.name || 'blob'\n };\n if (blob.type) {\n options.contentType = blob.type;\n }\n return {\n value: Readable.fromWeb(blob.stream()),\n options: options\n };\n}\n\n/**\n * Prepares a value for `FormData#append` of the `form-data` package.\n *\n * Everything the package can not stream is either converted here or reported with an error which\n * names the field, instead of the \"source.on is not a function\"/\"Illegal invocation\" thrown from\n * deep inside `combined-stream` with nothing pointing at the value which caused it\n *\n * @param {String} key\n * @param {*} value\n * @returns {{ value: *, options: Object|undefined }}\n */\nfunction normalizeFormPart(key, value) {\n if (isBlob(value)) {\n return blobToFormPart(value);\n }\n if (isBytes(value) && typeof Buffer !== 'undefined' && !Buffer.isBuffer(value)) {\n // a Uint8Array is not a Buffer and the package treats it as a stream, the view is\n // wrapped without copying the bytes\n return {\n value: Buffer.from(value.buffer, value.byteOffset, value.byteLength)\n };\n }\n if (isObject(value) && !isStream(value) && !(typeof Buffer !== 'undefined' && Buffer.isBuffer(value))) {\n throw new Error(\"The form field \\\"\".concat(key, \"\\\" can not be sent, \") + \"expected a Buffer, a stream, a Blob or a primitive value, received \".concat(describeValue(value), \".\"));\n }\n return {\n value: value\n };\n}\nfunction describeValue(value) {\n if (Array.isArray(value)) {\n return 'an Array';\n }\n var name = value.constructor && value.constructor.name;\n return name ? \"an instance of \".concat(name) : 'an object';\n}", "\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.TLSError = exports.ResponseError = void 0;\nexports.toTLSError = toTLSError;\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\nfunction _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nvar ResponseError = exports.ResponseError = /*#__PURE__*/function (_Error) {\n _inherits(ResponseError, _Error);\n var _super = _createSuper(ResponseError);\n function ResponseError(response) {\n var _this;\n _classCallCheck(this, ResponseError);\n _this = _super.call(this);\n var error = parseError(response);\n _this.message = error.message || error;\n _this.code = error.code;\n _this.status = response.status;\n _this.headers = response.headers;\n _this.body = response.body;\n return _this;\n }\n return _createClass(ResponseError);\n}( /*#__PURE__*/_wrapNativeSuper(Error));\nfunction parseError(res) {\n if (res.status === 502) {\n return 'No connection with server';\n }\n return res.body || \"Status Code \".concat(res.status, \" (\").concat(res.statusText, \")\");\n}\n\n/**\n * An error which is raised when a TLS connection can not be established.\n *\n * A raw TLS failure surfaces as an opaque socket error (ECONNRESET, EPROTO, an OpenSSL code),\n * which makes the most common operational failures - a missing, rejected or expired client\n * certificate - indistinguishable from a network problem.\n *\n * Never put any part of the certificate, the private key or the passphrase into the message,\n * the reasons below are the only text this error is built from.\n */\nvar TLSError = exports.TLSError = /*#__PURE__*/function (_Error2) {\n _inherits(TLSError, _Error2);\n var _super2 = _createSuper(TLSError);\n function TLSError(reason, cause) {\n var _this2;\n _classCallCheck(this, TLSError);\n _this2 = _super2.call(this, cause && cause.code ? \"\".concat(reason, \" (\").concat(cause.code, \")\") : reason);\n _this2.name = 'TLSError';\n _this2.code = cause && cause.code || 'TLS_ERROR';\n if (cause) {\n _this2.cause = cause;\n }\n return _this2;\n }\n return _createClass(TLSError);\n}( /*#__PURE__*/_wrapNativeSuper(Error)); // the local certificate/key material can not even be loaded, the connection is never attempted\nvar SECURE_CONTEXT_REASONS = [{\n match: /bad decrypt|bad password read|wrong final block length/i,\n reason: 'The private key could not be decrypted, the passphrase is missing or incorrect.'\n}, {\n match: /no start line|not enough data|PEM_read_bio|DECODER routines/i,\n reason: 'The client certificate or the private key is not valid PEM.'\n}, {\n match: /key values mismatch/i,\n reason: 'The private key does not match the client certificate.'\n}];\n\n// the server refused our client certificate during the handshake\nvar HANDSHAKE_ALERT_REASONS = [{\n // the server demands a client certificate before it looks at anything else, including auth\n match: /certificate[ _]required/i,\n reason: 'The server requires a client certificate and none was supplied.'\n}, {\n match: /certificate expired/i,\n reason: 'The server rejected the client certificate because it has expired.'\n}, {\n match: /certificate revoked/i,\n reason: 'The server rejected the client certificate because it has been revoked.'\n}, {\n match: /unknown ca/i,\n reason: 'The server does not trust the authority which issued the client certificate.'\n}, {\n match: /(bad|unsupported|unknown|no) certificate/i,\n reason: 'The server rejected the client certificate.'\n}, {\n match: /handshake failure/i,\n reason: 'The server rejected the TLS handshake, the client certificate is missing or was rejected.'\n}];\n\n// the certificate presented by the server could not be verified\nvar NO_CA_REASON = 'The server certificate could not be verified, a CA bundle may be required.';\nvar PEER_CERTIFICATE_REASONS = {\n CERT_HAS_EXPIRED: 'The server certificate has expired.',\n CERT_NOT_YET_VALID: 'The server certificate is not valid yet.',\n SELF_SIGNED_CERT_IN_CHAIN: 'The server certificate chain is self signed, a CA bundle may be required.',\n DEPTH_ZERO_SELF_SIGNED_CERT: 'The server certificate is self signed, a CA bundle may be required.',\n ERR_TLS_CERT_ALTNAME_INVALID: 'The server certificate does not match the requested host.',\n UNABLE_TO_VERIFY_LEAF_SIGNATURE: NO_CA_REASON,\n UNABLE_TO_GET_ISSUER_CERT_LOCALLY: NO_CA_REASON\n};\nfunction findReason(reasons, text) {\n var found = reasons.find(function (_ref) {\n var match = _ref.match;\n return match.test(text);\n });\n return found && found.reason;\n}\nfunction findPeerCertificateReason(code) {\n return code && PEER_CERTIFICATE_REASONS.hasOwnProperty(code) ? PEER_CERTIFICATE_REASONS[code] : undefined;\n}\n\n/**\n * Converts a low level socket/OpenSSL failure into a TLSError with an actionable message.\n *\n * @param {Error} error the error raised by the http client\n * @param {Boolean} withClientCert whether a client certificate was supplied for this request\n * @returns {TLSError|null} null when the error is not TLS related and should be reported as is\n */\nfunction toTLSError(error, withClientCert) {\n if (!error) {\n return null;\n }\n var text = \"\".concat(error.code || '', \" \").concat(error.message || '');\n var reason = findPeerCertificateReason(error.code) || findReason(SECURE_CONTEXT_REASONS, text) || findReason(HANDSHAKE_ALERT_REASONS, text);\n if (reason) {\n return new TLSError(reason, error);\n }\n\n // a server which demands a client certificate usually just drops the connection when it does not\n // get one it accepts, there is no alert to read, so this is the best guess we can offer\n if (withClientCert && (error.code === 'ECONNRESET' || error.code === 'EPROTO')) {\n return new TLSError('The connection was closed during the TLS handshake, ' + 'the client certificate was most likely missing, rejected or expired.', error);\n }\n return null;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.sendNodeAPIRequest = sendNodeAPIRequest;\nvar _utils = require(\"./utils\");\nvar _error = require(\"./error\");\nfunction sendNodeAPIRequest(path, method, headers, body, encoding, timeout, withCredentials, tlsOptions) {\n return new Promise(function (resolve, reject) {\n var u = require('url').parse(path);\n var form = (0, _utils.isFormData)(body) && body;\n var https = u.protocol === 'https:';\n var options = {\n host: u.hostname,\n port: u.port || (https ? 443 : 80),\n path: (0, _utils.normalizeTrailingSlashInPath)(path, u) + (u.search || ''),\n method: method,\n headers: headers,\n timeout: timeout\n };\n if (typeof withCredentials === 'boolean') {\n options.withCredentials = withCredentials;\n }\n var withClientCert = !!(tlsOptions && (tlsOptions.cert || tlsOptions.key));\n if (tlsOptions) {\n if (!https) {\n // going ahead would silently drop the certificate and send the request in plain text,\n // there is no mutual TLS without TLS\n return reject(new _error.TLSError('A client certificate can only be used with an https:// URL.'));\n }\n Object.assign(options, tlsOptions);\n }\n\n // a TLS failure arrives here as an opaque socket/OpenSSL error, translate the ones we recognize\n var rejectWithError = function rejectWithError(error) {\n return reject((0, _error.toTLSError)(error, withClientCert) || error);\n };\n var _send = function _send() {\n var Buffer = require('buffer').Buffer;\n var httpClient = require(https ? 'https' : 'http');\n var req = httpClient.request(options, function (res) {\n var strings = [];\n var buffers = [];\n var bufferLength = 0;\n var body = '';\n var status = res.statusCode,\n statusText = res.statusMessage,\n headers = res.headers;\n res.on('data', function (chunk) {\n if (!Buffer.isBuffer(chunk)) {\n strings.push(chunk);\n } else if (chunk.length) {\n bufferLength += chunk.length;\n buffers.push(chunk);\n }\n });\n res.on('end', function () {\n if (bufferLength) {\n body = Buffer.concat(buffers, bufferLength);\n if (encoding != null) {\n body = body.toString(encoding);\n }\n } else if (strings.length) {\n body = strings.join();\n } else if (encoding == null) {\n // a raw request asked for bytes, and a 0 byte response is an empty buffer,\n // not the empty string the body is initialized with\n body = Buffer.alloc(0);\n }\n resolve({\n status: status,\n statusText: statusText,\n headers: headers,\n body: body\n });\n });\n res.on('error', rejectWithError);\n });\n req.on('error', rejectWithError);\n req.on('timeout', function () {\n req.destroy(new Error('Connection aborted due to timeout'));\n });\n if (body) {\n if ((0, _utils.isStream)(body)) {\n body.pipe(req);\n return;\n }\n req.write(body);\n }\n req.end();\n };\n\n // an unusable certificate/key/passphrase makes https.request() throw synchronously, and for a\n // form body _send() runs from a callback where a throw would escape the promise altogether\n var send = function send() {\n try {\n _send();\n } catch (error) {\n rejectWithError(error);\n }\n };\n if (form) {\n Object.assign(options.headers, form.getHeaders());\n form.getLength(function (err, length) {\n if (!err && !isNaN(length)) {\n options.headers['content-length'] = length;\n }\n send();\n });\n } else {\n if (body && !options.headers['content-length']) {\n var Buffer = require('buffer').Buffer;\n options.headers['content-length'] = Buffer.byteLength(body);\n }\n send();\n }\n });\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar EventEmitter = exports[\"default\"] = /*#__PURE__*/function () {\n function EventEmitter() {\n _classCallCheck(this, EventEmitter);\n this.events = {};\n }\n _createClass(EventEmitter, [{\n key: \"on\",\n value: function on(eventName, callback) {\n this.events[eventName] = this.events[eventName] || [];\n this.events[eventName].push(callback);\n return this;\n }\n }, {\n key: \"off\",\n value: function off(eventName, callback) {\n if (!eventName) {\n this.events = {};\n } else if (this.events[eventName]) {\n if (callback) {\n this.events[eventName] = this.events[eventName].filter(function (c) {\n return c !== callback;\n });\n } else {\n delete this.events[eventName];\n }\n }\n return this;\n }\n }, {\n key: \"emit\",\n value: function emit(eventName) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n if (this.events[eventName]) {\n this.events[eventName].forEach(function (callback) {\n return callback.apply(void 0, args);\n });\n }\n }\n }]);\n return EventEmitter;\n}();", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.stringify = void 0;\nvar _utils = require(\"./utils\");\n/**\n * Produces a URL query string from a given obj by iterating through the object's \"own properties\".\n * @param {Object} obj\n * @returns {string}\n */\nvar stringify = exports.stringify = function stringify(obj) {\n var tokens = [];\n Object.keys(obj).forEach(function (key) {\n var value = obj[key];\n if (value !== undefined) {\n (0, _utils.castArray)(value).forEach(function (value) {\n tokens.push(\"\".concat(encodeURIComponent(key), \"=\").concat(encodeURIComponent(value)));\n });\n }\n });\n return tokens.join('&');\n};", "\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.Request = void 0;\nvar _eventEmitter = _interopRequireDefault(require(\"./event-emitter\"));\nvar qs = _interopRequireWildcard(require(\"./qs\"));\nvar _utils = require(\"./utils\");\nvar _error = require(\"./error\");\nfunction _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== \"function\") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }\nfunction _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") { return { \"default\": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj[\"default\"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nvar CONTENT_TYPE_HEADER = 'Content-Type';\n\n// the only TLS options a caller may pass, everything else (rejectUnauthorized and friends) is\n// dropped on purpose so that a config blob can not weaken the connection by accident\nvar TLS_OPTION_KEYS = ['cert', 'key', 'passphrase', 'ca'];\nvar REQUEST_EVENT = 'request';\nvar RESPONSE_EVENT = 'response';\nvar ERROR_EVENT = 'error';\nvar DONE_EVENT = 'done';\nvar Request = exports.Request = /*#__PURE__*/function (_EventEmitter) {\n _inherits(Request, _EventEmitter);\n var _super = _createSuper(Request);\n function Request(path, method, body) {\n var _this;\n _classCallCheck(this, Request);\n _this = _super.call(this);\n _this.method = method;\n _this.path = (0, _utils.ensureEncoding)(path);\n _this.body = body;\n _this.unwrap = true;\n _this.raw = false;\n _this.headers = {};\n _this.queryParams = {};\n _this.encoding = 'utf8';\n _this.timeout = 0;\n _this.withCredentials = null;\n\n // the private key is credential material, a non enumerable property keeps it out of\n // console.log(request)/JSON.stringify(request) in whatever logging a caller has around\n Object.defineProperty(_assertThisInitialized(_this), 'tlsOptions', {\n value: undefined,\n writable: true,\n enumerable: false,\n configurable: true\n });\n return _this;\n }\n\n /**\n * Sets a header\n *\n * @param {String|Object} key or map of headers\n * @param {String} [value]\n * @returns {Request}\n */\n _createClass(Request, [{\n key: \"set\",\n value: function set(key, value) {\n if ((0, _utils.isObject)(key)) {\n for (var headerName in key) {\n this.set(headerName, key[headerName]);\n }\n } else if (typeof value !== 'undefined') {\n this.headers[key] = value;\n }\n return this;\n }\n\n /**\n * Shortcut for req.set('Authorization', `Basic ${basicAuth.token}`)\n *\n * @param {Object} [basicAuth]\n * @param {String} basicAuth.token\n * @returns {Request}\n */\n }, {\n key: \"basicAuth\",\n value: function basicAuth(_basicAuth) {\n if (_basicAuth) {\n this.set({\n Authorization: \"Basic \".concat(_basicAuth.token)\n });\n }\n return this;\n }\n\n /**\n * Shortcut for req.set('auth-key', authKey)\n *\n * @param {String} [authKey]\n * @returns {Request}\n */\n }, {\n key: \"authKey\",\n value: function authKey(_authKey) {\n if (_authKey) {\n this.set({\n 'auth-key': _authKey\n });\n }\n return this;\n }\n\n /**\n * Attaches a TLS client certificate and private key to the request (mutual TLS).\n *\n * Works only for Node js, in a browser the client certificate is chosen by the browser itself.\n *\n * Calling the method several times merges the options, so the certificate and the key may come\n * from different places. Options other than the ones listed below are ignored.\n *\n * @param {Object} [tlsOptions]\n * @param {String|Buffer|Array} tlsOptions.cert PEM encoded client certificate (or chain)\n * @param {String|Buffer|Array} tlsOptions.key PEM encoded private key\n * @param {String} [tlsOptions.passphrase] passphrase of an encrypted private key\n * @param {String|Buffer|Array} [tlsOptions.ca] PEM encoded CA bundle to verify the server with\n * @returns {Request}\n */\n }, {\n key: \"cert\",\n value: function cert(tlsOptions) {\n var options = tlsOptions && pickTLSOptions(tlsOptions);\n if (options && Object.keys(options).length) {\n this.tlsOptions = _objectSpread(_objectSpread({}, this.tlsOptions), options);\n }\n return this;\n }\n\n /**\n * @param {Object} queryParams\n * @returns {Request}\n */\n }, {\n key: \"query\",\n value: function query(queryParams) {\n Object.assign(this.queryParams, queryParams);\n return this;\n }\n\n /**\n * Sets a multipart form as the request body.\n *\n * Accepts an instance of `Request.FormData`, a WHATWG `FormData` (the Node 18+ global one) and\n * a plain object. A Blob or a File, which the `form-data` package can not stream on its own,\n * is converted, and a value it can not send at all is reported with an error naming the field.\n *\n * @param {Object} form\n * @returns {Request}\n */\n }, {\n key: \"form\",\n value: function form(_form) {\n if (_form) {\n if ((0, _utils.isFormData)(_form)) {\n this.body = _form;\n } else if ((0, _utils.isWebFormData)(_form)) {\n this.body = toRequestFormData(_form);\n } else {\n var formData = new Request.FormData();\n var _loop = function _loop(formKey) {\n if (formKey) {\n (0, _utils.castArray)(_form[formKey]).forEach(function (formValue) {\n if (formValue && formValue.hasOwnProperty('value') && formValue.hasOwnProperty('options')) {\n appendFormPart(formData, formKey, formValue.value, formValue.options);\n } else {\n appendFormPart(formData, formKey, formValue);\n }\n });\n }\n };\n for (var formKey in _form) {\n _loop(formKey);\n }\n this.body = formData;\n }\n }\n return this;\n }\n\n /**\n * Shortcut for req.set('Content-Type', value)\n *\n * @param {String} contentType\n * @returns {Request}\n */\n }, {\n key: \"type\",\n value: function type(contentType) {\n this.set(CONTENT_TYPE_HEADER, contentType);\n return this;\n }\n\n /**\n * Should we unwrap the response and return only body. true by default\n * @param {Boolean} unwrap\n * @returns {Request}\n */\n }, {\n key: \"unwrapBody\",\n value: function unwrapBody(unwrap) {\n this.unwrap = unwrap;\n return this;\n }\n\n /**\n * set encoding to response\n * works only for Node js\n *\n * @param {String} encoding\n * @returns {Request}\n */\n }, {\n key: \"setEncoding\",\n value: function setEncoding(encoding) {\n this.encoding = encoding;\n return this;\n }\n\n /**\n * Sends the request and resolves the response body as raw bytes.\n *\n * Unlike `setEncoding(null)` the result is guaranteed: a `Buffer` in Node js, a `Uint8Array`\n * in a browser (a Buffer is a Uint8Array, so `instanceof Uint8Array` holds in both), an empty\n * one for a 0 byte response, and never a value that `JSON.parse` got to first.\n *\n * The method is terminal, it implies a raw transfer and overrides whatever `setEncoding` was\n * given before it, so there is no need to call `setEncoding(null)` as well.\n *\n * An unsuccessful response is rejected the same way as for any other request, with the error\n * body still JSON parsed when it is JSON - a vendor answers a failed binary download with a\n * JSON error and `error.body.message` has to keep working.\n *\n * @returns {Promise<Buffer|Uint8Array>}\n */\n }, {\n key: \"toBuffer\",\n value: function toBuffer() {\n this.raw = true;\n this.encoding = null;\n this.promise = this.promise || this.send(this.body);\n return this.promise;\n }\n\n /**\n * set withCredentials option\n *\n * @param {Boolean} value\n * @returns {Request}\n */\n }, {\n key: \"setWithCredentials\",\n value: function setWithCredentials(value) {\n this.withCredentials = value;\n return this;\n }\n\n /**\n * A number specifying request timeout in milliseconds.\n * @param {Number} ms\n * @returns {Request}\n */\n }, {\n key: \"setTimeout\",\n value: function setTimeout(ms) {\n this.timeout = ms;\n return this;\n }\n\n /**\n * Sends the request\n *\n * @param {Object} body\n * @returns {Promise}\n */\n }, {\n key: \"send\",\n value: function send(body) {\n var _this2 = this;\n this.emit(REQUEST_EVENT, this);\n var path = this.path;\n var queryString = qs.stringify(this.queryParams);\n if (queryString) {\n path += '?' + queryString;\n }\n if (!(0, _utils.isFormData)(body) && (0, _utils.isWebFormData)(body)) {\n body = toRequestFormData(body);\n }\n var type = this.headers[CONTENT_TYPE_HEADER];\n if (!type && (0, _utils.isObject)(body) && !(0, _utils.isFormData)(body)) {\n this.type('application/json');\n }\n if (body) {\n var isJSON = this.headers[CONTENT_TYPE_HEADER] === 'application/json';\n body = isJSON && typeof body !== 'string' ? JSON.stringify(body) : body;\n }\n var unwrapBody = function unwrapBody(res) {\n return _this2.unwrap ? res.body : res;\n };\n if (Request.verbose) {\n console.log(this.method.toUpperCase(), decodeURIComponent(path), body, this.headers);\n }\n var withCredentials = typeof this.withCredentials === 'boolean' ? this.withCredentials : Request.withCredentials;\n var syncError = new Error();\n var request = Request.send(path, this.method.toUpperCase(), this.headers, body, this.encoding, this.timeout, withCredentials, this.tlsOptions).then(function (res) {\n return parseBody(res, _this2.raw);\n }).then(function (res) {\n return ensureRawBody(res, _this2.raw);\n }).then(checkStatus).then(unwrapBody)[\"catch\"](function (error) {\n error.stack = \"\".concat(error.stack).concat(syncError.stack);\n throw error;\n });\n request.then(function (result) {\n _this2.emit(RESPONSE_EVENT, result);\n _this2.emit(DONE_EVENT, null, result);\n })[\"catch\"](function (error) {\n _this2.emit(ERROR_EVENT, error);\n _this2.emit(DONE_EVENT, error);\n });\n return request;\n }\n\n /**\n * If you are too lazy to use method 'send', don't use it and stay cool :)\n *\n * @param {Function} successHandler\n * @param {Function} errorHandler\n * @returns {Promise}\n */\n }, {\n key: \"then\",\n value: function then(successHandler, errorHandler) {\n this.promise = this.promise || this.send(this.body);\n return this.promise.then(successHandler, errorHandler);\n }\n\n /**\n * @param {Function} errorHandler\n * @returns {Promise}\n */\n }, {\n key: \"catch\",\n value: function _catch(errorHandler) {\n this.promise = this.promise || this.send(this.body);\n return this.promise[\"catch\"](errorHandler);\n }\n }]);\n return Request;\n}(_eventEmitter[\"default\"]);\n/**\n * Keeps only the known TLS options and skips the empty ones,\n * `undefined` values would otherwise overwrite already collected options on a merge\n */\nfunction pickTLSOptions(tlsOptions) {\n var result = {};\n TLS_OPTION_KEYS.forEach(function (key) {\n if (tlsOptions[key] !== undefined && tlsOptions[key] !== null) {\n result[key] = tlsOptions[key];\n }\n });\n return result;\n}\n\n/**\n * Copies a WHATWG FormData into a `Request.FormData`.\n *\n * Iterating with `for (var key in webFormData)` , which is what a plain object gets, walks the\n * enumerable WebIDL operations of the prototype and appends `append`, `get`, `set`, `forEach` ...\n * as form parts, and streaming then calls one of them unbound\n */\nfunction toRequestFormData(webFormData) {\n var formData = new Request.FormData();\n webFormData.forEach(function (value, key) {\n return appendFormPart(formData, key, value);\n });\n return formData;\n}\nfunction appendFormPart(formData, key, value, options) {\n if (typeof formData.getHeaders !== 'function') {\n // a browser FormData, it takes a Blob, a File and a typed array natively\n return options ? formData.append(key, value, options) : formData.append(key, value);\n }\n var part = (0, _utils.normalizeFormPart)(key, value);\n var partOptions = _objectSpread(_objectSpread({}, part.options), options);\n if (Object.keys(partOptions).length) {\n formData.append(key, part.value, partOptions);\n } else {\n formData.append(key, part.value);\n }\n}\nfunction isSuccessStatus(status) {\n return status >= 200 && status < 300;\n}\n\n/**\n * `JSON.parse` coerces its argument with `String()`, so it destroys a body that was asked for as\n * raw bytes whenever those bytes happen to be valid JSON. A raw request skips it for a successful\n * response only, an error body keeps being parsed as it always was.\n */\nfunction parseBody(res, raw) {\n if (raw && isSuccessStatus(res.status)) {\n return res;\n }\n try {\n return _objectSpread(_objectSpread({}, res), {}, {\n body: JSON.parse(raw ? (0, _utils.decodeBytes)(res.body) : res.body)\n });\n } catch (e) {\n return res;\n }\n}\nfunction ensureRawBody(res, raw) {\n return raw && isSuccessStatus(res.status) ? _objectSpread(_objectSpread({}, res), {}, {\n body: (0, _utils.toBytes)(res.body)\n }) : res;\n}\n\n/**\n * Checks if a network request came back fine, and throws an error if not\n *\n * @param {object} response A response from a network request\n *\n * @return {object|undefined} Returns either the response, or throws an error\n */\nfunction checkStatus(response) {\n if (isSuccessStatus(response.status)) {\n return response;\n }\n throw new _error.ResponseError(response);\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.sendXmlHttpRequest = sendXmlHttpRequest;\nvar _request2 = require(\"./request\");\nfunction sendXmlHttpRequest(path, method, headers, body, encoding, timeout, withCredentials) {\n return new Promise(function sendRequest(resolve, reject) {\n var request = new _request2.Request.XMLHttpRequest();\n request.timeout = timeout;\n if (!encoding) {\n request.responseType = 'arraybuffer';\n }\n request.open(method.toUpperCase(), path, true);\n if (typeof withCredentials === 'boolean') {\n request.withCredentials = withCredentials;\n }\n request.onload = function handleLoadEvent() {\n var headers = parseHeaders(request.getAllResponseHeaders());\n var _request = request,\n status = _request.status,\n statusText = _request.statusText;\n var result = {\n status: status,\n statusText: statusText,\n headers: headers\n };\n if (encoding) {\n // `responseType` was left as the default one for any encoding, XMLHttpRequest has no way\n // to decode an arbitrary charset, so the body is the text the browser decoded for us.\n // Wrapping that string into a Uint8Array, as it used to be for a non utf8 encoding,\n // produced an empty array and lost the response entirely\n result.body = request.response || request.responseText;\n } else {\n // `responseType` is 'arraybuffer' here, a 0 byte response has to stay bytes as well\n result.body = request.response ? new Uint8Array(request.response) : new Uint8Array(0);\n }\n resolve(result);\n request = null;\n };\n request.onerror = function handleErrorEvent() {\n reject(new Error('Network Error'));\n request = null;\n };\n request.ontimeout = function handleTimeout() {\n reject(new Error('Connection aborted due to timeout'));\n request = null;\n };\n Object.keys(headers).forEach(function (key) {\n request.setRequestHeader(key, headers[key]);\n });\n request.send(body);\n });\n}\nfunction parseHeaders(headersString) {\n var parsed = {};\n if (!headersString) {\n return parsed;\n }\n headersString.split('\\n').forEach(function (line) {\n var i = line.indexOf(':');\n var key = line.substr(0, i).trim();\n var val = line.substr(i + 1).trim();\n if (key) {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n return parsed;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar _clientNode = require(\"./client-node\");\nvar _clientBrowser = require(\"./client-browser\");\nvar _request = require(\"./request\");\nvar _utils = require(\"./utils\");\nObject.defineProperty(_request.Request, 'FormData', {\n get: function get() {\n return (0, _utils.getFormData)();\n },\n set: function set(value) {\n (0, _utils.setFormData)(value);\n }\n});\n_request.Request.XMLHttpRequest = typeof XMLHttpRequest !== 'undefined' ? XMLHttpRequest : undefined;\n\n// `tlsOptions` is meaningful for the Node client only, XMLHttpRequest gives no control over the\n// client certificate - a browser picks it from the OS/browser keystore when a server asks for one\n_request.Request.send = function (path, method, headers, body, encoding, timeout, withCredentials, tlsOptions) {\n var sender = typeof _request.Request.XMLHttpRequest !== 'undefined' ? _clientBrowser.sendXmlHttpRequest : _clientNode.sendNodeAPIRequest;\n return sender(path, method, headers, body, encoding, timeout, withCredentials, tlsOptions);\n};\n_request.Request.verbose = false;\n_request.Request.withCredentials = false;\n_request.Request.methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];\n_request.Request.methods.forEach(function (method) {\n _request.Request[method] = function (path, body) {\n return new _request.Request(path, method, body);\n };\n});\nexports = module.exports = _request.Request;\nvar _default = exports[\"default\"] = _request.Request;", "module.exports = {\n /* The local file header */\n LOCHDR : 30, // LOC header size\n LOCSIG : 0x04034b50, // \"PK\\003\\004\"\n LOCVER : 4,\t// version needed to extract\n LOCFLG : 6, // general purpose bit flag\n LOCHOW : 8, // compression method\n LOCTIM : 10, // modification time (2 bytes time, 2 bytes date)\n LOCCRC : 14, // uncompressed file crc-32 value\n LOCSIZ : 18, // compressed size\n LOCLEN : 22, // uncompressed size\n LOCNAM : 26, // filename length\n LOCEXT : 28, // extra field length\n\n /* The Data descriptor */\n EXTSIG : 0x08074b50, // \"PK\\007\\008\"\n EXTHDR : 16, // EXT header size\n EXTCRC : 4, // uncompressed file crc-32 value\n EXTSIZ : 8, // compressed size\n EXTLEN : 12, // uncompressed size\n\n /* The central directory file header */\n CENHDR : 46, // CEN header size\n CENSIG : 0x02014b50, // \"PK\\001\\002\"\n CENVEM : 4, // version made by\n CENVER : 6, // version needed to extract\n CENFLG : 8, // encrypt, decrypt flags\n CENHOW : 10, // compression method\n CENTIM : 12, // modification time (2 bytes time, 2 bytes date)\n CENCRC : 16, // uncompressed file crc-32 value\n CENSIZ : 20, // compressed size\n CENLEN : 24, // uncompressed size\n CENNAM : 28, // filename length\n CENEXT : 30, // extra field length\n CENCOM : 32, // file comment length\n CENDSK : 34, // volume number start\n CENATT : 36, // internal file attributes\n CENATX : 38, // external file attributes (host system dependent)\n CENOFF : 42, // LOC header offset\n\n /* The entries in the end of central directory */\n ENDHDR : 22, // END header size\n ENDSIG : 0x06054b50, // \"PK\\005\\006\"\n ENDSUB : 8, // number of entries on this disk\n ENDTOT : 10, // total number of entries\n ENDSIZ : 12, // central directory size in bytes\n ENDOFF : 16, // offset of first CEN header\n ENDCOM : 20, // zip file comment length\n\n END64HDR : 20, // zip64 END header size\n END64SIG : 0x07064b50, // zip64 Locator signature, \"PK\\006\\007\"\n END64START : 4, // number of the disk with the start of the zip64\n END64OFF : 8, // relative offset of the zip64 end of central directory\n END64NUMDISKS : 16, // total number of disks\n\n ZIP64SIG : 0x06064b50, // zip64 signature, \"PK\\006\\006\"\n ZIP64HDR : 56, // zip64 record minimum size\n ZIP64LEAD : 12, // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE\n ZIP64SIZE : 4, // zip64 size of the central directory record\n ZIP64VEM : 12, // zip64 version made by\n ZIP64VER : 14, // zip64 version needed to extract\n ZIP64DSK : 16, // zip64 number of this disk\n ZIP64DSKDIR : 20, // number of the disk with the start of the record directory\n ZIP64SUB : 24, // number of entries on this disk\n ZIP64TOT : 32, // total number of entries\n ZIP64SIZB : 40, // zip64 central directory size in bytes\n ZIP64OFF : 48, // offset of start of central directory with respect to the starting disk number\n ZIP64EXTRA : 56, // extensible data sector\n\n /* Compression methods */\n STORED : 0, // no compression\n SHRUNK : 1, // shrunk\n REDUCED1 : 2, // reduced with compression factor 1\n REDUCED2 : 3, // reduced with compression factor 2\n REDUCED3 : 4, // reduced with compression factor 3\n REDUCED4 : 5, // reduced with compression factor 4\n IMPLODED : 6, // imploded\n // 7 reserved for Tokenizing compression algorithm\n DEFLATED : 8, // deflated\n ENHANCED_DEFLATED: 9, // enhanced deflated\n PKWARE : 10,// PKWare DCL imploded\n // 11 reserved by PKWARE\n BZIP2 : 12, // compressed using BZIP2\n // 13 reserved by PKWARE\n LZMA : 14, // LZMA\n // 15-17 reserved by PKWARE\n IBM_TERSE : 18, // compressed using IBM TERSE\n IBM_LZ77 : 19, // IBM LZ77 z\n AES_ENCRYPT : 99, // WinZIP AES encryption method\n\n /* General purpose bit flag */\n // values can obtained with expression 2**bitnr\n FLG_ENC : 1, // Bit 0: encrypted file\n FLG_COMP1 : 2, // Bit 1, compression option\n FLG_COMP2 : 4, // Bit 2, compression option\n FLG_DESC : 8, // Bit 3, data descriptor\n FLG_ENH : 16, // Bit 4, enhanced deflating\n FLG_PATCH : 32, // Bit 5, indicates that the file is compressed patched data.\n FLG_STR : 64, // Bit 6, strong encryption (patented)\n // Bits 7-10: Currently unused.\n FLG_EFS : 2048, // Bit 11: Language encoding flag (EFS)\n // Bit 12: Reserved by PKWARE for enhanced compression.\n // Bit 13: encrypted the Central Directory (patented).\n // Bits 14-15: Reserved by PKWARE.\n FLG_MSK : 4096, // mask header values\n\n /* Load type */\n FILE : 2,\n BUFFER : 1,\n NONE : 0,\n\n /* 4.5 Extensible data fields */\n EF_ID : 0,\n EF_SIZE : 2,\n\n /* Header IDs */\n ID_ZIP64 : 0x0001,\n ID_AVINFO : 0x0007,\n ID_PFS : 0x0008,\n ID_OS2 : 0x0009,\n ID_NTFS : 0x000a,\n ID_OPENVMS : 0x000c,\n ID_UNIX : 0x000d,\n ID_FORK : 0x000e,\n ID_PATCH : 0x000f,\n ID_X509_PKCS7 : 0x0014,\n ID_X509_CERTID_F : 0x0015,\n ID_X509_CERTID_C : 0x0016,\n ID_STRONGENC : 0x0017,\n ID_RECORD_MGT : 0x0018,\n ID_X509_PKCS7_RL : 0x0019,\n ID_IBM1 : 0x0065,\n ID_IBM2 : 0x0066,\n ID_POSZIP : 0x4690,\n\n EF_ZIP64_OR_32 : 0xffffffff,\n EF_ZIP64_OR_16 : 0xffff,\n EF_ZIP64_SUNCOMP : 0,\n EF_ZIP64_SCOMP : 8,\n EF_ZIP64_RHO : 16,\n EF_ZIP64_DSN : 24\n};\n", "const errors = {\n /* Header error messages */\n INVALID_LOC: \"Invalid LOC header (bad signature)\",\n INVALID_CEN: \"Invalid CEN header (bad signature)\",\n INVALID_END: \"Invalid END header (bad signature)\",\n\n /* Descriptor */\n DESCRIPTOR_NOT_EXIST: \"No descriptor present\",\n DESCRIPTOR_UNKNOWN: \"Unknown descriptor format\",\n DESCRIPTOR_FAULTY: \"Descriptor data is malformed\",\n\n /* ZipEntry error messages*/\n NO_DATA: \"Nothing to decompress\",\n BAD_CRC: \"CRC32 checksum failed {0}\",\n MAX_OUTPUT_EXCEEDED: \"Decompressed data exceeds the declared uncompressed size\",\n FILE_IN_THE_WAY: \"There is a file in the way: {0}\",\n UNKNOWN_METHOD: \"Invalid/unsupported compression method\",\n\n /* Inflater error messages */\n AVAIL_DATA: \"inflate::Available inflate data did not terminate\",\n INVALID_DISTANCE: \"inflate::Invalid literal/length or distance code in fixed or dynamic block\",\n TO_MANY_CODES: \"inflate::Dynamic block code description: too many length or distance codes\",\n INVALID_REPEAT_LEN: \"inflate::Dynamic block code description: repeat more than specified lengths\",\n INVALID_REPEAT_FIRST: \"inflate::Dynamic block code description: repeat lengths with no first length\",\n INCOMPLETE_CODES: \"inflate::Dynamic block code description: code lengths codes incomplete\",\n INVALID_DYN_DISTANCE: \"inflate::Dynamic block code description: invalid distance code lengths\",\n INVALID_CODES_LEN: \"inflate::Dynamic block code description: invalid literal/length code lengths\",\n INVALID_STORE_BLOCK: \"inflate::Stored block length did not match one's complement\",\n INVALID_BLOCK_TYPE: \"inflate::Invalid block type (type == 3)\",\n\n /* ADM-ZIP error messages */\n CANT_EXTRACT_FILE: \"Could not extract the file\",\n CANT_OVERRIDE: \"Target file already exists\",\n DISK_ENTRY_TOO_LARGE: \"Number of disk entries is too large\",\n NO_ZIP: \"No zip file was loaded\",\n NO_ENTRY: \"Entry doesn't exist\",\n DUPLICATE_ENTRY: \"Duplicate entry name {0}\",\n DIRECTORY_CONTENT_ERROR: \"A directory cannot have content\",\n FILE_NOT_FOUND: 'File not found: \"{0}\"',\n NOT_IMPLEMENTED: \"Not implemented\",\n INVALID_FILENAME: \"Invalid filename\",\n INVALID_FORMAT: \"Invalid or unsupported zip format. No END header found\",\n ZIP64_VALUE_TOO_LARGE: \"Zip64 value exceeds the maximum safe integer\",\n INVALID_PASS_PARAM: \"Incompatible password parameter\",\n WRONG_PASSWORD: \"Wrong Password\",\n\n /* ADM-ZIP */\n COMMENT_TOO_LONG: \"Comment is too long\", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space)\n EXTRA_FIELD_PARSE_ERROR: \"Extra field parsing error\"\n};\n\n// template\nfunction E(message) {\n return function (...args) {\n if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number\n message = message.replace(/\\{(\\d)\\}/g, (_, n) => args[n] || '');\n }\n\n return new Error('ADM-ZIP: ' + message);\n };\n}\n\n// Init errors with template\nfor (const msg of Object.keys(errors)) {\n exports[msg] = E(errors[msg]);\n}\n", "const fsystem = require(\"fs\");\nconst pth = require(\"path\");\nconst Constants = require(\"./constants\");\nconst Errors = require(\"./errors\");\nconst isWin = typeof process === \"object\" && \"win32\" === process.platform;\n\nconst is_Obj = (obj) => typeof obj === \"object\" && obj !== null;\n\n// generate CRC32 lookup table\nconst crcTable = new Uint32Array(256).map((t, c) => {\n for (let k = 0; k < 8; k++) {\n if ((c & 1) !== 0) {\n c = 0xedb88320 ^ (c >>> 1);\n } else {\n c >>>= 1;\n }\n }\n return c >>> 0;\n});\n\n// UTILS functions\n\nfunction Utils(opts) {\n this.sep = pth.sep;\n this.fs = fsystem;\n\n if (is_Obj(opts)) {\n // custom filesystem\n if (is_Obj(opts.fs) && typeof opts.fs.statSync === \"function\") {\n this.fs = opts.fs;\n }\n }\n}\n\nmodule.exports = Utils;\n\n// INSTANTIABLE functions\n\nUtils.prototype.makeDir = function (/*String*/ folder) {\n const self = this;\n\n // Sync - make directories tree\n function mkdirSync(/*String*/ fpath) {\n let resolvedPath = fpath.split(self.sep)[0];\n fpath.split(self.sep).forEach(function (name) {\n if (!name || name.substr(-1, 1) === \":\") return;\n resolvedPath += self.sep + name;\n var stat;\n try {\n stat = self.fs.statSync(resolvedPath);\n } catch (e) {\n if (e.message && e.message.startsWith('ENOENT')) {\n self.fs.mkdirSync(resolvedPath);\n } else {\n throw e;\n }\n }\n if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`\"${resolvedPath}\"`);\n });\n }\n\n mkdirSync(folder);\n};\n\nUtils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr) {\n const self = this;\n if (self.fs.existsSync(path)) {\n if (!overwrite) return false; // cannot overwrite\n\n var stat = self.fs.statSync(path);\n if (stat.isDirectory()) {\n return false;\n }\n }\n var folder = pth.dirname(path);\n if (!self.fs.existsSync(folder)) {\n self.makeDir(folder);\n }\n\n var fd;\n try {\n fd = self.fs.openSync(path, \"w\", 0o666); // 0666\n } catch (e) {\n self.fs.chmodSync(path, 0o666);\n fd = self.fs.openSync(path, \"w\", 0o666);\n }\n if (fd) {\n try {\n self.fs.writeSync(fd, content, 0, content.length, 0);\n } finally {\n self.fs.closeSync(fd);\n }\n }\n self.fs.chmodSync(path, attr || 0o666);\n return true;\n};\n\nUtils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr, /*Function*/ callback) {\n if (typeof attr === \"function\") {\n callback = attr;\n attr = undefined;\n }\n\n const self = this;\n\n self.fs.exists(path, function (exist) {\n if (exist && !overwrite) return callback(false);\n\n self.fs.stat(path, function (err, stat) {\n if (exist && stat && stat.isDirectory()) {\n return callback(false);\n }\n\n var folder = pth.dirname(path);\n self.fs.exists(folder, function (exists) {\n if (!exists) {\n // makeDir is synchronous and can throw (e.g. EACCES); report failure\n // rather than letting it escape this callback as an uncaught exception\n try {\n self.makeDir(folder);\n } catch (e) {\n return callback(false);\n }\n }\n\n // write the content to an open descriptor, then apply the attributes\n const writeToFd = function (fd) {\n self.fs.write(fd, content, 0, content.length, 0, function (writeErr) {\n self.fs.close(fd, function () {\n // surface write failures instead of silently reporting success (issue #402)\n if (writeErr) return callback(false);\n self.fs.chmod(path, attr || 0o666, function () {\n callback(true);\n });\n });\n });\n };\n\n self.fs.open(path, \"w\", 0o666, function (err, fd) {\n if (err) {\n // the target may exist but be read-only: make it writable and retry once\n self.fs.chmod(path, 0o666, function () {\n self.fs.open(path, \"w\", 0o666, function (retryErr, fd) {\n // Previously the retry error was ignored and an undefined fd was\n // passed to fs.write, throwing an uncaught ERR_INVALID_ARG_TYPE that\n // crashed the process (issues #470, #459, #402). Report failure instead.\n if (retryErr || !fd) return callback(false);\n writeToFd(fd);\n });\n });\n } else if (fd) {\n writeToFd(fd);\n } else {\n callback(false);\n }\n });\n });\n });\n });\n};\n\n// Guard extraction against writing through a symlink that already exists inside\n// the target directory. sanitize() only proves the textual path stays under the\n// root; it cannot see that a component on disk is a symlink pointing elsewhere,\n// so open()/mkdir() would follow it and write outside the root. Walk every path\n// component strictly below root and reject any that is a symlink. Components at\n// or above root are the caller's own choice and are left untouched, so a root\n// that itself lives under a symlink (e.g. /tmp on macOS) still extracts.\nUtils.prototype.assertPathSafe = function (/*String*/ root, /*String*/ target) {\n const self = this;\n if (typeof self.fs.lstatSync !== \"function\") return;\n\n const resolvedRoot = pth.resolve(root);\n const resolvedTarget = pth.resolve(target);\n if (resolvedTarget === resolvedRoot) return;\n\n const rel = pth.relative(resolvedRoot, resolvedTarget);\n // Not under root: sanitize() is responsible for that case; nothing to walk.\n if (!rel || rel === \"..\" || rel.startsWith(\"..\" + pth.sep) || pth.isAbsolute(rel)) return;\n\n let cur = resolvedRoot;\n for (const part of rel.split(pth.sep)) {\n if (!part || part === \".\") continue;\n cur = pth.join(cur, part);\n let stat;\n try {\n stat = self.fs.lstatSync(cur);\n } catch (e) {\n break; // component does not exist yet: nothing below it can be a symlink\n }\n if (stat.isSymbolicLink()) throw Errors.FILE_IN_THE_WAY(`\"${cur}\"`);\n }\n};\n\nUtils.prototype.findFiles = function (/*String*/ path) {\n const self = this;\n const canLstat = typeof self.fs.lstatSync === \"function\";\n const rootReal = self.fs.realpathSync(path);\n\n // A symlink whose target lies outside the folder being archived must not be\n // followed: statSync would dereference it and copy the target's contents into\n // the archive, disclosing files outside the root (GHSA-wx42-xcp7-pgr4). Allow\n // symlinks that resolve to a location inside the root, reject any that escape.\n function escapesRoot(/*String*/ p) {\n if (!canLstat) return false;\n if (!self.fs.lstatSync(p).isSymbolicLink()) return false;\n let real;\n try {\n real = self.fs.realpathSync(p);\n } catch (e) {\n return true; // dangling or unresolvable symlink: do not follow\n }\n return !(real === rootReal || real.startsWith(rootReal + pth.sep));\n }\n\n function findSync(/*String*/ dir, /*RegExp*/ pattern, /*Boolean*/ recursive, /*Set*/ visited) {\n if (typeof pattern === \"boolean\") {\n recursive = pattern;\n pattern = undefined;\n }\n let files = [];\n self.fs.readdirSync(dir).forEach(function (file) {\n const path = pth.join(dir, file);\n\n if (escapesRoot(path)) return;\n\n const stat = self.fs.statSync(path);\n\n if (!pattern || pattern.test(path)) {\n files.push(pth.normalize(path) + (stat.isDirectory() ? self.sep : \"\"));\n }\n\n if (stat.isDirectory() && recursive) {\n // Descend by resolved real path and skip directories we have already\n // visited. This stops a symlink that points back to an ancestor from\n // recursing forever until the path fails with ELOOP / ENAMETOOLONG\n // (issue #541).\n const realDir = self.fs.realpathSync(path);\n if (!visited.has(realDir)) {\n visited.add(realDir);\n files = files.concat(findSync(path, pattern, recursive, visited));\n }\n }\n });\n return files;\n }\n\n return findSync(path, undefined, true, new Set([rootReal]));\n};\n\n/**\n * Callback for showing if everything was done.\n *\n * @callback filelistCallback\n * @param {Error} err - Error object\n * @param {string[]} list - was request fully completed\n */\n\n/**\n *\n * @param {string} dir\n * @param {filelistCallback} cb\n */\nUtils.prototype.findFilesAsync = function (dir, cb) {\n const self = this;\n const results = [];\n let finished = false;\n const finish = function (err) {\n if (finished) return;\n finished = true;\n cb(err, err ? undefined : results);\n };\n\n const canLstat = typeof self.fs.lstat === \"function\";\n let rootReal = null;\n\n // Reject a symlink whose target escapes the root being archived, so its\n // contents are not dereferenced and copied into the archive\n // (GHSA-wx42-xcp7-pgr4). A symlink resolving to a location inside the root is\n // allowed; a dangling or escaping one is skipped. Calls back (err, escapes).\n const escapesRoot = function (file, cb) {\n if (!canLstat) return cb(null, false);\n self.fs.lstat(file, function (err, lst) {\n if (err) return cb(err);\n if (!lst || !lst.isSymbolicLink()) return cb(null, false);\n self.fs.realpath(file, function (err, real) {\n if (err) return cb(null, true); // dangling: do not follow\n cb(null, !(real === rootReal || real.startsWith(rootReal + pth.sep)));\n });\n });\n };\n\n // Descend by resolved real path and skip directories already visited, so a\n // symlink pointing back to an ancestor cannot recurse forever (issue #541).\n const walk = function (dir, visited, done) {\n self.fs.readdir(dir, function (err, list) {\n if (err) return done(err);\n let pending = list.length;\n if (!pending) return done();\n list.forEach(function (name) {\n const file = pth.join(dir, name);\n escapesRoot(file, function (err, escapes) {\n if (err) return done(err);\n if (escapes) {\n if (!--pending) done();\n return;\n }\n self.fs.stat(file, function (err, stat) {\n if (err) return done(err);\n if (!stat) {\n if (!--pending) done();\n return;\n }\n results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : \"\"));\n if (!stat.isDirectory()) {\n if (!--pending) done();\n return;\n }\n self.fs.realpath(file, function (err, realDir) {\n if (err) return done(err);\n if (visited.has(realDir)) {\n if (!--pending) done();\n return;\n }\n visited.add(realDir);\n walk(file, visited, function (err) {\n if (err) return done(err);\n if (!--pending) done();\n });\n });\n });\n });\n });\n });\n };\n\n self.fs.realpath(dir, function (err, realDir) {\n if (err) return finish(err);\n rootReal = realDir;\n walk(dir, new Set([realDir]), finish);\n });\n};\n\nUtils.prototype.getAttributes = function () {};\n\nUtils.prototype.setAttributes = function () {};\n\n// STATIC functions\n\n// crc32 single update (it is part of crc32)\nUtils.crc32update = function (crc, byte) {\n return crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n};\n\nUtils.crc32 = function (buf) {\n if (typeof buf === \"string\") {\n buf = Buffer.from(buf, \"utf8\");\n }\n\n let len = buf.length;\n let crc = ~0;\n for (let off = 0; off < len; ) crc = Utils.crc32update(crc, buf[off++]);\n // xor and cast as uint32 number\n return ~crc >>> 0;\n};\n\nUtils.methodToString = function (/*Number*/ method) {\n switch (method) {\n case Constants.STORED:\n return \"STORED (\" + method + \")\";\n case Constants.DEFLATED:\n return \"DEFLATED (\" + method + \")\";\n default:\n return \"UNSUPPORTED (\" + method + \")\";\n }\n};\n\n/**\n * removes \"..\" style path elements\n * @param {string} path - fixable path\n * @returns string - fixed filepath\n */\nUtils.canonical = function (/*string*/ path) {\n if (!path) return \"\";\n // trick normalize think path is absolute\n const safeSuffix = pth.posix.normalize(\"/\" + path.split(\"\\\\\").join(\"/\"));\n return pth.join(\".\", safeSuffix);\n};\n\n/**\n * fix file names in achive\n * @param {string} path - fixable path\n * @returns string - fixed filepath\n */\n\nUtils.zipnamefix = function (path) {\n if (!path) return \"\";\n // trick normalize think path is absolute\n const safeSuffix = pth.posix.normalize(\"/\" + path.split(\"\\\\\").join(\"/\"));\n return pth.posix.join(\".\", safeSuffix);\n};\n\n/**\n *\n * @param {Array} arr\n * @param {function} callback\n * @returns\n */\nUtils.findLast = function (arr, callback) {\n if (!Array.isArray(arr)) throw new TypeError(\"arr is not array\");\n\n const len = arr.length >>> 0;\n for (let i = len - 1; i >= 0; i--) {\n if (callback(arr[i], i, arr)) {\n return arr[i];\n }\n }\n return void 0;\n};\n\n// make absolute paths taking prefix as root folder\nUtils.sanitize = function (/*string*/ prefix, /*string*/ name) {\n prefix = pth.resolve(pth.normalize(prefix));\n var parts = name.split(\"/\");\n for (var i = 0, l = parts.length; i < l; i++) {\n var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));\n if (path === prefix || path.startsWith(prefix + pth.sep)) {\n return path;\n }\n }\n return pth.normalize(pth.join(prefix, pth.basename(name)));\n};\n\n// converts buffer, Uint8Array, string types to buffer\nUtils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input, /* function */ encoder) {\n if (Buffer.isBuffer(input)) {\n return input;\n } else if (input instanceof Uint8Array) {\n return Buffer.from(input);\n } else {\n // expect string all other values are invalid and return empty buffer\n return typeof input === \"string\" ? encoder(input) : Buffer.alloc(0);\n }\n};\n\nUtils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) {\n const lo = buffer.readUInt32LE(index);\n const hi = buffer.readUInt32LE(index + 4);\n const value = hi * 0x100000000 + lo;\n // The result is a JS number, so values above 2^53 - 1 cannot be represented\n // exactly. These are zip64 sizes/offsets/counts used as buffer indices; a\n // silently rounded value would misparse the archive. Reject instead.\n if (value > Number.MAX_SAFE_INTEGER) {\n throw Errors.ZIP64_VALUE_TOO_LARGE();\n }\n return value;\n};\n\nUtils.writeBigUInt64LE = function (/*Buffer*/ buffer, /*Number*/ value, /*int*/ index) {\n const lo = value >>> 0;\n const hi = Math.floor(value / 0x100000000) >>> 0;\n buffer.writeUInt32LE(lo, index);\n buffer.writeUInt32LE(hi, index + 4);\n};\n\nUtils.fromDOS2Date = function (val) {\n return new Date(((val >> 25) & 0x7f) + 1980, Math.max(((val >> 21) & 0x0f) - 1, 0), Math.max((val >> 16) & 0x1f, 1), (val >> 11) & 0x1f, (val >> 5) & 0x3f, (val & 0x1f) << 1);\n};\n\nUtils.fromDate2DOS = function (val) {\n let date = 0;\n let time = 0;\n if (val.getFullYear() > 1979) {\n date = (((val.getFullYear() - 1980) & 0x7f) << 9) | ((val.getMonth() + 1) << 5) | val.getDate();\n time = (val.getHours() << 11) | (val.getMinutes() << 5) | (val.getSeconds() >> 1);\n }\n return (date << 16) | time;\n};\n\nUtils.isWin = isWin; // Do we have windows system\nUtils.crcTable = crcTable;\n", "const pth = require(\"path\");\n\nmodule.exports = function (/*String*/ path, /*Utils object*/ { fs }) {\n var _path = path || \"\",\n _obj = newAttr(),\n _stat = null;\n\n function newAttr() {\n return {\n directory: false,\n readonly: false,\n hidden: false,\n executable: false,\n mtime: 0,\n atime: 0\n };\n }\n\n if (_path && fs.existsSync(_path)) {\n _stat = fs.statSync(_path);\n _obj.directory = _stat.isDirectory();\n _obj.mtime = _stat.mtime;\n _obj.atime = _stat.atime;\n _obj.executable = (0o111 & _stat.mode) !== 0; // file is executable who ever har right not just owner\n _obj.readonly = (0o200 & _stat.mode) === 0; // readonly if owner has no write right\n _obj.hidden = pth.basename(_path)[0] === \".\";\n } else {\n console.warn(\"Invalid path: \" + _path);\n }\n\n return {\n get directory() {\n return _obj.directory;\n },\n\n get readOnly() {\n return _obj.readonly;\n },\n\n get hidden() {\n return _obj.hidden;\n },\n\n get mtime() {\n return _obj.mtime;\n },\n\n get atime() {\n return _obj.atime;\n },\n\n get executable() {\n return _obj.executable;\n },\n\n decodeAttributes: function () {},\n\n encodeAttributes: function () {},\n\n toJSON: function () {\n return {\n path: _path,\n isDirectory: _obj.directory,\n isReadOnly: _obj.readonly,\n isHidden: _obj.hidden,\n isExecutable: _obj.executable,\n mTime: _obj.mtime,\n aTime: _obj.atime\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n", "module.exports = {\n efs: true,\n encode: (data) => Buffer.from(data, \"utf8\"),\n decode: (data) => data.toString(\"utf8\")\n};\n", "module.exports = require(\"./utils\");\nmodule.exports.Constants = require(\"./constants\");\nmodule.exports.Errors = require(\"./errors\");\nmodule.exports.FileAttr = require(\"./fattr\");\nmodule.exports.decoder = require(\"./decoder\");\n", "var Utils = require(\"../util\"),\n Constants = Utils.Constants;\n\n/* The central directory file header */\nmodule.exports = function () {\n var _verMade = 20, // v2.0\n _version = 10, // v1.0\n _flags = 0,\n _method = 0,\n _time = 0,\n _crc = 0,\n _compressedSize = 0,\n _size = 0,\n _fnameLen = 0,\n _extraLen = 0,\n _comLen = 0,\n _diskStart = 0,\n _inattr = 0,\n _attr = 0,\n _offset = 0;\n\n _verMade |= Utils.isWin ? 0x0a00 : 0x0300;\n\n // Set EFS flag since filename and comment fields are all by default encoded using UTF-8.\n // Without it file names may be corrupted for other apps when file names use unicode chars\n _flags |= Constants.FLG_EFS;\n\n const _localHeader = {\n extraLen: 0\n };\n\n // casting\n const uint32 = (val) => Math.max(0, val) >>> 0;\n const uint16 = (val) => Math.max(0, val) & 0xffff;\n const uint8 = (val) => Math.max(0, val) & 0xff;\n\n _time = Utils.fromDate2DOS(new Date());\n\n return {\n get made() {\n return _verMade;\n },\n set made(val) {\n _verMade = val;\n },\n\n get version() {\n return _version;\n },\n set version(val) {\n _version = val;\n },\n\n get flags() {\n return _flags;\n },\n set flags(val) {\n _flags = val;\n },\n\n get flags_efs() {\n return (_flags & Constants.FLG_EFS) > 0;\n },\n set flags_efs(val) {\n if (val) {\n _flags |= Constants.FLG_EFS;\n } else {\n _flags &= ~Constants.FLG_EFS;\n }\n },\n\n get flags_desc() {\n return (_flags & Constants.FLG_DESC) > 0;\n },\n set flags_desc(val) {\n if (val) {\n _flags |= Constants.FLG_DESC;\n } else {\n _flags &= ~Constants.FLG_DESC;\n }\n },\n\n get method() {\n return _method;\n },\n set method(val) {\n switch (val) {\n case Constants.STORED:\n this.version = 10;\n break;\n case Constants.DEFLATED:\n default:\n this.version = 20;\n }\n _method = val;\n },\n\n get time() {\n return Utils.fromDOS2Date(this.timeval);\n },\n set time(val) {\n val = new Date(val);\n this.timeval = Utils.fromDate2DOS(val);\n },\n\n get timeval() {\n return _time;\n },\n set timeval(val) {\n _time = uint32(val);\n },\n\n get timeHighByte() {\n return uint8(_time >>> 8);\n },\n get crc() {\n return _crc;\n },\n set crc(val) {\n _crc = uint32(val);\n },\n\n get compressedSize() {\n return _compressedSize;\n },\n set compressedSize(val) {\n _compressedSize = uint32(val);\n },\n\n get size() {\n return _size;\n },\n set size(val) {\n _size = uint32(val);\n },\n\n get fileNameLength() {\n return _fnameLen;\n },\n set fileNameLength(val) {\n _fnameLen = val;\n },\n\n get extraLength() {\n return _extraLen;\n },\n set extraLength(val) {\n _extraLen = val;\n },\n\n get extraLocalLength() {\n return _localHeader.extraLen;\n },\n set extraLocalLength(val) {\n _localHeader.extraLen = val;\n },\n\n get commentLength() {\n return _comLen;\n },\n set commentLength(val) {\n _comLen = val;\n },\n\n get diskNumStart() {\n return _diskStart;\n },\n set diskNumStart(val) {\n _diskStart = uint32(val);\n },\n\n get inAttr() {\n return _inattr;\n },\n set inAttr(val) {\n _inattr = uint32(val);\n },\n\n get attr() {\n return _attr;\n },\n set attr(val) {\n _attr = uint32(val);\n },\n\n // get Unix file permissions\n get fileAttr() {\n // Mask to the 9 rwxrwxrwx bits only. The setuid (0o4000), setgid\n // (0o2000) and sticky (0o1000) bits are attacker-controlled archive\n // metadata; preserving them on extraction (keepOriginalPermission)\n // lets a crafted zip plant a setuid-root binary when extracting as\n // root, a local privilege escalation (GHSA-679w-jf3m-wh39).\n return ((_attr || 0) >> 16) & 0o777;\n },\n\n get offset() {\n return _offset;\n },\n set offset(val) {\n _offset = uint32(val);\n },\n\n get encrypted() {\n return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC;\n },\n\n get centralHeaderSize() {\n return Constants.CENHDR + _fnameLen + _extraLen + _comLen;\n },\n\n get realDataOffset() {\n return _offset + Constants.LOCHDR + _localHeader.fnameLen + _localHeader.extraLen;\n },\n\n get localHeader() {\n return _localHeader;\n },\n\n loadLocalHeaderFromBinary: function (/*Buffer*/ input) {\n // The LOC offset comes from the central directory and is attacker\n // controlled. Reject one that would read past the end of the buffer,\n // otherwise readUInt32LE below throws a raw RangeError instead of a\n // clean INVALID_LOC (and escapes the async error path).\n if (_offset < 0 || _offset + Constants.LOCHDR > input.length) {\n throw Utils.Errors.INVALID_LOC();\n }\n var data = input.slice(_offset, _offset + Constants.LOCHDR);\n // 30 bytes and should start with \"PK\\003\\004\"\n if (data.readUInt32LE(0) !== Constants.LOCSIG) {\n throw Utils.Errors.INVALID_LOC();\n }\n\n // version needed to extract\n _localHeader.version = data.readUInt16LE(Constants.LOCVER);\n // general purpose bit flag\n _localHeader.flags = data.readUInt16LE(Constants.LOCFLG);\n // desc flag\n _localHeader.flags_desc = (_localHeader.flags & Constants.FLG_DESC) > 0;\n // compression method\n _localHeader.method = data.readUInt16LE(Constants.LOCHOW);\n // modification time (2 bytes time, 2 bytes date)\n _localHeader.time = data.readUInt32LE(Constants.LOCTIM);\n // uncompressed file crc-32 valu\n _localHeader.crc = data.readUInt32LE(Constants.LOCCRC);\n // compressed size\n _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ);\n // uncompressed size\n _localHeader.size = data.readUInt32LE(Constants.LOCLEN);\n // filename length\n _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM);\n // extra field length\n _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT);\n\n // read extra data\n const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen;\n const extraEnd = extraStart + _localHeader.extraLen;\n return input.slice(extraStart, extraEnd);\n },\n\n loadFromBinary: function (/*Buffer*/ data) {\n // data should be 46 bytes and start with \"PK 01 02\"\n if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {\n throw Utils.Errors.INVALID_CEN();\n }\n // version made by\n _verMade = data.readUInt16LE(Constants.CENVEM);\n // version needed to extract\n _version = data.readUInt16LE(Constants.CENVER);\n // encrypt, decrypt flags\n _flags = data.readUInt16LE(Constants.CENFLG);\n // compression method\n _method = data.readUInt16LE(Constants.CENHOW);\n // modification time (2 bytes time, 2 bytes date)\n _time = data.readUInt32LE(Constants.CENTIM);\n // uncompressed file crc-32 value\n _crc = data.readUInt32LE(Constants.CENCRC);\n // compressed size\n _compressedSize = data.readUInt32LE(Constants.CENSIZ);\n // uncompressed size\n _size = data.readUInt32LE(Constants.CENLEN);\n // filename length\n _fnameLen = data.readUInt16LE(Constants.CENNAM);\n // extra field length\n _extraLen = data.readUInt16LE(Constants.CENEXT);\n // file comment length\n _comLen = data.readUInt16LE(Constants.CENCOM);\n // volume number start\n _diskStart = data.readUInt16LE(Constants.CENDSK);\n // internal file attributes\n _inattr = data.readUInt16LE(Constants.CENATT);\n // external file attributes\n _attr = data.readUInt32LE(Constants.CENATX);\n // LOC header offset\n _offset = data.readUInt32LE(Constants.CENOFF);\n },\n\n localHeaderToBinary: function () {\n // LOC header size (30 bytes)\n var data = Buffer.alloc(Constants.LOCHDR);\n // \"PK\\003\\004\"\n data.writeUInt32LE(Constants.LOCSIG, 0);\n // version needed to extract\n data.writeUInt16LE(_version, Constants.LOCVER);\n // general purpose bit flag\n // clear bit 3 (data descriptor): we always write the real crc-32\n // and sizes into this local header, so no trailing descriptor is\n // emitted. Leaving the flag set would make the output unreadable\n // (see issue #555).\n data.writeUInt16LE(_flags & ~Constants.FLG_DESC, Constants.LOCFLG);\n // compression method\n data.writeUInt16LE(_method, Constants.LOCHOW);\n // modification time (2 bytes time, 2 bytes date)\n data.writeUInt32LE(_time, Constants.LOCTIM);\n // uncompressed file crc-32 value\n data.writeUInt32LE(_crc, Constants.LOCCRC);\n // compressed size\n data.writeUInt32LE(_compressedSize, Constants.LOCSIZ);\n // uncompressed size\n data.writeUInt32LE(_size, Constants.LOCLEN);\n // filename length\n data.writeUInt16LE(_fnameLen, Constants.LOCNAM);\n // extra field length\n data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT);\n return data;\n },\n\n centralHeaderToBinary: function () {\n // CEN header size (46 bytes)\n var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen);\n // \"PK\\001\\002\"\n data.writeUInt32LE(Constants.CENSIG, 0);\n // version made by\n data.writeUInt16LE(_verMade, Constants.CENVEM);\n // version needed to extract\n data.writeUInt16LE(_version, Constants.CENVER);\n // encrypt, decrypt flags\n // clear bit 3 (data descriptor) to match the local header we emit\n // (real crc/sizes are written, no descriptor follows the data) \u2014 issue #555\n data.writeUInt16LE(_flags & ~Constants.FLG_DESC, Constants.CENFLG);\n // compression method\n data.writeUInt16LE(_method, Constants.CENHOW);\n // modification time (2 bytes time, 2 bytes date)\n data.writeUInt32LE(_time, Constants.CENTIM);\n // uncompressed file crc-32 value\n data.writeUInt32LE(_crc, Constants.CENCRC);\n // compressed size\n data.writeUInt32LE(_compressedSize, Constants.CENSIZ);\n // uncompressed size\n data.writeUInt32LE(_size, Constants.CENLEN);\n // filename length\n data.writeUInt16LE(_fnameLen, Constants.CENNAM);\n // extra field length\n data.writeUInt16LE(_extraLen, Constants.CENEXT);\n // file comment length\n data.writeUInt16LE(_comLen, Constants.CENCOM);\n // volume number start\n data.writeUInt16LE(_diskStart, Constants.CENDSK);\n // internal file attributes\n data.writeUInt16LE(_inattr, Constants.CENATT);\n // external file attributes\n data.writeUInt32LE(_attr, Constants.CENATX);\n // LOC header offset\n data.writeUInt32LE(_offset, Constants.CENOFF);\n return data;\n },\n\n toJSON: function () {\n const bytes = function (nr) {\n return nr + \" bytes\";\n };\n\n return {\n made: _verMade,\n version: _version,\n flags: _flags,\n method: Utils.methodToString(_method),\n time: this.time,\n crc: \"0x\" + _crc.toString(16).toUpperCase(),\n compressedSize: bytes(_compressedSize),\n size: bytes(_size),\n fileNameLength: bytes(_fnameLen),\n extraLength: bytes(_extraLen),\n commentLength: bytes(_comLen),\n diskNumStart: _diskStart,\n inAttr: _inattr,\n attr: _attr,\n offset: _offset,\n centralHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen)\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n", "var Utils = require(\"../util\"),\n Constants = Utils.Constants;\n\n/* The entries in the end of central directory */\nmodule.exports = function () {\n var _volumeEntries = 0,\n _totalEntries = 0,\n _size = 0,\n _offset = 0,\n _commentLength = 0;\n\n const needsZip64 = () => _volumeEntries > Constants.EF_ZIP64_OR_16 || _totalEntries > Constants.EF_ZIP64_OR_16 || _size > Constants.EF_ZIP64_OR_32 || _offset > Constants.EF_ZIP64_OR_32;\n\n return {\n get diskEntries() {\n return _volumeEntries;\n },\n set diskEntries(/*Number*/ val) {\n _volumeEntries = _totalEntries = val;\n },\n\n get totalEntries() {\n return _totalEntries;\n },\n set totalEntries(/*Number*/ val) {\n _totalEntries = _volumeEntries = val;\n },\n\n get size() {\n return _size;\n },\n set size(/*Number*/ val) {\n _size = val;\n },\n\n get offset() {\n return _offset;\n },\n set offset(/*Number*/ val) {\n _offset = val;\n },\n\n get commentLength() {\n return _commentLength;\n },\n set commentLength(/*Number*/ val) {\n _commentLength = val;\n },\n\n get mainHeaderSize() {\n return (needsZip64() ? Constants.ZIP64HDR + Constants.END64HDR : 0) + Constants.ENDHDR + _commentLength;\n },\n\n loadFromBinary: function (/*Buffer*/ data) {\n // data should be 22 bytes and start with \"PK 05 06\"\n // or be 56+ bytes and start with \"PK 06 06\" for Zip64\n if (\n (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) &&\n (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)\n ) {\n throw Utils.Errors.INVALID_END();\n }\n\n if (data.readUInt32LE(0) === Constants.ENDSIG) {\n // number of entries on this volume\n _volumeEntries = data.readUInt16LE(Constants.ENDSUB);\n // total number of entries\n _totalEntries = data.readUInt16LE(Constants.ENDTOT);\n // central directory size in bytes\n _size = data.readUInt32LE(Constants.ENDSIZ);\n // offset of first CEN header\n _offset = data.readUInt32LE(Constants.ENDOFF);\n // zip file comment length\n _commentLength = data.readUInt16LE(Constants.ENDCOM);\n } else {\n // number of entries on this volume\n _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB);\n // total number of entries\n _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT);\n // central directory size in bytes\n _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZB);\n // offset of first CEN header\n _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF);\n\n _commentLength = 0;\n }\n },\n\n toBinary: function () {\n if (!needsZip64()) {\n var b = Buffer.alloc(Constants.ENDHDR + _commentLength);\n // \"PK 05 06\" signature\n b.writeUInt32LE(Constants.ENDSIG, 0);\n b.writeUInt32LE(0, 4);\n // number of entries on this volume\n b.writeUInt16LE(_volumeEntries, Constants.ENDSUB);\n // total number of entries\n b.writeUInt16LE(_totalEntries, Constants.ENDTOT);\n // central directory size in bytes\n b.writeUInt32LE(_size, Constants.ENDSIZ);\n // offset of first CEN header\n b.writeUInt32LE(_offset, Constants.ENDOFF);\n // zip file comment length\n b.writeUInt16LE(_commentLength, Constants.ENDCOM);\n // fill comment memory with spaces so no garbage is left there\n b.fill(\" \", Constants.ENDHDR);\n\n return b;\n }\n\n var b = Buffer.alloc(this.mainHeaderSize);\n let offset = 0;\n\n // Zip64 end of central directory record.\n b.writeUInt32LE(Constants.ZIP64SIG, offset);\n Utils.writeBigUInt64LE(b, Constants.ZIP64HDR - Constants.ZIP64LEAD, offset + Constants.ZIP64SIZE);\n b.writeUInt16LE(45, offset + Constants.ZIP64VEM);\n b.writeUInt16LE(45, offset + Constants.ZIP64VER);\n b.writeUInt32LE(0, offset + Constants.ZIP64DSK);\n b.writeUInt32LE(0, offset + Constants.ZIP64DSKDIR);\n Utils.writeBigUInt64LE(b, _volumeEntries, offset + Constants.ZIP64SUB);\n Utils.writeBigUInt64LE(b, _totalEntries, offset + Constants.ZIP64TOT);\n Utils.writeBigUInt64LE(b, _size, offset + Constants.ZIP64SIZB);\n Utils.writeBigUInt64LE(b, _offset, offset + Constants.ZIP64OFF);\n\n const zip64EndOffset = _offset + _size;\n offset += Constants.ZIP64HDR;\n\n // Zip64 end of central directory locator.\n b.writeUInt32LE(Constants.END64SIG, offset);\n b.writeUInt32LE(0, offset + Constants.END64START);\n Utils.writeBigUInt64LE(b, zip64EndOffset, offset + Constants.END64OFF);\n b.writeUInt32LE(1, offset + Constants.END64NUMDISKS);\n offset += Constants.END64HDR;\n\n // \"PK 05 06\" signature\n b.writeUInt32LE(Constants.ENDSIG, offset);\n b.writeUInt32LE(0, offset + 4);\n // number of entries on this volume\n b.writeUInt16LE(Math.min(_volumeEntries, Constants.EF_ZIP64_OR_16), offset + Constants.ENDSUB);\n // total number of entries\n b.writeUInt16LE(Math.min(_totalEntries, Constants.EF_ZIP64_OR_16), offset + Constants.ENDTOT);\n // central directory size in bytes\n b.writeUInt32LE(Math.min(_size, Constants.EF_ZIP64_OR_32), offset + Constants.ENDSIZ);\n // offset of first CEN header\n b.writeUInt32LE(Math.min(_offset, Constants.EF_ZIP64_OR_32), offset + Constants.ENDOFF);\n // zip file comment length\n b.writeUInt16LE(_commentLength, offset + Constants.ENDCOM);\n // fill comment memory with spaces so no garbage is left there\n b.fill(\" \", offset + Constants.ENDHDR);\n\n return b;\n },\n\n toJSON: function () {\n // creates 0x0000 style output\n const offset = function (nr, len) {\n let offs = nr.toString(16).toUpperCase();\n while (offs.length < len) offs = \"0\" + offs;\n return \"0x\" + offs;\n };\n\n return {\n diskEntries: _volumeEntries,\n totalEntries: _totalEntries,\n size: _size + \" bytes\",\n offset: offset(_offset, 4),\n commentLength: _commentLength\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n// Misspelled\n", "exports.EntryHeader = require(\"./entryHeader\");\nexports.MainHeader = require(\"./mainHeader\");\n", "module.exports = function (/*Buffer*/ inbuf) {\n var zlib = require(\"zlib\");\n\n var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 };\n\n return {\n deflate: function () {\n return zlib.deflateRawSync(inbuf, opts);\n },\n\n deflateAsync: function (/*Function*/ callback) {\n var tmp = zlib.createDeflateRaw(opts),\n parts = [],\n total = 0;\n tmp.on(\"data\", function (data) {\n parts.push(data);\n total += data.length;\n });\n tmp.on(\"end\", function () {\n var buf = Buffer.alloc(total),\n written = 0;\n buf.fill(0);\n for (var i = 0; i < parts.length; i++) {\n var part = parts[i];\n part.copy(buf, written);\n written += part.length;\n }\n callback && callback(buf);\n });\n tmp.end(inbuf);\n }\n };\n};\n", "const version = +(process?.versions?.node ?? \"\").split(\".\")[0] || 0;\nconst Errors = require(\"../util/errors\");\n\nmodule.exports = function (/*Buffer*/ inbuf, /*number*/ expectedLength) {\n var zlib = require(\"zlib\");\n // Cap decompression output at the entry's declared uncompressed size to bound\n // decompression bombs (CVE-2026-39244). A declared size of 0 must not disable\n // the cap: a genuinely empty entry inflates to 0 bytes, so a 1-byte floor\n // still lets it through while stopping a bomb that lies about its size\n // (GHSA-rcw4-f5rp-g42v). zlib requires maxOutputLength >= 1.\n const maxOutputLength = expectedLength > 0 ? expectedLength : 1;\n const option = version >= 15 ? { maxOutputLength } : {};\n\n return {\n inflate: function () {\n return zlib.inflateRawSync(inbuf, option);\n },\n\n inflateAsync: function (/*Function*/ callback) {\n var tmp = zlib.createInflateRaw(option),\n parts = [],\n total = 0,\n done = false;\n const fail = function (err) {\n if (done) return;\n done = true;\n tmp.destroy();\n callback && callback(Buffer.alloc(0), err);\n };\n // Route stream errors (e.g. Z_DATA_ERROR on malformed input) through the\n // callback. Without an \"error\" listener zlib re-throws the event as an\n // uncaught exception on a later tick, crashing the host process instead\n // of failing the call (GHSA-8238-w5pm-2374).\n tmp.on(\"error\", function (err) {\n fail(err);\n });\n tmp.on(\"data\", function (data) {\n if (done) return;\n total += data.length;\n // The streaming API ignores maxOutputLength, so enforce the cap by\n // hand; otherwise the async path decompresses without limit while the\n // sync path is capped (GHSA-v429-h5qx-84wm, GHSA-c6fg-446q-cg94).\n if (total > maxOutputLength) {\n return fail(Errors.MAX_OUTPUT_EXCEEDED());\n }\n parts.push(data);\n });\n tmp.on(\"end\", function () {\n if (done) return;\n done = true;\n var buf = Buffer.alloc(total),\n written = 0;\n buf.fill(0);\n for (var i = 0; i < parts.length; i++) {\n var part = parts[i];\n part.copy(buf, written);\n written += part.length;\n }\n callback && callback(buf);\n });\n tmp.end(inbuf);\n }\n };\n};\n", "\"use strict\";\n\n// node crypt, we use it for generate salt\n// eslint-disable-next-line node/no-unsupported-features/node-builtins\nconst { randomFillSync } = require(\"crypto\");\nconst Errors = require(\"../util/errors\");\n\n// generate CRC32 lookup table\nconst crctable = new Uint32Array(256).map((t, crc) => {\n for (let j = 0; j < 8; j++) {\n if (0 !== (crc & 1)) {\n crc = (crc >>> 1) ^ 0xedb88320;\n } else {\n crc >>>= 1;\n }\n }\n return crc >>> 0;\n});\n\n// C-style uInt32 Multiply (discards higher bits, when JS multiply discards lower bits)\nconst uMul = (a, b) => Math.imul(a, b) >>> 0;\n\n// crc32 byte single update (actually same function is part of utils.crc32 function :) )\nconst crc32update = (pCrc32, bval) => {\n return crctable[(pCrc32 ^ bval) & 0xff] ^ (pCrc32 >>> 8);\n};\n\n// function for generating salt for encrytion header\nconst genSalt = () => {\n if (\"function\" === typeof randomFillSync) {\n return randomFillSync(Buffer.alloc(12));\n } else {\n // fallback if function is not defined\n return genSalt.node();\n }\n};\n\n// salt generation with node random function (mainly as fallback)\ngenSalt.node = () => {\n const salt = Buffer.alloc(12);\n const len = salt.length;\n for (let i = 0; i < len; i++) salt[i] = (Math.random() * 256) & 0xff;\n return salt;\n};\n\n// general config\nconst config = {\n genSalt\n};\n\n// Class Initkeys handles same basic ops with keys\nfunction Initkeys(pw) {\n const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw);\n this.keys = new Uint32Array([0x12345678, 0x23456789, 0x34567890]);\n for (let i = 0; i < pass.length; i++) {\n this.updateKeys(pass[i]);\n }\n}\n\nInitkeys.prototype.updateKeys = function (byteValue) {\n const keys = this.keys;\n keys[0] = crc32update(keys[0], byteValue);\n keys[1] += keys[0] & 0xff;\n keys[1] = uMul(keys[1], 134775813) + 1;\n keys[2] = crc32update(keys[2], keys[1] >>> 24);\n return byteValue;\n};\n\nInitkeys.prototype.next = function () {\n const k = (this.keys[2] | 2) >>> 0; // key\n return (uMul(k, k ^ 1) >> 8) & 0xff; // decode\n};\n\nfunction make_decrypter(/*Buffer*/ pwd) {\n // 1. Stage initialize key\n const keys = new Initkeys(pwd);\n\n // return decrypter function\n return function (/*Buffer*/ data) {\n // result - we create new Buffer for results\n const result = Buffer.alloc(data.length);\n let pos = 0;\n // process input data\n for (let c of data) {\n //c ^= keys.next();\n //result[pos++] = c; // decode & Save Value\n result[pos++] = keys.updateKeys(c ^ keys.next()); // update keys with decoded byte\n }\n return result;\n };\n}\n\nfunction make_encrypter(/*Buffer*/ pwd) {\n // 1. Stage initialize key\n const keys = new Initkeys(pwd);\n\n // return encrypting function, result and pos is here so we dont have to merge buffers later\n return function (/*Buffer*/ data, /*Buffer*/ result, /* Number */ pos = 0) {\n // result - we create new Buffer for results\n if (!result) result = Buffer.alloc(data.length);\n // process input data\n for (let c of data) {\n const k = keys.next(); // save key byte\n result[pos++] = c ^ k; // save val\n keys.updateKeys(c); // update keys with decoded byte\n }\n return result;\n };\n}\n\nfunction decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) {\n if (!data || !Buffer.isBuffer(data) || data.length < 12) {\n return Buffer.alloc(0);\n }\n\n // 1. We Initialize and generate decrypting function\n const decrypter = make_decrypter(pwd);\n\n // 2. decrypt salt what is always 12 bytes and is a part of file content\n const salt = decrypter(data.slice(0, 12));\n\n // if bit 3 (0x08) of the general-purpose flags field is set, check salt[11] with the high byte of the header time\n // 2 byte data block (as per Info-Zip spec), otherwise check with the high byte of the header entry\n const verifyByte = (header.flags & 0x8) === 0x8 ? header.timeHighByte : header.crc >>> 24;\n\n //3. does password meet expectations\n if (salt[11] !== verifyByte) {\n throw Errors.WRONG_PASSWORD();\n }\n\n // 4. decode content\n return decrypter(data.slice(12));\n}\n\n// lets add way to populate salt, NOT RECOMMENDED for production but maybe useful for testing general functionality\nfunction _salter(data) {\n if (Buffer.isBuffer(data) && data.length >= 12) {\n // be aware - currently salting buffer data is modified\n config.genSalt = function () {\n return data.slice(0, 12);\n };\n } else if (data === \"node\") {\n // test salt generation with node random function\n config.genSalt = genSalt.node;\n } else {\n // if value is not acceptable config gets reset.\n config.genSalt = genSalt;\n }\n}\n\nfunction encrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd, /*Boolean*/ oldlike = false) {\n // 1. test data if data is not Buffer we make buffer from it\n if (data == null) data = Buffer.alloc(0);\n // if data is not buffer be make buffer from it\n if (!Buffer.isBuffer(data)) data = Buffer.from(data.toString());\n\n // 2. We Initialize and generate encrypting function\n const encrypter = make_encrypter(pwd);\n\n // 3. generate salt (12-bytes of random data)\n const salt = config.genSalt();\n salt[11] = (header.crc >>> 24) & 0xff;\n\n // old implementations (before PKZip 2.04g) used two byte check\n if (oldlike) salt[10] = (header.crc >>> 16) & 0xff;\n\n // 4. create output\n const result = Buffer.alloc(data.length + 12);\n encrypter(salt, result);\n\n // finally encode content\n return encrypter(data, result, 12);\n}\n\nmodule.exports = { decrypt, encrypt, _salter };\n", "exports.Deflater = require(\"./deflater\");\nexports.Inflater = require(\"./inflater\");\nexports.ZipCrypto = require(\"./zipcrypto\");\n", "var Utils = require(\"./util\"),\n Headers = require(\"./headers\"),\n Constants = Utils.Constants,\n Methods = require(\"./methods\");\n\nmodule.exports = function (/** object */ options, /*Buffer*/ input) {\n var _centralHeader = new Headers.EntryHeader(),\n _entryName = Buffer.alloc(0),\n _comment = Buffer.alloc(0),\n _isDirectory = false,\n uncompressedData = null,\n _extra = Buffer.alloc(0),\n _extralocal = Buffer.alloc(0),\n _efs = true;\n\n // assign options\n const opts = options;\n\n const decoder = typeof opts.decoder === \"object\" ? opts.decoder : Utils.decoder;\n _efs = decoder.hasOwnProperty(\"efs\") ? decoder.efs : false;\n\n function getCompressedDataFromZip() {\n //if (!input || !Buffer.isBuffer(input)) {\n if (!input || !(input instanceof Uint8Array)) {\n return Buffer.alloc(0);\n }\n _extralocal = _centralHeader.loadLocalHeaderFromBinary(input);\n const dataOffset = _centralHeader.realDataOffset;\n const dataEnd = dataOffset + _centralHeader.compressedSize;\n // The offsets and sizes come from attacker-controlled headers. Require the\n // declared compressed extent to be fully present rather than letting slice()\n // silently clamp to a short buffer (which only surfaces later as a CRC\n // failure). Fail loudly with a header error instead (GHSA-wwrv-q5gf-5843).\n if (dataOffset < 0 || dataEnd < dataOffset || dataEnd > input.length) {\n throw Utils.Errors.INVALID_LOC();\n }\n return input.slice(dataOffset, dataEnd);\n }\n\n function crc32OK(data) {\n // When bit 3 (0x08) of the general-purpose flags is set, the crc-32 and\n // sizes were unknown when the local file header was written, so that\n // header carries placeholder zeros and the real values are repeated in a\n // data descriptor after the compressed data. adm-zip always parses the\n // central directory, whose header holds the authoritative crc-32 and\n // sizes, so we validate the payload against that value.\n //\n // Earlier versions instead located and parsed the trailing descriptor and\n // threw when it was absent or in an unexpected shape. Many valid archives\n // set the descriptor flag but write the real crc/sizes into the local and\n // central headers without emitting a descriptor (or write one we did not\n // recognise), so that strict handling rejected readable zips\n // (issues #533, #548, #554). Trusting the central-directory crc keeps the\n // integrity check while accepting those archives.\n const expectedCrc = _centralHeader.flags_desc || _centralHeader.localHeader.flags_desc ? _centralHeader.crc : _centralHeader.localHeader.crc;\n\n return Utils.crc32(data) === expectedCrc;\n }\n\n function decompress(/*Boolean*/ async, /*Function*/ callback, /*String, Buffer*/ pass) {\n if (typeof callback === \"undefined\" && typeof async === \"string\") {\n pass = async;\n async = void 0;\n }\n if (_isDirectory) {\n if (async && callback) {\n callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error.\n }\n return Buffer.alloc(0);\n }\n\n var compressedData;\n try {\n compressedData = getCompressedDataFromZip();\n\n if (compressedData.length === 0) {\n // File is empty, nothing to decompress.\n if (async && callback) callback(compressedData);\n return compressedData;\n }\n\n if (_centralHeader.encrypted) {\n if (\"string\" !== typeof pass && !Buffer.isBuffer(pass)) {\n throw Utils.Errors.INVALID_PASS_PARAM();\n }\n compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass);\n }\n } catch (err) {\n // These synchronous parse/setup steps run before any callback fires.\n // In async mode a malformed local header (e.g. a bad LOC offset) would\n // otherwise throw out of getDataAsync and bypass the callback error\n // channel, crashing the caller. Route it through the callback instead.\n if (async && callback) {\n callback(Buffer.alloc(0), err);\n return Buffer.alloc(0);\n }\n throw err;\n }\n\n var data;\n\n switch (_centralHeader.method) {\n case Utils.Constants.STORED:\n // STORED entries are not compressed, so the uncompressed output is\n // exactly the bytes present in the archive. Allocate from the real\n // data length rather than the attacker-declared central-directory\n // size, otherwise a tiny archive can declare a huge size and force a\n // multi-gigabyte allocation before any validation (CVE-2026-39244).\n data = Buffer.alloc(compressedData.length);\n compressedData.copy(data);\n if (!crc32OK(data)) {\n if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error\n throw Utils.Errors.BAD_CRC();\n } else {\n //si added otherwise did not seem to return data.\n if (async && callback) callback(data);\n return data;\n }\n case Utils.Constants.DEFLATED:\n // Do not pre-allocate the declared uncompressed size. The inflater\n // grows its output buffer as zlib emits data and caps the total at\n // the declared size (maxOutputLength), so a bogus size can no longer\n // trigger an eager allocation before the data is read (CVE-2026-39244).\n var inflater = new Methods.Inflater(compressedData, _centralHeader.size);\n if (!async) {\n data = inflater.inflate();\n if (!crc32OK(data)) {\n throw Utils.Errors.BAD_CRC(`\"${decoder.decode(_entryName)}\"`);\n }\n return data;\n } else {\n inflater.inflateAsync(function (result, err) {\n if (!callback) return;\n if (err) {\n // surface inflater/stream failures instead of validating\n // the empty placeholder buffer against the CRC\n callback(Buffer.alloc(0), err);\n } else if (!crc32OK(result)) {\n callback(result, Utils.Errors.BAD_CRC()); //si added error\n } else {\n callback(result);\n }\n });\n }\n break;\n default:\n if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD());\n throw Utils.Errors.UNKNOWN_METHOD();\n }\n }\n\n function compress(/*Boolean*/ async, /*Function*/ callback) {\n if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) {\n // no data set or the data wasn't changed to require recompression\n if (async && callback) callback(getCompressedDataFromZip());\n return getCompressedDataFromZip();\n }\n\n if (uncompressedData.length && !_isDirectory) {\n var compressedData;\n // Local file header\n switch (_centralHeader.method) {\n case Utils.Constants.STORED:\n _centralHeader.compressedSize = _centralHeader.size;\n\n compressedData = Buffer.alloc(uncompressedData.length);\n uncompressedData.copy(compressedData);\n\n if (async && callback) callback(compressedData);\n return compressedData;\n default:\n case Utils.Constants.DEFLATED:\n var deflater = new Methods.Deflater(uncompressedData);\n if (!async) {\n var deflated = deflater.deflate();\n _centralHeader.compressedSize = deflated.length;\n return deflated;\n } else {\n deflater.deflateAsync(function (data) {\n compressedData = Buffer.alloc(data.length);\n _centralHeader.compressedSize = data.length;\n data.copy(compressedData);\n callback && callback(compressedData);\n });\n }\n deflater = null;\n break;\n }\n } else if (async && callback) {\n callback(Buffer.alloc(0));\n } else {\n return Buffer.alloc(0);\n }\n }\n\n function readUInt64LE(buffer, offset) {\n return Utils.readBigUInt64LE(buffer, offset);\n }\n\n function parseExtra(data) {\n try {\n var offset = 0;\n var signature, size, part;\n while (offset + 4 < data.length) {\n signature = data.readUInt16LE(offset);\n offset += 2;\n size = data.readUInt16LE(offset);\n offset += 2;\n part = data.slice(offset, offset + size);\n offset += size;\n if (Constants.ID_ZIP64 === signature) {\n parseZip64ExtendedInformation(part);\n }\n }\n } catch (error) {\n throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR();\n }\n }\n\n //Override header field values with values from the ZIP64 extra field\n function parseZip64ExtendedInformation(data) {\n var size, compressedSize, offset, diskNumStart;\n\n if (data.length >= Constants.EF_ZIP64_SCOMP) {\n size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);\n if (_centralHeader.size === Constants.EF_ZIP64_OR_32) {\n _centralHeader.size = size;\n }\n }\n if (data.length >= Constants.EF_ZIP64_RHO) {\n compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP);\n if (_centralHeader.compressedSize === Constants.EF_ZIP64_OR_32) {\n _centralHeader.compressedSize = compressedSize;\n }\n }\n if (data.length >= Constants.EF_ZIP64_DSN) {\n offset = readUInt64LE(data, Constants.EF_ZIP64_RHO);\n if (_centralHeader.offset === Constants.EF_ZIP64_OR_32) {\n _centralHeader.offset = offset;\n }\n }\n if (data.length >= Constants.EF_ZIP64_DSN + 4) {\n diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN);\n if (_centralHeader.diskNumStart === Constants.EF_ZIP64_OR_16) {\n _centralHeader.diskNumStart = diskNumStart;\n }\n }\n }\n\n return {\n get entryName() {\n return decoder.decode(_entryName);\n },\n get rawEntryName() {\n return _entryName;\n },\n set entryName(val) {\n _entryName = Utils.toBuffer(val, decoder.encode);\n var lastChar = _entryName[_entryName.length - 1];\n _isDirectory = lastChar === 47 || lastChar === 92;\n _centralHeader.fileNameLength = _entryName.length;\n },\n\n get efs() {\n if (typeof _efs === \"function\") {\n return _efs(this.entryName);\n } else {\n return _efs;\n }\n },\n\n get extra() {\n return _extra;\n },\n set extra(val) {\n _extra = val;\n _centralHeader.extraLength = val.length;\n parseExtra(val);\n },\n\n get comment() {\n return decoder.decode(_comment);\n },\n set comment(val) {\n _comment = Utils.toBuffer(val, decoder.encode);\n _centralHeader.commentLength = _comment.length;\n if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG();\n },\n\n get name() {\n const n = decoder.decode(_entryName);\n // For directories the name is the last path segment; drop the trailing\n // separator first so \"a/b/c/\" yields \"c\" and not \"\" (issue #466).\n return _isDirectory\n ? n\n .replace(/[/\\\\]$/, \"\")\n .split(\"/\")\n .pop()\n : n.split(\"/\").pop();\n },\n get isDirectory() {\n return _isDirectory;\n },\n\n getCompressedData: function () {\n return compress(false, null);\n },\n\n getCompressedDataAsync: function (/*Function*/ callback) {\n compress(true, callback);\n },\n\n setData: function (value) {\n uncompressedData = Utils.toBuffer(value, Utils.decoder.encode);\n if (!_isDirectory && uncompressedData.length) {\n _centralHeader.size = uncompressedData.length;\n _centralHeader.method = Utils.Constants.DEFLATED;\n _centralHeader.crc = Utils.crc32(value);\n _centralHeader.changed = true;\n } else {\n // folders and blank files should be stored\n _centralHeader.method = Utils.Constants.STORED;\n }\n },\n\n getData: function (pass) {\n if (_centralHeader.changed) {\n return uncompressedData;\n } else {\n return decompress(false, null, pass);\n }\n },\n\n getDataAsync: function (/*Function*/ callback, pass) {\n if (_centralHeader.changed) {\n callback(uncompressedData);\n } else {\n decompress(true, callback, pass);\n }\n },\n\n set attr(attr) {\n _centralHeader.attr = attr;\n },\n get attr() {\n return _centralHeader.attr;\n },\n\n set header(/*Buffer*/ data) {\n _centralHeader.loadFromBinary(data);\n },\n\n get header() {\n return _centralHeader;\n },\n\n packCentralHeader: function () {\n _centralHeader.flags_efs = this.efs;\n _centralHeader.extraLength = _extra.length;\n // 1. create header (buffer)\n var header = _centralHeader.centralHeaderToBinary();\n var addpos = Utils.Constants.CENHDR;\n // 2. add file name\n _entryName.copy(header, addpos);\n addpos += _entryName.length;\n // 3. add extra data\n _extra.copy(header, addpos);\n addpos += _centralHeader.extraLength;\n // 4. add file comment\n _comment.copy(header, addpos);\n return header;\n },\n\n packLocalHeader: function () {\n let addpos = 0;\n _centralHeader.flags_efs = this.efs;\n _centralHeader.extraLocalLength = _extralocal.length;\n // 1. construct local header Buffer\n const localHeaderBuf = _centralHeader.localHeaderToBinary();\n // 2. localHeader - crate header buffer\n const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength);\n // 2.1 add localheader\n localHeaderBuf.copy(localHeader, addpos);\n addpos += localHeaderBuf.length;\n // 2.2 add file name\n _entryName.copy(localHeader, addpos);\n addpos += _entryName.length;\n // 2.3 add extra field\n _extralocal.copy(localHeader, addpos);\n addpos += _extralocal.length;\n\n return localHeader;\n },\n\n toJSON: function () {\n const bytes = function (nr) {\n return \"<\" + ((nr && nr.length + \" bytes buffer\") || \"null\") + \">\";\n };\n\n return {\n entryName: this.entryName,\n name: this.name,\n comment: this.comment,\n isDirectory: this.isDirectory,\n header: _centralHeader.toJSON(),\n compressedData: bytes(input),\n data: bytes(uncompressedData)\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n", "const ZipEntry = require(\"./zipEntry\");\nconst Headers = require(\"./headers\");\nconst Utils = require(\"./util\");\n\nmodule.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) {\n var entryList = [],\n // prototype-less: entry names come from untrusted input, so keys like\n // \"__proto__\" or \"constructor\" must be plain data, not touch the prototype\n // chain (which otherwise crashes addFile and hides such entries)\n entryTable = Object.create(null),\n _comment = Buffer.alloc(0),\n mainHeader = new Headers.MainHeader(),\n loadedEntries = false;\n var password = null;\n const temporary = new Set();\n\n // assign options\n const opts = options;\n\n const { noSort, decoder } = opts;\n\n if (inBuffer) {\n // is a memory buffer\n readMainHeader(opts.readEntries);\n } else {\n // none. is a new file\n loadedEntries = true;\n }\n\n function makeTemporaryFolders() {\n const foldersList = new Set();\n\n // Make list of all folders in file\n for (const elem of Object.keys(entryTable)) {\n const elements = elem.split(\"/\");\n elements.pop(); // filename\n if (!elements.length) continue; // no folders\n for (let i = 0; i < elements.length; i++) {\n const sub = elements.slice(0, i + 1).join(\"/\") + \"/\";\n foldersList.add(sub);\n }\n }\n\n // create missing folders as temporary\n for (const elem of foldersList) {\n if (!(elem in entryTable)) {\n const tempfolder = new ZipEntry(opts);\n tempfolder.entryName = elem;\n tempfolder.attr = 0x10;\n tempfolder.temporary = true;\n entryList.push(tempfolder);\n entryTable[tempfolder.entryName] = tempfolder;\n temporary.add(tempfolder);\n }\n }\n }\n\n function readEntries() {\n loadedEntries = true;\n entryTable = Object.create(null);\n if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) {\n throw Utils.Errors.DISK_ENTRY_TOO_LARGE();\n }\n entryList = new Array(mainHeader.diskEntries); // total number of entries\n var index = mainHeader.offset; // offset of first CEN header\n for (var i = 0; i < entryList.length; i++) {\n var tmp = index,\n entry = new ZipEntry(opts, inBuffer);\n entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR));\n\n entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength));\n\n if (entry.header.extraLength) {\n entry.extra = inBuffer.slice(tmp, (tmp += entry.header.extraLength));\n }\n\n if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);\n\n index += entry.header.centralHeaderSize;\n\n // Reject archives that declare the same entry name twice. adm-zip keeps\n // every entry in entryList but only the last in entryTable, so getEntry()\n // (table) and extractAllTo() (list) could resolve one name to different\n // content: an app that validates entry bytes via getEntry() before\n // extracting could approve one file while a different one lands on disk\n // (GHSA-p634-w6r4-rjp2). Fail closed on the ambiguity.\n if (entry.entryName in entryTable) {\n throw Utils.Errors.DUPLICATE_ENTRY(`\"${entry.entryName}\"`);\n }\n\n entryList[i] = entry;\n entryTable[entry.entryName] = entry;\n }\n temporary.clear();\n makeTemporaryFolders();\n }\n\n function readMainHeader(/*Boolean*/ readNow) {\n var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size\n max = Math.max(0, i - 0xffff), // 0xFFFF is the max zip file comment length\n n = max,\n endStart = inBuffer.length,\n endOffset = -1, // Start offset of the END header\n commentEnd = 0;\n\n // option to search header form entire file\n const trailingSpace = typeof opts.trailingSpace === \"boolean\" ? opts.trailingSpace : false;\n if (trailingSpace) max = 0;\n\n for (i; i >= n; i--) {\n if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P'\n if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) {\n // \"PK\\005\\006\"\n endOffset = i;\n commentEnd = i;\n endStart = i + Utils.Constants.ENDHDR;\n // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature\n n = i - Utils.Constants.END64HDR;\n continue;\n }\n\n if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) {\n // Found a zip64 signature, let's continue reading the whole zip64 record\n n = max;\n continue;\n }\n\n if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) {\n // Found the zip64 record, let's determine it's size\n endOffset = i;\n endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD;\n break;\n }\n }\n\n if (endOffset == -1) throw Utils.Errors.INVALID_FORMAT();\n\n mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart));\n if (mainHeader.commentLength) {\n _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR);\n }\n if (readNow) readEntries();\n }\n\n function sortEntries() {\n if (entryList.length > 1 && !noSort) {\n // Decode + lowercase each name once rather than on every comparison:\n // the entryName getter re-decodes the underlying buffer on each access,\n // so the previous inline comparator did O(n log n) redundant decoding.\n // Ordering is unchanged (same localeCompare on the same keys).\n entryList = entryList\n .map((entry) => ({ entry, key: entry.entryName.toLowerCase() }))\n .sort((a, b) => a.key.localeCompare(b.key))\n .map((pair) => pair.entry);\n }\n }\n\n return {\n /**\n * Returns an array of ZipEntry objects existent in the current opened archive\n * @return Array\n */\n get entries() {\n if (!loadedEntries) {\n readEntries();\n }\n return entryList.filter((e) => !temporary.has(e));\n },\n\n /**\n * Archive comment\n * @return {String}\n */\n get comment() {\n return decoder.decode(_comment);\n },\n set comment(val) {\n _comment = Utils.toBuffer(val, decoder.encode);\n mainHeader.commentLength = _comment.length;\n },\n\n getEntryCount: function () {\n if (!loadedEntries) {\n return mainHeader.diskEntries;\n }\n\n return entryList.length;\n },\n\n forEach: function (callback) {\n this.entries.forEach(callback);\n },\n\n /**\n * Returns a reference to the entry with the given name or null if entry is inexistent\n *\n * @param entryName\n * @return ZipEntry\n */\n getEntry: function (/*String*/ entryName) {\n if (!loadedEntries) {\n readEntries();\n }\n return entryTable[entryName] || null;\n },\n\n /**\n * Adds the given entry to the entry list\n *\n * @param entry\n */\n setEntry: function (/*ZipEntry*/ entry) {\n if (!loadedEntries) {\n readEntries();\n }\n entryList.push(entry);\n entryTable[entry.entryName] = entry;\n mainHeader.totalEntries = entryList.length;\n },\n\n /**\n * Removes the file with the given name from the entry list.\n *\n * If the entry is a directory, then all nested files and directories will be removed\n * @param entryName\n * @returns {void}\n */\n deleteFile: function (/*String*/ entryName, withsubfolders = true) {\n if (!loadedEntries) {\n readEntries();\n }\n const entry = entryTable[entryName];\n const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName);\n\n list.forEach(this.deleteEntry);\n },\n\n /**\n * Removes the entry with the given name from the entry list.\n *\n * @param {string} entryName\n * @returns {void}\n */\n deleteEntry: function (/*String*/ entryName) {\n if (!loadedEntries) {\n readEntries();\n }\n const entry = entryTable[entryName];\n const index = entryList.indexOf(entry);\n if (index >= 0) {\n entryList.splice(index, 1);\n delete entryTable[entryName];\n mainHeader.totalEntries = entryList.length;\n }\n },\n\n /**\n * Iterates and returns all nested files and directories of the given entry\n *\n * @param entry\n * @return Array\n */\n getEntryChildren: function (/*ZipEntry*/ entry, subfolders = true) {\n if (!loadedEntries) {\n readEntries();\n }\n if (typeof entry === \"object\") {\n if (entry.isDirectory && subfolders) {\n const list = [];\n const name = entry.entryName;\n\n for (const zipEntry of entryList) {\n if (zipEntry.entryName.startsWith(name)) {\n list.push(zipEntry);\n }\n }\n return list;\n } else {\n return [entry];\n }\n }\n return [];\n },\n\n /**\n * How many child elements entry has\n *\n * @param {ZipEntry} entry\n * @return {integer}\n */\n getChildCount: function (entry) {\n if (entry && entry.isDirectory) {\n const list = this.getEntryChildren(entry);\n return list.includes(entry) ? list.length - 1 : list.length;\n }\n return 0;\n },\n\n /**\n * Returns the zip file\n *\n * @return Buffer\n */\n compressToBuffer: function () {\n if (!loadedEntries) {\n readEntries();\n }\n sortEntries();\n\n const dataBlock = [];\n const headerBlocks = [];\n let totalSize = 0;\n let dindex = 0;\n\n mainHeader.size = 0;\n mainHeader.offset = 0;\n let totalEntries = 0;\n\n for (const entry of this.entries) {\n // compress data and set local and entry header accordingly. Reason why is called first\n const compressedData = entry.getCompressedData();\n entry.header.offset = dindex;\n\n // 1. construct local header\n const localHeader = entry.packLocalHeader();\n\n // 2. offsets\n const dataLength = localHeader.length + compressedData.length;\n dindex += dataLength;\n\n // 3. store values in sequence\n dataBlock.push(localHeader);\n dataBlock.push(compressedData);\n\n // 4. construct central header\n const centralHeader = entry.packCentralHeader();\n headerBlocks.push(centralHeader);\n // 5. update main header\n mainHeader.size += centralHeader.length;\n totalSize += dataLength + centralHeader.length;\n totalEntries++;\n }\n\n totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length\n // point to end of data and beginning of central directory first record\n mainHeader.offset = dindex;\n mainHeader.totalEntries = totalEntries;\n\n dindex = 0;\n const outBuffer = Buffer.alloc(totalSize);\n // write data blocks\n for (const content of dataBlock) {\n content.copy(outBuffer, dindex);\n dindex += content.length;\n }\n\n // write central directory entries\n for (const content of headerBlocks) {\n content.copy(outBuffer, dindex);\n dindex += content.length;\n }\n\n // write main header\n const mh = mainHeader.toBinary();\n if (_comment) {\n _comment.copy(mh, mh.length - _comment.length); // add zip file comment\n }\n mh.copy(outBuffer, dindex);\n\n // Since we update entry and main header offsets,\n // they are no longer valid and we have to reset content\n // (Issue 64)\n\n inBuffer = outBuffer;\n loadedEntries = false;\n\n return outBuffer;\n },\n\n toAsyncBuffer: function (/*Function*/ onSuccess, /*Function*/ onFail, /*Function*/ onItemStart, /*Function*/ onItemEnd) {\n try {\n if (!loadedEntries) {\n readEntries();\n }\n sortEntries();\n\n const dataBlock = [];\n const centralHeaders = [];\n let totalSize = 0;\n let dindex = 0;\n let totalEntries = 0;\n\n mainHeader.size = 0;\n mainHeader.offset = 0;\n\n const compress2Buffer = function (entryLists) {\n if (entryLists.length > 0) {\n const entry = entryLists.shift();\n const name = entry.entryName + entry.extra.toString();\n if (onItemStart) onItemStart(name);\n entry.getCompressedDataAsync(function (compressedData) {\n if (onItemEnd) onItemEnd(name);\n entry.header.offset = dindex;\n\n // 1. construct local header\n const localHeader = entry.packLocalHeader();\n\n // 2. offsets\n const dataLength = localHeader.length + compressedData.length;\n dindex += dataLength;\n\n // 3. store values in sequence\n dataBlock.push(localHeader);\n dataBlock.push(compressedData);\n\n // central header\n const centalHeader = entry.packCentralHeader();\n centralHeaders.push(centalHeader);\n mainHeader.size += centalHeader.length;\n totalSize += dataLength + centalHeader.length;\n totalEntries++;\n\n compress2Buffer(entryLists);\n });\n } else {\n totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length\n // point to end of data and beginning of central directory first record\n mainHeader.offset = dindex;\n mainHeader.totalEntries = totalEntries;\n\n dindex = 0;\n const outBuffer = Buffer.alloc(totalSize);\n dataBlock.forEach(function (content) {\n content.copy(outBuffer, dindex); // write data blocks\n dindex += content.length;\n });\n centralHeaders.forEach(function (content) {\n content.copy(outBuffer, dindex); // write central directory entries\n dindex += content.length;\n });\n\n const mh = mainHeader.toBinary();\n if (_comment) {\n _comment.copy(mh, mh.length - _comment.length); // add zip file comment\n }\n\n mh.copy(outBuffer, dindex); // write main header\n\n // Since we update entry and main header offsets, they are no\n // longer valid and we have to reset content using our new buffer\n // (Issue 64)\n\n inBuffer = outBuffer;\n loadedEntries = false;\n\n onSuccess(outBuffer);\n }\n };\n\n compress2Buffer(Array.from(this.entries));\n } catch (e) {\n onFail(e);\n }\n }\n };\n};\n", "const Utils = require(\"./util\");\nconst pth = require(\"path\");\nconst ZipEntry = require(\"./zipEntry\");\nconst ZipFile = require(\"./zipFile\");\n\nconst get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === \"boolean\");\nconst get_Str = (...val) => Utils.findLast(val, (c) => typeof c === \"string\");\nconst get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === \"function\");\n\nconst defaultOptions = {\n // option \"noSort\" : if true it disables files sorting\n noSort: false,\n // read entries during load (initial loading may be slower)\n readEntries: false,\n // default method is none\n method: Utils.Constants.NONE,\n // file system\n fs: null\n};\n\nmodule.exports = function (/**String*/ input, /** object */ options) {\n let inBuffer = null;\n\n // create object based default options, allowing them to be overwritten\n const opts = Object.assign(Object.create(null), defaultOptions);\n\n // test input variable\n if (input && \"object\" === typeof input) {\n // if value is not buffer we accept it to be object with options\n if (!(input instanceof Uint8Array)) {\n Object.assign(opts, input);\n input = opts.input ? opts.input : undefined;\n if (opts.input) delete opts.input;\n }\n\n // if input is buffer\n if (Buffer.isBuffer(input)) {\n inBuffer = input;\n opts.method = Utils.Constants.BUFFER;\n input = undefined;\n }\n }\n\n // assign options\n Object.assign(opts, options);\n\n // instanciate utils filesystem\n const filetools = new Utils(opts);\n\n // Restore the archived permissions on extracted directories. This has to run\n // after a directory's contents are written: applying a restrictive mode\n // (e.g. 0o500) up front would stop us writing the files it contains. Applying\n // the deepest paths first keeps parent directories traversable while their\n // children are updated (issue #530).\n const applyDirAttributes = (dirEntries) => {\n dirEntries\n .filter((d) => d.attr)\n .sort((a, b) => b.path.length - a.path.length)\n .forEach((d) => filetools.fs.chmodSync(d.path, d.attr));\n };\n\n if (typeof opts.decoder !== \"object\" || typeof opts.decoder.encode !== \"function\" || typeof opts.decoder.decode !== \"function\") {\n opts.decoder = Utils.decoder;\n }\n\n // if input is file name we retrieve its content\n if (input && \"string\" === typeof input) {\n // load zip file\n if (filetools.fs.existsSync(input)) {\n opts.method = Utils.Constants.FILE;\n opts.filename = input;\n inBuffer = filetools.fs.readFileSync(input);\n } else {\n throw Utils.Errors.INVALID_FILENAME();\n }\n }\n\n // create variable\n const _zip = new ZipFile(inBuffer, opts);\n\n const { canonical, sanitize, zipnamefix } = Utils;\n\n function getEntry(/**Object*/ entry) {\n if (entry && _zip) {\n var item;\n // If entry was given as a file name\n if (typeof entry === \"string\") item = _zip.getEntry(pth.posix.normalize(entry));\n // if entry was given as a ZipEntry object\n if (typeof entry === \"object\" && typeof entry.entryName !== \"undefined\" && typeof entry.header !== \"undefined\") item = _zip.getEntry(entry.entryName);\n\n if (item) {\n return item;\n }\n }\n return null;\n }\n\n function fixPath(zipPath) {\n const { join, normalize, sep } = pth.posix;\n // convert windows file separators and normalize\n return join(pth.isAbsolute(zipPath) ? \"/\": '.', normalize(sep + zipPath.split(\"\\\\\").join(sep) + sep));\n }\n\n function filenameFilter(filterfn) {\n if (filterfn instanceof RegExp) {\n // if filter is RegExp wrap it\n return (function (rx) {\n return function (filename) {\n return rx.test(filename);\n };\n })(filterfn);\n } else if (\"function\" !== typeof filterfn) {\n // if filter is not function we will replace it\n return () => true;\n }\n return filterfn;\n }\n\n // keep last character on folders\n const relativePath = (local, entry) => {\n let lastChar = entry.slice(-1);\n lastChar = lastChar === filetools.sep ? filetools.sep : \"\";\n return pth.relative(local, entry) + lastChar;\n };\n\n return {\n /**\n * Extracts the given entry from the archive and returns the content as a Buffer object\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {Buffer|string} [pass] - password\n * @return Buffer or Null in case of error\n */\n readFile: function (entry, pass) {\n var item = getEntry(entry);\n return (item && item.getData(pass)) || null;\n },\n\n /**\n * Returns how many child elements has on entry (directories) on files it is always 0\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @returns {integer}\n */\n childCount: function (entry) {\n const item = getEntry(entry);\n if (item) {\n return _zip.getChildCount(item);\n }\n },\n\n /**\n * Asynchronous readFile\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {callback} callback\n *\n * @return Buffer or Null in case of error\n */\n readFileAsync: function (entry, callback) {\n var item = getEntry(entry);\n if (item) {\n item.getDataAsync(callback);\n } else {\n callback(null, \"getEntry failed for:\" + entry);\n }\n },\n\n /**\n * Extracts the given entry from the archive and returns the content as plain text in the given encoding\n * @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry\n * @param {string} encoding - Optional. If no encoding is specified utf8 is used\n *\n * @return String\n */\n readAsText: function (entry, encoding) {\n var item = getEntry(entry);\n if (item) {\n var data = item.getData();\n if (data && data.length) {\n return data.toString(encoding || \"utf8\");\n }\n }\n return \"\";\n },\n\n /**\n * Asynchronous readAsText\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {callback} callback\n * @param {string} [encoding] - Optional. If no encoding is specified utf8 is used\n *\n * @return String\n */\n readAsTextAsync: function (entry, callback, encoding) {\n var item = getEntry(entry);\n if (item) {\n item.getDataAsync(function (data, err) {\n if (err) {\n callback(data, err);\n return;\n }\n\n if (data && data.length) {\n callback(data.toString(encoding || \"utf8\"));\n } else {\n callback(\"\");\n }\n });\n } else {\n callback(\"\");\n }\n },\n\n /**\n * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory\n *\n * @param {ZipEntry|string} entry\n * @param {boolean} withsubfolders\n * @returns {void}\n */\n deleteFile: function (entry, withsubfolders = true) {\n // @TODO: test deleteFile\n var item = getEntry(entry);\n if (item) {\n _zip.deleteFile(item.entryName, withsubfolders);\n }\n },\n\n /**\n * Remove the entry from the file or directory without affecting any nested entries\n *\n * @param {ZipEntry|string} entry\n * @returns {void}\n */\n deleteEntry: function (entry) {\n // @TODO: test deleteEntry\n var item = getEntry(entry);\n if (item) {\n _zip.deleteEntry(item.entryName);\n }\n },\n\n /**\n * Adds a comment to the zip. The zip must be rewritten after adding the comment.\n *\n * @param {string} comment\n */\n addZipComment: function (comment) {\n // @TODO: test addZipComment\n _zip.comment = comment;\n },\n\n /**\n * Returns the zip comment\n *\n * @return String\n */\n getZipComment: function () {\n return _zip.comment || \"\";\n },\n\n /**\n * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment\n * The comment cannot exceed 65535 characters in length\n *\n * @param {ZipEntry} entry\n * @param {string} comment\n */\n addZipEntryComment: function (entry, comment) {\n var item = getEntry(entry);\n if (item) {\n item.comment = comment;\n }\n },\n\n /**\n * Returns the comment of the specified entry\n *\n * @param {ZipEntry} entry\n * @return String\n */\n getZipEntryComment: function (entry) {\n var item = getEntry(entry);\n if (item) {\n return item.comment || \"\";\n }\n return \"\";\n },\n\n /**\n * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content\n *\n * @param {ZipEntry} entry\n * @param {Buffer} content\n */\n updateFile: function (entry, content) {\n var item = getEntry(entry);\n if (item) {\n item.setData(content);\n }\n },\n\n /**\n * Adds a file from the disk to the archive\n *\n * @param {string} localPath File to add to zip\n * @param {string} [zipPath] Optional path inside the zip\n * @param {string} [zipName] Optional name for the file\n * @param {string} [comment] Optional file comment\n */\n addLocalFile: function (localPath, zipPath, zipName, comment) {\n if (filetools.fs.existsSync(localPath)) {\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // p - local file name\n const p = pth.win32.basename(pth.win32.normalize(localPath));\n\n // add file name into zippath\n zipPath += zipName ? zipName : p;\n\n // read file attributes\n const _attr = filetools.fs.statSync(localPath);\n\n // get file content\n const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0);\n\n // if folder\n if (_attr.isDirectory()) zipPath += filetools.sep;\n\n // add file into zip file\n this.addFile(zipPath, data, comment, _attr);\n } else {\n throw Utils.Errors.FILE_NOT_FOUND(localPath);\n }\n },\n\n /**\n * Callback for showing if everything was done.\n *\n * @callback doneCallback\n * @param {Error} err - Error object\n * @param {boolean} done - was request fully completed\n */\n\n /**\n * Adds a file from the disk to the archive\n *\n * @param {(object|string)} options - options object, if it is string it us used as localPath.\n * @param {string} options.localPath - Local path to the file.\n * @param {string} [options.comment] - Optional file comment.\n * @param {string} [options.zipPath] - Optional path inside the zip\n * @param {string} [options.zipName] - Optional name for the file\n * @param {doneCallback} callback - The callback that handles the response.\n */\n addLocalFileAsync: function (options, callback) {\n options = typeof options === \"object\" ? options : { localPath: options };\n const localPath = pth.resolve(options.localPath);\n const { comment } = options;\n let { zipPath, zipName } = options;\n const self = this;\n\n filetools.fs.stat(localPath, function (err, stats) {\n if (err) return callback(err, false);\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n // p - local file name\n const p = pth.win32.basename(pth.win32.normalize(localPath));\n // add file name into zippath\n zipPath += zipName ? zipName : p;\n\n if (stats.isFile()) {\n filetools.fs.readFile(localPath, function (err, data) {\n if (err) return callback(err, false);\n self.addFile(zipPath, data, comment, stats);\n return setImmediate(callback, undefined, true);\n });\n } else if (stats.isDirectory()) {\n zipPath += filetools.sep;\n self.addFile(zipPath, Buffer.alloc(0), comment, stats);\n return setImmediate(callback, undefined, true);\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {string} localPath - local path to the folder\n * @param {string} [zipPath] - optional path inside zip\n * @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included.\n */\n addLocalFolder: function (localPath, zipPath, filter) {\n // Prepare filter\n filter = filenameFilter(filter);\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // normalize the path first\n localPath = pth.normalize(localPath);\n\n if (filetools.fs.existsSync(localPath)) {\n const items = filetools.findFiles(localPath);\n const self = this;\n\n if (items.length) {\n for (const filepath of items) {\n const p = pth.join(zipPath, relativePath(localPath, filepath));\n if (filter(p)) {\n self.addLocalFile(filepath, pth.dirname(p));\n }\n }\n }\n } else {\n throw Utils.Errors.FILE_NOT_FOUND(localPath);\n }\n },\n\n /**\n * Asynchronous addLocalFolder\n * @param {string} localPath\n * @param {callback} callback\n * @param {string} [zipPath] optional path inside zip\n * @param {RegExp|function} [filter] optional RegExp or Function if files match will\n * be included.\n */\n addLocalFolderAsync: function (localPath, callback, zipPath, filter) {\n // Prepare filter\n filter = filenameFilter(filter);\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // normalize the path first\n localPath = pth.normalize(localPath);\n\n var self = this;\n filetools.fs.open(localPath, \"r\", function (err) {\n if (err && err.code === \"ENOENT\") {\n callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));\n } else if (err) {\n callback(undefined, err);\n } else {\n var items = filetools.findFiles(localPath);\n var i = -1;\n\n var next = function () {\n i += 1;\n if (i < items.length) {\n var filepath = items[i];\n var p = relativePath(localPath, filepath).split(\"\\\\\").join(\"/\"); //windows fix\n p = p\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/[^\\x20-\\x7E]/g, \"\"); // accent fix\n if (filter(p)) {\n filetools.fs.stat(filepath, function (er0, stats) {\n if (er0) callback(undefined, er0);\n if (stats.isFile()) {\n filetools.fs.readFile(filepath, function (er1, data) {\n if (er1) {\n callback(undefined, er1);\n } else {\n self.addFile(zipPath + p, data, \"\", stats);\n next();\n }\n });\n } else {\n self.addFile(zipPath + p + \"/\", Buffer.alloc(0), \"\", stats);\n next();\n }\n });\n } else {\n process.nextTick(() => {\n next();\n });\n }\n } else {\n callback(true, undefined);\n }\n };\n\n next();\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {object | string} options - options object, if it is string it us used as localPath.\n * @param {string} options.localPath - Local path to the folder.\n * @param {string} [options.zipPath] - optional path inside zip.\n * @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included.\n * @param {function|string} [options.namefix] - optional function to help fix filename\n * @param {doneCallback} callback - The callback that handles the response.\n *\n */\n addLocalFolderAsync2: function (options, callback) {\n const self = this;\n options = typeof options === \"object\" ? options : { localPath: options };\n // Resolve the local filesystem path with the platform resolver. Do NOT\n // run it through fixPath: that normalizes ZIP-internal paths to POSIX\n // and prepends \"/\", which turns a Windows path like C:\\dir into\n // \\C:\\dir, so readdir finds nothing and the archive comes out empty.\n const localPath = pth.resolve(options.localPath);\n let { zipPath, filter, namefix } = options;\n\n if (filter instanceof RegExp) {\n filter = (function (rx) {\n return function (filename) {\n return rx.test(filename);\n };\n })(filter);\n } else if (\"function\" !== typeof filter) {\n filter = function () {\n return true;\n };\n }\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // Check Namefix function\n if (namefix === \"latin1\") {\n namefix = (str) =>\n str\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/[^\\x20-\\x7E]/g, \"\"); // accent fix (latin1 characers only)\n }\n\n if (typeof namefix !== \"function\") namefix = (str) => str;\n\n // internal, create relative path + fix the name\n const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry)));\n const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry)));\n\n filetools.fs.open(localPath, \"r\", function (err) {\n if (err && err.code === \"ENOENT\") {\n // callback is (err, done); errors belong in the first argument,\n // otherwise addLocalFolderPromise treats the error as \"done\" and\n // resolves instead of rejecting.\n callback(Utils.Errors.FILE_NOT_FOUND(localPath), false);\n } else if (err) {\n callback(err, false);\n } else {\n filetools.findFilesAsync(localPath, function (err, fileEntries) {\n if (err) return callback(err, false);\n fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir)));\n // Nothing to add (empty folder or everything filtered out) is a\n // success, not an error. Report done and stop, otherwise the\n // reduce below runs and the callback fires a second time -- and\n // signalling done=false left addLocalFolderPromise hanging.\n if (!fileEntries.length) return callback(undefined, true);\n\n setImmediate(\n fileEntries.reverse().reduce(function (next, entry) {\n return function (err, done) {\n if (err || done === false) return setImmediate(next, err, false);\n\n self.addLocalFileAsync(\n {\n localPath: entry,\n zipPath: pth.dirname(relPathFix(entry)),\n zipName: fileNameFix(entry)\n },\n next\n );\n };\n }, callback)\n );\n });\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {string} localPath - path where files will be extracted\n * @param {object} props - optional properties\n * @param {string} [props.zipPath] - optional path inside zip\n * @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included.\n * @param {function|string} [props.namefix] - optional function to help fix filename\n */\n addLocalFolderPromise: function (localPath, props) {\n return new Promise((resolve, reject) => {\n this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => {\n if (err) return reject(err);\n if (done) resolve(this);\n });\n });\n },\n\n /**\n * Allows you to create a entry (file or directory) in the zip file.\n * If you want to create a directory the entryName must end in / and a null buffer should be provided.\n * Comment and attributes are optional\n *\n * @param {string} entryName\n * @param {Buffer | string} content - file content as buffer or utf8 coded string\n * @param {string} [comment] - file comment\n * @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object\n */\n addFile: function (entryName, content, comment, attr) {\n entryName = zipnamefix(entryName);\n let entry = getEntry(entryName);\n const update = entry != null;\n\n // prepare new entry\n if (!update) {\n entry = new ZipEntry(opts);\n entry.entryName = entryName;\n }\n entry.comment = comment || \"\";\n\n const isStat = \"object\" === typeof attr && attr instanceof filetools.fs.Stats;\n\n // last modification time from file stats\n if (isStat) {\n entry.header.time = attr.mtime;\n }\n\n // Set file attribute\n var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag)\n\n // extended attributes field for Unix\n // set file type either S_IFDIR / S_IFREG\n let unix = entry.isDirectory ? 0x4000 : 0x8000;\n\n if (isStat) {\n // File attributes from file stats\n unix |= 0xfff & attr.mode;\n } else if (\"number\" === typeof attr) {\n // attr from given attr values\n unix |= 0xfff & attr;\n } else {\n // Default values:\n unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--)\n }\n\n fileattr = (fileattr | (unix << 16)) >>> 0; // add attributes\n\n entry.attr = fileattr;\n\n entry.setData(content);\n if (!update) _zip.setEntry(entry);\n\n return entry;\n },\n\n /**\n * Returns an array of ZipEntry objects representing the files and folders inside the archive\n *\n * @param {string} [password]\n * @returns Array\n */\n getEntries: function (password) {\n _zip.password = password;\n return _zip ? _zip.entries : [];\n },\n\n /**\n * Returns a ZipEntry object representing the file or folder specified by ``name``.\n *\n * @param {string} name\n * @return ZipEntry\n */\n getEntry: function (/**String*/ name) {\n return getEntry(name);\n },\n\n getEntryCount: function () {\n return _zip.getEntryCount();\n },\n\n forEach: function (callback) {\n return _zip.forEach(callback);\n },\n\n /**\n * Extracts the given entry to the given targetPath\n * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted\n *\n * @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry\n * @param {string} targetPath - Target folder where to write the file\n * @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE\n * @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true.\n * @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true.\n * @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file)\n *\n * @return Boolean\n */\n extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) {\n overwrite = get_Bool(false, overwrite);\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n maintainEntryPath = get_Bool(true, maintainEntryPath);\n outFileName = get_Str(keepOriginalPermission, outFileName);\n\n var item = getEntry(entry);\n if (!item) {\n throw Utils.Errors.NO_ENTRY();\n }\n\n var entryName = canonical(item.entryName);\n\n var target = sanitize(targetPath, outFileName && !item.isDirectory ? canonical(outFileName) : maintainEntryPath ? entryName : pth.basename(entryName));\n\n if (item.isDirectory) {\n var children = _zip.getEntryChildren(item);\n children.forEach(function (child) {\n if (child.isDirectory) return;\n var content = child.getData();\n if (!content) {\n throw Utils.Errors.CANT_EXTRACT_FILE();\n }\n // When not maintaining the full entry path, keep each child's path\n // relative to the extracted directory (drop the directory's own\n // prefix) instead of flattening every file to its basename, which\n // collapsed subdirectories together (issue #306).\n var name = canonical(maintainEntryPath ? child.entryName : child.entryName.substring(item.entryName.length));\n var childName = sanitize(targetPath, name);\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, childName);\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined;\n filetools.writeFileTo(childName, content, overwrite, fileAttr);\n });\n return true;\n }\n\n var content = item.getData(_zip.password);\n if (!content) throw Utils.Errors.CANT_EXTRACT_FILE();\n\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, target);\n\n if (filetools.fs.existsSync(target) && !overwrite) {\n throw Utils.Errors.CANT_OVERRIDE();\n }\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileTo(target, content, overwrite, fileAttr);\n\n return true;\n },\n\n /**\n * Test the archive\n * @param {string} [pass]\n */\n test: function (pass) {\n if (!_zip) {\n return false;\n }\n\n for (var entry of _zip.entries) {\n try {\n if (entry.isDirectory) {\n continue;\n }\n // was `_zip.entries[entry]` (indexing the array with an entry\n // object -> undefined -> threw -> test() always returned false)\n var content = entry.getData(pass);\n if (!content) {\n return false;\n }\n } catch (err) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Extracts the entire archive to the given location\n *\n * @param {string} targetPath Target location\n * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.\n * Default is FALSE\n * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.\n * Default is FALSE\n * @param {string|Buffer} [pass] password\n */\n extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) {\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n pass = get_Str(keepOriginalPermission, pass);\n overwrite = get_Bool(false, overwrite);\n if (!_zip) throw Utils.Errors.NO_ZIP();\n\n const dirEntries = [];\n _zip.entries.forEach(function (entry) {\n var entryName = sanitize(targetPath, canonical(entry.entryName));\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, entryName);\n if (entry.isDirectory) {\n filetools.makeDir(entryName);\n // defer restoring the directory permission until its files are written\n if (keepOriginalPermission) dirEntries.push({ path: entryName, attr: entry.header.fileAttr });\n return;\n }\n var content = entry.getData(pass);\n if (!content) {\n throw Utils.Errors.CANT_EXTRACT_FILE();\n }\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileTo(entryName, content, overwrite, fileAttr);\n try {\n // best-effort: an invalid date in the archive or a filesystem that\n // rejects utimes must not fail extraction of already-written content (issue #379)\n filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);\n } catch (err) {\n /* ignore timestamp failures */\n }\n });\n\n applyDirAttributes(dirEntries);\n },\n\n /**\n * Asynchronous extractAllTo\n *\n * @param {string} targetPath Target location\n * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.\n * Default is FALSE\n * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.\n * Default is FALSE\n * @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown.\n */\n extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) {\n callback = get_Fun(overwrite, keepOriginalPermission, callback);\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n overwrite = get_Bool(false, overwrite);\n if (!callback) {\n return new Promise((resolve, reject) => {\n this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) {\n if (err) {\n reject(err);\n } else {\n resolve(this);\n }\n });\n });\n }\n if (!_zip) {\n callback(Utils.Errors.NO_ZIP());\n return;\n }\n\n targetPath = pth.resolve(targetPath);\n // convert entryName to\n const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName)));\n const getError = (msg, file) => new Error(msg + ': \"' + file + '\"');\n\n // separate directories from files\n const dirEntries = [];\n const fileEntries = [];\n _zip.entries.forEach((e) => {\n if (e.isDirectory) {\n dirEntries.push(e);\n } else {\n fileEntries.push(e);\n }\n });\n\n // Create directory entries first synchronously\n // this prevents race condition and assures folders are there before writing files\n const deferredDirAttr = [];\n for (const entry of dirEntries) {\n const dirPath = getPath(entry);\n // The reverse operation for attr depend on method addFile()\n const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n try {\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, dirPath);\n filetools.makeDir(dirPath);\n } catch (er) {\n callback(getError(\"Unable to create folder\", dirPath));\n continue;\n }\n // defer restoring the directory permission until its files are written:\n // a restrictive mode applied now would block writing them\n if (dirAttr) deferredDirAttr.push({ path: dirPath, attr: dirAttr });\n try {\n // in unix timestamp will change if files are later added to folder, but still.\n // best-effort: a utimes failure must not abort extraction (issue #379)\n filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time);\n } catch (er) {\n /* ignore timestamp failures */\n }\n }\n\n // restore directory permissions once every file has been extracted\n const done = (err) => {\n if (!err) {\n try {\n applyDirAttributes(deferredDirAttr);\n } catch (er) {\n return callback(getError(\"Unable to set folder permissions\", er.path || \"\"));\n }\n }\n callback(err);\n };\n\n fileEntries.reverse().reduce(function (next, entry) {\n return function (err) {\n if (err) {\n next(err);\n } else {\n const entryName = pth.normalize(canonical(entry.entryName));\n const filePath = sanitize(targetPath, entryName);\n try {\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, filePath);\n } catch (er) {\n return next(er);\n }\n entry.getDataAsync(function (content, err_1) {\n if (err_1) {\n next(err_1);\n } else if (!content) {\n next(Utils.Errors.CANT_EXTRACT_FILE());\n } else {\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) {\n if (!succ) {\n return next(getError(\"Unable to write file\", filePath));\n }\n filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function () {\n // best-effort: a utimes failure must not abort extraction\n // of already-written content (issue #379)\n next();\n });\n });\n }\n });\n }\n };\n }, done)();\n },\n\n /**\n * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip\n *\n * @param {string} targetFileName\n * @param {function} callback\n */\n writeZip: function (targetFileName, callback) {\n if (arguments.length === 1) {\n if (typeof targetFileName === \"function\") {\n callback = targetFileName;\n targetFileName = \"\";\n }\n }\n\n if (!targetFileName && opts.filename) {\n targetFileName = opts.filename;\n }\n if (!targetFileName) return;\n\n var zipData = _zip.compressToBuffer();\n if (zipData) {\n var ok = filetools.writeFileTo(targetFileName, zipData, true);\n if (typeof callback === \"function\") callback(!ok ? new Error(\"failed\") : null, \"\");\n }\n },\n\n /**\n *\n * @param {string} targetFileName\n * @param {object} [props]\n * @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true.\n * @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true.\n\n * @returns {Promise<void>}\n */\n writeZipPromise: function (/**String*/ targetFileName, /* object */ props) {\n const { overwrite, perm } = Object.assign({ overwrite: true }, props);\n\n return new Promise((resolve, reject) => {\n // find file name\n if (!targetFileName && opts.filename) targetFileName = opts.filename;\n if (!targetFileName) reject(\"ADM-ZIP: ZIP File Name Missing\");\n\n this.toBufferPromise().then((zipData) => {\n const ret = (done) => (done ? resolve(done) : reject(\"ADM-ZIP: Wasn't able to write zip file\"));\n filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);\n }, reject);\n });\n },\n\n /**\n * @returns {Promise<Buffer>} A promise to the Buffer.\n */\n toBufferPromise: function () {\n return new Promise((resolve, reject) => {\n _zip.toAsyncBuffer(resolve, reject);\n });\n },\n\n /**\n * Returns the content of the entire zip file as a Buffer object\n *\n * @prop {function} [onSuccess]\n * @prop {function} [onFail]\n * @prop {function} [onItemStart]\n * @prop {function} [onItemEnd]\n * @returns {Buffer}\n */\n toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) {\n if (typeof onSuccess === \"function\") {\n _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);\n return null;\n }\n return _zip.compressToBuffer();\n }\n };\n};\n", "// The programmatic API \u2014 what `require('@flowrunner/cli')` gives you.\n//\n// Importing this must have no side effects: no argv parsing, no output, no process exit. The command-line\n// program lives in `cli/index.ts` and is reached through `bin/flowrunner.js`, never through here. Anything\n// exported below is callable from a Node program that wants to do what the CLI does without being a CLI.\n\n// \u2500\u2500\u2500 Failures \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Every operation reports problems by throwing one of these. Branch on `error.code`, or catch `CliError`\n// for the lot.\n\nexport type { ClusterName, ProviderLayout } from './constants'\nexport {\n AI_INSTRUCTIONS_DIRECTORY,\n CLAUDE_PROVIDER,\n CLUSTERS,\n DEFAULT_CLUSTER,\n DEFAULT_SERVER_URL,\n PROVIDERS,\n SANDBOX_DIRECTORY,\n TEST_DEV_DEPENDENCIES,\n TEST_SCRIPTS,\n TESTING_FILES,\n} from './constants'\nexport type { CliErrorCode, SkippedService } from './errors'\nexport {\n AiDocsMissingError,\n CliError,\n DeployFailedError,\n ERROR_CODES,\n HttpError,\n LoginFailedError,\n LoginTimeoutError,\n NoServicesDirectoryError,\n NoServicesError,\n NotAProjectError,\n NotLoggedInError,\n NoWorkspaceError,\n PromptAbortedError,\n PromptRequiredError,\n SelectionAbortedError,\n TemplateNotFoundError,\n TokenExpiredError,\n UnknownServerError,\n} from './errors'\n\n// \u2500\u2500\u2500 Operations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Each one takes `{ cwd, onEvent }`, returns what it did, and throws one of the errors above. None of them\n// print, prompt or exit \u2014 supply `onEvent` to watch progress.\n\nexport type {\n DeployedService,\n DeployEvent,\n DeployOptions,\n DeployResult,\n DiscoveredService,\n DiscoveryResult,\n PlannedService,\n PublicFile,\n Selection,\n ServiceStatus,\n Workspace,\n} from './operations/deploy'\nexport {\n collectPublicFiles,\n computeServiceHash,\n createServiceZip,\n deploy,\n discoverServices,\n selectServices,\n} from './operations/deploy'\nexport type {\n InitEvent,\n InitOptions,\n InitResult,\n TargetDescription,\n TestingFilesResult,\n} from './operations/init'\nexport { describeTarget, init, testingFilesDirectory, writeTestingFiles } from './operations/init'\nexport type { Ask, AskRequest, ResolveAnswersOptions } from './operations/init/answers'\nexport { resolveAnswers } from './operations/init/answers'\nexport type {\n CreateServiceEvent,\n CreateServiceOptions,\n ScaffoldedService,\n} from './operations/init/create-service'\nexport { createService, resolveTemplateId, scaffoldFromTemplate } from './operations/init/create-service'\nexport type {\n InitClaudeEvent,\n InitClaudeOptions,\n InitClaudeResult,\n MergeResult,\n SegmentOutcome,\n} from './operations/init-claude'\nexport {\n BEGIN_MARKER,\n END_MARKER,\n initClaude,\n mergeSegment,\n providerDirectory,\n} from './operations/init-claude'\nexport type { LoginEvent, LoginOptions, LoginResult } from './operations/login'\nexport { login } from './operations/login'\nexport type { LogoutEvent, LogoutOptions, LogoutResult } from './operations/logout'\nexport { logout } from './operations/logout'\nexport type {\n PulledService,\n PullEvent,\n PullOptions,\n PullResult,\n} from './operations/pull'\nexport { declaredDependencies, extractService, isSafeServiceId, localState, pull } from './operations/pull'\nexport { CLUSTER_NAMES, clusterFor, normalizeServerUrl, resolveServerTarget } from './operations/server-target'\nexport type { OperationOptions } from './operations/types'\nexport type { UseServerResult } from './operations/use-server'\nexport { useServer } from './operations/use-server'\n\n// \u2500\u2500\u2500 Project state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type { AuthGap, AuthToSave, StoredAuth } from './project/auth'\nexport { authGap, clearAuth, describeWorkspace, loadAuth, requireAuth } from './project/auth'\nexport { getServerUrl, getWorkspaceId } from './project/config'\n\n// \u2500\u2500\u2500 Service templates \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type { Answers, Prompt, Template, TemplateManifest } from './templates'\nexport { defaultTemplate, findTemplate, listTemplates } from './templates'\n", "// What goes into a deployed package.\n//\n// A service is self-contained: `services/<id>/` holds its own source, its own `package.json`, and its own\n// `node_modules`. That folder IS the package \u2014 nothing from the project root travels with it, which is what\n// makes a service the same thing wherever it is checked out.\n\n/**\n * Packed, but left out of the source hash.\n *\n * `node_modules` has to ship \u2014 the pod installs nothing \u2014 but hashing it would mean walking thousands of\n * generated files on every deploy to learn what the service's own `package-lock.json` already says.\n */\nexport const HASH_EXCLUDED_FOLDERS = [\n 'node_modules',\n]\n", "// What a Flowrunner extensions project looks like on disk. Shared by `init` (which creates these) and\n// `project/` (which reads and writes them).\n\nexport const CONFIG_FILE = 'flowrunner.json'\n\nexport const TOKEN_DIR = '.flowrunner'\nexport const TOKEN_FILE = `${ TOKEN_DIR }/token`\n\n// \u2500\u2500\u2500 AI docs, shipped inside the installed package \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Packed by `scripts/pack-ai-docs.mjs` from the console repo's feature docs, so they are readable from a\n// customer's project without it having the repo. Every path below is relative to the *installed package*.\n//\n// `init` writes none of these into the project: which file an agent reads, and where, is provider-specific\n// (see `providers.ts`), so wiring one up is its own `init-<provider>` command.\n\n/** Where the CLI ships instructions written for an AI agent, relative to the installed package. */\nexport const AI_DOCS_DIRECTORY = 'ai-docs'\n\n/** The one shared authoring reference \u2014 how to write a service. Provider-independent. */\nexport const AI_INSTRUCTIONS_DIRECTORY = `${ AI_DOCS_DIRECTORY }/instructions/service-code-format`\n\n/** Per-provider glue: agent definitions and the segment for that provider's instructions file. */\nexport const AI_PROVIDERS_DIRECTORY = `${ AI_DOCS_DIRECTORY }/providers`\n", "// Where each AI provider keeps its instructions, and what the CLI ships for it.\n//\n// Every provider has its own rules \u2014 which file it reads as project instructions, whether it has a notion of\n// subagents, and where those live. None of that is guessable from one provider's layout, so it is declared\n// per provider here rather than inferred. Adding a provider is adding an entry plus its own `init-<provider>`\n// command; nothing about one provider's layout leaks into another's.\n//\n// This is the *target project* side. The packed side \u2014 what the CLI ships under\n// `ai-docs/providers/<id>/` \u2014 is the same `id` plus the two names below it.\n\n/** The orchestrator segment, inside `ai-docs/providers/<id>/`. */\nexport const ORCHESTRATOR_SEGMENT_FILE = 'main-orchestrator-segment.md'\n\n/** The agent definitions, inside `ai-docs/providers/<id>/`. */\nexport const PROVIDER_AGENTS_DIRECTORY = 'agents'\n\nexport interface ProviderLayout {\n /** Directory name under `ai-docs/providers/`, and the CLI's name for the provider. */\n id: string\n /** How the provider is named in output written for a human. */\n label: string\n /**\n * The provider's own project-instructions file, relative to the project root.\n *\n * The CLI never owns this file \u2014 it owns only the region between its markers inside it.\n */\n instructionsFile: string\n /**\n * Where the provider looks for subagent definitions, relative to the project root.\n *\n * These files *are* CLI-owned and are overwritten on every run.\n */\n agentsDirectory: string\n}\n\n/**\n * Claude Code.\n *\n * It reads `CLAUDE.md` and specifically **not** `AGENTS.md` \u2014 the cross-vendor convention is invisible to it,\n * which is the whole reason provider wiring cannot be one shared file written by `init`.\n */\nexport const CLAUDE_PROVIDER = 'claude'\n\nexport const PROVIDERS: Record<string, ProviderLayout> = {\n [CLAUDE_PROVIDER]: {\n id : CLAUDE_PROVIDER,\n label : 'Claude Code',\n instructionsFile: 'CLAUDE.md',\n agentsDirectory : '.claude/agents',\n },\n}\n", "// Where the CLI points, and the clusters it knows by name.\n\n/**\n * The Flowrunner clusters, by short name.\n *\n * A named table rather than free-form URLs so that `flowrunner use dev` is a typo-proof way to move a\n * project between them: a name that is not in here is refused, where a mistyped URL would be accepted and\n * only fail later, against a server that does not exist.\n */\nexport const CLUSTERS = {\n prod : 'https://app.flowrunner.ai',\n dev : 'https://dev.flowrunner.ai',\n local: 'http://localhost:3000',\n} as const\n\nexport type ClusterName = keyof typeof CLUSTERS\n\n/**\n * The cluster a fresh project points at.\n *\n * One line, deliberately: moving the default from local to dev to prod as the product ships should not mean\n * hunting for a URL literal in half a dozen places.\n */\nexport const DEFAULT_CLUSTER: ClusterName = 'prod'\n\n/**\n * The console a project talks to when it has not been told otherwise.\n *\n * A fresh project must be able to run `login` before anything has written `flowrunner.json` \u2014 asking the\n * user for a URL they have no way of knowing is the one thing a first run cannot afford.\n */\nexport const DEFAULT_SERVER_URL: string = CLUSTERS[DEFAULT_CLUSTER]\n\n/** Overrides the default without editing the project file \u2014 how you point the CLI at a local console. */\nexport const SERVER_URL_ENV = 'FLOWRUNNER_SERVER_URL'\n", "// The unit-test harness `init` copies into a project.\n//\n// Two halves that have to agree: the files under `project-files/` in this package, and what a project\n// needs installed to run them. Both are declared here so a change to one is made next to the other.\n\n/** Files shipped inside this package for copying into a project, relative to the package root. */\nexport const PROJECT_FILES_DIRECTORY = 'project-files'\n\n/** Where the harness lands in the project. Test suites reach it as `require('../../../sandbox')`. */\nexport const SANDBOX_DIRECTORY = 'sandbox'\n\n/**\n * What `init` copies, as paths relative to both `project-files/` and the project root.\n *\n * An explicit list rather than a directory walk: a file that ships in this package but is not meant to\n * land in a customer's project should not do so by being added to a folder.\n */\nexport const TESTING_FILES = [\n 'jest.config.js',\n 'jest.setup.js',\n `${ SANDBOX_DIRECTORY }/index.js`,\n `${ SANDBOX_DIRECTORY }/service.js`,\n `${ SANDBOX_DIRECTORY }/nock-mock.js`,\n `${ SANDBOX_DIRECTORY }/files-mock.js`,\n]\n\n/**\n * What the harness needs installed, pinned to the majors it was written against.\n *\n * `query-string` is the sharp one, and the pin is load-bearing: v8 and up are ESM-only, which jest's\n * CommonJS runtime refuses to execute \u2014 `Must use import to load ES Module` \u2014 however the package is\n * declared here, since installing it is not what fails. Getting off v7 therefore means bundling the\n * library into something the sandbox requires, or putting babel into every project; a version bump\n * alone only breaks the harness. `nock-mock.js` also depends on its `parseNumbers` / `parseBooleans`\n * options to put JS types back on a query string that carries none.\n *\n * `nock` 14 is the first version that intercepts `fetch` as well as `http`, which is what makes the\n * mock work for a service using a bundled SDK.\n */\nexport const TEST_DEV_DEPENDENCIES: Record<string, string> = {\n jest : '^30.0.0',\n nock : '^14.0.0',\n 'query-string': '^7.1.3',\n}\n\n/** Added to `scripts`, and only where the project has no script of that name already. */\nexport const TEST_SCRIPTS: Record<string, string> = {\n test : 'jest',\n 'test:coverage': 'jest --coverage',\n}\n\n/**\n * Script values that count as absent \u2014 `npm init -y` writes this one, and it is not a decision anybody made.\n *\n * Without it the extremely common `npm init -y` \u2192 `flowrunner init` \u2192 `npm test` ends at\n * *Error: no test specified*, with a jest config and a sandbox sitting right there unused. Matched on the\n * exact string, so a project that has written its own `test` script keeps it whatever it says.\n */\nexport const PLACEHOLDER_SCRIPTS: Record<string, string> = {\n test: 'echo \"Error: no test specified\" && exit 1',\n}\n\n/** Both are produced by a test run: coverage reports, and the Files sandbox's blob storage. */\nexport const TEST_GITIGNORE_ENTRIES = ['coverage/', 'temp/']\n", "// Every way an operation can fail, as one hierarchy.\n//\n// An operation called from code cannot report a problem by printing it and ending the process, so each\n// failure is a class with a stable `code` a caller can branch on. The message here states the fact and\n// nothing more \u2014 the advice that goes with it (\"run `flowrunner login`\") belongs to whoever is talking to a\n// human, which is `cli/fail.ts`. A library consumer gets the fact and writes their own sentence.\n\nexport const ERROR_CODES = [\n 'FR_NOT_LOGGED_IN',\n 'FR_NO_WORKSPACE',\n 'FR_NO_SERVICES_DIR',\n 'FR_NO_SERVICES',\n 'FR_SELECTION_REQUIRED',\n 'FR_UNKNOWN_SERVICE',\n 'FR_TOKEN_EXPIRED',\n 'FR_DEPLOY_FAILED',\n 'FR_LOGIN_TIMEOUT',\n 'FR_LOGIN_FAILED',\n 'FR_PROMPT_REQUIRED',\n 'FR_PROMPT_ABORTED',\n 'FR_TEMPLATE_NOT_FOUND',\n 'FR_UNKNOWN_SERVER',\n 'FR_NOT_A_PROJECT',\n 'FR_AI_DOCS_MISSING',\n 'FR_HTTP',\n] as const\n\nexport type CliErrorCode = typeof ERROR_CODES[number]\n\n/**\n * The base every failure below extends, so a caller can catch the whole family at once.\n *\n * `name` is assigned from the constructor rather than left to the class, because the bundler is free to\n * rename classes and `error.name` is the one thing that tends to end up in someone's log.\n */\nexport class CliError extends Error {\n readonly code: CliErrorCode\n\n constructor(code: CliErrorCode, message: string, name = 'CliError') {\n super(message)\n\n this.code = code\n this.name = name\n }\n}\n\n// \u2500\u2500\u2500 Auth \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** No `flowrunner.json` naming a server, or no token in `.flowrunner/`. */\nexport class NotLoggedInError extends CliError {\n constructor(message = 'This project is not connected to a Flowrunner server.') {\n super('FR_NOT_LOGGED_IN', message, 'NotLoggedInError')\n }\n}\n\n/** Logged in, but `flowrunner.json` names no workspace \u2014 so there is nowhere to deploy to. */\nexport class NoWorkspaceError extends CliError {\n constructor(message = 'This project has a login but no workspace attached.') {\n super('FR_NO_WORKSPACE', message, 'NoWorkspaceError')\n }\n}\n\n/** The server rejected the deploy token. */\nexport class TokenExpiredError extends CliError {\n constructor(message = 'The stored deploy token is no longer valid.') {\n super('FR_TOKEN_EXPIRED', message, 'TokenExpiredError')\n }\n}\n\nexport class LoginTimeoutError extends CliError {\n constructor(message = 'Login timed out. Please try again.') {\n super('FR_LOGIN_TIMEOUT', message, 'LoginTimeoutError')\n }\n}\n\nexport class LoginFailedError extends CliError {\n constructor(message: string) {\n super('FR_LOGIN_FAILED', message, 'LoginFailedError')\n }\n}\n\n// \u2500\u2500\u2500 Deploy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The project has no `services/` directory at all. */\nexport class NoServicesDirectoryError extends CliError {\n constructor(message = 'This project has no services/ directory.') {\n super('FR_NO_SERVICES_DIR', message, 'NoServicesDirectoryError')\n }\n}\n\n/**\n * `services/` exists but nothing in it loaded as a service.\n *\n * Carries the folders that were skipped and why: with the whole deploy refusing to run, the reason a\n * particular folder was not counted is the only thing that tells anyone what to fix.\n */\nexport class NoServicesError extends CliError {\n readonly skipped: SkippedService[]\n\n constructor(skipped: SkippedService[] = [], message = 'No deployable services were found under services/.') {\n super('FR_NO_SERVICES', message, 'NoServicesError')\n\n this.skipped = skipped\n }\n}\n\nexport interface SkippedService {\n serviceId: string\n reason: string\n}\n\n/**\n * More than one service is deployable and none was chosen.\n *\n * A deploy now touches only the services it names, so \"all of them\" has to be asked for rather than assumed\n * \u2014 silently deploying every service would be the old behaviour wearing a new coat.\n */\nexport class SelectionRequiredError extends CliError {\n readonly available: string[]\n\n constructor(available: string[], message = 'This project has more than one service, so the deploy needs to know which.') {\n super('FR_SELECTION_REQUIRED', message, 'SelectionRequiredError')\n\n this.available = available\n }\n}\n\n/** A `-s` name that matches no deployable service in this project. */\nexport class UnknownServiceError extends CliError {\n readonly serviceId: string\n readonly available: string[]\n\n constructor(serviceId: string, available: string[]) {\n super(\n 'FR_UNKNOWN_SERVICE',\n `Unknown service \"${ serviceId }\". Available: ${ available.join(', ') }`,\n 'UnknownServiceError'\n )\n\n this.serviceId = serviceId\n this.available = available\n }\n}\n\n/** The server accepted the request and refused the package. */\nexport class DeployFailedError extends CliError {\n readonly status?: number\n readonly body?: string\n\n constructor(message: string, { status, body }: { status?: number; body?: string } = {}) {\n super('FR_DEPLOY_FAILED', message, 'DeployFailedError')\n\n this.status = status\n this.body = body\n }\n}\n\n// \u2500\u2500\u2500 Templates and answers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class TemplateNotFoundError extends CliError {\n readonly templateId: string\n readonly available: string[]\n\n constructor(templateId: string, available: string[]) {\n super(\n 'FR_TEMPLATE_NOT_FOUND',\n `Unknown template \"${ templateId }\". Available: ${ available.join(', ') }`,\n 'TemplateNotFoundError'\n )\n\n this.templateId = templateId\n this.available = available\n }\n}\n\n/**\n * An answer is needed and there is no way to ask for it.\n *\n * The programmatic path throws this instead of blocking on a terminal that may not exist; supply the answer\n * up front, or pass the hook that knows how to ask.\n */\nexport class PromptRequiredError extends CliError {\n readonly promptName: string\n\n constructor(promptName: string, message: string) {\n super('FR_PROMPT_REQUIRED', message, 'PromptRequiredError')\n\n this.promptName = promptName\n }\n}\n\n/** The user was asked and declined \u2014 Ctrl-C, Escape, or an answer that failed its own validator. */\nexport class PromptAbortedError extends CliError {\n constructor(message: string) {\n super('FR_PROMPT_ABORTED', message, 'PromptAbortedError')\n }\n}\n\n/** Ctrl-C or Escape out of an interactive list. Its own type so a caller can offer something else instead. */\nexport class SelectionAbortedError extends PromptAbortedError {\n constructor(message = 'Cancelled.') {\n super(message)\n\n this.name = 'SelectionAbortedError'\n }\n}\n\n// \u2500\u2500\u2500 Project \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** There is no `flowrunner.json` here, so there is no project to act on. */\nexport class NotAProjectError extends CliError {\n constructor(message = 'There is no flowrunner.json here, so this is not a Flowrunner project.') {\n super('FR_NOT_A_PROJECT', message, 'NotAProjectError')\n }\n}\n\n/** A server name that is not one of the known clusters, and not a URL either. */\nexport class UnknownServerError extends CliError {\n readonly target: string\n readonly available: string[]\n\n constructor(target: string, available: string[]) {\n super(\n 'FR_UNKNOWN_SERVER',\n `Unknown server \"${ target }\". Available: ${ available.join(', ') }`,\n 'UnknownServerError'\n )\n\n this.target = target\n this.available = available\n }\n}\n\n// \u2500\u2500\u2500 AI docs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The installed CLI ships no AI docs for the requested provider.\n *\n * They are build output packed into the package, so this means an install that predates them \u2014 or a repo\n * checkout that has not been built. Carries the directory looked for, because \"which path did you expect\"\n * is the only question anyone asks next.\n */\nexport class AiDocsMissingError extends CliError {\n readonly directory: string\n\n constructor(directory: string, message = `The installed FlowRunner CLI ships no AI docs at ${ directory }.`) {\n super('FR_AI_DOCS_MISSING', message, 'AiDocsMissingError')\n\n this.directory = directory\n }\n}\n\n// \u2500\u2500\u2500 Transport \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * A non-2xx response, with the status kept as a number.\n *\n * The status is the whole point: deciding \"expired token\" by looking for \"401\" inside a message is a test\n * that passes for any server that happens to mention the number.\n *\n * `what` names the call for a human (\"Token exchange\", \"Deploy\"); without it the message names the URL.\n */\nexport class HttpError extends CliError {\n readonly status: number\n readonly body: string\n readonly url: string\n\n constructor(status: number, body: string, url: string, what?: string) {\n super('FR_HTTP', `${ what ?? `Request to ${ url }` } failed (${ status }): ${ body }`, 'HttpError')\n\n this.status = status\n this.body = body\n this.url = url\n }\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport { listRemoteServices, uploadService } from '../../api/console-client'\nimport type { SkippedService } from '../../errors'\nimport {\n DeployFailedError,\n HttpError,\n NoServicesDirectoryError,\n NoServicesError,\n NotLoggedInError,\n NoWorkspaceError,\n TokenExpiredError,\n} from '../../errors'\nimport type { AuthGap, StoredAuth } from '../../project/auth'\nimport { authGap, loadAuth } from '../../project/auth'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport type { DiscoveredService } from './discover-services'\nimport { discoverServices } from './discover-services'\nimport { computeServiceHash } from './hash'\nimport type { PublicFile } from './public-files'\nimport { collectPublicFiles } from './public-files'\nimport type { Selection } from './select'\nimport { selectServices } from './select'\nimport { createServiceZip } from './zip'\n\nexport type { DiscoveredService, DiscoveryResult } from './discover-services'\nexport { discoverServices } from './discover-services'\nexport { computeServiceHash } from './hash'\nexport type { PublicFile, PublicFilesResult } from './public-files'\nexport { collectPublicFiles } from './public-files'\nexport type { Selection } from './select'\nexport { selectServices } from './select'\nexport { createServiceZip } from './zip'\n\n// Deploying: read the project, work out what has actually changed, and upload each changed service on its\n// own.\n//\n// One service per upload is the whole point. The workspace keeps whatever was deployed before from anywhere\n// else, so services authored in separate projects accumulate rather than replace one another.\n//\n// Every service is compared against the workspace before anything is packaged, so the run can say which are\n// new and which merely moved \u2014 and can decline to re-upload one that is byte-for-byte already there. A\n// service's `sourceHash` covers its folder and nothing else, which is what makes that comparison meaningful\n// from any project.\n//\n// Nothing here prints and nothing here exits. A missing login is an error, not a prompt \u2014 the CLI passes\n// `onAuthRequired` and turns it back into an offer, and everyone else gets something they can catch.\n\n/** What deploying a service would do to the workspace. */\nexport type ServiceStatus = 'new' | 'modified' | 'same'\n\nexport interface PlannedService {\n service: DiscoveredService\n serviceId: string\n /** The hash this deploy would publish. */\n sourceHash: string\n status: ServiceStatus\n}\n\nexport type DeployEvent =\n | { type: 'connecting'; serverUrl: string; workspace: Workspace }\n | { type: 'discovered'; planned: PlannedService[] }\n | { type: 'skipped'; skipped: SkippedService }\n | { type: 'selected'; planned: PlannedService[] }\n | { type: 'icon-missing'; serviceId: string; relativePath: string }\n | { type: 'deployed'; entry: DeployedService }\n | { type: 'unchanged'; entry: PlannedService }\n\nexport interface DeployOptions extends OperationOptions<DeployEvent>, Selection {\n /**\n * Called when the project has no usable credentials, before giving up.\n *\n * The CLI passes an interactive login here, which is why `flowrunner deploy` can offer to connect a\n * project mid-run. A caller that passes nothing gets NotLoggedInError or NoWorkspaceError thrown instead \u2014\n * a library must not open a browser on someone's behalf.\n */\n onAuthRequired?: (gap: AuthGap) => Promise<void>\n\n /**\n * Called when the project has several services and the caller named none.\n *\n * Same bargain as `onAuthRequired`: the CLI turns it into a picker, and a caller that passes nothing gets\n * SelectionRequiredError to handle its own way. Receives the classified list, so a picker can say which\n * services would actually change.\n */\n onSelectionRequired?: (available: PlannedService[]) => Promise<Selection>\n\n /**\n * Upload a service even when the workspace already has exactly this code.\n *\n * The default is to skip it \u2014 the deploy would produce the version that is already active, at the cost of\n * shipping the whole package. Worth overriding when the stored package itself is in doubt.\n */\n force?: boolean\n}\n\nexport interface Workspace {\n workspaceId: string\n workspaceName: string\n}\n\nexport interface DeployedService {\n serviceId: string\n serviceName: string\n sourceHash: string\n packageBytes: number\n /** `new` the first time the workspace sees it, `modified` when it replaces a different version. */\n status: Exclude<ServiceStatus, 'same'>\n}\n\nexport interface DeployResult {\n workspace: Workspace\n serverUrl: string\n /** Services actually uploaded. */\n services: DeployedService[]\n /** Selected, but the workspace already had exactly this code. */\n unchanged: PlannedService[]\n /** Folders under `services/` that were not deployable, and why. Empty on a clean run. */\n skipped: SkippedService[]\n}\n\n/**\n * Resolve the credentials, giving `onAuthRequired` one chance to fill a gap.\n *\n * Re-reads from disk afterwards rather than trusting the hook's return value: the login writes\n * `flowrunner.json` and the token file, and reading them back is what proves it actually happened.\n */\nasync function resolveAuth(projectRoot: string, onAuthRequired?: DeployOptions['onAuthRequired']): Promise<StoredAuth> {\n const stored = loadAuth(projectRoot)\n const gap = authGap(stored)\n\n if (!gap) {\n return stored as StoredAuth\n }\n\n if (!onAuthRequired) {\n throw errorForGap(gap)\n }\n\n await onAuthRequired(gap)\n\n const refreshed = loadAuth(projectRoot)\n const remaining = authGap(refreshed)\n\n if (remaining) {\n throw errorForGap(remaining)\n }\n\n return refreshed as StoredAuth\n}\n\nfunction errorForGap(gap: AuthGap): Error {\n return gap === 'not-logged-in' ? new NotLoggedInError() : new NoWorkspaceError()\n}\n\nexport async function deploy(options: DeployOptions = {}): Promise<DeployResult> {\n const projectRoot = options.cwd ?? process.cwd()\n const emit = emitter(options)\n\n const { serverUrl, workspaceId, workspaceName, deployToken } = await resolveAuth(projectRoot, options.onAuthRequired)\n const credentials = { serverUrl, workspaceId, deployToken }\n const workspace = { workspaceId, workspaceName }\n\n if (!fs.existsSync(path.resolve(projectRoot, 'services'))) {\n throw new NoServicesDirectoryError()\n }\n\n emit({ type: 'connecting', serverUrl, workspace })\n\n const { services: discovered, skipped } = discoverServices(projectRoot)\n\n for (const entry of skipped) {\n emit({ type: 'skipped', skipped: entry })\n }\n\n if (discovered.length === 0) {\n throw new NoServicesError(skipped)\n }\n\n // Classified before anything is selected, so a picker can say which services would actually change.\n const planned = await plan(projectRoot, discovered, credentials)\n\n emit({ type: 'discovered', planned })\n\n const selected = await resolveSelection(planned, options)\n\n emit({ type: 'selected', planned: selected })\n\n const deployed: DeployedService[] = []\n const unchanged: PlannedService[] = []\n\n // Sequential, and each upload stands alone: if the third service fails, the first two are deployed and\n // stay deployed. There is no package-wide transaction to roll back any more.\n for (const entry of selected) {\n if (entry.status === 'same' && !options.force) {\n unchanged.push(entry)\n emit({ type: 'unchanged', entry })\n\n continue\n }\n\n const { service, sourceHash } = entry\n const { files: icons, missing } = collectPublicFiles([service], projectRoot)\n\n for (const icon of missing) {\n emit({ type: 'icon-missing', ...icon })\n }\n\n const definition = { sourceHash, service }\n const zipBuffer = await createServiceZip(definition, projectRoot, service.serviceId)\n const result = await upload(credentials, zipBuffer, definition, icons)\n\n // `same` only reaches here under --force, where re-publishing the active version is the point.\n const status = entry.status === 'new' ? 'new' : 'modified'\n const record: DeployedService = { ...result, packageBytes: zipBuffer.length, status }\n\n deployed.push(record)\n emit({ type: 'deployed', entry: record })\n }\n\n return { workspace, serverUrl, services: deployed, unchanged, skipped }\n}\n\n/**\n * What deploying each discovered service would do, judged against what the workspace has active.\n *\n * The comparison is on `sourceHash`, which covers the service folder alone \u2014 so \"same\" means the active\n * version is this exact code, whichever project put it there.\n */\nasync function plan(\n projectRoot: string,\n discovered: DiscoveredService[],\n credentials: { serverUrl: string; workspaceId: string; deployToken: string }\n): Promise<PlannedService[]> {\n const remote = await guarded(() => listRemoteServices(credentials))\n const active = new Map(remote.map(service => [service.serviceId, service.sourceHash]))\n\n return Promise.all(discovered.map(async service => {\n const sourceHash = await computeServiceHash(projectRoot, service.serviceId)\n const deployedHash = active.get(service.serviceId)\n\n const status: ServiceStatus = deployedHash === undefined\n ? 'new'\n : deployedHash === sourceHash ? 'same' : 'modified'\n\n return { service, serviceId: service.serviceId, sourceHash, status }\n }))\n}\n\nasync function resolveSelection(\n planned: PlannedService[],\n options: DeployOptions\n): Promise<PlannedService[]> {\n try {\n return selectServices(planned, options)\n } catch (error) {\n if (!options.onSelectionRequired || (error as { code?: string }).code !== 'FR_SELECTION_REQUIRED') {\n throw error\n }\n\n // The hook answers the question this operation cannot ask; its answer goes back through the same\n // resolver so an unknown id is rejected identically however it arrived.\n return selectServices(planned, await options.onSelectionRequired(planned))\n }\n}\n\n/** One upload, with the transport's failures translated into the CLI's vocabulary. */\nasync function upload(\n credentials: { serverUrl: string; workspaceId: string; deployToken: string },\n zipBuffer: Buffer,\n definition: { sourceHash: string; service: DiscoveredService },\n icons: PublicFile[]\n) {\n return guarded(() => uploadService(credentials, zipBuffer, definition, icons))\n}\n\n/** Translates a transport failure into the CLI's vocabulary. */\nasync function guarded<T>(call: () => Promise<T>): Promise<T> {\n try {\n return await call()\n } catch (error) {\n // The status is the tell, not the prose. A console that mentions \"401\" while rejecting a package for an\n // unrelated reason used to be read as an expired session.\n if (error instanceof HttpError) {\n if (error.status === 401 || error.body.includes('CLI_TOKEN_EXPIRED')) {\n throw new TokenExpiredError()\n }\n\n throw new DeployFailedError(error.message, { status: error.status, body: error.body })\n }\n\n throw error\n }\n}\n", "import FormData from 'form-data'\nimport fetch from 'node-fetch'\n\nimport { HttpError } from '../errors'\n\n// Everything the CLI sends to a Flowrunner console. The counterpart of `server/`, which only listens.\n//\n// A non-2xx response becomes an HttpError carrying the status as a number, so callers can tell an expired\n// token from a rejected package without reading the message.\n//\n// This is also the only module that still says `appId` / `appName`. The console calls a workspace an \"app\"\n// in its URLs, its query strings and its token-exchange response; everything on our side of this boundary\n// calls it a workspace \u2014 `workspaceId`, `workspaceName`, and those are the names `flowrunner.json` uses too.\n// The translation happens here so that vocabulary does not leak into the rest of the CLI.\n\n// \u2500\u2500\u2500 Authorization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** What the console sends back. `appId` is its name for the workspace id. */\ninterface ExchangeResponse {\n token: string\n appId: string\n appName?: string\n}\n\nexport interface ExchangeResult {\n token: string\n workspaceId: string\n /** Absent from an older console; the CLI falls back to showing the id alone. */\n workspaceName?: string\n}\n\n/**\n * Where to send the user to authorize the CLI and choose a workspace.\n *\n * Built here rather than at the call site because the query string is the console's contract \u2014 `appId`\n * included \u2014 and this module is where that vocabulary is allowed to live.\n */\nexport function authorizeUrl(\n { serverUrl, callbackUrl, workspaceId }: { serverUrl: string; callbackUrl: string; workspaceId?: string }\n): string {\n const url = `${ serverUrl }/developer/cli/authorize` +\n `?callback=${ encodeURIComponent(callbackUrl) }` +\n '&clientType=cloud-code-deploy'\n\n // A workspace the project is already attached to is pre-selected on the page \u2014 shown as a disabled\n // control, with a \"use another workspace\" link beside it. Pre-selected, not locked: moving a project\n // between workspaces has to be possible without hand-editing flowrunner.json.\n return workspaceId ? `${ url }&appId=${ encodeURIComponent(workspaceId) }` : url\n}\n\n/**\n * Where a workspace's custom extensions live in the console.\n *\n * The path segment is the workspace *name*: `/app/:appName/\u2026` is the console's own route shape, and this\n * module is where that vocabulary is allowed to live.\n *\n * Builds unconditionally. Whether there is a name worth linking to is the caller's question \u2014 a project with\n * none recorded has nothing to put in that slot, and an id there would not resolve.\n */\nexport function customExtensionsUrl(serverUrl: string, workspaceName: string): string {\n return `${ serverUrl }/app/${ encodeURIComponent(String(workspaceName)) }/custom-extensions`\n}\n\nexport async function exchangeCodeForToken(serverUrl: string, code: string): Promise<ExchangeResult> {\n const url = `${ serverUrl }/developer/cli/token/exchange`\n\n const response = await fetch(url, {\n method : 'POST',\n headers: { 'Content-Type': 'application/json' },\n body : JSON.stringify({ code }),\n })\n\n if (!response.ok) {\n throw new HttpError(response.status, await response.text(), url, 'Token exchange')\n }\n\n const body = await response.json() as ExchangeResponse\n\n return { token: body.token, workspaceId: body.appId, workspaceName: body.appName }\n}\n\nexport async function revokeToken(serverUrl: string, token: string): Promise<void> {\n try {\n await fetch(`${ serverUrl }/developer/cli/token/revoke`, {\n method : 'POST',\n headers: { 'Content-Type': 'application/json' },\n body : JSON.stringify({ token }),\n })\n } catch {\n // Best effort: the local token is being deleted either way, and a revoke that never reached the server\n // is not a reason to leave the user still looking logged in.\n }\n}\n\n// \u2500\u2500\u2500 Deploy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface DeployCredentials {\n serverUrl: string\n workspaceId: string\n deployToken: string\n}\n\n/**\n * A file uploaded alongside the package \u2014 today the icons a service declares.\n *\n * Declared here rather than imported from `operations/deploy`: this layer knows how to send bytes with a\n * name attached, and nothing about what makes a file worth sending.\n */\nexport interface UploadFile {\n serviceId: string\n relativePath: string\n buffer: Buffer\n}\n\nexport interface UploadResult {\n packageId: string\n serviceId: string\n serviceName: string\n sourceHash: string\n}\n\n/** One service in the workspace, as `flowrunner pull` sees it. */\nexport interface RemoteService {\n serviceId: string\n serviceName: string\n /** The version, and \u2014 because it covers the service folder and nothing else \u2014 comparable to a local copy. */\n sourceHash: string\n}\n\n/**\n * Upload one service: its zip, its definition, and any icons it declares.\n *\n * One service per request \u2014 the server activates exactly what it receives and leaves every other service in\n * the workspace alone, which is what lets several projects deploy into the same workspace.\n */\nexport async function uploadService(\n credentials: DeployCredentials,\n zipBuffer: Buffer,\n definition: object,\n publicFiles: UploadFile[] = []\n): Promise<UploadResult> {\n const form = new FormData()\n\n form.append('file', zipBuffer, {\n filename : 'service.zip',\n contentType: 'application/zip',\n })\n form.append('definition', JSON.stringify(definition))\n\n for (const file of publicFiles) {\n // Just the path: the request already carries exactly one service, so the name has nothing to qualify.\n form.append('publicFiles', file.buffer, {\n filename : file.relativePath,\n contentType: 'application/octet-stream',\n })\n }\n\n const url = `${ credentials.serverUrl }/api/manage/app/${ credentials.workspaceId }/custom-extensions/deploy`\n\n const response = await fetch(url, {\n method : 'POST',\n headers: {\n 'deploy-token': credentials.deployToken,\n ...form.getHeaders(),\n },\n body: form,\n })\n\n if (!response.ok) {\n throw new HttpError(response.status, await response.text(), url, 'Deploy')\n }\n\n return response.json() as Promise<UploadResult>\n}\n\n// \u2500\u2500\u2500 Pull \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The workspace's active services \u2014 one entry per service, whichever project deployed it. */\nexport async function listRemoteServices(credentials: DeployCredentials): Promise<RemoteService[]> {\n const url = `${ credentials.serverUrl }/api/manage/app/${ credentials.workspaceId }/custom-extensions/cli/services`\n\n const response = await fetch(url, {\n headers: { 'deploy-token': credentials.deployToken },\n })\n\n if (!response.ok) {\n throw new HttpError(response.status, await response.text(), url, 'List services')\n }\n\n return response.json() as Promise<RemoteService[]>\n}\n\n/** The zip of a service's active version. */\nexport async function downloadRemoteService(credentials: DeployCredentials, serviceId: string): Promise<Buffer> {\n const url = `${ credentials.serverUrl }/api/manage/app/${ credentials.workspaceId }` +\n `/custom-extensions/cli/services/${ encodeURIComponent(serviceId) }/download`\n\n const response = await fetch(url, {\n headers: { 'deploy-token': credentials.deployToken },\n })\n\n if (!response.ok) {\n throw new HttpError(response.status, await response.text(), url, 'Download service')\n }\n\n return Buffer.from(await response.arrayBuffer())\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport { CONFIG_FILE, DEFAULT_SERVER_URL, SERVER_URL_ENV } from '../constants'\n\n// `flowrunner.json` \u2014 the tracked half of a project's identity. It names the server and the workspace, and\n// it belongs in git; the token that goes with it does not (see `./token`).\n//\n// Every function here takes the project root explicitly. It defaults to the current directory because that\n// is what a CLI means, but a caller driving this from code is usually pointing at a project somewhere else.\n\nexport interface ProjectConfig {\n serverUrl?: string\n workspaceId?: string\n /** Cosmetic: which workspace the id refers to, so the CLI can name it instead of printing a GUID. */\n workspaceName?: string\n [key: string]: unknown\n}\n\nexport interface EnsuredServerUrl {\n serverUrl: string\n /** `flowrunner.json` did not exist and was created. */\n created: boolean\n /** It existed but did not name a server, or named a different one, and was rewritten. */\n updated: boolean\n}\n\nexport function configPath(projectRoot: string = process.cwd()): string {\n return path.resolve(projectRoot, CONFIG_FILE)\n}\n\nexport function readConfig(projectRoot: string = process.cwd()): ProjectConfig {\n const fullPath = configPath(projectRoot)\n\n if (!fs.existsSync(fullPath)) {\n return {}\n }\n\n return JSON.parse(fs.readFileSync(fullPath, 'utf-8'))\n}\n\nexport function writeConfig(config: ProjectConfig, projectRoot: string = process.cwd()): void {\n fs.writeFileSync(configPath(projectRoot), JSON.stringify(config, null, 2) + '\\n', 'utf-8')\n}\n\n/**\n * Which console this project talks to: the project file first, then the environment, then the shipped\n * default. Never empty \u2014 a project that has never logged in still has somewhere to log in to.\n */\nexport function getServerUrl(projectRoot: string = process.cwd()): string {\n return readConfig(projectRoot).serverUrl || process.env[SERVER_URL_ENV] || DEFAULT_SERVER_URL\n}\n\nexport function getWorkspaceId(projectRoot: string = process.cwd()): string {\n return readConfig(projectRoot).workspaceId || ''\n}\n\n/**\n * Make the project's server URL explicit in `flowrunner.json`, creating the file if it is missing.\n *\n * Leaving it implicit reads as working by accident: the project would behave differently depending on an\n * environment variable, or on which CLI version happens to be installed. `init` writes the choice down\n * once, and every command after that reads the project's own decision.\n */\nexport function ensureServerUrl(projectRoot: string = process.cwd(), serverUrl?: string): EnsuredServerUrl {\n const exists = fs.existsSync(configPath(projectRoot))\n const config = readConfig(projectRoot)\n const resolved = serverUrl || config.serverUrl || process.env[SERVER_URL_ENV] || DEFAULT_SERVER_URL\n\n if (exists && config.serverUrl === resolved) {\n return { serverUrl: resolved, created: false, updated: false }\n }\n\n writeConfig({ ...config, serverUrl: resolved }, projectRoot)\n\n return { serverUrl: resolved, created: !exists, updated: exists }\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport { TOKEN_DIR, TOKEN_FILE } from '../constants'\n\n// `.flowrunner/token` \u2014 the untracked half. Writing one always makes sure `.gitignore` covers it: a deploy\n// token committed to a repository is the kind of mistake that is discovered by someone else.\n\nexport function tokenPath(projectRoot: string = process.cwd()): string {\n return path.resolve(projectRoot, TOKEN_FILE)\n}\n\nexport function readToken(projectRoot: string = process.cwd()): string | null {\n const fullPath = tokenPath(projectRoot)\n\n if (!fs.existsSync(fullPath)) {\n return null\n }\n\n return fs.readFileSync(fullPath, 'utf-8').trim()\n}\n\nexport function writeToken(token: string, projectRoot: string = process.cwd()): void {\n const dir = path.resolve(projectRoot, TOKEN_DIR)\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true })\n }\n\n fs.writeFileSync(tokenPath(projectRoot), token, 'utf-8')\n}\n\nexport function deleteToken(projectRoot: string = process.cwd()): void {\n const fullPath = tokenPath(projectRoot)\n\n if (fs.existsSync(fullPath)) {\n fs.unlinkSync(fullPath)\n }\n}\n\nexport function ensureGitignore(projectRoot: string = process.cwd()): void {\n const gitignorePath = path.resolve(projectRoot, '.gitignore')\n\n if (!fs.existsSync(gitignorePath)) {\n fs.writeFileSync(gitignorePath, `${ TOKEN_DIR }/\\n`, 'utf-8')\n\n return\n }\n\n const content = fs.readFileSync(gitignorePath, 'utf-8')\n\n if (!content.includes(TOKEN_DIR)) {\n fs.appendFileSync(gitignorePath, `\\n${ TOKEN_DIR }/\\n`)\n }\n}\n", "import { NotLoggedInError, NoWorkspaceError } from '../errors'\nimport { readConfig, writeConfig } from './config'\nimport { deleteToken, ensureGitignore, readToken, writeToken } from './token'\n\n// The two files above, read as one thing: is this project connected, and to what.\n\nexport interface StoredAuth {\n serverUrl: string\n workspaceId: string\n workspaceName: string\n deployToken: string\n}\n\n/** What is missing, when something is. The two gaps have different causes and different fixes. */\nexport type AuthGap = 'not-logged-in' | 'no-workspace'\n\n/** What a completed login has to write down. `workspaceName` is cosmetic and an older console may not send it. */\nexport interface AuthToSave {\n serverUrl: string\n workspaceId: string\n deployToken: string\n workspaceName?: string\n}\n\nexport function saveAuth(\n { serverUrl, workspaceId, deployToken, workspaceName }: AuthToSave,\n projectRoot: string = process.cwd()\n): void {\n writeConfig({ ...readConfig(projectRoot), serverUrl, workspaceId, ...(workspaceName ? { workspaceName } : {}) }, projectRoot)\n writeToken(deployToken, projectRoot)\n ensureGitignore(projectRoot)\n}\n\nexport function loadAuth(projectRoot: string = process.cwd()): StoredAuth | null {\n const config = readConfig(projectRoot)\n const token = readToken(projectRoot)\n\n if (!token || !config.serverUrl) {\n return null\n }\n\n return {\n serverUrl : config.serverUrl,\n workspaceId : config.workspaceId || '',\n workspaceName: config.workspaceName || '',\n deployToken : token,\n }\n}\n\nexport function clearAuth(projectRoot: string = process.cwd()): void {\n deleteToken(projectRoot)\n}\n\n/** Which half of the connection is missing, or null when the project is fully connected. */\nexport function authGap(stored: StoredAuth | null): AuthGap | null {\n if (!stored || !stored.serverUrl || !stored.deployToken) {\n return 'not-logged-in'\n }\n\n if (!stored.workspaceId) {\n return 'no-workspace'\n }\n\n return null\n}\n\n/**\n * The credentials, or a thrown error naming what is absent.\n *\n * Deliberately does nothing about the gap. Offering a login is an interaction, and an operation that opens\n * a browser on its own cannot be called from a program, a test or a CI job \u2014 so the offer lives in `cli/`\n * and this stays a question with two possible answers.\n */\nexport function requireAuth(projectRoot: string = process.cwd()): StoredAuth {\n const stored = loadAuth(projectRoot)\n const gap = authGap(stored)\n\n if (gap === 'not-logged-in') {\n throw new NotLoggedInError()\n }\n\n if (gap === 'no-workspace') {\n throw new NoWorkspaceError()\n }\n\n return stored as StoredAuth\n}\n\n/**\n * How to refer to the connected workspace in output: its name when the console gave us one, else the id.\n *\n * The full form states the connection \u2014 name *and* id, since the id is what lives in `flowrunner.json`. The\n * short form is for every mention after that: repeating a GUID three times in one screen of output is noise\n * that makes the name harder to notice, not easier.\n */\nexport function describeWorkspace(\n { workspaceId, workspaceName }: { workspaceId: string; workspaceName?: string },\n { short = false }: { short?: boolean } = {}\n): string {\n if (!workspaceName) {\n return workspaceId\n }\n\n return short ? workspaceName : `\"${ workspaceName }\" (${ workspaceId })`\n}\n", "// What every operation accepts, and how it talks while it works.\n\n/**\n * Progress, as structured events rather than sentences.\n *\n * An operation that called `report('Packaged 1.2 MB')` would still be composing English for a human, which\n * is the thing being moved out of this layer \u2014 and a caller rendering progress into a web page or a log line\n * would have to parse it back apart. Each operation declares its own event union instead, and whoever is\n * watching decides what those events look like. `cli/reporter.ts` turns them into the terminal output the\n * CLI has always produced.\n */\nexport interface OperationOptions<TEvent = never> {\n /**\n * Which project to work on. Defaults to the current directory, because that is what a command means, but\n * a caller driving this from code usually has a project somewhere else in mind.\n */\n cwd?: string\n /** Called as the operation progresses. Omitted means the operation runs silently, which is the default. */\n onEvent?: (event: TEvent) => void\n}\n\n/** Narrows `options.onEvent` to something always callable, so operations need no null checks. */\nexport function emitter<TEvent>(options: OperationOptions<TEvent>): (event: TEvent) => void {\n return options.onEvent ?? (() => undefined)\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { SharedExtensionConfigItem, SharedExtensionDefinition } from '@shared/scheme'\nimport { buildServiceDefinition, getServiceConfigs } from '@flowrunner/flow-extension-runner'\nimport { parseJsDocToServiceJson } from '@flowrunner/jsdoc-parser'\n\nimport type { SkippedService } from '../../errors'\n\nexport interface DiscoveredService {\n /** Entry point relative to the service root \u2014 'src/index.js', not 'services/<id>/src/index.js'. */\n serviceFilePath: string\n serviceId: string\n serviceInfo: SharedExtensionDefinition['serviceInfo']\n methodsMap: SharedExtensionDefinition['methodsMap']\n configDescriptions: SharedExtensionConfigItem[]\n /** Which authoring format the entry point turned out to be \u2014 the deploy carries it so the console can branch. */\n runnerVersion: SharedExtensionDefinition['runnerVersion']\n /** v2 only: the declared config schema, encoded. `null` for a JSDoc-parsed service. */\n configSchema: SharedExtensionDefinition['configSchema']\n}\n\nexport interface DiscoveryResult {\n services: DiscoveredService[]\n /**\n * Folders under `services/` that did not become a service, and why.\n *\n * Returned rather than warned about: a folder silently missing from a deploy is the kind of thing someone\n * notices a week later, and a caller driving this from code has no console to have missed a warning on.\n */\n skipped: SkippedService[]\n}\n\n/** Scan `services/*` under the project root and build each service's definition, v2 declarative or v1 JSDoc. */\nexport function discoverServices(projectRoot: string = process.cwd()): DiscoveryResult {\n const servicesDir = path.resolve(projectRoot, 'services')\n\n if (!fs.existsSync(servicesDir)) {\n return { services: [], skipped: [] }\n }\n\n const serviceIds = fs\n .readdirSync(servicesDir, { withFileTypes: true })\n .filter(file => file.isDirectory())\n .map(file => file.name)\n\n const services: DiscoveredService[] = []\n const skipped: SkippedService[] = []\n\n for (const serviceId of serviceIds) {\n const serviceDir = path.resolve(servicesDir, serviceId)\n const serviceDISTEntryPoint = path.resolve(serviceDir, './dist/index.js')\n const serviceSRCEntryPoint = path.resolve(serviceDir, './src/index.js')\n\n let serviceFilePath = null\n\n try {\n if (fs.existsSync(serviceDISTEntryPoint)) {\n serviceFilePath = serviceDISTEntryPoint\n } else if (fs.existsSync(serviceSRCEntryPoint)) {\n serviceFilePath = serviceSRCEntryPoint\n }\n\n if (!serviceFilePath) {\n skipped.push({ serviceId, reason: 'it has neither a dist/index.js nor a src/index.js' })\n\n continue\n }\n\n // null for a v1 service, which the JSDoc parser models instead. The cast is load-bearing: the runner's\n // model mirror and @shared/scheme have drifted and are not assignable in either direction.\n const v2Definition = buildServiceDefinition(serviceId, serviceFilePath) as SharedExtensionDefinition | null\n\n const { methodsMap, serviceInfo } = v2Definition ?? parseJsDocToServiceJson(serviceFilePath)\n\n // Only files that define a service (v1: @integrationName; v2: createExtension id).\n if (!serviceInfo || !serviceInfo.serviceClassName) {\n skipped.push({ serviceId, reason: 'its entry point does not define a service' })\n\n continue\n }\n\n // A failure here shouldn't drop the whole service \u2014 record it and fall back to an empty config.\n let configDescriptions: SharedExtensionConfigItem[] = []\n\n try {\n configDescriptions = getServiceConfigs(serviceId, serviceFilePath)\n } catch (error) {\n skipped.push({\n serviceId,\n reason: `its config items could not be read (${ (error as Error).message }) \u2014 deployed without them`,\n })\n }\n\n services.push({\n // Relative to the service, because the deployed archive's root IS the service.\n serviceFilePath: path.relative(serviceDir, serviceFilePath),\n serviceId,\n serviceInfo,\n methodsMap,\n configDescriptions,\n // v2 only. The console renders a v2 config dialog from the schema itself rather than from the\n // `configDescriptions` projection, so both travel: the schema for the new path, the projection for\n // every consumer that predates it.\n runnerVersion: v2Definition ? 'v2' : 'v1',\n configSchema : v2Definition?.configSchema ?? null,\n })\n } catch (error) {\n // Anything that throws while loading the entry point: a syntax error, a missing require, a module that\n // runs something at import time. The reason is the only clue the author gets about why their service\n // is not in the deploy, so it travels rather than being swallowed.\n skipped.push({ serviceId, reason: (error as Error).message })\n }\n }\n\n return { services, skipped }\n}\n", "import BLRequest from 'backendless-request'\n\nimport type { FlowrunnerRuntime } from './global'\nimport { createExtension } from './v2/create-extension'\nimport { crypto } from './v2/crypto'\nimport { z } from './v2/params'\nimport { getExtension } from './v2/registry'\n\n// Installs the single global `Flowrunner` namespace shared by v1 and v2. Importing this module for its\n// side effect guarantees the global exists before any service module is required. The v1 registration\n// seam (`ServerCode`) starts null and is toggled per-require by v1/namespace.ts.\n\nconst flowrunnerRuntime: FlowrunnerRuntime = {\n Request: BLRequest,\n z,\n crypto,\n createExtension,\n getExtension,\n ServerCode: null,\n}\n\nglobal.Flowrunner = flowrunnerRuntime\n\nexport { flowrunnerRuntime }\n", "import type { FlowExtensionErrorCode } from './codes'\n\n// Base class for all flow-extension runtime errors. Mirrors the console's `ApiError` shape (statusCode +\n// type/code + message + details) so the server can map it straight onto an HTTP response, while staying\n// self-contained (the runner never imports the console workspace).\n\nexport interface FlowExtensionErrorJSON {\n name: string\n code: FlowExtensionErrorCode\n statusCode: number\n message: string\n details?: unknown\n}\n\nexport class FlowExtensionError<DetailsT = unknown> extends Error {\n // Discriminant that survives structured-clone / JSON across the worker boundary, where `instanceof` fails.\n readonly isFlowExtensionError = true\n\n constructor(\n public readonly code: FlowExtensionErrorCode,\n public readonly statusCode: number,\n message: string,\n public readonly details?: DetailsT\n ) {\n super(message)\n this.name = this.constructor.name\n\n // Maintains a proper stack trace for where the error was thrown (V8 only).\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n\n toJSON(): FlowExtensionErrorJSON {\n return {\n name: this.name,\n code: this.code,\n statusCode: this.statusCode,\n message: this.message,\n details: this.details,\n }\n }\n}\n\n// True for a FlowExtensionError instance, or a plain object carrying the discriminant (e.g. after the error\n// crossed the worker IPC boundary and lost its prototype).\nexport function isFlowExtensionError(value: unknown): value is FlowExtensionError {\n if (value instanceof FlowExtensionError) {\n return true\n }\n\n return typeof value === 'object' &&\n value !== null &&\n (value as { isFlowExtensionError?: unknown }).isFlowExtensionError === true\n}\n", "// Stable, machine-readable codes for flow-extension runtime errors. These survive the worker \u2192 server IPC\n// boundary (as the error `code`), so the console and client can resolve/branch on the error type rather\n// than string-matching messages. Do not renumber/rename existing codes \u2014 they are part of the contract.\nexport const FlowExtensionErrorCodes = {\n // A method name that isn't a registered action/dictionary/trigger/SYSTEM method.\n UNKNOWN_METHOD: 'FR_EXT_UNKNOWN_METHOD',\n // A required named param (invocation / callbackObject / refreshToken) was absent from the method input.\n MISSING_METHOD_PARAM: 'FR_EXT_MISSING_METHOD_PARAM',\n // The method input failed its schema (action params, helper payload, SYSTEM invocation).\n INVALID_METHOD_INPUT: 'FR_EXT_INVALID_METHOD_INPUT',\n // A dictionary/loader `criteria` failed the declared criteria schema \u2014 reported apart from the payload so\n // the UI can point at the dependent fields instead of the whole call.\n INVALID_CRITERIA: 'FR_EXT_INVALID_CRITERIA',\n // Two registered items (action/dictionary/trigger) share an id.\n DUPLICATE_ITEM_ID: 'FR_EXT_DUPLICATE_ITEM_ID',\n // No v2 extension registered for the given serviceId after requiring the module.\n EXTENSION_NOT_REGISTERED: 'FR_EXT_NOT_REGISTERED',\n // A declared config value is missing or the wrong shape (see v2/schema/normalize).\n INVALID_CONFIG: 'FR_EXT_INVALID_CONFIG',\n // A schema slot that must be a z.object was declared as something else (see v2/schema/assert-object-schema).\n INVALID_SCHEMA: 'FR_EXT_INVALID_SCHEMA',\n // A polling trigger declared zero or multiple mechanisms, or is missing its fetch.\n INVALID_TRIGGER_CONFIG: 'FR_EXT_INVALID_TRIGGER_CONFIG',\n // A trigger dispatch referenced an unregistered trigger id.\n UNKNOWN_TRIGGER: 'FR_EXT_UNKNOWN_TRIGGER',\n // setupRealtimeTriggers is misconfigured (missing subscribe/unsubscribe, or declared twice).\n REALTIME_SETUP: 'FR_EXT_REALTIME_SETUP',\n // Inbound webhook failed signature verification.\n // setupOauth2 is misconfigured (e.g. declared twice).\n OAUTH_SETUP: 'FR_EXT_OAUTH_SETUP',\n // A handler accessed an opt-in feature (oauth/files) that the extension didn't enable.\n FEATURE_NOT_ENABLED: 'FR_EXT_FEATURE_NOT_ENABLED',\n // ...\n INVALID_DICTIONARY_OUTPUT_SCHEME: 'INVALID_DICTIONARY_OUTPUT_SCHEME',\n} as const\n\nexport type FlowExtensionErrorCode = (typeof FlowExtensionErrorCodes)[keyof typeof FlowExtensionErrorCodes]\n", "import { FlowExtensionError } from './base'\nimport { FlowExtensionErrorCodes } from './codes'\n\n// Concrete flow-extension errors. Messages are kept stable (callers/tests rely on them); the `code` is the\n// machine-resolvable identity.\n\nexport class UnknownMethodError extends FlowExtensionError {\n constructor(serviceId: string, methodName: string) {\n super(\n FlowExtensionErrorCodes.UNKNOWN_METHOD,\n 404,\n `[flow-extension:${ serviceId }] unknown method \"${ methodName }\"`,\n { serviceId, methodName }\n )\n }\n}\n\nexport class MissingMethodParamError extends FlowExtensionError {\n constructor(serviceId: string, param: string) {\n super(\n FlowExtensionErrorCodes.MISSING_METHOD_PARAM,\n 400,\n `[flow-extension:${ serviceId }] missing required \"${ param }\" in method input`,\n { serviceId, param }\n )\n }\n}\n\n// A single schema violation, flattened out of zod so the details survive the worker IPC boundary.\nexport interface ValidationIssue {\n // Dot/bracket path inside the validated value ('' when the value itself is invalid).\n path: string\n message: string\n code?: string\n}\n\nfunction formatIssues(issues: ValidationIssue[]): string {\n return issues.map(issue => (issue.path ? `${ issue.path }: ${ issue.message }` : issue.message)).join('; ')\n}\n\n// A method was called with input that doesn't match its schema \u2014 action params, a helper `payload`, or a\n// SYSTEM method's invocation. `target` names the validated slot so the caller can point at it.\nexport class InvalidMethodInputError extends FlowExtensionError {\n constructor(serviceId: string, methodName: string, target: string, issues: ValidationIssue[]) {\n super(\n FlowExtensionErrorCodes.INVALID_METHOD_INPUT,\n 400,\n `[flow-extension:${ serviceId }] invalid ${ target } for method \"${ methodName }\" \u2014 ${ formatIssues(issues) }`,\n { serviceId, methodName, target, issues }\n )\n }\n}\n\n// The `criteria` of a dictionary/loader call failed its declared schema. Separate from the payload error so\n// the console can surface \"these dependent fields are wrong\" rather than \"the whole call is malformed\".\nexport class InvalidCriteriaError extends FlowExtensionError {\n constructor(serviceId: string, methodName: string, issues: ValidationIssue[]) {\n super(\n FlowExtensionErrorCodes.INVALID_CRITERIA,\n 400,\n `[flow-extension:${ serviceId }] invalid criteria for method \"${ methodName }\" \u2014 ${ formatIssues(issues) }`,\n { serviceId, methodName, target: 'criteria', issues }\n )\n }\n}\n\nexport class DuplicateItemIdError extends FlowExtensionError {\n constructor(serviceId: string, id: string, kind: string) {\n super(\n FlowExtensionErrorCodes.DUPLICATE_ITEM_ID,\n 400,\n `[flow-extension:${ serviceId }] duplicate id \"${ id }\" (${ kind }) \u2014 ids must be unique across all registered items`,\n { serviceId, id, kind }\n )\n }\n}\n\nexport class ExtensionNotRegisteredError extends FlowExtensionError {\n constructor(serviceId: string, entryPoint?: string) {\n super(\n FlowExtensionErrorCodes.EXTENSION_NOT_REGISTERED,\n 404,\n `[flow-extension] no v2 extension registered for serviceId=\"${ serviceId }\"${ entryPoint ? ` (${ entryPoint })` : '' }`,\n { serviceId, entryPoint }\n )\n }\n}\n\nexport class InvalidConfigError extends FlowExtensionError {\n // Raised when the resolved `configItems` do not satisfy what the service declared. Carries one issue per\n // offending field, so the console can point at the config form rather than reporting the whole call.\n constructor(serviceId: string, issues: ValidationIssue[]) {\n super(\n FlowExtensionErrorCodes.INVALID_CONFIG,\n 400,\n `[flow-extension:${ serviceId }] invalid config \u2014 ${ formatIssues(issues) }`,\n { serviceId, issues }\n )\n }\n}\n\nexport class InvalidSchemaError extends FlowExtensionError {\n // `message` is composed by the guard, which knows how to describe what was received and what to do\n // about it (see v2/schema/assert-object-schema.ts).\n constructor(message: string, details: Record<string, unknown>) {\n super(FlowExtensionErrorCodes.INVALID_SCHEMA, 400, message, details)\n }\n}\n\nexport class InvalidTriggerConfigError extends FlowExtensionError {\n // `message` carries the specifics (kept verbatim for existing tests).\n constructor(serviceId: string, message: string, details?: Record<string, unknown>) {\n super(FlowExtensionErrorCodes.INVALID_TRIGGER_CONFIG, 400, `[flow-extension:${ serviceId }] ${ message }`, { serviceId, ...details })\n }\n}\n\nexport class UnknownTriggerError extends FlowExtensionError {\n constructor(serviceId: string, triggerId: string, kind = 'polling') {\n super(\n FlowExtensionErrorCodes.UNKNOWN_TRIGGER,\n 404,\n `[flow-extension:${ serviceId }] no ${ kind } trigger \"${ triggerId }\"`,\n { serviceId, triggerId, kind }\n )\n }\n}\n\nexport class RealtimeSetupError extends FlowExtensionError {\n constructor(serviceId: string, message: string) {\n super(FlowExtensionErrorCodes.REALTIME_SETUP, 400, `[flow-extension:${ serviceId }] ${ message }`, { serviceId })\n }\n}\n\nexport class OAuthSetupError extends FlowExtensionError {\n constructor(serviceId: string, message: string) {\n super(FlowExtensionErrorCodes.OAUTH_SETUP, 400, `[flow-extension:${ serviceId }] ${ message }`, { serviceId })\n }\n}\n\nexport class FeatureNotEnabledError extends FlowExtensionError {\n constructor(feature: string, hint: string) {\n super(\n FlowExtensionErrorCodes.FEATURE_NOT_ENABLED,\n 400,\n `[flow-extension] \"${ feature }\" is not enabled for this extension \u2014 ${ hint }`,\n { feature }\n )\n }\n}\n\nexport class InvalidDictionaryOutputScheme extends FlowExtensionError {\n constructor(serviceId: string, dictionaryName: string) {\n super(\n FlowExtensionErrorCodes.INVALID_DICTIONARY_OUTPUT_SCHEME,\n 400,\n `[flow-extension:${ serviceId }] dictionary \"${ dictionaryName }\" execution returns wrong result, it must result list of object {value, label, hist} or object {cursor:'string', items:[...]}`,\n { serviceId, dictionaryName }\n )\n }\n}\n", "import type { MethodParams } from '../params'\nimport type { ResultSpec } from '../result'\nimport type { AnySchema, HandlerBag } from '../types'\n\n// What a generated loader needs from the item it belongs to. Actions, polling triggers and realtime\n// triggers can all declare a loader `result`, so this is the narrow contract between them and ../loaders \u2014\n// it keeps a loader from having to know which of the three registered it.\n//\n// All three method classes implement it directly \u2014 a loader is handed its owner, not a description of one.\n\n// The generated loader method names. Frozen \u2014 these are published method names, derived from the owner's id.\nexport const sampleResultLoaderName = (ownerId: string): string => `${ ownerId }_SampleResultLoader`\nexport const dynamicParamsLoaderName = (ownerId: string): string => `${ ownerId }_DynamicParams`\n\nexport interface LoaderOwner {\n readonly id: string\n // The owner's grouping label; its loaders inherit it so they sort alongside it.\n readonly category: string\n readonly params: MethodParams\n readonly result: ResultSpec\n}\n\n// Only actions declare `dynamicParams`.\nexport interface DynamicParamsOwner extends LoaderOwner {\n readonly dynamicParamsCriteria: MethodParams\n resolveDynamicParams(bag: HandlerBag & { criteria: Record<string, unknown> }): AnySchema | Promise<AnySchema>\n}\n", "import { InvalidSchemaError } from '../../../errors'\nimport type { SchemaSource } from '../types'\nimport type { AnyZod } from './introspect'\n\n// Every schema slot is OPTIONAL. Declare it and it must be a `z.object` \u2014 because that is the only thing the\n// runner can do anything with: a container of named fields to validate input against and publish as the\n// method's input model.\n//\n// Without this guard a wrong shape degrades SILENTLY. `params: z.string()` has no `.shape`, so the method\n// publishes no params, the console renders a node with no inputs, validation becomes a passthrough, and the\n// service deploys clean \u2014 the author finds out when the action cannot be called correctly in production.\n//\n// So the check runs at REGISTRATION time, while the service module is being `require`d. That means it fires\n// on the first call the CLI or console makes against the extension, including the `buildServiceDefinition`\n// that `flowrunner deploy` performs per service \u2014 so a bad schema stops the deploy instead of shipping.\n\n// Zod's single-child wrappers. An object inside one of these cannot serve as a container: the wrapper has no\n// `.shape` and no `.partial()`, so every field would be invisible.\nconst WRAPPERS = new Set(['optional', 'nullable', 'nullish', 'default', 'prefault'])\n\nconst typeOf = (value: unknown): string | undefined =>\n (value as AnyZod | undefined)?._zod?.def?.type as string | undefined\n\n// How to name what the author actually passed, in their own vocabulary.\nfunction describe(value: unknown): string {\n const type = typeOf(value)\n\n if (type) {\n if (WRAPPERS.has(type)) {\n const inner = typeOf((value as { _zod?: { def?: { innerType?: unknown } } })._zod?.def?.innerType)\n\n return `z.${ inner ?? 'unknown' }().${ type }()`\n }\n\n return `z.${ type }()`\n }\n\n if (value === null) {\n return 'null'\n }\n\n if (Array.isArray(value)) {\n return 'an array'\n }\n\n if (typeof value === 'object') {\n return 'a plain object'\n }\n\n return `a ${ typeof value }`\n}\n\n// The most useful next step for this particular mistake.\nfunction hint(value: unknown, slot: string, isReturn: boolean): string {\n const type = typeOf(value)\n\n if (type && WRAPPERS.has(type)) {\n return '; an object container cannot be optional \u2014 mark its fields optional instead'\n }\n\n if (!type && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n return ' \u2014 did you forget to wrap it in z.object({ \u2026 })?'\n }\n\n // Every slot may simply be left out, which is usually what an author reaching for a non-object wanted.\n return isReturn ? '' : `; omit \\`${ slot }\\` entirely if there is nothing to declare`\n}\n\n/**\n * Throws unless `scheme` is a `z.object` (including `z.looseObject` / `z.strictObject`). `undefined` passes \u2014\n * an undeclared slot is legal everywhere.\n */\nexport function assertObjectSchema(scheme: unknown, source: SchemaSource): void {\n if (scheme == null || typeOf(scheme) === 'object') {\n return\n }\n\n const slot = source.slot ?? 'schema'\n const kind = source.kind ?? 'extension'\n // A slot spelled with parentheses is a function whose RETURN is being checked.\n const isReturn = slot.endsWith('()')\n // The extension itself has no item id to name; everything else does.\n const subject = source.itemId ? `${ kind } \"${ source.itemId }\": ` : ''\n const received = describe(scheme)\n\n throw new InvalidSchemaError(\n `[flow-extension:${ source.serviceId }] ${ subject }\\`${ slot }\\` ${ isReturn ? 'must return' : 'must be' }` +\n ` a z.object({ \u2026 }) \u2014 received ${ received }${ hint(scheme, slot, isReturn) }`,\n { serviceId: source.serviceId, kind, itemId: source.itemId, slot, received }\n )\n}\n", "/**\n * Platform param GROUPS \u2014 a whole `z.object` the runtime ships (see ./files-options.ts), not a control.\n *\n * They travel in the same `uiComponent.type` slot as a control token, so they belong in the map below. They\n * are named apart from it because **nothing renders a single input for one**: a consumer reads the token to\n * decide how to draw the whole group, and a registry of one-input-per-token has no entry for it.\n *\n * An author's own `z.object` carries none of these.\n */\nexport const FlowExtensionParamGroupTypes = {\n FILE_UPLOAD_OPTIONS: 'FILE_UPLOAD_OPTIONS',\n FILE_LIST_OPTIONS : 'FILE_LIST_OPTIONS',\n FILE_GET_OPTIONS : 'FILE_GET_OPTIONS',\n FILE_DELETE_OPTIONS: 'FILE_DELETE_OPTIONS',\n}\n\nexport const FlowExtensionParamWidgetTypes = {\n // Derived from a zod declaration \u2014 see `deriveWidget`.\n SINGLE_LINE_TEXT: 'SINGLE_LINE_TEXT',\n MULTI_LINE_TEXT : 'MULTI_LINE_TEXT',\n NUMERIC_STEPPER : 'NUMERIC_STEPPER',\n DATE_PICKER : 'DATE_PICKER',\n TOGGLE : 'TOGGLE',\n DROPDOWN : 'DROPDOWN',\n\n ...FlowExtensionParamGroupTypes,\n\n // legacy \u2014 no zod declaration produces these. They reach the console only from a legacy JSDoc-format\n // service, which writes `uiComponent` by hand. Kept because the console still renders them for an\n // already-installed extension.\n NUMERIC : 'NUMERIC',\n CHECKBOX : 'CHECKBOX',\n DATE_TIME_PICKER: 'DATE_TIME_PICKER',\n TIME_PICKER : 'TIME_PICKER',\n}\n\n/**\n * The widget tokens a declaration carries EXPLICITLY, as author metadata (`meta.frWidget`) \u2014 everything else\n * in the map above is DERIVED from the zod type by `deriveWidget`.\n *\n * `MULTI_LINE_TEXT` is `z.text()` / `z.json()`; the `FILE_*_OPTIONS` tokens name a platform param group.\n */\nexport type FrWidgetToken =\n | 'MULTI_LINE_TEXT'\n | 'FILE_UPLOAD_OPTIONS'\n | 'FILE_LIST_OPTIONS'\n | 'FILE_GET_OPTIONS'\n | 'FILE_DELETE_OPTIONS'\n\n/** The subset that names a platform param GROUP rather than a single control. */\nexport type FrGroupToken = Exclude<FrWidgetToken, 'MULTI_LINE_TEXT'>\n", "// Introspection over the extended zod schemas: walk a declared object's fields, unwrap the modifiers that do\n// not change what a field IS, collect merged author meta (outer wins), and derive the param type +\n// `uiComponent` widget. Everything here reads a schema and returns plain data \u2014 it is the layer both the\n// runner's model builder and the console's renderer sit on top of.\n//\n// This module DESCRIBES a schema; it never decides whether the schema is allowed. A declaration the runtime\n// cannot render is refused at registration by ./assert-supported-schema.ts, which reads `resolvedType` from\n// here. Keeping the two apart is what lets the runtime's own SYSTEM schemes \u2014 which model a wire contract\n// rather than a rendered form \u2014 be described by the same code that refuses an author writing the same thing\n// in a parameter.\nimport { FlowExtensionParamWidgetTypes } from '../widget-types'\nimport type { FrMeta } from '../zod'\n\nexport interface Inspected {\n // The unwrapped core schema (past the modifiers below).\n core: AnyZod\n // Core zod def type: 'string' | 'number' | 'boolean' | 'enum' | 'date' | 'object' | 'array' | \u2026\n // Defaulted to 'string' when the schema reports none, so every consumer has something to switch on.\n coreType: string\n // The SAME answer, undefined rather than defaulted. What the registration guard has to read: in `coreType`\n // \"declared nothing\" and \"declared a string\" are the same value, and a policy decision cannot conflate them.\n resolvedType?: string\n /**\n * A `z.union()`'s declared branches, outermost union only \u2014 `undefined` for everything else.\n *\n * `core` and `coreType` above have already been resolved to the FIRST branch, which is what publishes and\n * what picks the widget. That answer is right for every consumer that only needs a type, and wrong for the\n * two that must consider all of them: the registration guard has to refuse a union with an unsupported\n * branch, and coercion has to try each branch in turn. They read this.\n */\n branches?: AnyZod[]\n required: boolean\n defaultValue: unknown\n meta: FrMeta\n}\n\n// Structural zod shape \u2014 we read internals (`_zod.def`) rather than depend on zod's public generics.\nexport type AnyZod = {\n _zod?: { def?: Record<string, unknown> }\n meta?: () => Record<string, unknown> | undefined\n shape?: Record<string, AnyZod>\n options?: unknown[]\n}\n\nconst OPTIONAL_WRAPPERS = new Set(['optional', 'nullable', 'nullish'])\nexport const DEFAULT_WRAPPERS = new Set(['default', 'prefault'])\n\n/**\n * Modifiers that constrain or re-shape a value without changing what the AUTHOR declared it to be. The\n * runtime looks straight through them: they decide nothing about the widget, the published type, or which\n * coercion runs.\n *\n * - `readonly` \u2014 freezes zod's output; the declared type is the inner one.\n * - `pipe` \u2014 `.pipe(b)` and `.transform(fn)` both produce this. We follow `def.in`, the INPUT side, because\n * the published model describes **what a caller supplies**: it is what the console renders a form for, what\n * the AI-tool schema advertises, and what the coercion layer must convert to before zod sees the value.\n * What `execute` ends up receiving is the pipe's own business and is not a published fact.\n * - `lazy` \u2014 a thunk, for a recursive declaration.\n *\n * `.catch()` is deliberately NOT here. It is refused at registration instead (see\n * ./assert-supported-schema.ts): unwrapping it would fix the published type while leaving the declaration\n * silently substituting a fallback for invalid input, which is the more serious half of that defect.\n */\nexport const TRANSPARENT_WRAPPERS = new Set(['readonly', 'pipe', 'lazy'])\n\n// Where the schema inside a wrapper lives \u2014 it is not always `innerType`.\nexport function innerOf(def: Record<string, unknown>, type: string): AnyZod | undefined {\n if (type === 'pipe') {\n return def.in as AnyZod | undefined\n }\n\n if (type === 'lazy') {\n return (def.getter as (() => AnyZod) | undefined)?.()\n }\n\n return def.innerType as AnyZod | undefined\n}\n\n// A self-referential `z.lazy()` would peel forever. Nothing legitimate nests modifiers anywhere near this deep.\n// Shared with ../json/encode.ts, whose own wrapper walk has to stop on the same declarations this one does.\nexport const MAX_UNWRAP_DEPTH = 64\n\nexport function inspect(schema: AnyZod): Inspected {\n let current: AnyZod | undefined = schema\n // An `.optional()` / `.default()` seen OUTSIDE any `.nonoptional()`. The chain is walked outer\u2192inner and\n // the outermost modifier is the author's final word, so `.optional().nonoptional()` is required while\n // `.nonoptional().optional()` is not \u2014 `sealed` is what stops an inner one from speaking for an outer one.\n // Mirrors `declaredAbsence` in ./field-plan.ts, which has to reach the same answer.\n let optional = false\n let sealed = false\n let defaultValue: unknown\n let branches: AnyZod[] | undefined\n let depth = 0\n const metas: Record<string, unknown>[] = []\n\n while (current?._zod && depth++ < MAX_UNWRAP_DEPTH) {\n const meta = typeof current.meta === 'function' ? current.meta() : undefined\n\n if (meta) {\n metas.push(meta)\n }\n\n const def = current._zod.def || {}\n const type = def.type as string\n\n if (OPTIONAL_WRAPPERS.has(type)) {\n optional ||= !sealed\n current = def.innerType as AnyZod\n continue\n }\n\n if (DEFAULT_WRAPPERS.has(type)) {\n optional ||= !sealed\n\n if (defaultValue === undefined) {\n defaultValue = def.defaultValue\n }\n\n current = def.innerType as AnyZod\n continue\n }\n\n if (type === 'nonoptional') {\n sealed = true\n current = def.innerType as AnyZod\n continue\n }\n\n /**\n * A union resolves to its FIRST branch, and the branch list is carried on the result.\n *\n * \u26A0\uFE0F Declaration order is therefore published contract: `z.union([A, B])` and `z.union([B, A])` validate\n * identically and publish differently, and nothing in the source says so. It is documented in\n * service-code-format/02-zod-types.md; do not reorder a union's branches for readability.\n *\n * Only the OUTERMOST union is recorded \u2014 a nested one is resolved again when its own branch is walked.\n */\n if (type === 'union') {\n const options = def.options as AnyZod[] | undefined\n\n // A union with nothing in it resolves to nothing; leave it as the core so the guard reports it.\n if (!options?.length) {\n break\n }\n\n branches ??= options\n current = options[0]\n continue\n }\n\n if (TRANSPARENT_WRAPPERS.has(type)) {\n const inner = innerOf(def, type)\n\n // A wrapper we cannot see inside is the core as far as anything here is concerned; the guard reports it.\n if (!inner) {\n break\n }\n\n current = inner\n continue\n }\n\n break\n }\n\n // metas are collected outer\u2192inner; reverse so outer is applied last (wins) in the merge.\n const meta = Object.assign({}, ...metas.reverse()) as FrMeta\n const core = current as AnyZod\n const resolvedType = core?._zod?.def?.type as string | undefined\n\n return {\n core,\n coreType: resolvedType || 'string',\n resolvedType,\n required: !optional,\n defaultValue,\n meta,\n ...(branches ? { branches } : {}),\n }\n}\n\nexport interface WidgetInfo {\n paramType: string\n uiComponent?: Record<string, unknown>\n items?: { type: string }\n}\n\n/**\n * The runtime type of a `z.literal(\u2026)`, when every declared value agrees on one \u2014 `undefined` for a mixed\n * literal, which has neither a single widget nor a single conversion.\n *\n * Read by BOTH ends: `deriveWidget` publishes the type, ../schema/coerce.ts converts to it. They have to be\n * the same answer \u2014 a toggle the console draws for a field the runtime will not accept `'true'` for is the\n * defect this module exists to prevent \u2014 which is why the two read one function rather than each deciding.\n * `undefined` is what keeps a mixed literal out of coercion: stringifying the `1` in `z.literal(['a', 1])`\n * would turn a value the declaration accepts into one it rejects.\n */\n// `typeof` answers 'object' for null and 'function' for a function \u2014 neither is a widget, and `z.literal(null)`\n// drew an empty nested form before this was excluded. Only the scalar kinds name a real type.\nconst LITERAL_KINDS = new Set(['string', 'number', 'boolean', 'bigint'])\n\nexport function literalType(core: AnyZod): string | undefined {\n const values = (core._zod?.def?.values as unknown[] | undefined) ?? []\n const kinds = new Set(values.map(value => typeof value))\n const [kind] = [...kinds]\n\n return kinds.size === 1 && LITERAL_KINDS.has(kind) ? kind : undefined\n}\n\n// Derive the v1 param `type` + `uiComponent` from a core zod type (widget is derived from the type \u2014 there\n// is no `.uiComponent()` in v2). Tokens match the v1 conventions (MULTI_LINE_TEXT/NUMERIC_STEPPER/TOGGLE/\u2026).\n//\n// TOTAL by design: this is a projection, not a policy. It has to answer for the runtime's own SYSTEM schemes\n// too (see ../../model/params-model.ts `toOpaqueBodyParams`), which carry `z.unknown()` and loose records no\n// author would be allowed to declare in a parameter. What an AUTHOR may write is decided once, at\n// registration, by ./assert-supported-schema.ts.\nexport function deriveWidget(ins: Inspected): WidgetInfo {\n const { coreType, core, meta } = ins\n\n // `z.json()` \u2014 arbitrary JSON, typed into a textarea. Checked BEFORE the type switch because the\n // declaration underneath is `z.unknown()`: it has to accept the PARSED value once ./coerce.ts has run, so\n // the type says nothing about what the caller supplies. The meta does, and what the caller supplies is text.\n if (meta.frJson) {\n return { paramType: 'STRING', uiComponent: { type: FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT } }\n }\n\n switch (coreType) {\n case 'string':\n if (meta.frWidget === FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT) {\n return { paramType: 'STRING', uiComponent: { type: FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT } }\n }\n\n return { paramType: 'STRING' }\n\n case 'number':\n case 'bigint':\n return { paramType: 'NUMBER', uiComponent: { type: FlowExtensionParamWidgetTypes.NUMERIC_STEPPER } }\n\n case 'boolean':\n return { paramType: 'BOOLEAN', uiComponent: { type: FlowExtensionParamWidgetTypes.TOGGLE } }\n\n case 'date':\n return { paramType: 'STRING', uiComponent: { type: FlowExtensionParamWidgetTypes.DATE_PICKER } }\n\n case 'enum': {\n // `.map({ Label: value })` shows labels; otherwise the enum options are the values.\n // The options are always the declared VALUES \u2014 that is what a flow element stores. `.labels()` adds a\n // display name per value, published as `{ value, label }` pairs the console renders directly.\n const declared = ((core.options ?? Object.values((core._zod?.def?.entries as Record<string, unknown>) ?? {})) as unknown[])\n .map(String)\n const labels = meta.frLabels\n const values: unknown[] = labels\n ? declared.map(value => ({ value, label: labels[value] ?? value }))\n : declared\n\n return { paramType: 'STRING', uiComponent: { type: 'DROPDOWN', options: { values } } }\n }\n\n // A literal is a one-value type, so it renders as whatever that value IS rather than always as text.\n // A mixed one has no such type and falls back to text.\n case 'literal':\n return deriveWidget({ ...ins, coreType: literalType(core) ?? 'string' })\n\n // A platform param GROUP names itself: the runtime's own file-options objects (../files-options.ts) carry\n // a token so a consumer can render the group as the thing it is instead of as an anonymous nested form.\n // An author's own `z.object` carries no marker and publishes exactly as it always has.\n case 'object':\n return meta.frWidget\n ? { paramType: 'OBJECT', uiComponent: { type: meta.frWidget } }\n : { paramType: 'OBJECT' }\n\n // A record is an OBJECT whose KEYS are open. The coercion layer has always walked it as one (see\n // ./coerce.ts); publishing it as one is the model catching up with the runtime.\n case 'record':\n return { paramType: 'OBJECT' }\n\n case 'array': {\n const element = core._zod?.def?.element as AnyZod | undefined\n const elementType = element ? deriveWidget(inspect(element)).paramType : 'STRING'\n\n return { paramType: 'LIST', items: { type: elementType } }\n }\n\n // `z.any()` / `z.unknown()` declare nothing to render or to convert \u2014 the pipeline passes them through\n // untouched, and the model has no better word for \"anything\" than the permissive one.\n case 'any':\n case 'unknown':\n return { paramType: 'STRING' }\n\n // Reached only by a runtime-owned scheme; an author's is refused at registration. Text is the permissive\n // answer for a SYSTEM param the console never draws.\n default:\n return { paramType: 'STRING' }\n }\n}\n\n// The declared fields of a z.object, in declaration order. Tolerates a missing/!object schema by returning\n// nothing \u2014 an undeclared slot is treated as \"no fields\" (see ../params.ts).\nexport function shapeEntries(schema: AnyZod | undefined): [name: string, schema: AnyZod][] {\n const shape = schema?.shape\n\n return shape && typeof shape === 'object' ? Object.entries(shape) : []\n}\n\n// The display labels a field declared with `.labels({ value: 'Label' })`, if any. Display only \u2014 nothing is\n// translated at runtime, because the value the element stored is already the value the handler wants.\nexport function fieldLabels(schema: AnyZod): Record<string, string> | undefined {\n return inspect(schema).meta.frLabels\n}\n", "import { InvalidSchemaError } from '../../../errors'\nimport type { SchemaSource } from '../types'\nimport { type AnyZod, inspect, shapeEntries } from './introspect'\n\n// The declared type surface, enforced. Sibling of ./assert-object-schema.ts \u2014 that one checks the CONTAINER\n// is a z.object, this one checks what is declared INSIDE it, at every depth.\n//\n// Why it exists: the runtime reads a zod declaration to decide the published type, the widget the console\n// draws, and which coercion runs before `execute`. Everything it cannot classify used to fall through to\n// `STRING`. That fallback is worse than it looks, because it fails in two places at once \u2014 the parameter is\n// published as text (a list stops being a list, a toggle becomes a text box) AND it drops out of the\n// coercion layer, so the string values a flow supplies are never converted. A `z.boolean().catch(false)`\n// bound to a template therefore hands `execute` `false` for an explicit `'true'`: exactly the legacy boolean\n// defect that v2's coercion layer exists to close.\n//\n// So an unrecognised declaration must be an ERROR, not a guess. The supported set below is closed and\n// documented (service-code-format/02-zod-types.md); a zod release that adds a modifier cannot silently\n// degrade a parameter, because the new name simply is not in it.\n//\n// Runs at REGISTRATION, while the service module is being required \u2014 the same moment, and for the same\n// reason, as the object-container check: it fires on the first call the CLI or console makes against the\n// extension, including the `buildServiceDefinition` behind `flowrunner deploy`, so a bad declaration stops\n// the deploy instead of shipping.\n\n/**\n * Slots held to the documented surface \u2014 everything an AUTHOR writes.\n *\n * The runtime's own SYSTEM schemes (`kind: 'system method'`) are deliberately exempt: they model the wire\n * contract of a platform call rather than a rendered form, and legitimately carry `z.unknown()` bodies and\n * loose records. So is the anonymous slot used for per-invocation payload parsing, which re-wraps a schema\n * that was already checked where it was declared.\n */\nconst GUARDED_KINDS = new Set(['action', 'dictionary', 'polling trigger', 'realtime trigger', 'extension'])\n\n/**\n * The core types the runtime can publish, render and coerce.\n *\n * `any` / `unknown` are in deliberately: they declare nothing, the pipeline passes them through untouched,\n * and that is a coherent thing for an author to want. Everything absent is absent on purpose \u2014 `tuple` and\n * `intersection` have no single widget, and a `catch` is refused with its own message below.\n *\n * `union` is not listed because it never reaches this check as itself: `inspect()` resolves it to its first\n * branch, so `resolvedType` is that branch's type. Its branches are each held to this same set \u2014 see\n * `assertField` \u2014 so a union containing a `z.tuple()` is still refused.\n */\nconst SUPPORTED_TYPES = new Set([\n 'string', 'number', 'bigint', 'boolean', 'date', 'enum', 'literal',\n 'object', 'array', 'record',\n // `z.union([T, z.null()])` is the union-shaped spelling of `.nullable()`, which is supported \u2014 refusing one\n // and not the other is a distinction without a difference. It is also a branch of zod's own `z.json()`.\n 'null',\n 'any', 'unknown',\n])\n\n// Named in the \"supported\" half of an error message, in the spelling an author writes. Kept in step with\n// `SUPPORTED_TYPES` above and with the table in service-code-format/02-zod-types.md \u2014 an author who hits this\n// error reads the message, then the doc, and a type missing from either reads as one they may not use.\nconst SUPPORTED_SPELLING = 'z.string(), z.number(), z.bigint(), z.boolean(), z.date(), z.enum([\u2026]), ' +\n 'z.literal(\u2026), z.object({ \u2026 }), z.array(\u2026), z.record(\u2026), z.union([\u2026]), z.null(), z.any(), z.unknown()'\n\nconst MODIFIER_SPELLING = '.optional(), .nullable(), .nullish(), .default(v), .prefault(v), .readonly(), ' +\n '.nonoptional(), .pipe(\u2026)/.transform(\u2026) and z.lazy(\u2026)'\n\n// `action \"sendMessage\": `params.tags[]`` \u2014 enough for an author to find the declaration without a stack trace.\nfunction subjectOf(source: SchemaSource, path: string): string {\n const kind = source.kind ?? 'extension'\n const subject = source.itemId ? `${ kind } \"${ source.itemId }\": ` : ''\n\n return `${ subject }\\`${ path }\\``\n}\n\nfunction refuse(message: string, source: SchemaSource, path: string, received: string): never {\n throw new InvalidSchemaError(\n `[flow-extension:${ source.serviceId }] ${ message }`,\n { serviceId: source.serviceId, kind: source.kind ?? 'extension', itemId: source.itemId, slot: source.slot, path, received }\n )\n}\n\n/**\n * `.catch(v)` gets its own refusal, because the fix is not \"use a supported type\" \u2014 the author's intent is\n * fine and the spelling is one character away.\n *\n * It is refused rather than unwrapped on purpose. Unwrapping would restore the published type and the\n * coercion, but the declaration would still SWALLOW invalid input: zod replaces anything that fails with the\n * fallback, so a value the user actually supplied is silently discarded instead of being reported back. No\n * parameter should do that. `.default(v)` expresses the same intent honestly \u2014 it supplies the fallback when\n * the value is ABSENT, and still rejects one that is present and wrong.\n */\nfunction refuseCatch(source: SchemaSource, path: string): never {\n refuse(\n `${ subjectOf(source, path) } uses \\`.catch(\u2026)\\`, which a parameter may not: it replaces an invalid value` +\n ' with the fallback instead of reporting it, and drops the field out of type coercion.' +\n ' Use `.default(v)` \u2014 same fallback when the value is absent, and a supplied-but-invalid one still fails.',\n source, path, 'catch'\n )\n}\n\nfunction refuseType(source: SchemaSource, path: string, type: string | undefined): never {\n const received = type ? `z.${ type }()` : 'a value that is not a zod schema'\n\n refuse(\n `${ subjectOf(source, path) } declares ${ received }, which the runtime cannot publish as a parameter` +\n ' \u2014 it has no widget, no published type and no coercion for it.' +\n ` Supported: ${ SUPPORTED_SPELLING }; each may carry ${ MODIFIER_SPELLING }.`,\n source, path, type ?? 'unknown'\n )\n}\n\n// One declared field, then whatever it contains. `seen` stops a recursive `z.lazy()` from walking forever.\nfunction assertField(schema: AnyZod | undefined, source: SchemaSource, path: string, seen: Set<unknown>): void {\n if (!schema || seen.has(schema)) {\n return\n }\n\n seen.add(schema)\n\n const ins = inspect(schema)\n\n if (ins.resolvedType === 'catch') {\n refuseCatch(source, path)\n }\n\n if (!ins.resolvedType || !SUPPORTED_TYPES.has(ins.resolvedType)) {\n refuseType(source, path, ins.resolvedType)\n }\n\n // Every branch of a union is a declaration in its own right. The union itself already passed the check\n // above AS ITS FIRST BRANCH, which says nothing about the others.\n if (ins.branches) {\n // Numbered, because the reported path is otherwise the field \u2014 and \"declares z.tuple()\" against a field\n // the author wrote as a union names a type they cannot find in their own declaration.\n ins.branches.forEach((branch, index) => assertField(branch, source, `${ path }|branch ${ index + 1 }`, seen))\n }\n\n const def = ins.core._zod?.def ?? {}\n\n // A container's contents are declarations in their own right and are held to the same rule \u2014 the defect\n // this guards against is no less silent one level down.\n if (ins.resolvedType === 'array') {\n assertField(def.element as AnyZod | undefined, source, `${ path }[]`, seen)\n }\n\n if (ins.resolvedType === 'record') {\n assertField(def.valueType as AnyZod | undefined, source, `${ path }{}`, seen)\n }\n\n if (ins.resolvedType === 'object') {\n for (const [name, property] of shapeEntries(ins.core)) {\n assertField(property, source, `${ path }.${ name }`, seen)\n }\n }\n}\n\n/**\n * Throws unless every field `scheme` declares, at every depth, is something the runtime can publish, render\n * and coerce. `undefined` passes \u2014 an undeclared slot is legal everywhere.\n *\n * Only author-declared slots are checked (see `GUARDED_KINDS`).\n */\nexport function assertSupportedSchema(scheme: unknown, source: SchemaSource): void {\n if (scheme == null || !source.kind || !GUARDED_KINDS.has(source.kind)) {\n return\n }\n\n const slot = source.slot ?? 'schema'\n const seen = new Set<unknown>()\n\n for (const [name, field] of shapeEntries(scheme as AnyZod)) {\n assertField(field, source, `${ slot }.${ name }`, seen)\n }\n}\n", "import type { AnyZod, Inspected } from './introspect'\n\n// Everything date-shaped, in one place: what counts as a valid date input, and what each date declaration\n// hands the handler.\n//\n// The input space is whatever JSON can carry, because every path into the runner is an HTTP body \u2014 a real\n// `Date` instance is not reachable. That is why `z.date()`, which demands one, could never be satisfied and\n// had to be exempted from validation entirely. It is no longer exempt; instead the value is converted for\n// CHECKING and the declaration decides what comes out:\n//\n// z.date() the input, unchanged \u2014 converting would invent a time of day and a timezone\n// z.coerce.date() a real Date \u2014 zod's own opt-in, and the only honest way to ask for one\n// z.iso.datetime() an ISO datetime string\n// z.iso.date() an ISO date string\n// z.iso.time() an ISO time string\n// z.iso.duration() strict: a duration is not a point in time, so there is nothing to narrow or widen\n\n// A date-only string, and a datetime whose date half we can take without parsing.\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/\nconst HAS_TIME = /^(\\d{4}-\\d{2}-\\d{2})[T ](.+)$/\n// The trailing zone on an extracted time \u2014 `z.iso.time()` rejects it.\nconst ZONE = /(Z|[+-]\\d{2}:?\\d{2})$/\n\nconst isNumeric = (value: string): boolean => value.trim() !== '' && Number.isFinite(Number(value.trim()))\n\n/**\n * Any date input \u2192 a `Date`, or `undefined` when it is not a date at all.\n *\n * A finite number is EPOCH MILLIS, which is what the console's date control stores; a numeric string is that\n * same number through a stringly-typed transport. Everything else that is a string is handed to `Date`.\n *\n * `new Date('nope')` returns a `Date` whose value is `NaN` \u2014 and `z.date()` accepts it \u2014 so an invalid date\n * has to be rejected here explicitly, or garbage would reach a handler looking like a date.\n */\nexport function toDate(value: unknown): Date | undefined {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? undefined : value\n }\n\n if (typeof value === 'number') {\n return Number.isFinite(value) ? new Date(value) : undefined\n }\n\n if (typeof value !== 'string') {\n return undefined\n }\n\n const parsed = isNumeric(value) ? new Date(Number(value.trim())) : new Date(value)\n\n return Number.isNaN(parsed.getTime()) ? undefined : parsed\n}\n\n/**\n * A date input \u2192 the ISO shape the field declared.\n *\n * NARROWING IS LEXICAL. `'2024-06-01T23:00:00Z'` \u2192 `'2024-06-01'` takes the characters before the `T`;\n * parsing and reformatting would impose UTC, and in UTC+2 that instant is the 2nd, not the 1st. So a string\n * is sliced, never converted.\n *\n * Two conversions do assume UTC, and both are unavoidable:\n * \u2022 widening a date to a datetime invents a time of day (`'2024-06-01'` \u2192 `'2024-06-01T00:00:00Z'`)\n * \u2022 naming a date or a time from EPOCH MILLIS has to pick a wall clock \u2014 the same instant is 2024-06-01\n * in London and 2024-06-02 in Kiritimati\n *\n * `z.iso.datetime()` from millis is not in that class: the instant is preserved and UTC is merely which of\n * several equivalent spellings we emit.\n */\nexport function toIso(value: unknown, format: string): string | undefined {\n const text = typeof value === 'string' ? value.trim() : undefined\n // A string keeps its own wording wherever the shape can be reached by slicing it.\n const lexical = text && !isNumeric(text) ? sliceIso(text, format) : undefined\n\n if (lexical) {\n return lexical\n }\n\n const parsed = toDate(value)\n\n if (!parsed) {\n return undefined\n }\n\n const iso = parsed.toISOString()\n\n if (format === 'datetime') {\n return iso\n }\n\n if (format === 'date') {\n return iso.slice(0, 10)\n }\n\n if (format === 'time') {\n return iso.slice(11, 19)\n }\n\n return undefined\n}\n\n// The shape reachable from `text` without any timezone maths. `undefined` when slicing cannot get there.\nfunction sliceIso(text: string, format: string): string | undefined {\n const timed = HAS_TIME.exec(text)\n\n if (format === 'datetime') {\n // Already a datetime: keep the author's own spelling, offset and precision included.\n return timed ? text : undefined\n }\n\n if (format === 'date') {\n return timed ? timed[1] : DATE_ONLY.test(text) ? text : undefined\n }\n\n if (format === 'time') {\n const time = timed ? timed[2] : DATE_ONLY.test(text) ? undefined : text\n\n return time ? time.replace(ZONE, '') : undefined\n }\n\n return undefined\n}\n\n/** The zod format token a schema declared, if any: 'datetime' | 'date' | 'time' | 'duration' | \u2026 */\nexport const formatOf = (ins: Inspected): string | undefined =>\n (ins.core as { _zod?: { def?: { format?: string } } } | undefined)?._zod?.def?.format\n\n/** The ISO formats this module converts INTO. `duration` is absent on purpose \u2014 it stays strict. */\nexport const isConvertibleIso = (format?: string): boolean =>\n format === 'datetime' || format === 'date' || format === 'time'\n\n/**\n * True for `z.date()` and false for `z.coerce.date()`.\n *\n * `.coerce` is zod's own flag, set by `z.coerce.date()` and readable through the optional/nullable/default\n * wrappers \u2014 so the author's intent is a flag to look up rather than a heuristic to guess.\n */\nexport const passesDateThrough = (ins: Inspected): boolean =>\n ins.coreType === 'date' && !(ins.core as { _zod?: { def?: { coerce?: boolean } } })?._zod?.def?.coerce\n\n/** Whether a schema, at any depth, has a `z.date()` whose value must survive validation unchanged. */\nexport function hasPassThroughDate(schema: AnyZod | undefined, inspectSchema: (s: AnyZod) => Inspected,\n entriesOf: (s: AnyZod | undefined) => [string, AnyZod][]): boolean {\n if (!schema) {\n return false\n }\n\n const ins = inspectSchema(schema)\n\n if (passesDateThrough(ins)) {\n return true\n }\n\n const element = ins.core?._zod?.def?.element as AnyZod | undefined\n const valueType = ins.core?._zod?.def?.valueType as AnyZod | undefined\n const children = [\n ...entriesOf(ins.core).map(([, child]) => child),\n ...(element ? [element] : []),\n ...(valueType ? [valueType] : []),\n // Every branch of a union, not just the one it resolved to. `z.union([z.number(), z.date()])` coerces\n // through the date branch at runtime, so the restore walk has to know a date is reachable here \u2014 or the\n // handler receives the converted `Date` instead of the string the host sent.\n ...(ins.branches ?? []),\n ]\n\n return children.some(child => hasPassThroughDate(child, inspectSchema, entriesOf))\n}\n", "import { type AnyZod, inspect } from './introspect'\n\n// A field's display NAME. Unlike its description (./defaults.ts), this is never derived from the\n// declaration: the field key already carries intent a type or format cannot \u2014 `contactEmail` reads as\n// \"Contact Email\", where a per-format label would flatten it to \"Email\" \u2014 so a generic fallback word would\n// only ever be a downgrade.\n\n// Words a title-cased label should shout rather than capitalise. Without these, `baseUrl` reads as\n// \"Base Url\" \u2014 derived-looking in exactly the way that makes an author go and write the label by hand.\nconst ACRONYMS = new Set(['id', 'url', 'urls', 'api', 'uri', 'ip', 'ipv4', 'ipv6', 'uuid', 'guid', 'jwt',\n 'sms', 'html', 'css', 'json', 'xml', 'csv', 'pdf', 'sql', 'ttl', 'sku', 'utm', 'cc', 'bcc', 'crm', 'db'])\n\n// A field key as a human label: `contactEmail` \u2192 \"Contact Email\", `base_url` \u2192 \"Base URL\".\nexport function humanizeKey(name: string): string {\n return name\n // split camelCase and consecutive-capital runs (`baseURL` \u2192 `base URL`)\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .trim()\n .split(/\\s+/)\n .filter(Boolean)\n .map(word => ACRONYMS.has(word.toLowerCase())\n ? word.toUpperCase()\n : word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\n// The label as the console should show it: the author's, else the field key made human.\nexport const labelOf = (name: string, schema: AnyZod): string =>\n inspect(schema).meta.title || humanizeKey(name) || name\n", "import { hasPassThroughDate, passesDateThrough } from './dates'\nimport { type AnyZod, DEFAULT_WRAPPERS, innerOf, inspect, shapeEntries, TRANSPARENT_WRAPPERS } from './introspect'\nimport { labelOf } from './labels'\n\n// What one declared field needs, worked out ONCE and reused for every invocation.\n//\n// The interesting part is `absence`. An author writes `.optional()` or `.nullable()` \u2014 whichever reads\n// naturally \u2014 and should not have to predict which absent form a client will send. So instead of reading the\n// wrapper chain, we ASK THE SCHEMA what it accepts: two `safeParse` probes settle it, and they are immune to\n// wrapper order (`.optional().nullable()` vs `.nullable().optional()`), to `.refine()` wrapping the type, and\n// to any modifier zod adds later. Introspection would have to keep up with all three.\n\nexport type AbsencePolicy =\n // The schema tolerates both forms, so whichever arrived is passed through (`.nullish()`).\n | 'as-received'\n // Only `undefined` is accepted (`.optional()`, `.default(v)`), so any absence becomes that.\n | 'undefined'\n // Only `null` is accepted (`.nullable()`), so any absence becomes that.\n | 'null'\n // Neither \u2014 the field has nothing to fall back on.\n | 'required'\n\nexport interface FieldPlan {\n name: string\n schema: AnyZod\n // The author's display name, used in messages. Falls back to the key.\n label: string\n // Core zod type past the wrappers: 'string' | 'number' | 'boolean' | 'enum' | 'date' | \u2026\n // For a union this is the FIRST branch's type \u2014 see `isUnion`.\n coreType: string\n /**\n * True when the declaration is a `z.union()`.\n *\n * Carried because `coreType` alone stops describing the field: a union resolves to its first branch, so a\n * `z.union([z.email(), z.literal('')])` reports `'string'` and would then treat a blank as a VALUE. It is\n * not one \u2014 `''` has always been absence on a union, which is exactly what makes the documented\n * \"blank means not set\" spelling (`z.union([z.url(), z.literal('')]).optional()`) work.\n */\n isUnion: boolean\n absence: AbsencePolicy\n // True when a declared `.default(v)` will absorb an absent value \u2014 which is also what lets a blank string\n // fall back to the default rather than surviving as `''`.\n absorbsBlank: boolean\n /**\n * True for a `z.date()` whose value must reach the handler UNCHANGED \u2014 validated through a converted copy,\n * handed over as the host sent it. False for `z.coerce.date()`, which the author asked to convert.\n *\n * Set when the field ITSELF is such a date; `restoresDates` covers one nested anywhere inside it.\n */\n passThroughDate: boolean\n // Whether anything at any depth needs that treatment, so the restore walk can be skipped entirely.\n restoresDates: boolean\n}\n\n// Ask the schema which absent forms it accepts. A probe can only throw for an async refinement placed\n// outside the modifier, in which case treating the field as required is the safe reading.\n/**\n * The absent forms the author DECLARED, read off the wrapper chain.\n *\n * Used only where the probe below cannot be trusted \u2014 see `probeAbsence`. It has to agree with the probe on\n * every schema the probe handles, which is why it treats `.default()` as accepting `undefined`: zod applies\n * a default to `undefined`, so that is what the probe observes too.\n */\nfunction declaredAbsence(schema: AnyZod): { absence: AbsencePolicy; absorbsBlank: boolean } {\n let current: AnyZod | undefined = schema\n let acceptsUndefined = false\n let acceptsNull = false\n let absorbsBlank = false\n // `.nonoptional()` re-asserts a requirement over whatever it wraps \u2014 an `.optional()` further in does not\n // undo it, so nothing after it may set a flag. Mirrors the same rule in ./introspect.ts `inspect`.\n let sealed = false\n\n while (current?._zod) {\n const def = current._zod.def ?? {}\n const type = def.type as string\n\n if (type === 'nonoptional') {\n sealed = true\n } else if (TRANSPARENT_WRAPPERS.has(type)) {\n // Says nothing about absence \u2014 look straight through it, exactly as `inspect` does.\n current = innerOf(def, type)\n continue\n } else if (sealed) {\n break\n } else if (type === 'optional') {\n acceptsUndefined = true\n } else if (type === 'nullable') {\n acceptsNull = true\n } else if (type === 'nullish') {\n acceptsUndefined = true\n acceptsNull = true\n } else if (DEFAULT_WRAPPERS.has(type)) {\n acceptsUndefined = true\n absorbsBlank = true\n } else {\n break\n }\n\n current = def.innerType as AnyZod\n }\n\n const absence: AbsencePolicy = acceptsUndefined && acceptsNull ? 'as-received'\n : acceptsUndefined ? 'undefined'\n : acceptsNull ? 'null'\n : 'required'\n\n return { absence, absorbsBlank }\n}\n\n// `z.coerce.*` converts an ABSENT value into a junk one rather than rejecting it \u2014 `new Date(null)` is the\n// epoch, `Number('')` is 0, `String(undefined)` is the text `'undefined'`, `Boolean(null)` is false. So a\n// coercing schema answers \"yes\" to the probe below for a field the author declared REQUIRED, and a blank\n// silently becomes 1970-01-01 or 0 instead of being reported. Where coercion is what makes the answer yes,\n// the declaration is the authority instead.\nfunction coerces(schema: AnyZod): boolean {\n return inspect(schema).core?._zod?.def?.coerce === true\n}\n\n/**\n * `z.json()` \u2014 the same problem as `z.coerce.*` above, from the other direction.\n *\n * It declares `z.unknown()` underneath, because what reaches the handler is a parsed JSON value and `null`\n * is one of those. The probe then sees a schema that accepts `null` and reads it as \"null is how this field\n * spells absence\", so a bare `z.json()` published as OPTIONAL \u2014 a field the author never marked optional and\n * which the runtime does in fact reject when it is missing.\n *\n * The probe cannot tell a legal value from an absent form by asking, so the declaration is the authority\n * here too: `.nonoptional()` on the helper means required, and an author's own `.optional()` sits outside it\n * and still wins.\n */\nconst parsesJson = (schema: AnyZod): boolean => !!inspect(schema).meta.frJson\n\nfunction probeAbsence(schema: AnyZod): { absence: AbsencePolicy; absorbsBlank: boolean } {\n if (coerces(schema) || parsesJson(schema)) {\n return declaredAbsence(schema)\n }\n\n const parse = (value: unknown): { success: boolean; data?: unknown } => {\n try {\n return (schema as unknown as { safeParse: (v: unknown) => { success: boolean; data?: unknown } }).safeParse(value)\n } catch {\n return { success: false }\n }\n }\n\n const asUndefined = parse(undefined)\n const asNull = parse(null)\n\n // \"Accepts both\" must win over \"has a default\": for `z.string().nullable().default('x')` the author said\n // null is meaningful, and zod applies the default to `undefined` on its own.\n const absence: AbsencePolicy = asUndefined.success && asNull.success ? 'as-received'\n : asUndefined.success ? 'undefined'\n : asNull.success ? 'null'\n : 'required'\n\n // A default reveals itself by yielding something other than what was fed in. This is also why a falsy\n // default (`''`, `0`, `false`) is detected correctly, where a truthiness check would drop it.\n return { absence, absorbsBlank: asUndefined.success && asUndefined.data !== undefined }\n}\n\n// Probing costs two `safeParse` calls, and the deep walk asks the same element or property schema once per\n// item. Schemas are stable objects built at registration, so the answer is cached against the schema itself.\nconst probeCache = new WeakMap<object, { absence: AbsencePolicy; absorbsBlank: boolean }>()\n\n/** The absent forms a schema accepts, at any depth. Same question `planField` asks for a top-level field. */\nexport function absenceOf(schema: AnyZod | undefined): { absence: AbsencePolicy; absorbsBlank: boolean } {\n if (!schema || typeof schema !== 'object') {\n return { absence: 'as-received', absorbsBlank: false }\n }\n\n const cached = probeCache.get(schema as object)\n\n if (cached) {\n return cached\n }\n\n const probed = probeAbsence(schema)\n\n probeCache.set(schema as object, probed)\n\n return probed\n}\n\nexport function planField(name: string, schema: AnyZod): FieldPlan {\n const ins = inspect(schema)\n const { absence, absorbsBlank } = probeAbsence(schema)\n\n return {\n name,\n schema,\n label: labelOf(name, schema),\n coreType: ins.coreType,\n isUnion : !!ins.branches,\n absence,\n absorbsBlank,\n passThroughDate: passesDateThrough(ins),\n restoresDates : hasPassThroughDate(schema, inspect, shapeEntries),\n }\n}\n", "import { formatOf, isConvertibleIso, toDate, toIso } from './dates'\nimport { absenceOf } from './field-plan'\nimport { type AnyZod, inspect, type Inspected, literalType, shapeEntries } from './introspect'\n\n// Step 2 of the pipeline: turn a transport value into the declared type.\n//\n// Coercion exists because the transport is stringly-typed. `toConfigType` maps `z.number()` to a *string*\n// config item \u2014 the config form has no numeric widget \u2014 so a number is stored and sent as `'123'`.\n// Expression-bound params do the same. Without this, every numeric config item would fail its own schema.\n//\n// Coerce only where the intent is unambiguous; anything else is an error rather than a guess. Note that\n// `z.coerce.*` is unusable here: `z.coerce.number().parse('')` is `0` and `z.coerce.boolean().parse('false')`\n// is `true`. This runs AFTER absence normalization, so a blank never reaches it.\n\nexport interface Coerced {\n ok: boolean\n value?: unknown\n // The zod type token the value should have been; ../schema/messages turns it into wording.\n expected?: string\n}\n\nconst ok = (value: unknown): Coerced => ({ ok: true, value })\nconst fail = (expected: string): Coerced => ({ ok: false, expected })\n\n// Matched after trim + lowercase. The test for ADDING a token, so the set has a stopping rule rather than\n// growing by precedent: it must have an unambiguous opposite, and the pair must both be listed. A word with\n// no opposite is a STATUS, not a boolean, and belongs in a `z.enum([...])`.\n//\n// Widening is only safe BECAUSE an unrecognised value fails (see `toBooleanValue`). Making an unknown default\n// to `false` \u2014 the partial hand-rolled allow-list this replaces \u2014 silently turns an explicit off into an on.\n//\n// The list is published to authors, so a change here is a change in three more places: the exhaustive pass in\n// `__tests__/configs-service.test.ts`, the table in `service-code-format/02-zod-types.md` (shipped inside the\n// CLI package), and the prose in `docs/guides/flow-extensions-custom/parameters-and-types.md`.\nconst TRUE = new Set(['true', '1', 'yes', 'y', 't', 'on', 'checked', 'enabled', 'enable', 'active'])\nconst FALSE = new Set(['false', '0', 'no', 'n', 'f', 'off', 'unchecked', 'disabled', 'disable', 'inactive'])\n\nfunction toStringValue(value: unknown): Coerced {\n if (typeof value === 'string') {\n return ok(value)\n }\n\n // A number or a boolean in a text field has one obvious text form. A structure does not \u2014 `String({})` is\n // '[object Object]' and `String([1,2])` is '1,2', which are artefacts of JS rather than what was meant.\n if (typeof value === 'boolean') {\n return ok(String(value))\n }\n\n return typeof value === 'number' && Number.isFinite(value) ? ok(String(value)) : fail('string')\n}\n\nfunction toNumberValue(value: unknown): Coerced {\n if (typeof value === 'number') {\n return Number.isFinite(value) ? ok(value) : fail('number')\n }\n\n if (typeof value !== 'string') {\n return fail('number')\n }\n\n // `Number('')` is 0 and `Number(' ')` is 0, so require actual digits. A blank has already been treated as\n // absence by this point; anything else non-numeric is a caller error.\n const parsed = Number(value.trim())\n\n return value.trim() !== '' && Number.isFinite(parsed) ? ok(parsed) : fail('number')\n}\n\n// `z.bigint()` wants an actual BigInt, so `Number()` would never satisfy it \u2014 a whole number is the only\n// input that can be converted without losing information.\nfunction toBigIntValue(value: unknown): Coerced {\n if (typeof value === 'bigint') {\n return ok(value)\n }\n\n if (typeof value === 'number') {\n return Number.isInteger(value) ? ok(BigInt(value)) : fail('bigint')\n }\n\n if (typeof value !== 'string' || value.trim() === '') {\n return fail('bigint')\n }\n\n try {\n return ok(BigInt(value.trim()))\n } catch {\n return fail('bigint')\n }\n}\n\nfunction toBooleanValue(value: unknown): Coerced {\n if (typeof value === 'boolean') {\n return ok(value)\n }\n\n if (typeof value === 'number') {\n return value === 1 ? ok(true) : value === 0 ? ok(false) : fail('boolean')\n }\n\n if (typeof value !== 'string') {\n return fail('boolean')\n }\n\n const lowered = value.trim().toLowerCase()\n\n return TRUE.has(lowered) ? ok(true) : FALSE.has(lowered) ? ok(false) : fail('boolean')\n}\n\n/**\n * `z.json()` \u2014 the transport carries text, the handler gets the structure.\n *\n * Parsing belongs here rather than in a `.transform()` for the reason the whole module exists: a failure has\n * to arrive as the same `Coerced` miss every other wrong-typed value produces, so it is reported against the\n * field by its label (\u00ABPayload\u00BB must be valid JSON) instead of escaping as a raw `SyntaxError` that names\n * neither the extension, the method, nor the parameter.\n */\nfunction toJsonValue(value: unknown): Coerced {\n // Already a structure. A flow can bind the parameter to an expression that evaluates to one, so the value\n // does not always arrive as text \u2014 and `JSON.parse({})` would throw on exactly the payload this type\n // exists to carry. Nothing to convert means nothing to do.\n if (typeof value !== 'string') {\n return ok(value)\n }\n\n try {\n return ok(JSON.parse(value))\n } catch {\n return fail('json')\n }\n}\n\n/**\n * Coerce one SCALAR `value` for a field whose core zod type is `coreType`. Types with no meaningful coercion\n * \u2014 enum, and everything the runtime does not special-case \u2014 pass through for the author's schema to judge:\n * membership is zod's job, not ours.\n *\n * Dates need the SCHEMA rather than the type name, because `z.date()`, `z.coerce.date()` and `z.iso.date()`\n * convert differently \u2014 see `coerceLeaf`.\n */\nexport function coerceValue(value: unknown, coreType: string): Coerced {\n if (coreType === 'string') {\n return toStringValue(value)\n }\n\n if (coreType === 'number') {\n return toNumberValue(value)\n }\n\n if (coreType === 'bigint') {\n return toBigIntValue(value)\n }\n\n if (coreType === 'boolean') {\n return toBooleanValue(value)\n }\n\n if (coreType === 'date') {\n const parsed = toDate(value)\n\n return parsed ? ok(parsed) : fail('date')\n }\n\n // An enum's options may be numbers declared as strings, so stringify a number and let zod check membership.\n if (coreType === 'enum' && typeof value === 'number') {\n return ok(String(value))\n }\n\n return ok(value)\n}\n\n/** Whether a schema accepts a value outright. A probe, so a throwing refinement reads as \"no\". */\nexport function accepts(schema: AnyZod, value: unknown): boolean {\n try {\n return !!(schema as unknown as { safeParse?: (v: unknown) => { success: boolean } })\n .safeParse?.(value)?.success\n } catch {\n return false\n }\n}\n\n/**\n * A union, resolved by TRYING its branches in declaration order \u2014 the first that coerces to something its\n * own branch accepts wins.\n *\n * Trying rather than picking is what keeps D1/D7 closed inside a union: a flow template supplies every value\n * as a string, so `z.union([z.boolean(), z.string()])` given `'true'` has to convert through the boolean\n * branch and succeed there. Picking the first branch blindly would hand `execute` the string.\n *\n * \u26A0\uFE0F **A permissive branch shadows every branch after it.** `z.union([z.string(), z.boolean()])` given\n * `'true'` matches the string branch as-is, so the boolean branch is never reached and `execute` receives\n * `'true'`. That is the same positional rule as publishing (both read declaration order, left to right),\n * which is why it was chosen \u2014 one mental model covers both. It is documented, and pinned by a test.\n *\n * When NO branch accepts it, the value is handed back untouched so the author's own union error is what the\n * user sees. This step never invents an error.\n */\nfunction coerceUnion(value: unknown, branches: AnyZod[]): unknown {\n for (const branch of branches) {\n const coerced = coerceDeep(value, branch)\n\n if (accepts(branch, coerced)) {\n return coerced\n }\n }\n\n return value\n}\n\n// The container types that DECLARE something about their contents, and so can be walked. Everything else \u2014\n// `unknown`, a bare `any` \u2014 declares nothing and is passed through as it arrived.\nconst CONTAINERS = new Set(['object', 'array', 'record'])\n\n/**\n * The same coercion, applied at every DEPTH \u2014 inside a declared object's properties and inside a list's\n * elements, not only at the top of a field.\n *\n * Without this a declaration means different things depending on where it sits: `z.string()` takes `42` at\n * the top level but `z.array(z.string())` rejects `[42]`, and `z.object({ zip: z.string() })` rejects\n * `{ zip: 12345 }`. The transport is no more type-faithful inside a container than outside one.\n *\n * The rule is simply: **walk whatever declares its contents, convert whatever declares a type, and leave\n * everything else alone.** A `z.record(z.string(), z.unknown())` therefore coerces nothing \u2014 not because\n * records are exempt, but because `unknown` declares no type to coerce to \u2014 while\n * `z.record(z.string(), z.number())` converts its values like any other declaration.\n *\n * BEST-EFFORT below the top level: a value that cannot be converted is left exactly as it arrived, for the\n * author's own schema to reject. That keeps the failure reported against the property that actually failed\n * (`tags.1`, `address.zip`) rather than as a coercion error naming the whole field, and it keeps this step\n * incapable of making anything stricter \u2014 it only ever converts.\n *\n * Absence is resolved at every depth too, by the same rule the top level uses: ask the sub-schema which\n * absent forms it accepts, and hand it the one it wants. Without that, `.optional()` means one thing on a\n * field and another inside a list \u2014 `z.array(z.string().optional())` would reject `[null]` while a bare\n * `z.string().optional()` accepts it.\n *\n * A sub-schema that accepts NO absent form is left exactly as it arrived, so zod raises it and the message\n * is built against the property that failed (`\u00ABCity\u00BB is required`) \u2014 this step never invents an error.\n */\nexport function coerceDeep(value: unknown, schema: AnyZod | undefined): unknown {\n if (!schema) {\n return value\n }\n\n const ins = inspect(schema)\n\n if (isBlank(value, ins, schema)) {\n return absentAs(schema, value)\n }\n\n if (value == null) {\n return value\n }\n\n // Before any type branch below: a union has no single type to walk, it has a list to try.\n if (ins.branches) {\n return coerceUnion(value, ins.branches)\n }\n\n if (ins.coreType === 'array') {\n const element = ins.core?._zod?.def?.element as AnyZod | undefined\n\n return Array.isArray(value) ? value.map(item => coerceDeep(item, element)) : value\n }\n\n if (ins.coreType === 'record') {\n if (typeof value !== 'object' || Array.isArray(value)) {\n return value\n }\n\n const valueType = ins.core?._zod?.def?.valueType as AnyZod | undefined\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, coerceDeep(item, valueType)])\n )\n }\n\n if (ins.coreType === 'object') {\n if (typeof value !== 'object' || Array.isArray(value)) {\n return value\n }\n\n const source = value as Record<string, unknown>\n // Only DECLARED properties are walked. An undeclared key is either stripped by zod or carried through\n // untouched by `z.looseObject`; either way the runtime has no declaration to coerce it against.\n const coerced: Record<string, unknown> = { ...source }\n\n for (const [name, property] of shapeEntries(ins.core)) {\n if (name in source) {\n coerced[name] = coerceDeep(source[name], property)\n }\n }\n\n return coerced\n }\n\n const result = coerceLeaf(value, ins)\n\n return result.ok ? result.value : value\n}\n\n/** True when a field's own type is a container this module walks rather than converts. */\nexport const isContainer = (coreType: string): boolean => CONTAINERS.has(coreType)\n\n/**\n * One leaf, converted for VALIDATION.\n *\n * Everything reaches zod as the type it declared: a date arrives as a `Date` whatever form the host sent, and\n * an ISO field arrives as a string in its own declared shape. What the HANDLER receives is a separate\n * question \u2014 a `z.date()` value is restored to the original afterwards (see ../normalize.ts).\n */\nexport function coerceLeaf(value: unknown, ins: Inspected): Coerced {\n // A union reaches here when its first branch is a scalar (that is what `isContainer` was asked about).\n // Always `ok`: an unmatched value is passed on for the author's union to reject with its own message.\n if (ins.branches) {\n return ok(coerceUnion(value, ins.branches))\n }\n\n // Ahead of every type branch below: `z.json()` declares `unknown`, so there is no core type to switch on.\n if (ins.meta.frJson) {\n return toJsonValue(value)\n }\n\n const format = formatOf(ins)\n\n if (ins.coreType === 'string' && isConvertibleIso(format)) {\n const iso = toIso(value, format as string)\n\n if (iso !== undefined) {\n return ok(iso)\n }\n\n // Nothing to reshape. A STRING is handed on unchanged so the format check speaks for itself \u2014 \"expects\n // an ISO date, e.g. 2024-01-01\" tells the author more than \"must be a date\", and it is what a blank or\n // a typo deserves. A non-string could never satisfy a string field at all, so it fails here.\n return typeof value === 'string' ? ok(value) : fail('date')\n }\n\n // A literal publishes as the type of its value (see ./introspect.ts `deriveWidget`), so it has to CONVERT\n // to that type as well. The console draws a toggle for `z.literal(true)` and the flow supplies the string\n // `'true'` like any other boolean; publishing a typed widget without the matching conversion would leave\n // the field unfillable from a flow. A mixed literal declares no single type and is passed through.\n if (ins.coreType === 'literal') {\n const declared = literalType(ins.core)\n\n return declared ? coerceValue(value, declared) : ok(value)\n }\n\n return coerceValue(value, ins.coreType)\n}\n\n// The same \"is this blank?\" rule the top-level pipeline applies (see ../schema/normalize.ts): `''` is a value\n// on a string unless a declared default can absorb it, and absence for every other type.\nfunction isBlank(value: unknown, ins: Inspected, schema: AnyZod): boolean {\n if (value === undefined || value === null) {\n return true\n }\n\n if (value !== '') {\n return false\n }\n\n // A union treats a blank as absence whatever its first branch resolved to. `''` is a value only on a plain\n // string type, and a union is not one \u2014 which is what makes `z.union([z.url(), z.literal('')]).optional()`\n // mean \"blank is not set\", the spelling the docs give for an optional formatted field.\n if (ins.branches) {\n return true\n }\n\n return ins.coreType !== 'string' || absenceOf(schema).absorbsBlank\n}\n\n// Hand the schema whichever absent form it accepts. `required` returns the value untouched, leaving zod to\n// report it against its own path.\nfunction absentAs(schema: AnyZod, value: unknown): unknown {\n const { absence } = absenceOf(schema)\n\n if (absence === 'required') {\n return value\n }\n\n if (absence === 'as-received') {\n return value === '' ? undefined : value\n }\n\n return absence === 'null' ? null : undefined\n}\n", "import { FlowExtensionParamWidgetTypes } from '../widget-types'\nimport { type AnyZod, inspect } from './introspect'\n\n// What a declaration explains about itself when the author wrote no `.describe()` \u2014 so `z.email()` stays a\n// legal one-liner and still renders with usable help text.\n//\n// These are applied at RENDER time, not baked into the published definition: the console derives them from\n// the schema the definition carries, so rewording an entry here reaches every already-deployed service\n// without a redeploy. `field-mapper` therefore publishes the author's description or nothing at all.\n//\n// Also read by ./messages.ts, which restates a format failure using the same wording the field advertises.\n//\n// Labels are NOT derived this way at all \u2014 see ./labels.ts for why the field key always wins.\n\n// Three maps rather than one, because the three key spaces overlap: `date` is both a zod format\n// (`z.iso.date()`) and a core type (`z.date()`). Kept separate, each stays a flat literal table and a\n// collision is impossible.\n\n/** `z.text()` \u2014 FlowRunner's own marker, the most specific thing a field can declare. */\nexport const WIDGET_DESCRIPTIONS: Record<string, string> = {\n [FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT]: 'Expects text; line breaks are allowed',\n}\n\n/**\n * `z.json()`. More specific than the widget it carries: it renders as the same textarea `z.text()` does, so\n * the widget wording would say \"line breaks are allowed\" and leave out the only rule that actually rejects\n * anything \u2014 that what is typed has to parse.\n */\nexport const JSON_DESCRIPTION = 'Expects JSON, e.g. {\"key\": \"value\"}'\n\n/**\n * The plain core type, when nothing more specific is declared.\n *\n * Only worth filling in where the widget does NOT already convey the type. `z.number()` earns one because a\n * number renders as a plain text field \u2014 there is no numeric widget \u2014 so \"Expects a number\" is real\n * information. `z.string()` and `z.boolean()` do not: the field is visibly a text box or a toggle, and\n * filling them would put generic prose under every field of every service, overwriting the meaningful empty\n * state that says \"the service author documented this\".\n */\nexport const TYPE_DESCRIPTIONS: Record<string, string> = {\n number : 'Expects a number',\n bigint : 'Expects a whole number',\n literal: 'Expects one fixed value',\n enum : 'Expects one of the listed options',\n // `z.date()` is deferred until the DATE type gets a widget; `z.iso.date()` is the working alternative.\n date : 'Expects a date',\n // string / boolean / array / object are deliberately absent \u2014 see above.\n}\n\n/**\n * A zod `format` token. Spelled out rather than composed \u2014 the wording is what a customer reads, so it\n * should be editable here without reasoning about how it is assembled. Every example is a value that\n * actually satisfies its helper.\n */\nexport const FORMAT_DESCRIPTIONS: Record<string, string> = {\n // \u2500\u2500 web \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n url : 'Expects a URL, e.g. https://example.com',\n email : 'Expects an email address, e.g. foo@bar.com',\n hostname : 'Expects a hostname, e.g. api.example.com',\n e164 : 'Expects a phone number in E.164 form, e.g. +14155552671',\n emoji : 'Expects an emoji, e.g. \uD83C\uDF89',\n // \u2500\u2500 identifiers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n uuid : 'Expects a UUID, e.g. 3f2504e0-4f89-11d3-9a0c-0305e82c3301',\n guid : 'Expects a GUID, e.g. 3f2504e0-4f89-11d3-9a0c-0305e82c3301',\n nanoid : 'Expects a Nano ID, e.g. V1StGXR8_Z5jdHi6B-myT',\n cuid : 'Expects a CUID, e.g. cjld2cyuq0000t3rmniod1foy',\n cuid2 : 'Expects a CUID2, e.g. tz4a98xxat96iws9zmbrgj3a',\n ulid : 'Expects a ULID, e.g. 01ARZ3NDEKTSV4RRFFQ69G5FAV',\n xid : 'Expects an XID, e.g. 9m4e2mr0ui3e8a215n4g',\n ksuid : 'Expects a KSUID, e.g. 0ujsswThIGTUYm2K8FjOOfXtY1K',\n // \u2500\u2500 ISO 8601 (z.iso.*) \u2014 a validated STRING, unlike the deferred z.date() \u2500\u2500\u2500\n datetime : 'Expects an ISO date and time, e.g. 2024-01-01T00:00:00Z',\n date : 'Expects an ISO date, e.g. 2024-01-01',\n time : 'Expects an ISO time, e.g. 12:30:00',\n duration : 'Expects an ISO duration, e.g. P3Y6M4D',\n // \u2500\u2500 encodings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n base64 : 'Expects a base64 string, e.g. aGVsbG8=',\n base64url: 'Expects a base64url string, e.g. aGVsbG8',\n hex : 'Expects a hex string, e.g. deadbeef',\n jwt : 'Expects a JWT, e.g. eyJhbGciOiJIUzI1NiJ9.eyJhIjoxfQ.c2ln',\n // \u2500\u2500 network \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n ipv4 : 'Expects an IPv4 address, e.g. 192.168.0.1',\n ipv6 : 'Expects an IPv6 address, e.g. 2001:db8::1',\n cidrv4 : 'Expects an IPv4 range, e.g. 192.168.0.0/24',\n cidrv6 : 'Expects an IPv6 range, e.g. 2001:db8::/32',\n}\n\n/**\n * What a field's declaration explains about itself, most specific wins:\n *\n * 1. `z.json()` \u2014 the content rule, which outranks the widget it shares with `z.text()`\n * 2. a FlowRunner widget marker \u2014 `z.text()`, a string the console renders specially\n * 3. a zod `format` token \u2014 `z.email()`, `z.ipv4()`, `z.iso.date()`, \u2026\n * 4. the plain core type \u2014 `number`, `bigint`, `literal`, `enum`, `date`\n *\n * All three are read past the optional/nullable/default wrappers, so a modifier never changes the answer.\n */\nexport function describeField(schema: AnyZod): string | undefined {\n const ins = inspect(schema)\n const format = (ins.core as { _zod?: { def?: { format?: string } } } | undefined)?._zod?.def?.format\n\n if (ins.meta.frJson) {\n return JSON_DESCRIPTION\n }\n\n return WIDGET_DESCRIPTIONS[ins.meta.frWidget ?? ''] ??\n FORMAT_DESCRIPTIONS[format ?? ''] ??\n TYPE_DESCRIPTIONS[ins.coreType]\n}\n", "import type { ValidationIssue } from '../../../errors'\nimport type { ZodIssue } from '../types'\nimport { FORMAT_DESCRIPTIONS } from './defaults'\nimport type { FieldPlan } from './field-plan'\nimport { type AnyZod, inspect, shapeEntries } from './introspect'\nimport { labelOf } from './labels'\n\n// Step 3's output, made readable. Zod's defaults describe the parser's disappointment rather than the\n// author's mistake \u2014 \"Invalid input: expected string, received undefined\" \u2014 so each issue code is restated\n// against the field's own `.label()`. An author-supplied message (`z.string().min(3, 'Too short')`) is left\n// exactly as written; only zod's own wording is replaced.\n//\n// A failure can be DEEPER than the field: `address.city` inside an object, `tags.1` inside a list. Those are\n// named by walking the declaration down the issue's own path, so the message names the property the user has\n// to fix rather than the container it sits in.\n\n// zod's `format` tokens, in the author's vocabulary. A format it does not name (a bare `.regex()`, say) has\n// nothing worth restating, so it falls back to the generic wording.\n// zod's `expected` tokens, as the phrase that completes \"\u00ABLabel\u00BB must be \u2026\". Spelled out so the wording is\n// editable without composing articles.\nconst EXPECTED: Record<string, string> = {\n string : 'a string',\n number : 'a number',\n int : 'an integer',\n bigint : 'a whole number',\n boolean: 'true or false',\n date : 'a date',\n object : 'an object',\n array : 'an array',\n // `z.json()`. Not a zod token \u2014 ./coerce.ts raises it when the submitted text will not parse.\n json : 'valid JSON',\n}\n\nexport const requiredMessage = (plan: FieldPlan): string => `\u00AB${ plan.label }\u00BB is required`\n\nexport const invalidTypeMessage = (plan: FieldPlan, expected: string): string =>\n `\u00AB${ plan.label }\u00BB must be ${ EXPECTED[expected] ?? expected }`\n\n// What one issue is ABOUT: the deepest declared thing on its path, and the value that sits there.\ninterface IssueTarget {\n // How to name it: a nested property uses its own label; a list item names the list plus its position.\n label: string\n // The submitted value at that path \u2014 how \"left empty\" is told apart from \"wrong type\" below the top level,\n // where the absence pipeline never ran (it only normalizes the field, not the field's insides).\n value: unknown\n found: boolean\n}\n\nconst isIndex = (segment: string): boolean => /^\\d+$/.test(segment)\n\n/**\n * Walk the field's declaration and the submitted value together, one path segment at a time.\n *\n * Stops early if the path leads somewhere the declaration does not describe (a passthrough object, say) and\n * reports the deepest thing it did resolve \u2014 a slightly less specific label beats a wrong one.\n */\nfunction resolveTarget(plan: FieldPlan, segments: string[], fieldValue: unknown): IssueTarget {\n let schema: AnyZod | undefined = plan.schema\n let value: unknown = fieldValue\n let label = plan.label\n let found = true\n\n for (const segment of segments) {\n const core = schema ? inspect(schema).core : undefined\n const coreType = core ? inspect(schema as AnyZod).coreType : undefined\n\n value = value == null ? undefined : (value as Record<string, unknown>)[segment]\n\n if (coreType === 'array' && isIndex(segment)) {\n // A list item has no name of its own, so it borrows the list's and states its position. 1-based: the\n // message is read by whoever filled the form in, not by whoever indexed the array.\n label = `${ label } item ${ Number(segment) + 1 }`\n schema = core?._zod?.def?.element as AnyZod | undefined\n continue\n }\n\n const nested = shapeEntries(core).find(([name]) => name === segment)\n\n if (!nested) {\n found = false\n break\n }\n\n schema = nested[1]\n label = labelOf(segment, schema)\n }\n\n return { label, value, found }\n}\n\n/**\n * A range bound, as the author would recognise it.\n *\n * zod compares dates as instants, so `z.date().min(new Date('2024-01-01'))` reports its bound as\n * `1704067200000` \u2014 a number nobody typed. On a date field it is rendered back as an ISO string.\n */\nfunction bound(value: unknown, plan: FieldPlan): string {\n if (plan.coreType !== 'date' || typeof value !== 'number') {\n return String(value)\n }\n\n const asDate = new Date(value)\n\n return Number.isNaN(asDate.getTime()) ? String(value) : asDate.toISOString()\n}\n\n// A zod issue carrying a custom message the author wrote \u2014 nothing to restate.\nfunction isAuthored(issue: ZodIssue & { message?: string }): boolean {\n const message = issue.message ?? ''\n\n // Every zod default starts by naming the input or the constraint; an authored one is arbitrary prose.\n return !!message && !/^(Invalid|Too big|Too small|Unrecognized|Not multiple)/.test(message)\n}\n\n/**\n * Restate one zod issue for a field. `path` is the field key \u2014 issues from a nested object keep the zod path\n * appended, so a caller can still point at the exact property.\n */\nexport function toFieldIssue(\n plan: FieldPlan,\n issue: ZodIssue & { message?: string; expected?: string; minimum?: unknown; maximum?: unknown; values?: unknown[] },\n fieldValue?: unknown\n): ValidationIssue {\n const segments = (issue.path ?? []).map(String).filter(Boolean)\n const path = segments.length ? `${ plan.name }.${ segments.join('.') }` : plan.name\n const code = issue.code ?? 'custom'\n const target = resolveTarget(plan, segments, fieldValue)\n // `plan` carries the top-level label; below the top level the resolved target carries the right one.\n const named = { ...plan, label: target.label }\n\n if (isAuthored(issue)) {\n return { path, code, message: issue.message as string }\n }\n\n if (code === 'invalid_type') {\n // Absence reaching validation means nothing was there to fall back on. At the top level the pipeline has\n // already normalized absence, so zod's `received` settles it; deeper down nothing normalized the value,\n // so the submitted value itself is what says whether the field was left empty or filled in wrongly.\n const received = (issue as { received?: string }).received\n const absent = segments.length\n ? target.found && target.value == null\n : received === 'undefined' || received === 'null' || issue.expected === undefined\n\n return absent\n ? { path, code, message: requiredMessage(named) }\n : { path, code, message: invalidTypeMessage(named, issue.expected ?? '') }\n }\n\n if (code === 'too_small') {\n return { path, code, message: `\u00AB${ target.label }\u00BB must be at least ${ bound(issue.minimum, plan) }` }\n }\n\n if (code === 'too_big') {\n return { path, code, message: `\u00AB${ target.label }\u00BB must be at most ${ bound(issue.maximum, plan) }` }\n }\n\n if (code === 'invalid_value') {\n // zod reports the accepted set as `values`.\n const values = (issue.values ?? []).map(String)\n\n return { path, code, message: `\u00AB${ target.label }\u00BB must be one of: ${ values.join(', ') }` }\n }\n\n if (code === 'invalid_format') {\n // The format's own description already says what shape is expected, so restate that rather than\n // inventing a second phrasing for the same fact.\n const described = FORMAT_DESCRIPTIONS[(issue as { format?: string }).format ?? '']\n\n return described\n ? { path, code, message: `\u00AB${ target.label }\u00BB is invalid \u2014 ${ described.replace(/^Expects /, 'expects ') }` }\n : { path, code, message: `\u00AB${ target.label }\u00BB has an invalid format` }\n }\n\n return { path, code, message: `\u00AB${ target.label }\u00BB is invalid` }\n}\n", "import type { ValidationIssue } from '../../../errors'\nimport type { ZodIssue } from '../types'\nimport { accepts, coerceDeep, coerceLeaf, isContainer } from './coerce'\nimport { passesDateThrough } from './dates'\nimport type { FieldPlan } from './field-plan'\nimport { type AnyZod, inspect, shapeEntries } from './introspect'\nimport { invalidTypeMessage, requiredMessage, toFieldIssue } from './messages'\n\n// The pipeline, per field:\n//\n// 1. normalize absence \u2192 2. coerce to the declared type \u2192 3. validate (the author's own schema)\n//\n// The order is load-bearing. Absence first, or a blank becomes garbage (`Number('')` is 0). Validation last,\n// and against the author's schema unchanged, so `.min()`, `.max()`, `.int()`, `.regex()`, enum membership and\n// refinements all work natively \u2014 nothing here reimplements them.\n\nexport interface FieldResult {\n // Absent from the output entirely when the field resolved to \"not present\" and had nothing to stand in.\n value?: unknown\n present: boolean\n issues: ValidationIssue[]\n}\n\nconst resolved = (value: unknown): FieldResult => ({ value, present: true, issues: [] })\nconst rejected = (issues: ValidationIssue[]): FieldResult => ({ present: false, issues })\n\n// `undefined` and `null` are always absence. `''` is absence only where the type has no empty value, or\n// where a declared default can absorb it \u2014 on a string it is otherwise a real value.\nfunction isAbsent(value: unknown, plan: FieldPlan): boolean {\n if (value === undefined || value === null) {\n return true\n }\n\n if (value !== '') {\n return false\n }\n\n // Same rule the deep walk applies (see ./coerce.ts `isBlank`): `''` is a value only on a plain string\n // type. A union resolves to its first branch for publishing, but that must not turn a blank into a value.\n if (plan.isUnion) {\n return true\n }\n\n return plan.coreType !== 'string' || plan.absorbsBlank\n}\n\n// Absence becomes whichever form the schema accepts, so the author's choice of modifier decides what the\n// handler sees rather than what the client happened to send.\nfunction normalizeAbsence(value: unknown, plan: FieldPlan): FieldResult {\n if (plan.absence === 'required') {\n return rejected([{ path: plan.name, code: 'invalid_type', message: requiredMessage(plan) }])\n }\n\n if (plan.absence === 'as-received') {\n // `.nullish()` accepts both, so a blank collapses to `undefined` and the rest arrive as sent.\n return validate(value === '' ? undefined : value, plan)\n }\n\n return validate(plan.absence === 'null' ? null : undefined, plan)\n}\n\n// Step 3. Zod short-circuits on the absent form it accepts, so a constraint never fires on an absent value.\nfunction validate(value: unknown, plan: FieldPlan): FieldResult {\n const schema = plan.schema as unknown as {\n safeParse: (v: unknown) => { success: boolean; data?: unknown; error?: { issues?: ZodIssue[] } }\n }\n\n let result\n\n try {\n result = schema.safeParse(value)\n } catch {\n // An async refinement cannot be evaluated here; surface it as a plain failure rather than crashing.\n return rejected([{ path: plan.name, code: 'custom', message: `\u00AB${ plan.label }\u00BB could not be validated` }])\n }\n\n return result.success\n ? resolved(result.data)\n : rejected((result.error?.issues ?? []).map(issue => toFieldIssue(plan, issue, value)))\n}\n\nexport function normalizeField(value: unknown, plan: FieldPlan): FieldResult {\n if (isAbsent(value, plan)) {\n return normalizeAbsence(value, plan)\n }\n\n // A container is WALKED \u2014 its declared properties and its elements are coerced in place \u2014 where a scalar\n // is converted outright. A container that cannot be walked (a string where a list was declared) is passed\n // through for zod to reject as the wrong type.\n if (isContainer(plan.coreType)) {\n return restore(validate(coerceDeep(value, plan.schema), plan), value, plan)\n }\n\n const coerced = coerceLeaf(value, inspect(plan.schema))\n\n if (!coerced.ok) {\n return rejected([{\n path : plan.name,\n code : 'invalid_type',\n message: invalidTypeMessage(plan, coerced.expected as string),\n }])\n }\n\n return restore(validate(coerced.value, plan), value, plan)\n}\n\n/**\n * Give a `z.date()` back the value the host actually sent.\n *\n * Validation needs a real `Date` \u2014 `z.date()` accepts nothing else, and `.min()` / `.max()` compare instants\n * \u2014 but converting is not what the handler should see: `'2024-06-01'` becomes `2024-06-01T00:00:00.000Z`,\n * inventing a time of day and a timezone nobody chose. So the check runs on a converted copy and the\n * original is restored afterwards, at every depth.\n *\n * `z.coerce.date()` is untouched: the author asked for a `Date`, so zod's output stands.\n */\nfunction restore(result: FieldResult, original: unknown, plan: FieldPlan): FieldResult {\n if (!plan.restoresDates || !result.present || result.issues.length) {\n return result\n }\n\n if (plan.passThroughDate) {\n return resolved(original)\n }\n\n return resolved(restoreDeep(result.value, original, plan.schema))\n}\n\n// Walk zod's output and the submitted value together, taking the ORIGINAL wherever the declaration is a\n// pass-through date. Only declared shapes are walked \u2014 the same rule the coercion walk follows.\nfunction restoreDeep(output: unknown, original: unknown, schema: AnyZod | undefined): unknown {\n if (!schema || output == null || original == null) {\n return output\n }\n\n const ins = inspect(schema)\n\n if (passesDateThrough(ins)) {\n return original\n }\n\n // A union was coerced through whichever branch accepted the value, so the restore walk has to follow that\n // same branch \u2014 the resolved first one says nothing about which date, if any, the value actually took.\n if (ins.branches) {\n const branch = ins.branches.find(option => accepts(option, output))\n\n return branch ? restoreDeep(output, original, branch) : output\n }\n\n const element = ins.core?._zod?.def?.element as AnyZod | undefined\n\n if (ins.coreType === 'array' && element && Array.isArray(output) && Array.isArray(original)) {\n return output.map((item, index) => restoreDeep(item, original[index], element))\n }\n\n const valueType = ins.core?._zod?.def?.valueType as AnyZod | undefined\n\n if (ins.coreType === 'record' && valueType && isPlain(output) && isPlain(original)) {\n return Object.fromEntries(\n Object.entries(output).map(([key, item]) => [key, restoreDeep(item, original[key], valueType)])\n )\n }\n\n if (ins.coreType === 'object' && isPlain(output) && isPlain(original)) {\n const restored: Record<string, unknown> = { ...output }\n\n for (const [name, property] of shapeEntries(ins.core)) {\n if (name in output) {\n restored[name] = restoreDeep(output[name], original[name], property)\n }\n }\n\n return restored\n }\n\n return output\n}\n\nconst isPlain = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n", "import type { ValidationIssue } from '../../../errors'\nimport type { ZodIssue, ZodSchema } from '../types'\n\n// The zod-facing half of validation: run a schema over a value and flatten its issues. Deciding WHICH\n// schema and WHICH error a failure becomes is the caller's job (see ../params.ts) \u2014 this module only knows\n// how to ask zod and how to translate what it answers.\n//\n// This is the WRAPPER path: the runtime-owned `payload` / `invocation` / `callbackObject` a helper route or\n// SYSTEM seam is called with, rather than a field a person filled in. A failure here means the CALLER is\n// malformed, so there is no author label to restate against \u2014 but zod's own wording (\"Invalid input:\n// expected object, received string\") describes the parser rather than the mistake, so the shape of the\n// wrapper itself is restated against the param's name. Everything deeper keeps zod's message: it is a\n// runtime contract detail, and inventing wording for it would only obscure what actually arrived.\n\n// A `fail` callback owns the error identity; it never returns.\nexport type FailFn = (issues: ValidationIssue[]) => never\n\n// Matches ./messages.ts, so the two paths word the same expectation the same way.\nconst EXPECTED: Record<string, string> = {\n string : 'a string',\n number : 'a number',\n boolean: 'true or false',\n object : 'an object',\n array : 'an array',\n}\n\nexport function toIssues(error: { issues?: ZodIssue[] } | undefined, param?: string): ValidationIssue[] {\n return (error?.issues ?? []).map(issue => {\n const path = (issue.path ?? []).map(String).join('.')\n const expected = (issue as { expected?: string }).expected\n\n // Only the wrapper's own type is restated \u2014 a deeper path is left as zod put it.\n const restated = param && !path && issue.code === 'invalid_type' && expected\n ? `\u00AB${ param }\u00BB must be ${ EXPECTED[expected] ?? expected }`\n : undefined\n\n return { path, message: restated ?? issue.message ?? 'invalid value', code: issue.code }\n })\n}\n\n// Parse `value`, handing the flattened issues to `fail` (which throws). Schema-less slots pass through \u2014\n// authors may declare no params/criteria at all.\nexport function parseSchema<T>(\n schema: ZodSchema | undefined,\n value: unknown,\n fail: FailFn,\n param?: string\n): T {\n if (typeof schema?.safeParse !== 'function') {\n return value as T\n }\n\n const result = schema.safeParse(value)\n\n if (!result.success) {\n fail(toIssues(result.error, param))\n }\n\n return result.data as T\n}\n", "import type { ValidationIssue } from '../../errors'\nimport { assertObjectSchema } from './schema/assert-object-schema'\nimport { assertSupportedSchema } from './schema/assert-supported-schema'\nimport { type FieldPlan, planField } from './schema/field-plan'\nimport { type AnyZod, shapeEntries } from './schema/introspect'\nimport { normalizeField } from './schema/normalize'\nimport { type FailFn, parseSchema } from './schema/parse'\nimport type { NormalizedInput, SchemaSource, ZodSchema } from './types'\n\n// A declared schema slot, as the runner works with it. Two things live here and nowhere else: the author's\n// zod schema, and the operations the runner performs on it. Anything zod can already do is DELEGATED \u2014 this\n// is a wrapper, never a re-implementation. `MethodParams` (inputs) and `ConfigParams` (config) extend it.\n//\n// Every slot is optional: an undeclared one produces an instance with no `scheme` that answers \"no fields\"\n// and passes values through unparsed, so call sites never need an `if (params)` guard. But a slot that IS\n// declared must be a z.object \u2014 the constructor enforces that, so an instance is never half-usable.\n\nexport abstract class Params {\n readonly scheme?: ZodSchema\n\n // Derived once per declared slot, at registration. The absence policy comes from probing the schema, which\n // is two `safeParse` calls we would rather not repeat on every invocation.\n #plans?: FieldPlan[]\n\n protected constructor(scheme?: unknown, readonly source: SchemaSource = {}) {\n // Declared \u21D2 must be a z.object. Checked here so EVERY slot is covered by construction, and at\n // registration time rather than on some later invocation (see ./schema/assert-object-schema.ts).\n assertObjectSchema(scheme, source)\n // \u2026and every field inside it must be something the runtime can publish, render and coerce. Same moment,\n // same reason: a declaration the runner cannot classify is a wrong contract, not a rendering nicety\n // (see ./schema/assert-supported-schema.ts).\n assertSupportedSchema(scheme, source)\n\n this.scheme = (scheme ?? undefined) as ZodSchema | undefined\n }\n\n // The declared field names. This is what a `dependsOn` is derived from.\n keys(): string[] {\n return this.fields().map(([name]) => name)\n }\n\n // The declared fields, in declaration order. Public: a renderer needs them as much as the pipeline does.\n fields(): [name: string, schema: AnyZod][] {\n return shapeEntries(this.scheme as AnyZod | undefined)\n }\n\n protected plans(): FieldPlan[] {\n this.#plans ??= this.fields().map(([name, schema]) => planField(name, schema))\n\n return this.#plans\n }\n\n /**\n * Normalize, coerce and validate a whole input object against the declared fields.\n *\n * Only declared fields appear in the output \u2014 an undeclared key is dropped, as it always was. Every\n * declared field appears, holding whatever it resolved to, which for an absent `.optional()` is\n * `undefined`: the key is there, so a handler asks `params.x === undefined` rather than `'x' in params`.\n * A field is omitted only when it FAILED, and then the caller is looking at `issues` instead.\n *\n * Every field is attempted even after one fails, so the caller can report the whole form at once instead\n * of making a user fix one field per attempt.\n */\n normalizeInput(input?: Record<string, unknown>): NormalizedInput {\n const source = input ?? {}\n const values: Record<string, unknown> = {}\n const issues: ValidationIssue[] = []\n\n for (const plan of this.plans()) {\n const result = normalizeField(source[plan.name], plan)\n\n if (result.issues.length) {\n issues.push(...result.issues)\n } else if (result.present) {\n values[plan.name] = result.value\n }\n }\n\n return { values, issues }\n }\n\n // Strict: required fields enforced, unknown stripped. For input the flow engine produces against the\n // published model, where a violation is a real contract break.\n parse<T>(value: unknown, fail: FailFn): T {\n return parseSchema<T>(this.scheme, value, fail)\n }\n\n}\n", "import type { ServiceConfigsValues } from '../../common/constants'\nimport { InvalidConfigError } from '../../errors'\nimport { Params } from './params'\nimport type { SchemaSource } from './types'\n\n// The extension's `configItems` slot: its description for the console, and the resolution of a concrete\n// invocation's values.\n//\n// Resolution runs the shared normalize \u2192 coerce \u2192 validate pipeline (see ./params.ts and ./schema/normalize),\n// so `configItems` obeys exactly the same policy as every other declared slot. It replaces the v1\n// `prepareServiceConfig` for this format: that resolver routed by the `shared` flag and applied defaults by\n// truthiness, which silently dropped a falsy default and never type-checked anything.\n\nexport class ConfigParams extends Params {\n static of(scheme?: unknown, source: SchemaSource = {}): ConfigParams {\n return new ConfigParams(scheme, source)\n }\n\n static empty(): ConfigParams {\n return new ConfigParams(undefined)\n }\n\n /**\n * The effective config for one invocation.\n *\n * Fails with every offending field at once rather than the first, so a half-configured service reports its\n * whole form. A field the schema resolved to \"not present\" is simply absent from the result.\n */\n resolve(configs?: ServiceConfigsValues): ServiceConfigsValues {\n const { values, issues } = this.normalizeInput(configs)\n\n if (issues.length) {\n throw new InvalidConfigError(this.source.serviceId ?? 'unknown', issues)\n }\n\n return values\n }\n}\n", "import { Params } from './params'\nimport type { FailFn } from './schema/parse'\nimport type { SchemaSource } from './types'\n\n// Every input container a method declares: an action's or trigger's `params`, a dictionary's `criteria`,\n// a `dynamicParams.criteria`, the object a `dynamicParams.resolve()` returns, and a SYSTEM method's\n// runtime-owned scheme. One class because they are the same thing \u2014 a z.object the runner validates input\n// against and publishes as the method's input model.\n\nexport class MethodParams extends Params {\n static of(scheme?: unknown, source: SchemaSource = {}): MethodParams {\n return new MethodParams(scheme, source)\n }\n\n // An undeclared slot. A real instance, so callers never branch on undefined.\n static empty(): MethodParams {\n return new MethodParams(undefined)\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Run the shared normalize \u2192 coerce \u2192 validate pipeline and hand the issues to `fail` (which throws).\n *\n * `carryUnknown` keeps the input's undeclared keys underneath the normalized ones. Two slots need it: an\n * action with `dynamicParams`, whose generated top-level fields are not in the static schema, and the\n * generated loaders, whose owner's `result` fn may read those same fields.\n */\n normalize<T extends Record<string, unknown>>(\n input: Record<string, unknown> | undefined,\n fail: FailFn,\n options: { carryUnknown?: boolean } = {}\n ): T {\n const { values, issues } = this.normalizeInput(input)\n\n if (issues.length) {\n fail(issues)\n }\n\n return (options.carryUnknown ? { ...input, ...values } : values) as T\n }\n}\n", "import { z as baseZod } from 'zod'\n\nimport {\n filesDeleteOptions,\n filesGetOptions,\n filesListOptions,\n filesUploadOptions,\n} from './files-options'\nimport { FlowExtensionParamWidgetTypes, type FrWidgetToken } from './widget-types'\n\n// The v2 authoring surface: real zod v4 extended with FlowRunner authoring plugins and custom types.\n// Exposed to services as `Flowrunner.z` (services do `const z = Flowrunner.z`) \u2014 see ../../namespace.ts.\n//\n// Author metadata is stored on the schema via zod's native `.meta()` (merges, immutable clone). Native\n// keys drive display (`title`, `description`, `examples`); FlowRunner-specific bits use `fr`-prefixed keys\n// so they never collide with zod/OpenAPI meta. The runner reads them back via ../schema/introspect.\n\n// A dictionary ref carried by `.dictionary(ref)` \u2014 returned from `ext.dictionary(...)` (see create-extension).\nexport interface DictionaryRef {\n id: string\n dependsOn?: string[]\n}\n\n// FlowRunner meta keys attached by the plugins below.\nexport interface FrMeta {\n title?: string\n description?: string\n examples?: unknown[]\n frShared?: boolean\n frDictionary?: { id: string; dependsOn: string[] }\n frLabels?: Record<string, string>\n /** A widget token the declaration carries explicitly \u2014 see `FrWidgetToken` in ./widget-types.ts. */\n frWidget?: FrWidgetToken\n frSecret?: boolean\n /** `z.json()` \u2014 the value arrives as TEXT and is parsed before the handler sees it. See `json()` below. */\n frJson?: boolean\n}\n\ndeclare module 'zod' {\n interface ZodType {\n /** Display label \u2192 native `meta.title`. */\n label(text: string): this\n /** Sample value \u2192 appended to native `meta.examples`. */\n example(value: unknown): this\n /** Mark a config field as shared (global) rather than per-app (OAuth client id/secret, secrets). */\n shared(): this\n /**\n * Mark a `z.string()` CONFIG field as sensitive: the console masks it and offers a reveal toggle.\n *\n * Display only. The value is stored, transmitted and validated exactly as it would be without it \u2014 this\n * hides a credential from a passer-by, it does not protect it.\n *\n * No effect anywhere else. Not on `z.text()`, which has no password mode; and not on an action or\n * trigger param, whose value lives in the flow definition and is readable through the API, so masking\n * its input would suggest a protection that is not there.\n */\n secret(): this\n /** Bind a param to a dictionary for dynamic options; auto-derives `dependsOn` from the dictionary criteria. */\n dictionary(ref: DictionaryRef): this\n /**\n * Show a human label per declared VALUE: `.labels({ asc: 'Ascending' })`.\n *\n * The flow element stores the VALUE, so renaming a label changes nothing that was saved \u2014 and the\n * handler receives the value it declared, with no translation step anywhere.\n */\n labels(byValue: Record<string, string>): this\n /** @deprecated Inverted and renamed \u2014 see `labels`. Throws, so the change cannot pass silently. */\n map(mapping: Record<string, unknown>): never\n }\n}\n\nlet extended = false\n\nfunction extendPrototype(): void {\n if (extended) {\n return\n }\n extended = true\n\n const proto = baseZod.ZodType.prototype as unknown as Record<string, unknown>\n\n proto.label = function label(this: baseZod.ZodType, text: string) {\n return this.meta({ title: text })\n }\n\n proto.example = function example(this: baseZod.ZodType, value: unknown) {\n const existing = (this.meta() as FrMeta | undefined)?.examples ?? []\n\n return this.meta({ examples: [...existing, value] })\n }\n\n proto.shared = function shared(this: baseZod.ZodType) {\n return this.meta({ frShared: true })\n }\n\n proto.secret = function secret(this: baseZod.ZodType) {\n return this.meta({ frSecret: true })\n }\n\n proto.dictionary = function dictionary(this: baseZod.ZodType, ref: DictionaryRef) {\n return this.meta({ frDictionary: { id: ref.id, dependsOn: ref.dependsOn ?? [] } })\n }\n\n proto.labels = function labels(this: baseZod.ZodType, byValue: Record<string, string>) {\n return this.meta({ frLabels: byValue })\n }\n\n /**\n * `.map({ Label: value })` declared the LABELS as the accepted values, so a flow element stored a display\n * string \u2014 renaming a label then broke every saved element that used it. `.labels()` inverts it: the enum\n * declares the values, the labels are display only.\n *\n * It throws rather than being quietly accepted because the two forms take the same shape of argument with\n * the opposite meaning. Silently reading an old `.map()` would store labels again; ignoring it would drop\n * the labels. A loud failure at registration is the only reading that cannot corrupt a flow.\n */\n proto.map = function map(this: baseZod.ZodType): never {\n throw new Error(\n '`.map({ Label: value })` has been replaced by `.labels({ value: \\'Label\\' })` \u2014 declare the VALUES in ' +\n 'the enum and the labels here, so a flow element stores the value and renaming a label is safe. ' +\n 'e.g. z.enum([\\'asc\\', \\'desc\\']).labels({ asc: \\'Ascending\\', desc: \\'Descending\\' })'\n )\n }\n}\n\nextendPrototype()\n\n// Custom type: multi-line text is a `z.string()` carrying a widget marker.\nfunction text() {\n\n return baseZod.string().meta({ frWidget: FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT })\n}\n\n/**\n * Custom type: a parameter that takes arbitrary JSON.\n *\n * Three facts have to hold at once, and each picks one piece of this declaration:\n *\n * - **The console renders a textarea.** `frWidget` says so, and ../schema/introspect.ts publishes the\n * parameter as `STRING` \u2014 the model describes what a caller SUPPLIES, and what a caller supplies is text.\n * - **`execute` receives the parsed structure.** `frJson` tells ../schema/coerce.ts to `JSON.parse` the text\n * on the way in, so no service writes its own parse and none has to invent wording for text that is not\n * JSON. Coercion already sits between the transport and zod for exactly this kind of conversion \u2014 this is\n * the same arrangement as `z.string().pipe(z.coerce.number())`, with a fixed conversion.\n * - **The author's TYPE is the parsed value, not the text.** Hence `unknown` underneath: `z.infer` gives the\n * handler `unknown`, which is what it actually receives. Declaring `z.string()` here would publish and\n * coerce correctly and then lie to every author about what lands in `params`.\n *\n * \u26A0\uFE0F This SHADOWS zod's own `z.json()` (the namespace is `Object.create(baseZod)`). Deliberate, and safe\n * only because zod's version cannot currently be declared at all \u2014 it recurses until the stack is gone, and\n * the extension never registers (FR-3600). An author reaching for `z.json()` gets this one.\n */\nfunction json() {\n\n // `.nonoptional()` because `z.unknown()` accepts `undefined` on its own, and the console asks the same\n // absence probe the runtime resolves with (see ../model/field-mapper.ts `isRequired`) \u2014 so without it a\n // bare `z.json()` would publish as an OPTIONAL field and the runner would accept a missing value, which is\n // not what an author who did not write `.optional()` asked for. An author's own `.optional()` still wins:\n // it lands outside this, and the outermost modifier is the final word.\n return baseZod.unknown().nonoptional().meta({\n frWidget: FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT,\n frJson : true,\n })\n}\n\n// NB: never mutate `baseZod` itself \u2014 zod's module exports are not extensible. The ESM build exposes\n// `z` as a frozen module namespace, and since zod 4.6.0 the CJS build freezes its exports too, so\n// `Object.assign(baseZod, ...)` throws \"Cannot add property text, object is not extensible\" at module\n// load \u2014 which takes down the whole extension worker thread before any service code runs. Layering the\n// additions onto a child object keeps every zod export reachable through the prototype chain while\n// leaving zod's own exports untouched.\n// The additions are DEFINED rather than assigned, for a second-order version of the same hazard: `json`\n// SHADOWS a zod export, `Object.assign` writes through plain assignment, and assignment respects the\n// PROTOTYPE's descriptor \u2014 zod's `json` is non-writable, so it throws \"Cannot assign to read only property\n// 'json'\" at module load and takes the worker down exactly as mutating `baseZod` would. `defineProperty`\n// creates an own property without consulting the prototype, which is what shadowing requires.\n//\n// `Omit` on the base is what makes `z.json()` unambiguous: intersecting the two signatures would leave zod's\n// recursive-JSON overload callable, and an author would get its type for our value.\nconst namespace = Object.create(baseZod) as typeof baseZod\n\n// The file-options groups are custom types in the same sense \u2014 see ./files-options.ts for why they are\n// shipped rather than hand-copied into each service.\nObject.defineProperties(namespace, {\n text: { value: text, enumerable: true },\n json: { value: json, enumerable: true },\n filesUploadOptions: { value: filesUploadOptions, enumerable: true },\n filesListOptions: { value: filesListOptions, enumerable: true },\n filesGetOptions: { value: filesGetOptions, enumerable: true },\n filesDeleteOptions: { value: filesDeleteOptions, enumerable: true },\n})\n\nexport const z = namespace as unknown as\n Omit<typeof baseZod, 'json'> & {\n text: typeof text\n json: typeof json\n filesUploadOptions: typeof filesUploadOptions\n filesListOptions: typeof filesListOptions\n filesGetOptions: typeof filesGetOptions\n filesDeleteOptions: typeof filesDeleteOptions\n }\n\nexport type ExtendedZod = typeof z\n", "import { z as baseZod } from 'zod'\n\nimport { FlowExtensionParamWidgetTypes, type FrGroupToken } from './widget-types'\n\n// The platform's own file-storage option groups, declared once and handed to services through\n// `Flowrunner.z` (see ./zod.ts) \u2014 the v2 counterpart of the built-in `FilesUploadOptions` /\n// `FilesListOptions` / `FilesGetOptions` / `FilesDeleteOptions` param types the v1 JSDoc parser registers\n// (`jsdoc-parser/src/custom-type-defs/files.ts`).\n//\n// **Why this is shipped rather than copied.** A v1 service names the type and gets the platform's values,\n// labels, descriptions and defaults; reword a label here and every v1 service picks it up on the next parse.\n// Without an equivalent, every v2 service that stores a file owns a private copy of the same ten lines \u2014\n// nothing propagates, and a copy that drifts publishes a field the runtime does not have. That is not\n// hypothetical: the v1 services that shadow the built-in with their own typedef publish a `directory` option\n// `uploadFile` silently drops.\n//\n// **The `include` argument.** v1 subsets a group at publish time with `@paramDef {\u2026 \"include\":[\"scope\"]}`,\n// and 706 of the catalog's 729 `@paramDef`s do. The factories below take that same list, so an existing\n// `@paramDef` translates by inspection and the published param comes out identical. No argument means every\n// field, matching v1's no-`include` behaviour.\n//\n// Two display differences from v1 are expected and harmless, because both are widgets the console resolves\n// to the same control: a plain string publishes no `uiComponent` at all (the v2 model omits display defaults\n// so they can be reworded without a redeploy \u2014 `SINGLE_LINE_TEXT` is the console's fallback), and a number\n// publishes `NUMERIC_STEPPER` where v1 hand-wrote the legacy `NUMERIC`. `scope`, the only field the catalog\n// actually exposes, is byte-identical \u2014 see `__tests__/files-options-schema.test.ts`.\n//\n// \u26A0\uFE0F Imports `zod` directly, never `./zod`, to keep the dependency one-way. The authoring plugins used below\n// (`.label()`) are installed on zod's prototype by ./zod.ts, which imports THIS module \u2014 safe because a\n// factory can only be reached through the namespace that module builds, so the plugins are always in place\n// by the time one runs.\n\n// Kept in step with `FileScope` in ../../common/context-files.ts, which cannot be imported here: it pulls in\n// the HTTP client, and the params framework is compiled into the console's browser bundle. A test asserts\n// the two agree.\nconst SCOPE_VALUES = ['WORKSPACE', 'FLOW', 'EXECUTION'] as const\n\n// `scope` is the one field shared by all four groups \u2014 and the only one the catalog exposes to flow authors.\nconst scope = () => baseZod.enum(SCOPE_VALUES)\n .label('Scope')\n .describe('Storage scope: WORKSPACE (shared across flows), FLOW (this flow only), EXECUTION (this run only)')\n .default('FLOW')\n\nconst ttl = () => baseZod.number()\n .label('URL TTL (seconds)')\n .describe('How long the download URL remains valid')\n .optional()\n\nconst generateUrl = () => baseZod.boolean()\n .label('Generate download URL')\n .describe('Include a pre-signed download URL in the response')\n .default(true)\n\n// A group is a table of FACTORIES, not of schemas: each call hands the service a fresh object, so one\n// service's `.optional()` or `.describe()` can never reach another's.\ntype FieldTable = Record<string, () => baseZod.ZodType>\n\nconst UPLOAD_FIELDS = {\n scope,\n filename: () => baseZod.string()\n .label('Filename')\n .describe('Custom filename (defaults to the original name if omitted)')\n .optional(),\n ttl,\n objectTtl: () => baseZod.number()\n .label('File TTL (seconds)')\n .describe('How long the file is kept in storage (omit for permanent storage)')\n .optional(),\n overwrite: () => baseZod.boolean()\n .label('Overwrite existing')\n .describe('Replace the file if one with the same name already exists')\n .optional(),\n generateUrl,\n} satisfies FieldTable\n\nconst LIST_FIELDS = {\n scope,\n limit: () => baseZod.number()\n .label('Limit')\n .describe('Maximum number of files to return')\n .optional(),\n ttl: () => baseZod.number()\n .label('URL TTL (seconds)')\n .describe('How long the download URLs remain valid')\n .optional(),\n generateUrl: () => baseZod.boolean()\n .label('Generate download URLs')\n .describe('Include pre-signed download URLs in the response')\n .default(true),\n cursor: () => baseZod.string()\n .label('Cursor')\n .describe('Pagination cursor from a previous response')\n .optional(),\n} satisfies FieldTable\n\nconst GET_FIELDS = {\n scope,\n ttl,\n generateUrl,\n} satisfies FieldTable\n\nconst DELETE_FIELDS = {\n scope,\n} satisfies FieldTable\n\n// The object a factory returns: the picked fields, each typed as its own factory declares it.\ntype Group<T extends FieldTable, K extends keyof T> = baseZod.ZodObject<{ [P in K]: ReturnType<T[P]> }>\n\n/**\n * Build one group, optionally subset to `include`.\n *\n * Two details reproduce v1 exactly (`jsdoc-parser/src/index.ts` `buildParam`): the result keeps the\n * CANONICAL field order rather than the order of `include` \u2014 so `['filename', 'scope']` still publishes\n * `scope` first \u2014 and an empty list is treated as no list, i.e. every field.\n *\n * An unknown name THROWS, where v1 silently published an empty object. A typo there is invisible until a\n * flow author opens the block and finds no settings at all; here it fails while the service registers, which\n * is the only moment anyone is looking.\n */\nfunction group<T extends FieldTable, K extends keyof T & string>(\n typeName: string,\n widget: FrGroupToken,\n table: T,\n include?: readonly K[]\n): Group<T, K> {\n const names = Object.keys(table)\n\n if (include?.length) {\n const unknown = include.filter(name => !names.includes(name))\n\n if (unknown.length) {\n throw new Error(\n `z.${ typeName }(): unknown field${ unknown.length > 1 ? 's' : '' } ${ unknown.map(n => `'${ n }'`).join(', ') }. ` +\n `Available fields: ${ names.join(', ') }.`\n )\n }\n }\n\n const selected = include?.length ? names.filter(name => include.includes(name as K)) : names\n\n const shape = Object.fromEntries(selected.map(name => [name, table[name]()]))\n\n // The group names itself in the published model (`uiComponent: { type: 'FILE_UPLOAD_OPTIONS' }`), so a\n // consumer can tell the platform's own options object from an anonymous one a service declared and render\n // it accordingly. See ../model/field-mapper.ts, which publishes it at every depth.\n return baseZod.object(shape).meta({ frWidget: widget }) as Group<T, K>\n}\n\nexport type FilesUploadOptionsField = keyof typeof UPLOAD_FIELDS & string\nexport type FilesListOptionsField = keyof typeof LIST_FIELDS & string\nexport type FilesGetOptionsField = keyof typeof GET_FIELDS & string\nexport type FilesDeleteOptionsField = keyof typeof DELETE_FIELDS & string\n\n/** Options for `ctx.files.uploadFile()`. `z.filesUploadOptions(['scope'])` is the form the catalog uses. */\nexport function filesUploadOptions<K extends FilesUploadOptionsField = FilesUploadOptionsField>(\n include?: readonly K[]\n): Group<typeof UPLOAD_FIELDS, K> {\n return group('filesUploadOptions', FlowExtensionParamWidgetTypes.FILE_UPLOAD_OPTIONS as FrGroupToken, UPLOAD_FIELDS, include)\n}\n\n/** Options for `ctx.files.list()`. */\nexport function filesListOptions<K extends FilesListOptionsField = FilesListOptionsField>(\n include?: readonly K[]\n): Group<typeof LIST_FIELDS, K> {\n return group('filesListOptions', FlowExtensionParamWidgetTypes.FILE_LIST_OPTIONS as FrGroupToken, LIST_FIELDS, include)\n}\n\n/** Options for `ctx.files.get()`. */\nexport function filesGetOptions<K extends FilesGetOptionsField = FilesGetOptionsField>(\n include?: readonly K[]\n): Group<typeof GET_FIELDS, K> {\n return group('filesGetOptions', FlowExtensionParamWidgetTypes.FILE_GET_OPTIONS as FrGroupToken, GET_FIELDS, include)\n}\n\n/** Options for `ctx.files.delete()`. */\nexport function filesDeleteOptions<K extends FilesDeleteOptionsField = FilesDeleteOptionsField>(\n include?: readonly K[]\n): Group<typeof DELETE_FIELDS, K> {\n return group('filesDeleteOptions', FlowExtensionParamWidgetTypes.FILE_DELETE_OPTIONS as FrGroupToken, DELETE_FIELDS, include)\n}\n\n// Exported for the test that keeps this table and `FileScope` in step.\nexport { SCOPE_VALUES }\n", "import type { JsonValue } from './types'\n\n// The two declarable primitives JSON has no room for. Boxed rather than stringified, so decoding can tell a\n// `BigInt('12')` from the string `'12'` \u2014 which matters, because `z.bigint()` rejects the string.\n\nconst isBox = (value: unknown, key: '$bigint' | '$date'): boolean =>\n !!value && typeof value === 'object' && key in (value as Record<string, unknown>)\n\n/** A declared value (a `.default()`, an enum member, a constraint bound) on its way out. */\nexport function toJsonValue(value: unknown): JsonValue {\n if (typeof value === 'bigint') {\n return { $bigint: value.toString() }\n }\n\n if (value instanceof Date) {\n return { $date: value.toISOString() }\n }\n\n if (Array.isArray(value)) {\n return value.map(toJsonValue)\n }\n\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, toJsonValue(inner)]))\n }\n\n return value as JsonValue\n}\n\n/** The same value on its way back in. */\nexport function fromJsonValue(value: JsonValue): unknown {\n if (isBox(value, '$bigint')) {\n return BigInt((value as { $bigint: string }).$bigint)\n }\n\n if (isBox(value, '$date')) {\n return new Date((value as { $date: string }).$date)\n }\n\n if (Array.isArray(value)) {\n return value.map(fromJsonValue)\n }\n\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, fromJsonValue(inner)]))\n }\n\n return value\n}\n", "import type { AnyZod } from '../schema/introspect'\nimport type { CheckJSON, FieldType, JsonValue, RegexJSON } from './types'\nimport { fromJsonValue, toJsonValue } from './values'\n\n// The constraint table, read in both directions from one place so encode and decode cannot drift.\n//\n// zod v4 keeps checks in `_zod.def.checks`, each with its own `_zod.def.check` discriminator. The names are\n// zod's internals rather than its API: `.min()` on a string is `min_length`, on a number `greater_than`, and\n// `.int()` is a `number_format`. Decoding goes back through the public API, where `.min()` covers both.\n\ninterface ZodCheckDef {\n check?: string\n format?: string\n minimum?: unknown\n maximum?: unknown\n length?: unknown\n value?: unknown\n inclusive?: boolean\n pattern?: RegExp\n prefix?: string\n suffix?: string\n includes?: string\n error?: unknown\n}\n\nconst defOf = (check: unknown): ZodCheckDef =>\n ((check as { _zod?: { def?: ZodCheckDef } } | undefined)?._zod?.def ?? {})\n\n/**\n * An author's own message, if they wrote one.\n *\n * zod normalizes a string message into a function, so the string is only reachable by CALLING it. A message\n * the author wrote as a function reads the issue and cannot be replayed here \u2014 the call is guarded and the\n * pipeline's own wording applies instead.\n */\nexport function messageOf(source: { error?: unknown }): string | undefined {\n const { error } = source\n\n if (typeof error === 'string') {\n return error\n }\n\n if (typeof error !== 'function') {\n return undefined\n }\n\n try {\n const produced = (error as (issue: unknown) => unknown)({ code: 'custom', input: undefined })\n\n return typeof produced === 'string' ? produced : undefined\n } catch {\n return undefined\n }\n}\n\nconst regexToJson = (pattern: RegExp): RegexJSON => ({ source: pattern.source, flags: pattern.flags })\n\n/** One zod check \u2192 its wire form, or `undefined` when it cannot cross (a function-backed check). */\nfunction encodeCheck(check: unknown): CheckJSON | undefined {\n const def = defOf(check)\n const message = messageOf(def)\n const at = (kind: CheckJSON['kind'], value?: JsonValue, exclusive?: true): CheckJSON => ({\n kind,\n ...(value === undefined ? {} : { value }),\n ...(exclusive ? { exclusive } : {}),\n ...(message ? { message } : {}),\n })\n\n switch (def.check) {\n // strings and arrays\n case 'min_length':\n return at('min', toJsonValue(def.minimum))\n case 'max_length':\n return at('max', toJsonValue(def.maximum))\n case 'length_equals':\n return at('length', toJsonValue(def.length))\n\n // numbers and bigints\n case 'greater_than':\n return at('min', toJsonValue(def.value), def.inclusive ? undefined : true)\n case 'less_than':\n return at('max', toJsonValue(def.value), def.inclusive ? undefined : true)\n case 'multiple_of':\n return at('multipleOf', toJsonValue(def.value))\n case 'number_format':\n // `.int()` \u2014 a format check rather than a range one.\n return def.format === 'safeint' || def.format === 'int32' ? at('int') : undefined\n\n // the string sub-formats that are checks rather than types\n case 'string_format':\n if (def.format === 'regex' && def.pattern) {\n return at('regex', regexToJson(def.pattern))\n }\n\n if (def.format === 'starts_with') {\n return at('startsWith', def.prefix ?? '')\n }\n\n if (def.format === 'ends_with') {\n return at('endsWith', def.suffix ?? '')\n }\n\n if (def.format === 'includes') {\n return at('includes', def.includes ?? '')\n }\n\n return undefined\n\n default:\n return undefined\n }\n}\n\nexport interface EncodedChecks {\n checks: CheckJSON[]\n unsupported: string[]\n}\n\n/** Every check a core schema carries. What cannot cross is NAMED rather than silently dropped. */\nexport function encodeChecks(core: AnyZod | undefined): EncodedChecks {\n const declared = (core?._zod?.def?.checks as unknown[] | undefined) ?? []\n const checks: CheckJSON[] = []\n const unsupported: string[] = []\n\n for (const check of declared) {\n const encoded = encodeCheck(check)\n\n if (encoded) {\n checks.push(encoded)\n continue\n }\n\n const def = defOf(check)\n\n unsupported.push(`check:${ def.check ?? 'unknown' }${ def.format ? `/${ def.format }` : '' }`)\n }\n\n return { checks, unsupported }\n}\n\n// A zod schema with the constraint methods the table above needs. Structural, so this file stays independent\n// of zod's generics \u2014 the methods exist on the string/number/array types that carry these checks.\ntype Constrainable = {\n min?: (value: never, message?: string) => Constrainable\n max?: (value: never, message?: string) => Constrainable\n gt?: (value: never, message?: string) => Constrainable\n lt?: (value: never, message?: string) => Constrainable\n length?: (value: number, message?: string) => Constrainable\n int?: (message?: string) => Constrainable\n multipleOf?: (value: never, message?: string) => Constrainable\n regex?: (pattern: RegExp, message?: string) => Constrainable\n startsWith?: (value: string, message?: string) => Constrainable\n endsWith?: (value: string, message?: string) => Constrainable\n includes?: (value: string, message?: string) => Constrainable\n}\n\n/**\n * Re-apply one wire check to a rebuilt schema.\n *\n * `type` decides nothing about WHICH method to call \u2014 `.min()` is `.min()` on a string, a number and an\n * array \u2014 it only guards the numeric-only ones. A check whose method is missing on this type is skipped\n * rather than thrown: a schema decoded slightly loose is the documented failure mode.\n */\nexport function applyCheck(schema: unknown, check: CheckJSON, type: FieldType): unknown {\n const target = schema as Constrainable\n const value = check.value === undefined ? undefined : fromJsonValue(check.value)\n const numeric = type === 'number' || type === 'bigint'\n const call = (\n method: keyof Constrainable,\n arg?: unknown\n ): unknown => {\n const fn = target[method]\n\n return typeof fn === 'function'\n ? (fn as (...args: unknown[]) => unknown).call(target, ...(arg === undefined ? [] : [arg]), check.message)\n : schema\n }\n\n switch (check.kind) {\n case 'min':\n return call(check.exclusive && numeric ? 'gt' : 'min', value)\n case 'max':\n return call(check.exclusive && numeric ? 'lt' : 'max', value)\n case 'length':\n return call('length', value)\n case 'int':\n return call('int')\n case 'multipleOf':\n return call('multipleOf', value)\n case 'regex': {\n const { source, flags } = (check.value ?? { source: '', flags: '' }) as unknown as RegexJSON\n\n return call('regex', new RegExp(source, flags))\n }\n case 'startsWith':\n return call('startsWith', value)\n case 'endsWith':\n return call('endsWith', value)\n case 'includes':\n return call('includes', value)\n default:\n return schema\n }\n}\n", "import type { FrWidgetToken } from '../widget-types'\n\n// The wire form of a declared schema.\n//\n// Written by the runner when a service is deployed or installed, stored on the definition, and read back by\n// the console \u2014 which rebuilds real zod from it (see ./decode.ts) and runs the SAME pipeline the runner runs.\n// That is the whole point: a form reports exactly the errors an execution would, because both sides validate\n// against the same schema rather than against two hand-kept descriptions of it.\n//\n// Hand-rolled rather than `z.toJSONSchema()`, because JSON Schema drops everything that makes a FlowRunner\n// field a FlowRunner field \u2014 `.label()`, `.shared()`, `.dictionary()`, `.map()`, an author's own check\n// message \u2014 and rebuilding zod from it would need a JSON-Schema interpreter anyway.\n\n// A value that survives JSON. The two primitives that do not are boxed (see ./encode.ts).\nexport type JsonValue =\n | string | number | boolean | null\n | { $bigint: string }\n | { $date: string }\n | JsonValue[]\n | { [key: string]: JsonValue }\n\n/** A constraint the author declared. `min`/`max` cover both length and magnitude \u2014 zod spells them alike. */\nexport interface CheckJSON {\n kind: 'min' | 'max' | 'length' | 'int' | 'multipleOf' | 'regex' | 'startsWith' | 'endsWith' | 'includes'\n value?: JsonValue\n // `.min(3)` is inclusive, `.gt(3)` is not. Absent means inclusive.\n exclusive?: true\n // An author's own message (`z.string().min(3, 'Too short')`), so the console words the failure the way the\n // runtime will. Absent \u21D2 the pipeline's own wording applies.\n message?: string\n}\n\n/** A serialized regex \u2014 `RegExp` itself is not JSON. Indexable so it satisfies `JsonValue`. */\nexport interface RegexJSON {\n [key: string]: JsonValue\n source: string\n flags: string\n}\n\n// The metadata an author attached. Native zod keys drive display; `fr`-prefixed keys are FlowRunner's.\nexport interface MetaJSON {\n title?: string\n description?: string\n examples?: JsonValue[]\n frShared?: boolean\n frWidget?: FrWidgetToken\n frSecret?: boolean\n frDictionary?: { id: string; dependsOn: string[] }\n frLabels?: Record<string, string>\n}\n\nexport type FieldType =\n | 'string' | 'number' | 'bigint' | 'boolean' | 'date'\n | 'enum' | 'literal' | 'object' | 'array' | 'record' | 'union'\n /**\n * Anything the encoder does not model \u2014 and also where a declared `z.any()` / `z.unknown()` legitimately\n * lands, since \"validates nothing\" is exactly what those two declare. The `unsupported` breadcrumb is what\n * separates the two cases: a modelling gap carries `['type:\u2026']`, a declared pass-through carries nothing.\n *\n * Decodes to `z.unknown()` either way, so it validates nothing.\n */\n | 'unknown'\n\nexport interface FieldJSON {\n name: string\n type: FieldType\n // A zod format token: 'email' | 'url' | 'ipv4' | 'datetime' | 'safeint' | \u2026\n format?: string\n // Accepts `undefined` / `null`. Recorded separately because they are separate modifiers, and the pipeline's\n // absence policy is derived by PROBING the rebuilt schema rather than by reading these back.\n optional?: true\n nullable?: true\n default?: JsonValue\n checks?: CheckJSON[]\n // enum members, or the literal's own value(s).\n values?: JsonValue[]\n meta?: MetaJSON\n // A schema-level message (`z.email('must be an email')`).\n message?: string\n // type === 'object'\n properties?: FieldJSON[]\n // type === 'array'\n element?: FieldJSON\n /**\n * type === 'union' \u2014 every declared branch, in declaration order.\n *\n * All of them are carried, not just the first. The first decides what the console DRAWS, but the rebuilt\n * schema has to accept everything the author's does: `json/types.ts`'s one-directional invariant is that a\n * decoded schema is never STRICTER than the author's, and encoding one branch would break it \u2014 the form\n * would reject a shape execution accepts.\n */\n options?: FieldJSON[]\n /**\n * type === 'record' \u2014 the schema its VALUES are held to. Keys are not modelled: the runtime only ever\n * walks a record's values (see ../schema/coerce.ts), and a decoded `z.record` therefore accepts any string\n * key, which keeps it no stricter than the author's.\n */\n value?: FieldJSON\n /**\n * What could not cross the wire \u2014 `['check:overwrite']`, `['wrapper:prefault']`, `['format:xyz']`.\n *\n * Functions cannot be serialized, so `.refine()`, `.transform()`, `.trim()` and friends are dropped. The\n * invariant that follows is deliberate and one-directional: **a decoded schema is never STRICTER than the\n * author's**. The console may therefore accept a value the runtime later rejects, but never reject one the\n * runtime would accept \u2014 and the runtime re-validates every invocation, so it stays the authority.\n */\n unsupported?: string[]\n}\n\nexport interface ParamsSchemaJSON {\n // Bumped only for a breaking change to the shapes above. Stored payloads outlive the code that wrote them:\n // a definition is encoded once at deploy time and decoded by whatever console version is live later.\n v: 1\n fields: FieldJSON[]\n}\n\nexport const SCHEMA_JSON_VERSION = 1 as const\n", "import { z } from '../zod'\nimport { applyCheck } from './checks'\nimport { type FieldJSON, type ParamsSchemaJSON, SCHEMA_JSON_VERSION } from './types'\nimport { fromJsonValue } from './values'\n\n// Wire \u2192 zod. Rebuilt through the PUBLIC zod API (and through the FlowRunner-extended `z`, so `.meta()`\n// carries `frWidget` / `frDictionary` / `frLabels` back), which is what makes the result indistinguishable from\n// the author's own schema as far as the pipeline is concerned.\n\ntype AnySchema = { meta?: (value: Record<string, unknown>) => AnySchema }\n\n// A zod factory that takes an optional message, as every one of these does.\ntype Factory = (message?: string) => unknown\n\n/**\n * `format` \u2192 the constructor that produces it.\n *\n * Rebuilt with the real helper rather than as `z.string().regex(...)`, because the pipeline reads the format\n * token back off the schema \u2014 it is what picks the widget and what words an `invalid_format` failure.\n *\n * Guarded with `typeof`, so a token this zod release does not know degrades to a plain string instead of\n * throwing at decode time. Stored payloads outlive the code that wrote them.\n */\nconst FORMAT_FACTORIES: Record<string, Factory | undefined> = {\n url : z.url,\n email : z.email,\n hostname : z.hostname,\n e164 : z.e164,\n emoji : z.emoji,\n uuid : z.uuid,\n guid : z.guid,\n nanoid : z.nanoid,\n cuid : z.cuid,\n cuid2 : z.cuid2,\n ulid : z.ulid,\n xid : z.xid,\n ksuid : z.ksuid,\n base64 : z.base64,\n base64url: z.base64url,\n hex : z.hex,\n jwt : z.jwt,\n ipv4 : z.ipv4,\n ipv6 : z.ipv6,\n cidrv4 : z.cidrv4,\n cidrv6 : z.cidrv6,\n // z.iso.* \u2014 validated STRINGS, unlike the `date` core type below.\n datetime : z.iso?.datetime,\n date : z.iso?.date,\n time : z.iso?.time,\n duration : z.iso?.duration,\n}\n\nfunction decodeString(field: FieldJSON): unknown {\n const factory = field.format ? FORMAT_FACTORIES[field.format] : undefined\n\n return typeof factory === 'function' ? factory(field.message) : z.string(field.message)\n}\n\nfunction decodeBase(field: FieldJSON): unknown {\n switch (field.type) {\n case 'string':\n return decodeString(field)\n\n case 'number':\n // `z.int()` is `z.number()` carrying the `safeint` format, and the pipeline reads that token back.\n return field.format === 'safeint' || field.format === 'int32' ? z.int(field.message) : z.number(field.message)\n\n case 'bigint':\n return z.bigint(field.message)\n\n case 'boolean':\n return z.boolean(field.message)\n\n case 'date':\n return z.date(field.message)\n\n case 'enum':\n return z.enum((field.values ?? []).map(fromJsonValue) as string[], field.message)\n\n case 'literal':\n return z.literal((field.values ?? []).map(fromJsonValue) as (string | number | boolean)[], field.message)\n\n case 'object':\n return z.object(Object.fromEntries((field.properties ?? []).map(inner => [inner.name, decodeField(inner)])))\n\n case 'array':\n return z.array((field.element ? decodeField(field.element) : z.unknown()) as never)\n\n // Every branch, so the rebuild accepts everything the author's union does. A single branch would make\n // the console's form stricter than execution, which ./types.ts forbids in that direction.\n case 'union': {\n const options = (field.options ?? []).map(decodeField)\n\n return options.length ? z.union(options as never) : z.unknown()\n }\n\n // Keys are open, as they are in the declaration: only the VALUES were modelled (see ./types.ts), so the\n // rebuild accepts any string key and stays no stricter than the author's.\n case 'record':\n return z.record(z.string(), (field.value ? decodeField(field.value) : z.unknown()) as never)\n\n default:\n // A field the encoder could not model validates nothing rather than rejecting everything \u2014 the\n // decoded schema is never stricter than the author's (see ./types.ts).\n return z.unknown()\n }\n}\n\n/**\n * One field, rebuilt.\n *\n * Order is load-bearing:\n * 1. the base type \u2014 a format helper, not a hand-rolled regex\n * 2. the author's checks \u2014 `.min()`, `.regex()`, \u2026\n * 3. `.meta()` LAST of the three, because a check clones the schema and metadata does not follow the clone\n * 4. the modifiers, canonically: nullable \u2192 optional \u2192 default\n *\n * Step 4's canonical order is why the wire form can record modifiers as flags \u2014 see ./encode.ts.\n */\nexport function decodeField(field: FieldJSON): unknown {\n let schema = decodeBase(field)\n\n for (const check of field.checks ?? []) {\n schema = applyCheck(schema, check, field.type)\n }\n\n if (field.meta) {\n schema = (schema as AnySchema).meta?.(fromJsonValue(field.meta as never) as Record<string, unknown>) ?? schema\n }\n\n const modifiers = schema as {\n nullable: () => typeof modifiers\n optional: () => typeof modifiers\n default: (value: unknown) => typeof modifiers\n }\n\n let wrapped = modifiers\n\n if (field.nullable) {\n wrapped = wrapped.nullable()\n }\n\n if (field.optional) {\n wrapped = wrapped.optional()\n }\n\n if (field.default !== undefined) {\n wrapped = wrapped.default(fromJsonValue(field.default))\n }\n\n return wrapped\n}\n\n/**\n * A whole stored schema, rebuilt as the `z.object` every slot must be. Nothing usable in \u21D2 `undefined` out,\n * which callers already treat as \"this slot declares nothing\".\n *\n * An envelope whose `v` this build does not know is refused rather than read as if it were the current\n * shape. Stored payloads outlive the code that wrote them \u2014 a definition is encoded once at deploy time and\n * decoded by whatever is deployed later \u2014 so a future `v: 2` would otherwise be silently misread field by\n * field. Refusing degrades to \"no schema\" and the caller falls back to the legacy projection, which is the\n * same direction every other loss in this codec takes (see ./types.ts).\n */\nexport function decodeParams(json: ParamsSchemaJSON | null | undefined): unknown {\n if (!json?.fields || json.v !== SCHEMA_JSON_VERSION) {\n return undefined\n }\n\n return z.object(Object.fromEntries(json.fields.map(field => [field.name, decodeField(field)])))\n}\n", "import { type AnyZod, innerOf, inspect, MAX_UNWRAP_DEPTH, shapeEntries, TRANSPARENT_WRAPPERS } from '../schema/introspect'\nimport { encodeChecks, messageOf } from './checks'\nimport { type FieldJSON, type FieldType, type MetaJSON, type ParamsSchemaJSON, SCHEMA_JSON_VERSION } from './types'\nimport { toJsonValue } from './values'\n\n// zod \u2192 wire. Reads the same `_zod.def` internals the rest of the framework reads (see ../schema/introspect).\n\n/**\n * The core types with a wire form of their own.\n *\n * Kept in step with `SUPPORTED_TYPES` (../schema/assert-supported-schema.ts) \u2014 the set registration holds an\n * author to. `any` and `unknown` are supported declarations that deliberately have no form here: they model\n * \"anything\", which is what the `unknown` wire type already means, so they encode to it WITHOUT an\n * `unsupported` breadcrumb (see `problemsFor`).\n */\nconst FIELD_TYPES = new Set<string>([\n 'string', 'number', 'bigint', 'boolean', 'date', 'enum', 'literal', 'object', 'array', 'record',\n])\n\n// `union` is not in FIELD_TYPES: `inspect()` resolves a union to its first branch, so it never arrives as a\n// declared type. It is detected by the branch list instead (see `encodeField`).\nconst UNION_TYPE = 'union' as FieldType\n\n// Declarations whose whole content is \"no constraint\". They encode as `unknown` legitimately, not as a gap.\nconst PASS_THROUGH_TYPES = new Set(['any', 'unknown'])\n\n// Wrappers whose effect the wire form records as a flag, and the one that cannot be recorded at all.\nconst WRAPPERS = new Set(['optional', 'nullable', 'default'])\n\ninterface Unwrapped {\n optional: boolean\n nullable: boolean\n defaultValue: unknown\n hasDefault: boolean\n unsupported: string[]\n}\n\n/**\n * Peel the modifier chain, recording WHICH modifiers were present rather than their order.\n *\n * This walk answers only \"which absence modifiers were declared\". **It does not decide the core type** \u2014\n * `inspect()` does, and `encodeField` reads it from there. Keeping a second opinion on the core here is what\n * let this module fall behind the rest of the framework once already: it kept its own narrower wrapper set,\n * so every declaration the type surface legitimized (`.readonly()`, `.pipe()`, `z.lazy()`, `.nonoptional()`,\n * `z.record()`) still crossed the wire as `unknown` while the published model had it right.\n *\n * Order is safe to lose because the pipeline derives its absence policy by probing the schema for the forms\n * it accepts (see ../schema/field-plan.ts), and the canonical order ./decode.ts rebuilds in preserves that\n * set for every combination \u2014 `.optional().nullable()` and `.nullable().optional()` accept the same things.\n */\nfunction unwrap(schema: AnyZod): Unwrapped {\n const result: Unwrapped = {\n optional: false,\n nullable: false,\n defaultValue: undefined,\n hasDefault: false,\n unsupported: [],\n }\n\n let current: AnyZod | undefined = schema\n // `.nonoptional()` re-asserts a requirement over whatever it wraps \u2014 mirrors ../schema/field-plan.ts.\n let sealed = false\n // The same bound `inspect()` puts on its own peel, for the same reason: a `z.lazy()` whose getter returns\n // another wrapper would unwrap forever, and nothing legitimate nests modifiers anywhere near this deep.\n let depth = 0\n\n while (current?._zod && depth++ < MAX_UNWRAP_DEPTH) {\n const def = current._zod.def ?? {}\n const type = def.type as string\n\n if (type === 'nonoptional') {\n sealed = true\n current = def.innerType as AnyZod\n continue\n }\n\n /**\n * Look STRAIGHT THROUGH the modifiers that say nothing about absence \u2014 the same set `inspect()` and\n * `declaredAbsence` look through.\n *\n * Without this the walk stopped at the first one and lost every flag beneath it:\n * `z.string().optional().readonly()` encoded as a plain required string, so the console rebuilt a schema\n * that DEMANDED a value the runner accepts as absent \u2014 a form that can never be saved, and a violation\n * of the one-directional invariant in ./types.ts. The core type was moved to `inspect()` and this walk\n * was left behind; it is the same drift, one function along.\n */\n if (TRANSPARENT_WRAPPERS.has(type)) {\n current = innerOf(def, type)\n continue\n }\n\n if (sealed) {\n break\n }\n\n if (!WRAPPERS.has(type)) {\n // `.prefault()` runs before parsing rather than in place of an absent value \u2014 a different contract, so\n // it is named as unsupported instead of being flattened into `default`.\n if (type === 'prefault' || type === 'nullish') {\n result.unsupported.push(`wrapper:${ type }`)\n current = def.innerType as AnyZod\n continue\n }\n\n break\n }\n\n if (type === 'optional') {\n result.optional = true\n }\n\n if (type === 'nullable') {\n result.nullable = true\n }\n\n if (type === 'default' && !result.hasDefault) {\n result.hasDefault = true\n result.defaultValue = def.defaultValue\n }\n\n current = def.innerType as AnyZod\n }\n\n return result\n}\n\n// Author metadata, dropping the keys that carry no meaning on the wire. `frLabels` values are declared by the\n// author and may be any JSON; `frDictionary` is a plain ref.\nfunction encodeMeta(meta: Record<string, unknown>): MetaJSON | undefined {\n const encoded = toJsonValue(meta) as MetaJSON\n\n return Object.keys(encoded).length ? encoded : undefined\n}\n\n// enum members live in a `{ key: value }` map; a literal keeps its own `values` array.\nfunction encodeValues(core: AnyZod | undefined, type: FieldType): FieldJSON['values'] {\n if (type === 'enum') {\n const entries = (core?._zod?.def?.entries as Record<string, unknown> | undefined) ?? {}\n\n return Object.values(entries).map(toJsonValue)\n }\n\n if (type === 'literal') {\n const values = (core?._zod?.def?.values as unknown[] | undefined) ?? []\n\n return values.map(toJsonValue)\n }\n\n return undefined\n}\n\n/**\n * One declared field \u2192 its wire form.\n *\n * `seen` holds the declarations this field is currently INSIDE \u2014 the ancestors on the walk, not everything\n * already encoded \u2014 so a schema that legitimately appears twice side by side is still encoded twice. It is\n * added before descending and removed after, which makes the check below a cycle test rather than a\n * deduplication.\n */\nexport function encodeField(name: string, schema: AnyZod, seen: Set<unknown> = new Set()): FieldJSON {\n /**\n * A self-referential declaration contains itself, so the structural walk below has no bottom.\n *\n * `const Tree = z.lazy(() => z.union([z.string(), z.array(Tree)]))` encodes its union, whose array branch\n * has `Tree` as its element, whose union has an array branch\u2026 \u2014 and since a `z.lazy()` getter REBUILDS its\n * schema on every call, each level allocates a fresh one and the stack is gone in milliseconds. That was\n * FR-3600: a `RangeError` naming no extension, method or parameter, with the extension never registering.\n * The recursion is structural rather than data-driven, so remembering the ancestors is enough to stop it.\n *\n * The wire form has no way to SAY \"and here it is again\" \u2014 ./decode.ts rebuilds a finite schema \u2014 so the\n * repeat is encoded as the pass-through it has to become, with a breadcrumb saying why. Everything above\n * the cycle still crosses intact: `Tree` publishes as the string its first branch declares, and the parts\n * of the declaration that are not recursive keep their own types.\n */\n if (seen.has(schema)) {\n return { name, type: 'unknown', unsupported: ['recursion'] }\n }\n\n seen.add(schema)\n\n const { optional, nullable, defaultValue, hasDefault, unsupported } = unwrap(schema)\n // The core, and the type of it, from the one place that decides that for the whole framework.\n const ins = inspect(schema)\n const core = ins.core\n const declaredType = ins.branches ? UNION_TYPE : ins.resolvedType ?? 'unknown'\n const type = (ins.branches || FIELD_TYPES.has(declaredType) ? declaredType : 'unknown') as FieldType\n // `core` is a union's FIRST BRANCH, so its format/checks/message describe that branch and not the union.\n // Encoding them onto the union node would hand `decodeField` constraints to apply to a `ZodUnion`: today\n // they no-op because a union has no `.min()`, which is luck rather than design \u2014 the first one that did\n // map to a real method would make the rebuild reject what a later branch accepts. The branches carry their\n // own constraints in `options`, which is where they belong.\n const isUnion = !!ins.branches\n const format = isUnion ? undefined : core?._zod?.def?.format as string | undefined\n const { checks, unsupported: checkIssues } = isUnion ? { checks: [], unsupported: [] } : encodeChecks(core)\n const meta = encodeMeta(ins.meta as Record<string, unknown>)\n const message = isUnion ? undefined : messageOf((core?._zod?.def ?? {}) as { error?: unknown })\n const values = encodeValues(core, type)\n const problems = [...unsupported, ...checkIssues]\n\n // `unknown` reached by a declaration that MEANS \"anything\" is the wire form working, not failing.\n if (type === 'unknown' && !PASS_THROUGH_TYPES.has(declaredType)) {\n problems.push(`type:${ declaredType }`)\n }\n\n const encoded: FieldJSON = {\n name,\n type,\n ...(format ? { format } : {}),\n ...(optional ? { optional: true as const } : {}),\n ...(nullable ? { nullable: true as const } : {}),\n ...(hasDefault ? { default: toJsonValue(defaultValue) } : {}),\n ...(checks.length ? { checks } : {}),\n ...(values?.length ? { values } : {}),\n ...(meta ? { meta } : {}),\n ...(message ? { message } : {}),\n ...(type === 'object' ? { properties: shapeEntries(core).map(([key, inner]) => encodeField(key, inner, seen)) } : {}),\n ...(type === 'array' ? { element: encodeField('', core?._zod?.def?.element as AnyZod, seen) } : {}),\n ...(type === 'record' ? { value: encodeField('', core?._zod?.def?.valueType as AnyZod, seen) } : {}),\n ...(ins.branches ? { options: ins.branches.map(branch => encodeField('', branch, seen)) } : {}),\n ...(problems.length ? { unsupported: problems } : {}),\n }\n\n // Off the walk again: the field is fully encoded, so this declaration is no longer an ancestor of anything.\n seen.delete(schema)\n\n return encoded\n}\n\n/**\n * A whole declared slot \u2192 its wire form. `null` for an undeclared slot, which is legal everywhere: a method\n * with no params publishes no schema rather than an empty one.\n *\n * Takes `unknown` because this is a boundary: callers hold a schema through whichever view they happen to\n * have (`Params.scheme`, an author's `z.object`, a decoded rebuild), and none of those structural views are\n * assignable to each other. Narrowing once here beats a cast at every call site.\n */\nexport function encodeParams(scheme: unknown): ParamsSchemaJSON | null {\n const schema = scheme as AnyZod | undefined\n\n if (!schema?._zod) {\n return null\n }\n\n return {\n v: SCHEMA_JSON_VERSION,\n fields: shapeEntries(schema).map(([name, field]) => encodeField(name, field)),\n }\n}\n", "import { InvalidCriteriaError, InvalidMethodInputError, MissingMethodParamError } from '../../errors'\nimport { type FailFn, MethodParams, parseSchema } from '../params'\nimport type { ZodSchema } from '../types'\n\n// One invocation's `methodData`, and the two ways the runner reads it.\n//\n// A method's input is keyed by its declared param names (see the console's execution controller). SYSTEM\n// methods carry a single well-known param, helper methods a `payload`. Pulling one out and validating it are\n// separate failures on purpose:\n// \u2022 the param is absent \u2192 MissingMethodParamError \u2014 the CALL is malformed\n// \u2022 the param's value is invalid \u2192 InvalidMethodInputError \u2014 the VALUE is malformed, with issue paths\n// relative to that param\n// Criteria always fail as InvalidCriteriaError so the console can point at the dependent fields instead of\n// reporting the whole call as broken; the two `invalid*` factories below are how a caller picks which.\n\nexport class MethodInput {\n constructor(\n readonly serviceId: string,\n readonly methodName: string,\n private readonly data: Record<string, unknown> = {}\n ) {}\n\n // Extract a declared param. Absent is loud rather than silently defaulted \u2014 a missing param means a\n // malformed call, and failing here surfaces it at the source.\n require<T>(param: string): T {\n const value = (this.data ?? {})[param]\n\n if (value == null) {\n throw new MissingMethodParamError(this.serviceId, param)\n }\n\n return value as T\n }\n\n /**\n * Extract a declared param and validate its value against the schema that owns it.\n *\n * An OBJECT schema \u2014 every runtime-owned wrapper (`callbackObject`, `invocation`, `payload`) \u2014 goes\n * through the same per-field pipeline every author-declared slot uses, so `.optional()` means one thing\n * everywhere: a blank arrives as absence whether the host sent `null`, `''` or nothing at all.\n *\n * That consistency is the point. While these wrappers were parsed by a bare `safeParse`, `.optional()`\n * rejected `null` here while accepting it everywhere else, and each field had to be remembered as\n * `.nullish()` the first time a host sent a null \u2014 which is how `state` on the OAuth callback stayed\n * broken for a non-PKCE provider, where the console legitimately has no verifier to hand back.\n *\n * `carryUnknown` preserves the passthrough these schemas declare with `z.looseObject`: a host may send\n * fields a given milestone does not model yet, and dropping them silently would be worse.\n */\n parseField<T>(param: string, schema?: ZodSchema): T {\n const value = this.require<unknown>(param)\n const fail = this.invalidInput(param)\n\n // A wrapper that is not an object at all fails as the WRAPPER, not field by field: iterating declared\n // fields over a string would report \"\u00ABSearch\u00BB must be a string\" for a payload that was never an object.\n const isObject = !!value && typeof value === 'object' && !Array.isArray(value)\n\n if (!schema?.shape || !isObject) {\n return parseSchema<T>(schema, value, fail, param)\n }\n\n return MethodParams.of(schema).normalize<Record<string, unknown>>(\n value as Record<string, unknown>,\n fail,\n { carryUnknown: true }\n ) as T\n }\n\n // \u2500\u2500 failure identities, for the slots a caller parses itself \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // `target` names the slot that failed \u2014 a param name, or 'params' / 'triggerData' for the whole input.\n invalidInput(target: string): FailFn {\n return issues => {\n throw new InvalidMethodInputError(this.serviceId, this.methodName, target, issues)\n }\n }\n\n invalidCriteria(): FailFn {\n return issues => {\n throw new InvalidCriteriaError(this.serviceId, this.methodName, issues)\n }\n }\n}\n", "import type { ExecutionContext } from './context/execution-context'\nimport { MethodInput } from './context/method-input'\nimport type { Extension } from './extension'\nimport type { SharedExtensionMethod } from './model/model-types'\n\n// One callable method of an extension. Every kind \u2014 action, dictionary, generated loader, SYSTEM seam \u2014\n// answers the same three questions, which is the whole dispatch and model-build contract:\n//\n// toModel() what the console/flow-engine sees in `methodsMap`\n// validate(input) what this kind accepts, and how a bad call fails\n// execute(params) what running it does\n//\n// So dispatch is a map lookup plus `execute(validate(input))`, and building the definition is one pass over\n// `extension.methods()`. Adding a kind means adding a subclass, not editing a chain of `if`s.\n\nexport abstract class ExtensionMethod {\n constructor(protected readonly extension: Extension) {}\n\n // The published method name \u2014 the key in `methodsMap`, and what the flow engine invokes.\n abstract get name(): string\n\n // The v1 kind token: ACTION | DICTIONARY | POLLING_TRIGGER | REALTIME_TRIGGER | SYSTEM |\n // SAMPLE_RESULT_LOADER | PARAM_SCHEMA_DEFINITION.\n abstract get registerAs(): string\n\n abstract toModel(): SharedExtensionMethod\n\n // Extra OAuth scopes this method needs. Only the author-declared kinds can carry any; the generated\n // loaders and the SYSTEM seams never do.\n get oauth2Scopes(): string[] {\n return []\n }\n\n /**\n * Whether this method appears in the published `methodsMap`. Almost always yes \u2014 but the realtime refresh\n * seam is callable whether or not the author declared a `refresh` handler (the runtime answers `{}` when\n * they did not), while only being ADVERTISED when they did. Callable and advertised are therefore two\n * different questions, and this is the second one.\n */\n get published(): boolean {\n return true\n }\n\n // Turn raw `methodData` into whatever `execute` takes. The default accepts anything \u2014 a kind with no\n // declared input has nothing to check.\n validate(methodData: Record<string, unknown>): unknown {\n return methodData\n }\n\n // May return a promise or a plain value; the caller awaits either way, so a synchronous handler is not\n // forced through an async wrapper.\n abstract execute(params: unknown, ctx: ExecutionContext): unknown\n\n protected input(methodData: Record<string, unknown>): MethodInput {\n return new MethodInput(this.extension.id, this.name, methodData)\n }\n}\n", "// Version-agnostic config constants shared by v1 and v2.\n\nexport type ServiceConfigsValues = Record<string, unknown>\n\nexport const ServiceConfigItemTypes = {\n STRING: 'string',\n BOOL: 'bool',\n DATE: 'date',\n CHOICE: 'choice',\n TEXT: 'text',\n} as const\n\nexport type ServiceConfigItemType = (typeof ServiceConfigItemTypes)[keyof typeof ServiceConfigItemTypes]\n", "import { ServiceConfigItemTypes } from '../../common/constants'\nimport type { ConfigItem } from '../../common/types'\nimport { absenceOf } from '../params/schema/field-plan'\nimport { type AnyZod, deriveWidget, inspect, type Inspected, shapeEntries } from '../params/schema/introspect'\nimport { labelOf } from '../params/schema/labels'\nimport { FlowExtensionParamWidgetTypes } from '../params/widget-types'\nimport type { SharedExtensionMetaInfoArg, SharedExtensionParam } from './model-types'\n\n// One declared field \u2194 one entry of the v1 output model. Every mapping the runner performs on a single zod\n// field lives here; ./params-model.ts iterates a `Params`' declared shape and collects what these return.\n//\n// Where a field's DISPLAY metadata (label / uiComponent / dictionary / dependsOn) ends up depends on its\n// depth, matching the v1 jsdoc-parser layout: a top-level param carries structure only and publishes its\n// display side through `metaInfo.args` (\u2192 fieldToArg), while a nested property inlines both. That is the\n// single `nested` flag below \u2014 the two used to be near-duplicate functions.\n//\n// Display metadata is published EXACTLY as the author wrote it. What a bare `z.email()` should show when the\n// author wrote no label and no description is decided when the field is RENDERED, from the schema the\n// definition now carries (see ../params/schema/defaults.ts) \u2014 so those defaults can be reworded without\n// every service having to be redeployed to pick the change up.\n\n// The description as the console should show it: the author's, or nothing. An empty string is meaningful \u2014\n// it says \"the author documented nothing here\", which is what lets the renderer supply its own default.\nconst descriptionOf = (schema: AnyZod): string =>\n inspect(schema).meta.description || ''\n\n/**\n * Whether the console should mark the field mandatory \u2014 asked of the SAME probe the runtime resolves absence\n * with (see ../params/schema/field-plan.ts), not of the wrapper chain.\n *\n * They are two ways of asking one question, and only one of them is authoritative: the runtime decides what\n * it accepts by parsing, so publishing anything else lets the form demand a value the runner would have let\n * through, or leave optional one it will reject. Reading the same answer is what keeps the two from drifting.\n */\nconst isRequired = (schema: AnyZod): boolean =>\n absenceOf(schema).absence === 'required'\n\n// Whether the field is one of the platform's own param groups \u2014 an object that arrived with a widget token\n// on it, which only ../params/files-options.ts produces.\nconst isParamGroup = (ins: Inspected): boolean =>\n ins.coreType === 'object' && !!ins.meta.frWidget\n\nexport interface FieldToParamOptions {\n nested?: boolean\n}\n\nexport function fieldToParam(name: string, schema: AnyZod, options: FieldToParamOptions = {}): SharedExtensionParam {\n const ins = inspect(schema)\n const widget = deriveWidget(ins)\n\n const param: SharedExtensionParam = {\n name,\n required: isRequired(schema),\n description: descriptionOf(schema),\n type: widget.paramType,\n }\n\n /**\n * A platform param GROUP names itself on the param, at every depth.\n *\n * It is the one piece of `uiComponent` that is not display metadata derived from the field's type \u2014 the\n * rule below, which sends a top-level param's display side to `metaInfo.args`, is about how ONE CONTROL\n * should look. This says what the param IS: the runtime's own file-options object rather than an anonymous\n * `z.object` a service happened to declare (see ../params/files-options.ts). A consumer that walks\n * `bodyParams` alone can act on it, and it survives being nested inside another object.\n *\n * It is published through `metaInfo.args` as well, by `fieldToArg` below, because that is where the flow\n * designer reads a top-level param's `uiComponent` from.\n */\n if (isParamGroup(ins) && widget.uiComponent) {\n param.uiComponent = widget.uiComponent\n }\n\n if (options.nested) {\n param.label = labelOf(name, schema)\n\n if (widget.uiComponent) {\n param.uiComponent = widget.uiComponent\n }\n\n if (ins.meta.frDictionary) {\n param.dictionary = ins.meta.frDictionary.id\n\n if (ins.meta.frDictionary.dependsOn.length) {\n param.dependsOn = ins.meta.frDictionary.dependsOn\n }\n }\n }\n\n if (ins.defaultValue !== undefined) {\n param.defaultValue = ins.defaultValue\n }\n\n if (widget.items) {\n param.items = widget.items\n }\n\n // Only a z.object HAS declared properties. A record publishes as OBJECT too, but its keys are open \u2014 there\n // is no field list to publish, and an empty one would read as \"this object has no fields\".\n if (ins.coreType === 'object') {\n param.properties = propertiesOf(ins.core)\n }\n\n /**\n * A LIST of objects publishes the ELEMENT's fields as the param's own `properties`, next to `items`.\n *\n * That looks redundant next to `items.type` until you see what reads it: the console decides a list is a\n * repeatable row editor rather than a single expression box by testing `paramDefinition.properties` (see\n * flow-builder's `getAvailableStructureTypes`), and then renders one input per entry in it. With only\n * `items: { type: 'OBJECT' }` to go on it has no fields to draw and falls back to one text box \u2014 the\n * author's declared structure is simply invisible.\n *\n * The legacy JSDoc format has always published it this way, so this is the v2 model matching a contract\n * the console already implements rather than a new one.\n */\n if (widget.paramType === 'LIST' && widget.items?.type === 'OBJECT') {\n param.properties = propertiesOf(elementOf(ins.core))\n }\n\n return param\n}\n\n// The element schema of a declared array, past its own modifiers.\nfunction elementOf(arrayCore: AnyZod | undefined): AnyZod | undefined {\n const element = arrayCore?._zod?.def?.element as AnyZod | undefined\n\n return element ? inspect(element).core : undefined\n}\n\n// The nested properties of an OBJECT field \u2014 its core schema's own shape, each mapped in nested form.\nexport function propertiesOf(objectCore: AnyZod | undefined): SharedExtensionParam[] {\n return shapeEntries(objectCore).map(([name, schema]) => fieldToParam(name, schema, { nested: true }))\n}\n\n// The display half of a top-level param: what `metaInfo.args[name]` carries.\nexport function fieldToArg(name: string, schema: AnyZod): SharedExtensionMetaInfoArg {\n const ins = inspect(schema)\n const arg: SharedExtensionMetaInfoArg = { label: labelOf(name, schema) }\n // A LIST's display metadata describes ONE ITEM, not the list: the console renders a repeatable editor and\n // draws each entry with this control. So `z.array(z.enum([\u2026]))` advertises the element's dropdown, and\n // `z.array(z.string().dictionary(ref))` advertises the element's dictionary \u2014 which is what the console\n // has always expected here, and what makes a list of choices a list of choices rather than a text box.\n const display = ins.coreType === 'array' ? elementDisplay(ins) : ins\n const widget = deriveWidget(display)\n\n if (display.meta.frDictionary) {\n arg.dictionary = display.meta.frDictionary.id\n\n if (display.meta.frDictionary.dependsOn.length) {\n arg.dependsOn = display.meta.frDictionary.dependsOn\n }\n }\n\n if (widget.uiComponent) {\n arg.uiComponent = widget.uiComponent\n }\n\n return arg\n}\n\n/**\n * What a list should ADVERTISE: its element's declaration, falling back to the list's own.\n *\n * The fallback matters for `z.array(z.string()).dictionary(ref)` \u2014 binding the list rather than the element\n * reads just as naturally to an author, and both forms mean the same thing.\n */\nfunction elementDisplay(list: Inspected): Inspected {\n const element = list.core?._zod?.def?.element as AnyZod | undefined\n const inspected = element ? inspect(element) : undefined\n\n if (!inspected) {\n return list\n }\n\n return inspected.meta.frDictionary || deriveWidget(inspected).uiComponent\n ? inspected\n : { ...inspected, meta: { ...inspected.meta, ...list.meta } }\n}\n\n// \u2500\u2500 config items \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction toConfigType(coreType: string, frWidget?: string): ConfigItem['type'] {\n if (coreType === 'boolean') {\n return ServiceConfigItemTypes.BOOL\n }\n\n if (coreType === 'date') {\n return ServiceConfigItemTypes.DATE\n }\n\n if (coreType === 'enum') {\n return ServiceConfigItemTypes.CHOICE\n }\n\n if (frWidget === FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT) {\n return ServiceConfigItemTypes.TEXT\n }\n\n return ServiceConfigItemTypes.STRING\n}\n\n// A config field \u2192 the v1 `ConfigItem` the console renders. `.shared()` marks it global rather than per-app.\nexport function fieldToConfigItem(name: string, schema: AnyZod): ConfigItem {\n const ins = inspect(schema)\n\n return {\n name,\n type: toConfigType(ins.coreType, ins.meta.frWidget),\n shared: !!ins.meta.frShared,\n required: isRequired(schema),\n description: descriptionOf(schema),\n label: labelOf(name, schema),\n defaultValue: ins.defaultValue,\n options: ins.coreType === 'enum' ? ((ins.core.options as string[]) ?? []) : [],\n }\n}\n\n", "import type { SharedExtensionMetaInfoArg, SharedExtensionParam } from './model-types'\n\n// Shared pieces of the v1 method model \u2014 the shapes several kinds emit identically.\n\n// Every helper-route method (dictionaries, the generated loaders, and the OAuth/trigger SYSTEM methods) is\n// invoked with a single wrapper param \u2014 `payload` or `invocation` \u2014 via the console's helper-method route.\n// The method itself carries no per-field model params, so its input scheme is just that wrapper.\nexport function opaqueParam(name: string, type = 'OBJECT'): SharedExtensionParam {\n return { name, required: false, description: '', type }\n}\n\n// Describe a method's params in `metaInfo.args` (mirroring how actions describe theirs) so the method\n// advertises a labelled input instead of an empty `args` \u2014 consumers (AI tools, the console UI) rely on it.\nexport function argsFromParams(params: SharedExtensionParam[]): Record<string, SharedExtensionMetaInfoArg> {\n const args: Record<string, SharedExtensionMetaInfoArg> = {}\n\n for (const param of params) {\n const arg: SharedExtensionMetaInfoArg = { label: param.label ?? param.name }\n\n if (param.uiComponent) {\n arg.uiComponent = param.uiComponent\n }\n\n if (param.dictionary) {\n arg.dictionary = param.dictionary\n }\n\n if (param.dependsOn) {\n arg.dependsOn = param.dependsOn\n }\n\n args[param.name] = arg\n }\n\n return args\n}\n", "import type { ConfigItem } from '../../common/types'\nimport type { ConfigParams, MethodParams, Params } from '../params'\nimport { fieldToArg, fieldToConfigItem, fieldToParam, propertiesOf } from './field-mapper'\nimport { opaqueParam } from './method-model'\nimport type { SharedExtensionMetaInfoArg, SharedExtensionParam } from './model-types'\n\n// The v1 output model of a declared schema \u2014 `bodyParams`, `metaInfo.args`, `ConfigItem[]`.\n//\n// These are free functions rather than methods on `Params` on purpose: the params framework is consumed by\n// the console as well as the runner (it renders and validates the same schemas in the browser), and the v1\n// console model is meaningless there. So the framework describes a schema, and this module \u2014 which belongs\n// to the runner's output model \u2014 projects that description into the shapes v1 consumers expect.\n\n// Top-level params: structure only. Display metadata is published through `toArgs()`.\nexport function toBodyParams(params: MethodParams): SharedExtensionParam[] {\n return params.fields().map(([name, schema]) => fieldToParam(name, schema))\n}\n\n// `metaInfo.args` \u2014 the display half of the same fields.\nexport function toArgs(params: MethodParams): Record<string, SharedExtensionMetaInfoArg> {\n return Object.fromEntries(params.fields().map(([name, schema]) => [name, fieldToArg(name, schema)]))\n}\n\n/**\n * Top-level params rendered OPAQUELY: one entry per declared key, typed from its schema, with no recursion\n * into nested properties and nothing ever marked required.\n *\n * This is the SYSTEM seam's model shape. Those methods are invoked by the runtime with a whole invocation\n * object, never through a rendered form, so publishing their internals would be noise \u2014 and the v1 seam they\n * must stay compatible with declares them exactly this way.\n */\nexport function toOpaqueBodyParams(params: MethodParams): SharedExtensionParam[] {\n return params.fields().map(([name, schema]) => opaqueParam(name, fieldToParam(name, schema).type))\n}\n\n// The same fields as NESTED properties: display metadata inlined on each one. Used where the schema\n// describes the inside of a wrapper param rather than a method's top level (e.g. a dictionary's `criteria`\n// inside its `payload`).\nexport function toProperties(params: Params): SharedExtensionParam[] {\n return propertiesOf(params.scheme as Parameters<typeof propertiesOf>[0])\n}\n\n// The config descriptions the console renders. `.shared()` fields are marked shared (\u2192\n// sharedConfigDescriptions downstream); the rest are per-app.\nexport function toConfigItems(config: ConfigParams): ConfigItem[] {\n return config.fields().map(([name, schema]) => fieldToConfigItem(name, schema))\n}\n", "import { sampleResultLoaderName } from './loaders/loader-owner'\nimport type { SharedExtensionMetaInfo } from './model/model-types'\nimport type { MethodParams } from './params'\n\n// A declared `result`. Not a schema slot \u2014 it is a UNION zod cannot represent (a literal sample value, a zod\n// schema carrying `.example()`, or a loader fn that derives the sample from the current params), so it gets\n// its own wrapper rather than living in ../params.ts.\n//\n// It answers two questions for every owner (actions, both trigger kinds, dictionaries): what `returnType`\n// the method publishes, and where its sample comes from \u2014 an inline `sampleResult`, or a generated\n// SAMPLE_RESULT_LOADER method the console calls with the params filled in so far.\n\n// The loader is called with the owner's handler bag plus the current params.\ntype LoaderFn = (bag: object) => unknown\n\nfunction inferReturnType(value: unknown): string {\n if (Array.isArray(value)) {\n return 'LIST'\n }\n\n if (value && typeof value === 'object') {\n return 'OBJECT'\n }\n\n if (typeof value === 'string') {\n return 'STRING'\n }\n\n return 'VOID'\n}\n\nfunction isZodSchema(value: unknown): boolean {\n return !!value && typeof value === 'object' && '_zod' in (value as Record<string, unknown>)\n}\n\n// A zod `result` carries its sample in `.example(...)` \u2192 native `meta.examples`; the last one wins.\nfunction schemaExample(schema: { meta?: () => { examples?: unknown[] } | undefined }): unknown {\n const examples = typeof schema.meta === 'function' ? schema.meta()?.examples : undefined\n\n return examples && examples.length ? examples[examples.length - 1] : null\n}\n\nexport class ResultSpec {\n static from(result: unknown): ResultSpec {\n return new ResultSpec(result)\n }\n\n private constructor(private readonly declared: unknown) {}\n\n // The sample is not knowable statically \u2014 it comes from a generated loader method instead.\n get isLoader(): boolean {\n return typeof this.declared === 'function'\n }\n\n get returnType(): string {\n if (this.isLoader || isZodSchema(this.declared)) {\n return 'OBJECT'\n }\n\n return inferReturnType(this.declared)\n }\n\n // Whether anything was declared at all \u2014 a dictionary with no `result` still publishes OBJECT.\n get isDeclared(): boolean {\n return this.declared !== undefined\n }\n\n // The inline sample, or null when there is none (loader form, or an undeclared result).\n #sampleResult(): unknown {\n if (this.isLoader) {\n return null\n }\n\n if (isZodSchema(this.declared)) {\n return schemaExample(this.declared as { meta?: () => { examples?: unknown[] } | undefined })\n }\n\n return this.declared ?? null\n }\n\n // The `metaInfo` halves that describe the output. In loader form the sample is replaced by a reference to\n // the generated method, which depends on every param of its owner (any of them can change the shape).\n toMetaInfo(ownerId: string, params: MethodParams): Pick<SharedExtensionMetaInfo, 'sampleResult' | 'sampleResultLoader'> {\n if (this.isLoader) {\n return {\n sampleResult: null,\n sampleResultLoader: { methodName: sampleResultLoaderName(ownerId), dependsOn: params.keys() },\n }\n }\n\n return { sampleResult: this.#sampleResult(), sampleResultLoader: null }\n }\n\n // Run the loader form against a handler bag carrying the current params.\n async runLoader(bag: object): Promise<unknown> {\n return (this.declared as LoaderFn)(bag)\n }\n}\n", "import type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { dynamicParamsLoaderName, type LoaderOwner } from '../loaders/loader-owner'\nimport { ExtensionMethod } from '../method'\nimport type { SharedExtensionMetaInfo, SharedExtensionMethod } from '../model/model-types'\nimport { toArgs, toBodyParams } from '../model/params-model'\nimport { encodeParams, MethodParams } from '../params'\nimport { ResultSpec } from '../result'\nimport type { ActionProps, AnySchema, HandlerBag } from '../types'\n\n// An action \u2014 the primary operation a service exposes (07-actions.md). Its `params` are the method input\n// itself, keyed by param name, and its handler receives them already parsed.\n\nexport class ActionMethod extends ExtensionMethod implements LoaderOwner {\n readonly params: MethodParams\n readonly result: ResultSpec\n readonly dynamicParamsCriteria: MethodParams\n\n constructor(extension: Extension, private readonly props: ActionProps) {\n super(extension)\n\n this.params = MethodParams.of(props.params, { serviceId: extension.id, kind: 'action', itemId: props.id, slot: 'params' })\n this.result = ResultSpec.from(props.result)\n this.dynamicParamsCriteria = MethodParams.of(props.dynamicParams?.criteria, {\n serviceId: extension.id,\n kind: 'action',\n itemId: props.id,\n slot: 'dynamicParams.criteria',\n })\n }\n\n get id(): string {\n return this.props.id\n }\n\n get name(): string {\n return this.props.id\n }\n\n get registerAs(): string {\n return 'ACTION'\n }\n\n get category(): string {\n return this.props.category\n }\n\n get oauth2Scopes(): string[] {\n return this.props.oauth2Scopes ?? []\n }\n\n hasDynamicParams(): boolean {\n return !!this.props.dynamicParams\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Normalize, coerce and validate against the declared `params` \u2014 the same pipeline every other declared\n * slot uses, so an author expresses optionality in the schema and nowhere else.\n *\n * An action with `dynamicParams` carries the input's undeclared keys through, since its runtime-generated\n * top-level fields are not in the static schema.\n */\n validate(methodData: Record<string, unknown>): Record<string, unknown> {\n return this.params.normalize<Record<string, unknown>>(\n methodData,\n this.input(methodData).invalidInput('params'),\n { carryUnknown: this.hasDynamicParams() }\n )\n }\n\n execute(params: Record<string, unknown>, ctx: ExecutionContext): unknown {\n return this.props.execute(ctx.bagWith({ params }))\n }\n\n // Resolve the extra top-level param fields this action generates at runtime (see 03-parameters.md).\n resolveDynamicParams(bag: HandlerBag & { criteria: Record<string, unknown> }): AnySchema | Promise<AnySchema> {\n return this.props.dynamicParams!.resolve(bag)\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toModel(): SharedExtensionMethod {\n const [ownStart, ownEnd] = this.props.appearanceColors ?? []\n const [colorStart, colorEnd] = this.extension.appearanceColors\n const metaInfo: SharedExtensionMetaInfo = {\n args: toArgs(this.params),\n ...this.result.toMetaInfo(this.id, this.params),\n }\n\n if (this.hasDynamicParams()) {\n metaInfo.dynamicParams = {\n methodName: dynamicParamsLoaderName(this.id),\n dependsOn: this.dynamicParamsCriteria.keys(),\n }\n }\n\n return {\n name: this.id,\n operationName: this.props.label,\n description: this.props.description || '',\n registerAs: this.registerAs,\n category: this.category,\n colorStart: ownStart ?? colorStart,\n colorEnd: ownEnd ?? colorEnd,\n customIcon: this.props.logo ?? '',\n returnType: this.result.returnType,\n queryParams: [],\n bodyParams: toBodyParams(this.params),\n paramsSchema: encodeParams(this.params.scheme),\n metaInfo,\n }\n }\n}\n", "import BLRequest from 'backendless-request'\n\nexport const FileScope = {\n WORKSPACE: 'WORKSPACE',\n FLOW: 'FLOW',\n EXECUTION: 'EXECUTION',\n} as const\n\nexport type FileScope = (typeof FileScope)[keyof typeof FileScope]\n\n// The scope namespace as handlers receive it (`filesScope` in the bag), so author code names a layer instead\n// of spelling the string: `files.list({ scope: filesScope.WORKSPACE })`.\nexport type FileScopes = typeof FileScope\n\ntype FileScopePath = 'workspace' | 'flow' | 'execution'\n\nfunction toScopePath(scope: FileScope): FileScopePath {\n return scope.toLowerCase() as FileScopePath\n}\n\ntype CollectionFn = (flowId: string | null, executionId: string | null) => string\ntype FileFn = (filename: string, flowId: string | null, executionId: string | null) => string\n\nconst collectionPathByScope: Record<FileScopePath, CollectionFn> = {\n workspace: () => '/workspace',\n flow: flowId => {\n if (!flowId) {\n throw new Error('Flow scope requires flowId')\n }\n\n return `/flow/${ flowId }`\n },\n execution: (flowId, executionId) => {\n if (!flowId || !executionId) {\n throw new Error('Execution scope requires flowId and executionId')\n }\n\n return `/flow/${ flowId }/execution/${ executionId }`\n },\n}\n\nconst filePathByScope: Record<FileScopePath, FileFn> = {\n workspace: filename => `/workspace/${ filename }`,\n flow: (filename, flowId) => {\n if (!flowId) {\n throw new Error('Flow scope requires flowId')\n }\n\n return `/flow/${ flowId }/${ filename }`\n },\n execution: (filename, flowId, executionId) => {\n if (!flowId || !executionId) {\n throw new Error('Execution scope requires flowId and executionId')\n }\n\n return `/flow/${ flowId }/execution/${ executionId }/${ filename }`\n },\n}\n\nexport interface FlowrunnerContextFilesOptions {\n serverURL: string\n appId: string\n apiKey: string\n //\n runtimeKey: string\n //\n flowId?: string | null\n executionId?: string | null\n //\n retrieveNewS3Token: (runtimeKey: string) => Promise<{\n filesS3Token: string\n }>\n}\n\nexport interface UploadFileOptions {\n scope?: FileScope\n filename?: string\n ttl?: number\n generateUrl?: boolean\n objectTtl?: number\n overwrite?: boolean\n}\n\nexport interface ListOptions {\n scope?: FileScope\n ttl?: number\n generateUrl?: boolean\n limit?: number\n cursor?: string\n}\n\nexport interface GetOptions {\n scope?: FileScope\n ttl?: number\n generateUrl?: boolean\n}\n\nexport interface DeleteOptions {\n scope?: FileScope\n}\n\nexport interface UploadResult {\n key: string\n filename: string\n url: string\n size: number\n urlExpiresAt: string\n objectExpiresAt: string | null\n overwritten: boolean\n}\n\nexport interface FileInfo {\n key: string\n filename: string\n url: string\n size: number\n createdAt: string\n urlExpiresAt: string\n objectExpiresAt: string | null\n}\n\nexport interface ListResult {\n files: FileInfo[]\n cursor: string | null\n hasMore: boolean\n}\n\nexport interface DeleteResult {\n key: string\n freedBytes: number\n deleted: boolean\n}\n\nexport interface UsageResult {\n workspaceId: string\n usedBytes: number\n quotaBytes: number\n usedFormatted: string\n quotaFormatted: string\n utilizationPercent: number\n fileCount: number\n}\n\n// The file-service contract as HANDLERS see it (`ctx.files`) \u2014 the five methods, nothing about transport.\n// `FlowrunnerContextFiles` below is the implementation that talks to the console; a host may supply its\n// own via `runServiceMethod({ createFiles })`, which is how an e2e harness points file storage at a local\n// S3 without the runner knowing. Keep this in step with the class.\nexport interface FilesApi {\n uploadFile(file: Buffer | Uint8Array, options?: UploadFileOptions): Promise<UploadResult>\n list(options?: ListOptions): Promise<ListResult>\n get(filename: string, options?: GetOptions): Promise<FileInfo>\n delete(filename: string, options?: DeleteOptions): Promise<DeleteResult>\n usage(): Promise<UsageResult>\n}\n\nfunction cleanParams(params: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(params).filter(([, v]) => v !== undefined && v !== null)\n )\n}\n\n// Minimal shape of the node `form-data` instance BLRequest.FormData produces at\n// runtime \u2014 its append(name, value, options) signature differs from the DOM type.\ntype MultipartForm = {\n append: (name: string, value: unknown, options?: { filename?: string }) => void\n}\n\nfunction appendFormParams(form: MultipartForm, params: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n form.append(key, String(value))\n }\n }\n}\n\nexport class FlowrunnerContextFiles implements FilesApi {\n appId: string\n apiKey: string\n runtimeKey: string\n serverURL: string\n flowId: string | null\n executionId: string | null\n retrieveNewS3Token: (runtimeKey: string) => Promise<{\n filesS3Token: string\n }>\n\n constructor({\n appId,\n apiKey,\n runtimeKey,\n serverURL,\n flowId,\n executionId,\n retrieveNewS3Token,\n }: FlowrunnerContextFilesOptions) {\n this.appId = appId\n this.apiKey = apiKey\n this.runtimeKey = runtimeKey\n this.serverURL = serverURL\n this.flowId = flowId ?? null\n this.executionId = executionId ?? null\n\n this.retrieveNewS3Token = retrieveNewS3Token\n }\n\n get base(): string {\n return `${ this.serverURL }/${ this.appId }/${ this.apiKey }/v1/files`\n }\n\n private collectionPath(scope: FileScopePath): string {\n return this.base + collectionPathByScope[scope](this.flowId, this.executionId)\n }\n\n private filePath(filename: string, scope: FileScopePath): string {\n return this.base + filePathByScope[scope](encodeURIComponent(filename), this.flowId, this.executionId)\n }\n\n private async resolveFilesS3Token(): Promise<string> {\n const { filesS3Token } = await this.retrieveNewS3Token(this.runtimeKey)\n\n return filesS3Token\n }\n\n private async request<T>(method: string, url: string, body?: unknown, params?: Record<string, unknown>): Promise<T> {\n const token = await this.resolveFilesS3Token()\n\n const httpMethod = method.toLowerCase() as 'get' | 'post' | 'put' | 'patch' | 'delete'\n\n let req = BLRequest[httpMethod](url)\n .set('Authorization', `Bearer ${ token }`)\n\n if (params) {\n req = req.query(cleanParams(params))\n }\n\n // `.form()` returns a chainable request; `.send()` returns a promise directly.\n // The request instance is itself thenable, so returning it awaits the response.\n if (BLRequest.FormData && body instanceof BLRequest.FormData) {\n return req.form(body as unknown as Record<string, unknown>) as unknown as Promise<T>\n }\n\n if (body) {\n return req.send(body) as Promise<T>\n }\n\n return req as unknown as Promise<T>\n }\n\n async uploadFile(file: Buffer | Uint8Array, options: UploadFileOptions = {}): Promise<UploadResult> {\n const { scope = FileScope.FLOW, filename, ttl, generateUrl = true, objectTtl, overwrite } = options\n const scopePath = toScopePath(scope)\n\n // BLRequest.FormData is the node `form-data` instance at runtime (see MultipartForm) \u2014\n // cast to that shape to append a Buffer + filename.\n const form = new BLRequest.FormData!() as unknown as MultipartForm\n\n form.append('file', Buffer.from(file), { filename: filename ?? 'file' })\n appendFormParams(form, { filename, ttl, generateUrl, objectTtl, overwrite })\n\n return this.request<UploadResult>('POST', this.collectionPath(scopePath), form)\n }\n\n async list(options: ListOptions = {}): Promise<ListResult> {\n const { scope = FileScope.FLOW, ttl, generateUrl, limit, cursor } = options\n const scopePath = toScopePath(scope)\n\n return this.request<ListResult>('GET', this.collectionPath(scopePath), undefined, cleanParams({\n ttl,\n generateUrl,\n limit,\n cursor,\n }))\n }\n\n async get(filename: string, options: GetOptions = {}): Promise<FileInfo> {\n const { scope = FileScope.FLOW, ttl, generateUrl } = options\n const scopePath = toScopePath(scope)\n\n return this.request<FileInfo>('GET', this.filePath(filename, scopePath), undefined, cleanParams({\n ttl,\n generateUrl,\n }))\n }\n\n async delete(filename: string, options: DeleteOptions = {}): Promise<DeleteResult> {\n const { scope = FileScope.FLOW } = options\n\n return this.request<DeleteResult>('DELETE', this.filePath(filename, toScopePath(scope)))\n }\n\n async usage(): Promise<UsageResult> {\n return this.request<UsageResult>('GET', `${ this.collectionPath('workspace') }/usage`)\n }\n}\n", "import type { Logger } from '../types'\n\n// Default runtime logger handed to service handlers as `logger`. Service code uses `logger.debug/info`\n// for redacted tracing; only warn/error surface to the console by default (matching the no-bare-console\n// policy). A host can supply its own Logger to route these elsewhere.\n \nexport const defaultLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n}\n \n", "import { FeatureNotEnabledError } from '../../errors'\n\n// Throwing proxies for opt-in features (oauth / files). When a feature isn't enabled, its slot in the\n// handler bag is a proxy that throws on ANY access \u2014 so accidental use fails loudly at the call site\n// instead of silently no-op'ing or reading `undefined`. See 10-files-api.md and 06-oauth2.md.\n\nexport function createThrowingProxy(feature: string, hint: string): Record<string, never> {\n const fail = (): never => {\n throw new FeatureNotEnabledError(feature, hint)\n }\n\n return new Proxy(\n {},\n {\n get(_target, prop) {\n // Let promise-unwrapping / stringification probe the proxy without throwing.\n if (prop === 'then' || prop === Symbol.toPrimitive || prop === Symbol.toStringTag) {\n return undefined\n }\n\n return fail()\n },\n apply: fail,\n has: fail,\n }\n ) as Record<string, never>\n}\n", "import type { ServiceConfigsValues } from '../../common/constants'\nimport { type FilesApi,FileScope, type FileScopes } from '../../common/context-files'\nimport type { Extension } from '../extension'\nimport type { OAuthBag } from '../oauth/types'\nimport type { HandlerBag, Logger } from '../types'\nimport { defaultLogger } from './logger'\nimport { createThrowingProxy } from './proxies'\n\n// One invocation's resolved surroundings, and the `bag` handlers see (07-actions.md): the resolved `config`,\n// the `initContext` return as `context`, `oauth`, the bound `apiRequest`, `files`, `filesScope`, `logger`,\n// and `helpers`.\n//\n// Everything is derived LAZILY and memoized per instance. That matters because the OAuth callback needs a\n// second context bound to the freshly-obtained token (`withAccessToken`), and used to rebuild the whole bag\n// from scratch each time it asked \u2014 resolving config, running `initContext` and re-running the `helpers`\n// factory up to three times per callback. Now each context resolves each of those once, and a differently\n// tokened context is an explicit second instance rather than an implicit rebuild.\n//\n// `toBag()` returns a PLAIN OBJECT. Author code never receives a class instance \u2014 that is the frozen\n// handler contract.\n\nexport interface ExecutionContextOptions {\n configs?: ServiceConfigsValues\n accessToken?: string\n logger?: Logger\n // Provisioned by the caller only when the extension declares `usesFileStorage`; otherwise the bag's\n // `files` slot is a proxy that throws on any access.\n files?: unknown\n}\n\nexport class ExecutionContext {\n readonly #extension: Extension\n readonly #options: ExecutionContextOptions\n\n #config?: Record<string, unknown>\n #context?: unknown\n #oauth?: OAuthBag\n #apiRequest?: HandlerBag['apiRequest']\n #bag?: HandlerBag\n\n constructor(extension: Extension, options: ExecutionContextOptions = {}) {\n this.#extension = extension\n this.#options = options\n }\n\n get logger(): Logger {\n return this.#options.logger ?? defaultLogger\n }\n\n get config(): Record<string, unknown> {\n this.#config ??= this.#extension.config.resolve(this.#options.configs)\n\n return this.#config\n }\n\n // The header access token plus its deserialized composite payload \u2014 or a throwing proxy when the\n // extension never declared oauth, so accidental use fails loudly at the call site.\n get oauth(): OAuthBag {\n this.#oauth ??= this.#extension.oauth\n ? this.#extension.oauth.buildBag(this.#options.accessToken)\n : (createThrowingProxy('oauth', 'declare ext.setupOauth2(...) first') as OAuthBag)\n\n return this.#oauth\n }\n\n // The scope names, so a handler writes `filesScope.WORKSPACE` instead of the bare string. Deliberately NOT\n // gated on `usesFileStorage`: it is a set of constants, not a capability, and it is useful for building a\n // scope value to pass around even where no file call happens. Reaching for `files` without the opt-in still\n // fails loudly on its own.\n get filesScope(): FileScopes {\n return FileScope\n }\n\n // The proxy stands in for the real client and throws on ANY access, so handlers see one type either way.\n get files(): FilesApi {\n return (this.#props.usesFileStorage && this.#options.files\n ? this.#options.files\n : createThrowingProxy('files', 'set usesFileStorage:true in createExtension first')) as FilesApi\n }\n\n get context(): unknown {\n this.#context ??= this.#props.initContext\n ? this.#props.initContext({ config: this.config, oauth: this.oauth })\n : {}\n\n return this.#context\n }\n\n // The author's own `apiRequest`, with `context` + `logger` injected so handlers don't pass them. Both are\n // read at CALL time, off this context.\n get apiRequest(): HandlerBag['apiRequest'] {\n if (!this.#props.apiRequest) {\n return undefined as unknown as HandlerBag['apiRequest']\n }\n\n this.#apiRequest ??= ((arg: Record<string, unknown>) =>\n (this.#props.apiRequest as (a: unknown) => unknown)({\n ...arg,\n context: this.context,\n logger: this.logger,\n })) as HandlerBag['apiRequest']\n\n return this.#apiRequest\n }\n\n // The bag every handler receives. Memoized: one bag per context, so the `helpers` factory runs once.\n toBag(): HandlerBag {\n if (this.#bag) {\n return this.#bag\n }\n\n const bag = {\n config: this.config,\n context: this.context,\n oauth: this.oauth,\n apiRequest: this.apiRequest,\n files: this.files,\n filesScope: this.filesScope,\n logger: this.logger,\n } as HandlerBag\n\n // Published before `helpers` is attached: the factory receives the bag it is about to complete, and\n // anything it captures sees the finished object.\n this.#bag = bag\n bag.helpers = this.#props.helpers ? this.#props.helpers(bag) : undefined\n\n return bag\n }\n\n // A handler's bag plus whatever its kind adds \u2014 `params`, `criteria`, `providerEventData`, \u2026 Always a\n // fresh object, so a handler cannot mutate the shared bag.\n bagWith<T extends object>(extra: T): HandlerBag & T {\n return { ...this.toBag(), ...extra }\n }\n\n // A sibling context bound to a different access token \u2014 the OAuth callback runs its identity lookup\n // against the token it just obtained. Everything else (config source, files client, logger) is shared.\n withAccessToken(accessToken?: string): ExecutionContext {\n return new ExecutionContext(this.#extension, { ...this.#options, accessToken })\n }\n\n get #props() {\n return this.#extension.props\n }\n}\n", "import { z } from '../params'\n\n// The console's helper-method route invokes a dictionary with `methodData = { payload }`, where the payload\n// is `{ search, cursor, criteria }`: `search` and `cursor` are universal (the runtime always provides them),\n// `criteria` carries the current values of the params this dictionary depends on. LOOSE, like every wrapper\n// the runtime owns \u2014 unmodelled fields ride through rather than being silently dropped.\nexport const DictionaryPayloadSchema = z.looseObject({\n search: z.string().optional(),\n cursor: z.union([z.string(), z.number()]).nullish(),\n criteria: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport interface DictionaryPayload {\n search?: string\n cursor?: unknown\n criteria: Record<string, unknown>\n}\n", "import { InvalidDictionaryOutputScheme } from '../../errors'\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { ExtensionMethod } from '../method'\nimport type { SharedExtensionMethod, SharedExtensionParam } from '../model/model-types'\nimport { toProperties } from '../model/params-model'\nimport { MethodParams } from '../params'\nimport { ResultSpec } from '../result'\nimport type { DictionaryProps, DictionaryResult } from '../types'\nimport { type DictionaryPayload, DictionaryPayloadSchema } from './payload-schema'\n\n// A dictionary \u2014 the dynamic option source behind a param (05-dictionaries.md). Invoked through the\n// console's helper-method route while a user fills a form, and answers `{ items, cursor }`.\n\nexport class DictionaryMethod extends ExtensionMethod {\n readonly criteria: MethodParams\n readonly result: ResultSpec\n\n constructor(extension: Extension, private readonly props: DictionaryProps) {\n super(extension)\n\n this.criteria = MethodParams.of(props.criteria, {\n serviceId: extension.id,\n kind: 'dictionary',\n itemId: props.id,\n slot: 'criteria',\n })\n this.result = ResultSpec.from(props.result)\n }\n\n get id(): string {\n return this.props.id\n }\n\n get name(): string {\n return this.props.id\n }\n\n get registerAs(): string {\n return 'DICTIONARY'\n }\n\n // Optional on a dictionary (unlike an action), so `''` when undeclared. Also satisfies `LoaderOwner`, so a\n // generated loader inherits it the same way an action's does.\n get category(): string {\n return this.props.category ?? ''\n }\n\n get oauth2Scopes(): string[] {\n return this.props.oauth2Scopes ?? []\n }\n\n // The params a dictionary-bound field depends on \u2014 derived from the criteria, never hand-written.\n get dependsOn(): string[] {\n return this.criteria.keys()\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // Two-stage: the `{ search, cursor, criteria }` envelope the runtime owns, then the author-declared\n // criteria through the shared pipeline \u2014 reported as a criteria failure so the console can point at the\n // dependent fields rather than the whole call.\n validate(methodData: Record<string, unknown>): DictionaryPayload {\n const input = this.input(methodData)\n const payload = input.parseField<DictionaryPayload>('payload', DictionaryPayloadSchema)\n const criteria = this.criteria.normalize<Record<string, unknown>>(payload.criteria, input.invalidCriteria())\n\n return {\n search: payload.search,\n cursor: payload.cursor,\n criteria,\n }\n }\n\n // Authors may answer with the bare item list; the runtime contract is `{ cursor, items }`.\n async execute(payload: DictionaryPayload, ctx: ExecutionContext): Promise<DictionaryResult> {\n const result = await this.props.execute(ctx.bagWith(payload))\n\n if (Array.isArray(result)) {\n return { cursor: null, items: result } as unknown as DictionaryResult\n }\n\n if (result && typeof result === 'object' && Array.isArray(result.items)) {\n return { cursor: result.cursor, items: result.items }\n }\n\n throw new InvalidDictionaryOutputScheme(this.extension.id, this.name)\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toModel(): SharedExtensionMethod {\n const [colorStart, colorEnd] = this.extension.appearanceColors\n\n return {\n name: this.id,\n // Dictionaries are surfaced to the UI and to AI tools, so they need a human label. Fall back to the id.\n operationName: this.props.label ?? this.id,\n description: this.props.description || '',\n registerAs: this.registerAs,\n category: this.category,\n colorStart,\n colorEnd,\n customIcon: '',\n // A dictionary returns a `{ items, cursor }` OBJECT; default to OBJECT when no explicit sample is given.\n returnType: this.result.isDeclared ? this.result.returnType : 'OBJECT',\n queryParams: [],\n bodyParams: [this.#payloadParam()],\n // The `payload` wrapper's display label lives here (the bodyParam itself stays label-free, matching v1).\n metaInfo: {\n args: { payload: { label: 'Payload' } },\n ...this.result.toMetaInfo(this.id, this.criteria),\n },\n }\n }\n\n // Describe the full payload shape so the method advertises a complete, labelled input scheme (nested\n // props inline their own labels \u2014 mirroring the v1 jsdoc-parser layout).\n #payloadParam(): SharedExtensionParam {\n const properties: SharedExtensionParam[] = [\n { name: 'search', required: false, description: 'Optional search string to filter results.', type: 'STRING', label: 'Search' },\n { name: 'cursor', required: false, description: 'Pagination offset for retrieving the next page of results.', type: 'STRING', label: 'Cursor' },\n ]\n\n const criteriaProps = toProperties(this.criteria)\n\n if (criteriaProps.length) {\n properties.push({\n name: 'criteria',\n required: false,\n description: 'Current values of the params this dictionary depends on.',\n type: 'OBJECT',\n properties: criteriaProps,\n })\n }\n\n return {\n name: 'payload',\n required: false,\n description: 'Contains optional search string and pagination cursor.',\n type: 'OBJECT',\n properties,\n }\n }\n}\n", "import { z } from '../params'\n\n// The console's helper-method route invokes a loader with `methodData = { payload }`, and a loader's\n// payload is `{ criteria }` \u2014 the current values of the params it depends on. LOOSE, like every wrapper the\n// runtime owns: the console may send fields a given milestone doesn't model yet, and dropping them silently\n// would be worse than carrying them through.\nexport const LoaderPayloadSchema = z.looseObject({\n criteria: z.record(z.string(), z.unknown()).optional(),\n})\n", "import type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { ExtensionMethod } from '../method'\nimport { argsFromParams, opaqueParam } from '../model/method-model'\nimport type { SharedExtensionMethod, SharedExtensionParam } from '../model/model-types'\nimport { toBodyParams } from '../model/params-model'\nimport { MethodParams } from '../params'\nimport {\n dynamicParamsLoaderName,\n type DynamicParamsOwner,\n type LoaderOwner,\n sampleResultLoaderName,\n} from './loader-owner'\nimport { LoaderPayloadSchema } from './payload-schema'\n\n// The methods the RUNTIME generates from what an author declared \u2014 never written by hand:\n//\n// result: fn \u2192 a SAMPLE_RESULT_LOADER the console calls to preview the output shape\n// dynamicParams \u2192 a PARAM_SCHEMA_DEFINITION that resolves extra top-level param fields\n//\n// Both are invoked with `{ payload: { criteria } }` \u2014 the values of the params they depend on. They obey the\n// same policy as every other declared slot, so a sample-result loader (whose criteria ARE its owner's params)\n// only resolves once the owner's required params are filled.\n\nabstract class LoaderMethod extends ExtensionMethod {\n constructor(extension: Extension, protected readonly owner: LoaderOwner) {\n super(extension)\n }\n\n // The params this loader's criteria are checked against.\n protected abstract get criteria(): MethodParams\n\n validate(methodData: Record<string, unknown>): Record<string, unknown> {\n const input = this.input(methodData)\n const payload = input.parseField<{ criteria?: Record<string, unknown> }>('payload', LoaderPayloadSchema)\n\n // Undeclared keys ride through: the node's other params come along, and the owner's `result` fn may read\n // fields its `dynamicParams` generated.\n return this.criteria.normalize(payload.criteria, input.invalidCriteria(), { carryUnknown: true })\n }\n\n // Internal (SYSTEM-like): no icon, no colours, no sample. Its params are left opaque in the model \u2014 it is\n // invoked with `{ criteria }` at runtime, not through a rendered form.\n toModel(): SharedExtensionMethod {\n const bodyParams: SharedExtensionParam[] = [opaqueParam('payload')]\n\n return {\n name: this.name,\n operationName: this.name,\n description: '',\n registerAs: this.registerAs,\n category: this.owner.category,\n colorStart: '',\n colorEnd: '',\n customIcon: undefined,\n returnType: this.returnType,\n queryParams: [],\n bodyParams,\n metaInfo: { args: argsFromParams(bodyParams), sampleResult: null, sampleResultLoader: null },\n }\n }\n\n protected abstract get returnType(): string\n}\n\n// Derives the sample output from the params filled in so far \u2014 for shapes that aren't known statically\n// (user-defined fields, a record whose columns depend on which table was picked).\nexport class SampleResultLoaderMethod extends LoaderMethod {\n get name(): string {\n return sampleResultLoaderName(this.owner.id)\n }\n\n get registerAs(): string {\n return 'SAMPLE_RESULT_LOADER'\n }\n\n protected get returnType(): string {\n return 'OBJECT'\n }\n\n // The sample varies with ANY param of the owner, so all of them are its criteria.\n protected get criteria(): MethodParams {\n return this.owner.params\n }\n\n execute(criteria: Record<string, unknown>, ctx: ExecutionContext): unknown {\n return this.owner.result.runLoader(ctx.bagWith({ params: criteria }))\n }\n}\n\n// Resolves additional top-level param fields at runtime, returned as the v1 param model the console renders.\nexport class DynamicParamsLoaderMethod extends LoaderMethod {\n constructor(extension: Extension, protected readonly owner: DynamicParamsOwner) {\n super(extension, owner)\n }\n\n get name(): string {\n return dynamicParamsLoaderName(this.owner.id)\n }\n\n get registerAs(): string {\n return 'PARAM_SCHEMA_DEFINITION'\n }\n\n protected get returnType(): string {\n return 'LIST'\n }\n\n protected get criteria(): MethodParams {\n return this.owner.dynamicParamsCriteria\n }\n\n async execute(criteria: Record<string, unknown>, ctx: ExecutionContext): Promise<SharedExtensionParam[]> {\n const schema = await this.owner.resolveDynamicParams(ctx.bagWith({ criteria }))\n\n return toBodyParams(MethodParams.of(schema, {\n serviceId: this.extension.id,\n kind: 'action',\n itemId: this.owner.id,\n slot: 'dynamicParams.resolve()',\n }))\n }\n}\n", "import crypto from 'crypto'\n\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { z } from '../params'\nimport type { SystemMethodSpec } from '../system-method'\nimport { OAUTH_SYSTEM_METHODS } from './method-names'\nimport { OAuthCallbackObjectSchema, RefreshTokenSchema } from './system-params'\nimport type {\n OAuth2Props,\n OAuthBag,\n OAuthCallbackObject,\n OAuthCallbackResult,\n OAuthRefreshResult,\n} from './types'\n\n// `ext.setupOauth2(...)` \u2014 the OAuth2 subsystem (06-oauth2.md). Declarative for the common case, with an\n// escape hatch per step for providers that deviate. It owns the three v1 SYSTEM methods, the frozen runtime\n// seam the platform drives:\n//\n// getOAuth2ConnectionURL (GET) \u2192 where to send the user\n// executeCallback (POST) \u2192 trade the code for a token, and name the connection\n// refreshToken (PUT) \u2192 trade a refresh token for the next access token\n\nexport class OAuth2 {\n constructor(private readonly extension: Extension, private readonly props: OAuth2Props) {\n this.#registerSystemMethods()\n }\n\n // The handler bag's `oauth`: the header access token, plus its deserialized composite payload when the\n // author declared a deserializer (the pattern for providers whose \"token\" carries a realm or instance id).\n buildBag(accessToken?: string): OAuthBag {\n const token = this.props.deserializeToken && accessToken != null\n ? this.props.deserializeToken(accessToken)\n : undefined\n\n return { accessToken, token }\n }\n\n // \u2500\u2500 SYSTEM seam: name \u00B7 input \u00B7 return \u00B7 handler, in one table \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #registerSystemMethods(): void {\n const { CONNECTION_URL, EXECUTE_CALLBACK, REFRESH_TOKEN } = OAUTH_SYSTEM_METHODS\n\n // Every step runs where no usable access token exists yet \u2014 connect precedes one entirely, and the\n // callback and refresh are what PRODUCE the next one \u2014 so each sees a TOKENLESS context. The single\n // exception is the callback's identity lookup, which must use the token it just obtained (#handleCallback).\n const anonymous = (ctx: ExecutionContext): ExecutionContext => ctx.withAccessToken(undefined)\n\n this.extension.registerSystemMethods([\n {\n name: CONNECTION_URL,\n // Takes no input at all \u2014 no scheme.\n returnType: 'STRING',\n run: (_params, ctx) => this.#connectionUrl(anonymous(ctx), this.#composeScopes()),\n },\n {\n name: EXECUTE_CALLBACK,\n scheme: z.object({ callbackObject: OAuthCallbackObjectSchema }),\n run: ({ callbackObject }, ctx) => this.#handleCallback(callbackObject as OAuthCallbackObject, anonymous(ctx)),\n },\n {\n name: REFRESH_TOKEN,\n scheme: z.object({ refreshToken: RefreshTokenSchema }),\n run: ({ refreshToken }, ctx) => this.#refresh(refreshToken as string, anonymous(ctx)),\n },\n ] satisfies SystemMethodSpec[])\n }\n\n /**\n * The scopes to ask the user for: the base set \u222A every registered item's `oauth2Scopes`.\n *\n * Composed ON DEMAND, when the connect step actually runs, and never stored. `setupOauth2(...)` may be\n * called BEFORE the actions and triggers that carry scopes are registered \u2014 a service file is free to\n * order those however it likes \u2014 so a set computed at setup time would silently omit whatever registered\n * afterwards, and the user would be sent to a consent screen missing permissions the service needs.\n */\n #composeScopes(): string[] {\n return [...new Set([...(this.props.scopes ?? []), ...this.extension.declaredOAuthScopes()])]\n }\n\n // \u2500\u2500 the three steps \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n async #connectionUrl(ctx: ExecutionContext, scopes: string[]): Promise<string> {\n if (this.props.getConnectionURL) {\n return this.props.getConnectionURL(ctx.bagWith({ scopes }))\n }\n\n const { id } = this.#clientCreds(ctx.config)\n const params = new URLSearchParams({ client_id: id, response_type: 'code', scope: scopes.join(' ') })\n\n if (this.props.pkce) {\n // The verifier round-trips through `state`, which the console hands back on the callback.\n const verifier = crypto.randomBytes(32).toString('base64url')\n\n params.set('code_challenge', crypto.createHash('sha256').update(verifier).digest('base64url'))\n params.set('code_challenge_method', 'S256')\n params.set('state', verifier)\n }\n\n return `${ this.props.authorizeUrl }?${ params.toString() }`\n }\n\n async #handleCallback(callbackObject: OAuthCallbackObject, ctx: ExecutionContext): Promise<OAuthCallbackResult> {\n if (this.props.executeCallback) {\n return this.props.executeCallback(ctx.bagWith({ callbackObject }))\n }\n\n const tokenResponse = await this.#exchangeToken(ctx.config, {\n grant_type: 'authorization_code',\n code: callbackObject.code ?? '',\n redirect_uri: callbackObject.redirectURI ?? '',\n ...(callbackObject.state ? { code_verifier: callbackObject.state } : {}),\n })\n\n const accessToken = tokenResponse.access_token as string\n const refreshToken = tokenResponse.refresh_token as string | undefined\n\n // Identity lookup runs against the freshly-obtained token \u2014 the one exception to the tokenless rule.\n let identity: { name?: string; imageUrl?: string | null; userData?: unknown } = {}\n\n if (this.props.identityRequest) {\n const raw = await this.props.identityRequest(ctx.withAccessToken(accessToken).toBag())\n\n identity = this.props.identity ? this.props.identity(raw) : {}\n }\n\n return {\n token: this.#serialize(accessToken, refreshToken, identity.userData),\n expirationInSeconds: tokenResponse.expires_in as number | undefined,\n refreshToken,\n connectionIdentityName: identity.name || 'Unknown Account',\n connectionIdentityImageURL: identity.imageUrl ?? null,\n overwrite: true,\n userData: identity.userData,\n }\n }\n\n async #refresh(currentRefreshToken: string, ctx: ExecutionContext): Promise<OAuthRefreshResult> {\n if (this.props.refreshToken) {\n return this.props.refreshToken(ctx.bagWith({ refreshToken: currentRefreshToken }))\n }\n\n const tokenResponse = await this.#exchangeToken(ctx.config, {\n grant_type: 'refresh_token',\n refresh_token: currentRefreshToken,\n })\n\n // Providers that rotate refresh tokens send a new one; those that don't leave the current one valid.\n const nextRefresh = (tokenResponse.refresh_token as string | undefined) ?? currentRefreshToken\n\n return {\n token: this.#serialize(tokenResponse.access_token as string, nextRefresh),\n expirationInSeconds: tokenResponse.expires_in as number | undefined,\n refreshToken: nextRefresh,\n }\n }\n\n // \u2500\u2500 token exchange \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #serialize(accessToken: string, refreshToken?: string, userData?: unknown): string {\n return this.props.serializeToken\n ? this.props.serializeToken({ accessToken, refreshToken, userData })\n : accessToken\n }\n\n #clientCreds(config: Record<string, unknown>): { id: string; secret: string } {\n return {\n id: String(config[this.props.clientIdConfig ?? 'clientId'] ?? ''),\n secret: String(config[this.props.clientSecretConfig ?? 'clientSecret'] ?? ''),\n }\n }\n\n // x-www-form-urlencoded token exchange against `tokenUrl`; client creds go in the Basic header\n // (`clientAuth: 'basic'`) or the body (default).\n async #exchangeToken(config: Record<string, unknown>, body: Record<string, string>): Promise<Record<string, unknown>> {\n const { id, secret } = this.#clientCreds(config)\n const params = new URLSearchParams(body)\n const headers: Record<string, string> = { 'Content-Type': 'application/x-www-form-urlencoded' }\n\n if (this.props.clientAuth === 'basic') {\n headers.Authorization = `Basic ${ Buffer.from(`${ id }:${ secret }`).toString('base64') }`\n } else {\n params.set('client_id', id)\n params.set('client_secret', secret)\n }\n\n return Flowrunner.Request\n .post(this.props.tokenUrl as string)\n .set(headers)\n .send(params.toString()) as Promise<Record<string, unknown>>\n }\n}\n", "// The three runtime-owned OAuth SYSTEM methods \u2014 the frozen v1 seam. Do not rename: these are published\n// method names the platform invokes by string.\nexport const OAUTH_SYSTEM_METHODS = {\n CONNECTION_URL: 'getOAuth2ConnectionURL',\n EXECUTE_CALLBACK: 'executeCallback',\n REFRESH_TOKEN: 'refreshToken',\n} as const\n", "import { z } from '../params'\n\n// The input each OAuth SYSTEM method carries. Runtime-owned, not author-declared. LOOSE where the producer\n// is the console's OAuth controller: it may send fields a given milestone doesn't model yet, and dropping\n// them silently would be worse than carrying them through.\n\nexport const OAuthCallbackObjectSchema = z.looseObject({\n code: z.string().optional(),\n redirectURI: z.string().optional(),\n // The PKCE verifier round-trips through `state`.\n state: z.string().optional(),\n})\n\nexport const RefreshTokenSchema = z.string().min(1)\n", "// The single runtime-owned SYSTEM method shared by every polling trigger of a service; the runtime invokes\n// it on each tick and it routes by `invocation.eventName`. Frozen \u2014 a published method name.\nexport const POLLING_SYSTEM_METHOD = 'handleTriggerPollingForEvent'\n", "import { z } from '../params'\n\n// The invocation the runtime hands to the polling SYSTEM method on each tick. Runtime-owned, not\n// author-declared. LOOSE: the flow engine may send fields a given milestone doesn't model yet.\nexport const PollingInvocationSchema = z.looseObject({\n eventName: z.string().min(1),\n // The trigger instance's configured params \u2014 validated against the trigger's own schema separately.\n triggerData: z.record(z.string(), z.unknown()).optional(),\n state: z.record(z.string(), z.unknown()).nullish(),\n learningMode: z.boolean().optional(),\n connectionId: z.string().nullish(),\n})\n", "import { UnknownTriggerError } from '../../errors'\nimport type { Extension } from '../extension'\nimport { z } from '../params'\nimport type { SystemMethodSpec } from '../system-method'\nimport { POLLING_SYSTEM_METHOD } from './method-names'\nimport { PollingInvocationSchema } from './system-params'\nimport type { PollingTriggerMethod } from './trigger-method'\nimport type { PollingInvocation } from './types'\n\n// The polling triggers a service declares, as a set.\n//\n// The SYSTEM seam that drives them belongs HERE rather than to any one trigger: the runtime ticks a single\n// `handleTriggerPollingForEvent` and this routes it by `eventName`. Registering it on the first trigger\n// added is what makes it exist exactly when at least one trigger does \u2014 the model no longer needs a\n// separate \"are there any?\" check, because the method is simply there or not.\n\nexport class PollingTriggers {\n readonly #triggers = new Map<string, PollingTriggerMethod>()\n\n constructor(private readonly extension: Extension) {}\n\n get size(): number {\n return this.#triggers.size\n }\n\n get(id: string): PollingTriggerMethod | undefined {\n return this.#triggers.get(id)\n }\n\n all(): PollingTriggerMethod[] {\n return [...this.#triggers.values()]\n }\n\n add(trigger: PollingTriggerMethod): void {\n const first = this.size === 0\n\n this.#triggers.set(trigger.id, trigger)\n\n if (first) {\n this.#registerSystemMethods()\n }\n }\n\n // \u2500\u2500 SYSTEM seam: name \u00B7 input \u00B7 handler, in one place \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #registerSystemMethods(): void {\n this.extension.registerSystemMethods([{\n name: POLLING_SYSTEM_METHOD,\n scheme: z.object({ invocation: PollingInvocationSchema }),\n run: ({ invocation }, ctx) => {\n const value = invocation as PollingInvocation\n const trigger = this.get(value.eventName)\n\n if (!trigger) {\n throw new UnknownTriggerError(this.extension.id, value.eventName, 'polling')\n }\n\n return trigger.poll(value, ctx)\n },\n } satisfies SystemMethodSpec])\n }\n}\n", "// Read a dot-notation path (`a.b.c`) from a nested object; returns undefined if any segment is missing.\n// Shared by dictionaries/triggers for field-path config (dedupe/watermark `by`, match paths, extract*).\nexport function getPath(source: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>(\n (acc, key) => (acc == null ? acc : (acc as Record<string, unknown>)[key]),\n source\n )\n}\n", "import { InvalidTriggerConfigError } from '../../errors'\nimport { getPath } from '../path'\nimport type { HandlerBag } from '../types'\nimport type {\n DedupeConfig,\n PollingInvocation,\n PollingPollBag,\n PollingResult,\n PollingTriggerProps,\n WatermarkConfig,\n} from './types'\n\n// How a polling trigger decides what is NEW (08-polling-triggers.md). Three strategies, of which an author\n// declares exactly one:\n//\n// dedupe \u2014 remember the ids already seen, emit the rest (unordered feeds, no reliable timestamp)\n// watermark \u2014 remember the newest marker, emit anything past it (ordered feeds with a cursor field)\n// poll \u2014 the author owns the whole { events, state } contract (escape hatch)\n//\n// The first two share a lifecycle the base class owns, so a strategy only implements its own delta:\n// \u2022 first poll (no state) \u2192 SEED the state, emit nothing (wiring up must not fire a run)\n// \u2022 learningMode \u2192 emit the fetched head, state null (a sample for setup; nothing persisted)\n// \u2022 thereafter \u2192 emit the delta, advance the state\n//\n// The runtime drives the interval and the persistence; this file only computes `{ events, state }`.\n\n// What one invocation gives a strategy to work with.\ninterface PollCycle {\n bag: HandlerBag\n params: Record<string, unknown>\n isLearningMode: boolean\n state: Record<string, unknown> | null\n}\n\ntype FetchFn = (bag: HandlerBag & { params: Record<string, unknown>; isLearningMode: boolean }) =>\n unknown[] | Promise<unknown[]>\n\nexport abstract class PollingMechanism {\n /**\n * Pick the strategy an author declared, rejecting the combinations that cannot work. Runs at REGISTRATION\n * time, so a misconfigured trigger fails while the service module is being required rather than on some\n * later tick in production.\n */\n static from(props: PollingTriggerProps, serviceId: string): PollingMechanism {\n const declared = (['dedupe', 'watermark', 'poll'] as const)\n .filter(key => props[key] != null)\n\n if (declared.length !== 1) {\n throw new InvalidTriggerConfigError(\n serviceId,\n `polling trigger \"${ props.id }\" must declare exactly one of dedupe|watermark|poll (got: ${ declared.join(', ') || 'none' })`,\n { triggerId: props.id }\n )\n }\n\n if (props.poll) {\n return new CustomPollMechanism(props.poll)\n }\n\n // dedupe and watermark both filter a fetched list \u2014 without `fetch` there is nothing to filter.\n if (typeof props.fetch !== 'function') {\n throw new InvalidTriggerConfigError(\n serviceId,\n `polling trigger \"${ props.id }\" with dedupe/watermark requires a fetch(...) function`,\n { triggerId: props.id }\n )\n }\n\n return props.dedupe\n ? new DedupeMechanism(props.fetch as FetchFn, props.dedupe)\n : new WatermarkMechanism(props.fetch as FetchFn, props.watermark!)\n }\n\n run(invocation: PollingInvocation, bag: HandlerBag): Promise<PollingResult> {\n return this.poll({\n bag,\n params: invocation.triggerData ?? {},\n isLearningMode: !!invocation.learningMode,\n state: invocation.state ?? null,\n })\n }\n\n protected abstract poll(cycle: PollCycle): Promise<PollingResult>\n}\n\n// The escape hatch: the author owns fetching, comparison and state.\nclass CustomPollMechanism extends PollingMechanism {\n constructor(private readonly fn: NonNullable<PollingTriggerProps['poll']>) {\n super()\n }\n\n protected async poll({ bag, params, state, isLearningMode }: PollCycle): Promise<PollingResult> {\n return this.fn({ ...bag, params, state, isLearningMode } as PollingPollBag)\n }\n}\n\n// The shared lifecycle of the two strategies that filter a fetched list.\nabstract class FetchingMechanism extends PollingMechanism {\n constructor(private readonly fetch: FetchFn) {\n super()\n }\n\n protected async poll({ bag, params, state, isLearningMode }: PollCycle): Promise<PollingResult> {\n const items = await this.fetch({ ...bag, params, isLearningMode })\n\n // Learning mode: emit the fetched head as the sample; do not persist state.\n if (isLearningMode) {\n return { events: items, state: null }\n }\n\n return this.delta(items, state, params)\n }\n\n // What is new since `state`, and the state to remember next time.\n protected abstract delta(\n items: unknown[],\n state: Record<string, unknown> | null,\n params: Record<string, unknown>\n ): PollingResult\n}\n\n// \u2500\u2500 dedupe (seen-set) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass DedupeMechanism extends FetchingMechanism {\n readonly #by: (item: unknown) => unknown\n readonly #stateKey: string\n readonly #max: number\n\n constructor(fetch: FetchFn, config: DedupeConfig) {\n super(fetch)\n\n if (typeof config === 'function') {\n this.#by = config\n this.#stateKey = 'seen'\n this.#max = 500\n } else if (typeof config === 'string') {\n this.#by = item => getPath(item, config)\n this.#stateKey = 'seen'\n this.#max = 500\n } else {\n this.#by = typeof config.by === 'function' ? config.by : (item: unknown) => getPath(item, config.by as string)\n this.#stateKey = config.stateKey ?? 'seen'\n this.#max = config.max ?? 500\n }\n }\n\n protected delta(items: unknown[], state: Record<string, unknown> | null): PollingResult {\n const currentIds = items.map(this.#by).map(id => `${ id }`)\n\n // Seed on first poll: remember ids, emit nothing.\n if (!state?.[this.#stateKey]) {\n return { events: [], state: { [this.#stateKey]: this.#buildSeen([], currentIds) } }\n }\n\n const seen = toSeenList(state[this.#stateKey])\n const seenSet = new Set(seen)\n const events = items.filter((_item, index) => !seenSet.has(currentIds[index]))\n\n return { events, state: { [this.#stateKey]: this.#buildSeen(seen, currentIds) } }\n }\n\n // Bounded id list, oldest first, keeping the most-recent `max` ids. An id fetched again moves to the end,\n // so an item that is still in the feed is never the one evicted. It is a list, not an `{ id: 1 }` map: a\n // map orders integer-like keys numerically, which evicted the SMALLEST id instead of the oldest one.\n #buildSeen(seen: string[], currentIds: string[]): string[] {\n const fetched = new Set(currentIds)\n\n return [...seen.filter(id => !fetched.has(id)), ...fetched].slice(-this.#max)\n }\n}\n\n// State persisted before the list format is an `{ id: 1 }` map. It is still read so a live trigger keeps\n// its seen ids across the upgrade; its order is lost, which only matters until the next `max` ids roll in.\nconst toSeenList = (value: unknown): string[] => {\n return Array.isArray(value)\n ? value.map(id => `${ id }`)\n : Object.keys(value as Record<string, unknown>)\n}\n\n// \u2500\u2500 watermark (marker) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// Markers are compared with JS relational ordering, which is exactly what lets one `by` field work whether\n// the provider hands out ISO timestamps, sortable ids or plain numbers \u2014 the author never declares which.\nconst isNewer = (value: unknown, marker: unknown): boolean => (value as string) > (marker as string)\n\nclass WatermarkMechanism extends FetchingMechanism {\n readonly #stateKey: string\n\n constructor(fetch: FetchFn, private readonly config: WatermarkConfig) {\n super(fetch)\n\n this.#stateKey = config.stateKey ?? 'watermark'\n }\n\n protected delta(\n items: unknown[],\n state: Record<string, unknown> | null,\n params: Record<string, unknown>\n ): PollingResult {\n const valueOf = (item: unknown): unknown =>\n typeof this.config.by === 'function' ? this.config.by(item, { params }) : getPath(item, this.config.by)\n\n const advance = (start: unknown): unknown =>\n items.reduce((max, item) => {\n const value = valueOf(item)\n\n if (value == null) {\n return max\n }\n\n return max == null || isNewer(value, max) ? value : max\n }, start)\n\n // Seed on first poll: store the newest marker, emit nothing.\n if (state?.[this.#stateKey] === undefined || state?.[this.#stateKey] === null) {\n return { events: [], state: { [this.#stateKey]: advance(undefined) } }\n }\n\n const marker = state[this.#stateKey]\n const events: unknown[] = []\n\n for (const item of items) {\n const value = valueOf(item)\n\n if (value != null && isNewer(value, marker)) {\n events.push(item)\n } else if (this.config.sortedDesc) {\n // newest-first list \u2192 the first non-newer item means the rest are older too.\n break\n }\n }\n\n return { events, state: { [this.#stateKey]: advance(marker) } }\n }\n}\n", "import { UnknownMethodError } from '../../errors'\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport type { LoaderOwner } from '../loaders/loader-owner'\nimport { ExtensionMethod } from '../method'\nimport type { SharedExtensionMethod } from '../model/model-types'\nimport { toArgs, toBodyParams } from '../model/params-model'\nimport { encodeParams, MethodParams } from '../params'\nimport { ResultSpec } from '../result'\nimport { PollingMechanism } from './mechanisms'\nimport type { PollingInvocation, PollingResult, PollingTriggerProps } from './types'\n\n// A polling trigger (08-polling-triggers.md). It is a published method \u2014 the console renders it as a start\n// node with its own params and sample result \u2014 but it is NOT invocable by name: the runtime reaches it\n// through the shared polling SYSTEM method, which routes by `eventName` (see ./polling-triggers.ts).\n\nexport class PollingTriggerMethod extends ExtensionMethod implements LoaderOwner {\n readonly params: MethodParams\n readonly result: ResultSpec\n readonly mechanism: PollingMechanism\n\n constructor(extension: Extension, private readonly props: PollingTriggerProps) {\n super(extension)\n\n this.params = MethodParams.of(props.params, {\n serviceId: extension.id,\n kind: 'polling trigger',\n itemId: props.id,\n slot: 'params',\n })\n this.result = ResultSpec.from(props.result)\n // Validates the declared combination \u2014 see PollingMechanism.from.\n this.mechanism = PollingMechanism.from(props, extension.id)\n }\n\n get id(): string {\n return this.props.id\n }\n\n get name(): string {\n return this.props.id\n }\n\n get registerAs(): string {\n return 'POLLING_TRIGGER'\n }\n\n get category(): string {\n return this.props.category\n }\n\n get oauth2Scopes(): string[] {\n return this.props.oauth2Scopes ?? []\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // Not dispatchable by name \u2014 the platform ticks `handleTriggerPollingForEvent` instead, so a call that\n // lands here is a caller using the trigger id as if it were an action.\n execute(): never {\n throw new UnknownMethodError(this.extension.id, this.name)\n }\n\n // One tick for this trigger, with its instance params already validated.\n poll(invocation: PollingInvocation, ctx: ExecutionContext): Promise<PollingResult> {\n return this.mechanism.run(\n { ...invocation, triggerData: this.#triggerData(invocation.triggerData) },\n ctx.toBag()\n )\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toModel(): SharedExtensionMethod {\n const [ownStart, ownEnd] = this.props.appearanceColors ?? []\n const [colorStart, colorEnd] = this.extension.appearanceColors\n\n return {\n name: this.id,\n operationName: this.props.label,\n description: this.props.description || '',\n registerAs: this.registerAs,\n category: this.category,\n colorStart: ownStart ?? colorStart,\n colorEnd: ownEnd ?? colorEnd,\n customIcon: this.props.logo ?? '',\n returnType: this.result.returnType,\n queryParams: [],\n bodyParams: toBodyParams(this.params),\n paramsSchema: encodeParams(this.params.scheme),\n metaInfo: { args: toArgs(this.params), ...this.result.toMetaInfo(this.id, this.params) },\n }\n }\n\n // A trigger instance's configured params, through the same pipeline as everything else. A saved instance\n // missing a required param therefore fails the poll rather than polling with `undefined` \u2014 the trigger\n // genuinely cannot work without it. Unknown fields ride through to the handler.\n #triggerData(data: Record<string, unknown> = {}): Record<string, unknown> {\n return this.params.normalize(data, this.input(data).invalidInput('triggerData'), { carryUnknown: true })\n }\n}\n", "// The five runtime-owned realtime SYSTEM methods \u2014 the frozen v1 webhook lifecycle seam. Do not rename:\n// these are published method names the platform invokes by string.\nexport const REALTIME_SYSTEM_METHODS = {\n UPSERT: 'handleTriggerUpsertWebhook',\n RESOLVE: 'handleTriggerResolveEvents',\n SELECT: 'handleTriggerSelectMatched',\n DELETE: 'handleTriggerDeleteWebhook',\n REFRESH: 'handleTriggerRefreshWebhook',\n} as const\n", "import { z } from '../params'\n\n// The invocation shapes the runtime hands to the realtime SYSTEM methods (v1-compatible). Runtime-owned,\n// not author-declared, and all LOOSE: the flow engine may send fields a given milestone doesn't model yet,\n// and dropping them silently would be worse than carrying them through.\n\nconst anyRecord = () => z.record(z.string(), z.unknown())\n\nconst SubscriptionEventSchema = z.looseObject({\n name: z.string().min(1),\n triggerData: anyRecord().optional(),\n})\n\n// upsert + refresh \u2014 both subscribe the callback URL for a set of trigger instances.\nexport const RealtimeSubscriptionInvocationSchema = z.looseObject({\n callbackUrl: z.string().min(1),\n events: z.array(SubscriptionEventSchema).default([]),\n webhookData: anyRecord().nullish(),\n connectionId: z.string().nullish(),\n})\n\n// delete \u2014 the webhook is torn down from its stored data; the callback URL is informational.\nexport const RealtimeDeleteInvocationSchema = z.looseObject({\n callbackUrl: z.string().optional(),\n webhookData: anyRecord().nullish(),\n connectionId: z.string().nullish(),\n})\n\n// resolve \u2014 the raw inbound HTTP delivery, plus the webhook document persisted at subscription time.\n// `webhookData` is NULLISH on purpose: the platform looks the document up per workspace, so a delivery\n// arriving on the general callback of a service that is not app-hosted carries none, and neither does one\n// for which no document exists (yet).\nexport const RealtimeInboundInvocationSchema = z.looseObject({\n headers: anyRecord().optional(),\n queryParams: anyRecord().optional(),\n body: z.unknown(),\n rawBody: z.string().optional(),\n webhookData: anyRecord().nullish(),\n connectionId: z.string().nullish(),\n})\n\n// select \u2014 one resolved event fanned out over the registered trigger instances. `webhookData` rides along\n// for the same reason it does on resolve, and is READ-ONLY here too: this seam answers with matched ids and\n// enriched data, never with a new document.\nexport const RealtimeSelectInvocationSchema = z.looseObject({\n eventName: z.string().min(1),\n eventData: z.unknown(),\n webhookData: anyRecord().nullish(),\n triggers: z.array(z.looseObject({\n id: z.string().min(1),\n // A partially-configured instance is legal \u2014 `match` treats an empty param as \"matches all\".\n data: anyRecord().optional(),\n })).default([]),\n})\n", "import type { RealtimeVerify } from './types'\n\n// The declarative inbound-signature check (09-realtime-triggers.md): HMAC the raw body with a secret drawn\n// from config, compare it in constant time to the header the provider sent, and \u2014 when the provider stamps\n// its deliveries \u2014 reject anything too old to be a live event rather than a replay.\n//\n// Services cannot `require` node modules, so the primitives come from `Flowrunner.crypto` (see ../crypto).\n// An author who needs something this shape cannot express writes `verifyRequest` instead.\n\nexport function verifyDeclarative(\n verify: RealtimeVerify,\n rawBody: string | undefined,\n headers: Record<string, unknown>,\n config: Record<string, unknown>,\n // The stored webhook document of this delivery \u2014 `null` when none. A provider that mints the signing\n // secret at registration time keeps it here, so `secret` has to be able to read it.\n webhookData: unknown\n): boolean {\n const provided = (headers[verify.header] ?? headers[verify.header.toLowerCase()]) as string | undefined\n\n if (!provided) {\n return false\n }\n\n const secret = verify.secret(config, { webhookData })\n const computed = Flowrunner.crypto.hmac(verify.algo, secret, rawBody ?? '', verify.encoding)\n\n if (!Flowrunner.crypto.timingSafeEqual(provided, computed)) {\n return false\n }\n\n if (verify.freshness && verify.timestampHeader) {\n const timestamp = headers[verify.timestampHeader] as string | undefined\n\n if (timestamp && Flowrunner.crypto.ageSeconds(timestamp) > verify.freshness) {\n return false\n }\n }\n\n return true\n}\n", "import { RealtimeSetupError, UnknownTriggerError } from '../../errors'\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { z } from '../params'\nimport { getPath } from '../path'\nimport type { SystemMethodSpec } from '../system-method'\nimport type { AnySchema, ProviderPayload } from '../types'\nimport { REALTIME_SYSTEM_METHODS } from './method-names'\nimport {\n RealtimeDeleteInvocationSchema,\n RealtimeInboundInvocationSchema,\n RealtimeSelectInvocationSchema,\n RealtimeSubscriptionInvocationSchema,\n} from './system-params'\nimport type { RealtimeInvocation, RealtimeSetupProps, RealtimeSubTrigger } from './types'\nimport { verifyDeclarative } from './verify'\n\n// `ext.setupRealtimeTriggers(...)` \u2014 the webhook plumbing shared by every realtime trigger of a service\n// (09-realtime-triggers.md). The author writes declarative config plus lifecycle functions; this owns the\n// five v1 SYSTEM methods and drives them:\n//\n// handleTriggerUpsertWebhook \u2192 subscribe register the callback URL with the provider\n// handleTriggerDeleteWebhook \u2192 unsubscribe tear it down\n// handleTriggerRefreshWebhook \u2192 refresh (optional) renew a subscription that expires\n// handleTriggerResolveEvents \u2192 handshake \u2192 verify \u2192 route shape one inbound delivery into events\n// handleTriggerSelectMatched \u2192 per-instance match pick which configured instances fire\n//\n// Splitting resolve from select is what keeps the expensive work rare: resolve runs once per delivery and\n// touches no API, select runs per event and may enrich once, only if something actually matched.\n\n// Read a `string | fn` extractor against the request body.\nfunction readExtract(\n extract: string | ((bag: { requestBody: ProviderPayload }) => unknown) | undefined,\n body: unknown\n): unknown {\n if (typeof extract === 'function') {\n return extract({ requestBody: body })\n }\n\n if (typeof extract === 'string') {\n return getPath(body, extract)\n }\n\n return undefined\n}\n\nfunction isEmptyBody(body: unknown): boolean {\n return body == null || (typeof body === 'object' && Object.keys(body as object).length === 0)\n}\n\nexport class RealtimeSetup {\n constructor(private readonly extension: Extension, private readonly props: RealtimeSetupProps) {\n if (typeof props.subscribe !== 'function' || typeof props.unsubscribe !== 'function') {\n throw new RealtimeSetupError(extension.id, 'setupRealtimeTriggers requires subscribe and unsubscribe functions')\n }\n\n this.#registerSystemMethods()\n }\n\n get scope(): RealtimeSetupProps['scope'] {\n return this.props.scope\n }\n\n get hasRefresh(): boolean {\n return typeof this.props.refresh === 'function'\n }\n\n // \u2500\u2500 SYSTEM seam: name \u00B7 input \u00B7 handler, in one table \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #registerSystemMethods(): void {\n const M = REALTIME_SYSTEM_METHODS\n\n // Every realtime SYSTEM method takes the same single `invocation` param; only its shape differs.\n const spec = (\n name: string,\n schema: AnySchema,\n run: (invocation: RealtimeInvocation, ctx: ExecutionContext) => unknown,\n published = true\n ): SystemMethodSpec => ({\n name,\n scheme: z.object({ invocation: schema }),\n published,\n run: ({ invocation }, ctx) => run(invocation as RealtimeInvocation, ctx),\n })\n\n this.extension.registerSystemMethods([\n spec(M.UPSERT, RealtimeSubscriptionInvocationSchema, (i, ctx) => this.#subscribe(i, ctx)),\n spec(M.DELETE, RealtimeDeleteInvocationSchema, (i, ctx) => this.#unsubscribe(i, ctx)),\n spec(M.RESOLVE, RealtimeInboundInvocationSchema, (i, ctx) => this.#resolve(i, ctx)),\n spec(M.SELECT, RealtimeSelectInvocationSchema, (i, ctx) => this.#selectMatched(i, ctx)),\n // Refresh stays CALLABLE either way \u2014 it answers `{}` when no handler was declared \u2014 but is only\n // advertised in the model when the author actually declared one.\n spec(M.REFRESH, RealtimeSubscriptionInvocationSchema, (i, ctx) => this.#refresh(i, ctx), this.hasRefresh),\n ])\n }\n\n // \u2500\u2500 subscription lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n async #subscribe(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n const result = await this.props.subscribe(ctx.bagWith({\n callbackUrl: invocation.callbackUrl as string,\n triggers: this.#toSubTriggers(invocation.events),\n webhookData: invocation.webhookData ?? null,\n connectionId: invocation.connectionId,\n }))\n\n return {\n webhookData: result?.webhookData,\n eventScopeId: result?.eventScopeId,\n refreshIntervalInSeconds: result?.refreshIntervalInSeconds,\n }\n }\n\n async #unsubscribe(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n const result = await this.props.unsubscribe(ctx.bagWith({\n callbackUrl: invocation.callbackUrl,\n webhookData: invocation.webhookData,\n connectionId: invocation.connectionId,\n }))\n\n return { webhookData: result?.webhookData ?? {} }\n }\n\n async #refresh(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n if (!this.props.refresh) {\n return {}\n }\n\n const result = await this.props.refresh(ctx.bagWith({\n callbackUrl: invocation.callbackUrl as string,\n triggers: this.#toSubTriggers(invocation.events),\n webhookData: invocation.webhookData,\n }))\n\n return { webhookData: result?.webhookData, refreshIntervalInSeconds: result?.refreshIntervalInSeconds }\n }\n\n // v1 upsert/refresh hand over events [{ name, triggerData }]. A trigger that declares provider event\n // names expands to one entry EACH, which is what a provider's subscribe API actually wants.\n //\n // A trigger that declares NONE still gets an entry. `providerEventName` is a ROUTING declaration and this\n // is a LIFECYCLE seam: an extension that resolves its own events (`resolveEvents`) legitimately has nothing to\n // route by, yet its triggers still run and `subscribe`/`refresh` still have to reconcile them. Gating the\n // bag on the routing declaration handed such a service an empty bag on every subscribe \u2014 silently, since\n // an empty subscription is a perfectly well-formed result.\n //\n // NOTHING is dropped here. A `name` resolving to no trigger THROWS, because this is the CONTROL PLANE:\n // upsert/refresh are initiated by FlowRunner itself, something is waiting on the result, and no third\n // party is affected \u2014 so an error reaches a place where it can be acted on. `subscribe` is the seam that\n // registers with the PROVIDER, so a dropped entry meant a flow that reported LIVE while its trigger was\n // never subscribed \u2014 silent, and indistinguishable from a working flow that simply never fired. One throw\n // does block the rest of the batch from subscribing, and that is the intent: a flow refusing to start\n // beats a live flow with half its triggers registered. (The data plane is ruled the other way \u2014 see\n // `#selectMatched`, which declines rather than throws because nothing is waiting on it.)\n #toSubTriggers(events: RealtimeInvocation['events'] = []): RealtimeSubTrigger[] {\n const subTriggers: RealtimeSubTrigger[] = []\n\n for (const event of events) {\n const trigger = this.extension.findRealtimeTrigger(event.name)\n\n if (!trigger) {\n throw new UnknownTriggerError(this.extension.id, event.name, 'realtime')\n }\n\n const params = event.triggerData ?? {}\n const providerEventNames = trigger.providerEventNames(params)\n\n // No placeholder: a `providerEventName` the provider has never heard of would reach `subscribe`, the\n // seam that calls the provider's own subscription API. A missing field an author can test for is safer.\n if (!providerEventNames.length) {\n subTriggers.push({ id: event.name, params })\n continue\n }\n\n for (const providerEventName of providerEventNames) {\n subTriggers.push({ id: event.name, params, providerEventName })\n }\n }\n\n return subTriggers\n }\n\n // \u2500\u2500 inbound delivery \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n async #resolve(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n const headers = invocation.headers ?? {}\n const body = invocation.body\n const rawBody = invocation.rawBody\n // The document `subscribe` returned, as the platform stored it \u2014 the only way state registered with the\n // provider (a signing secret, an external webhook id) reaches the delivery it describes. Normalized to\n // `null` so every inbound seam reports \"nothing stored\" the one way, rather than `undefined` here and\n // `null` there depending on whether the platform sent the field or sent it empty.\n const webhookData = invocation.webhookData ?? null\n\n // 1. Endpoint-verification handshake (challenge/echo). Anything returned \u2192 ack without processing.\n if (this.props.handshake) {\n const result = await this.props.handshake(ctx.bagWith({ requestBody: body, headers, rawBody, webhookData }))\n\n if (result && (\n result.responseToExternalService !== undefined || result.responseHeaders || result.responseToWebhook\n )) {\n // Both shapes travel, exactly as the author wrote them. `responseToWebhook` is the newer, fuller\n // one, but the platform does not understand it yet \u2014 so translating the older pair into it would\n // drop the response of every service already using it. The platform picks whichever it supports.\n return {\n handshake: true,\n responseToExternalService: result.responseToExternalService,\n responseHeaders: result.responseHeaders,\n responseToWebhook: result.responseToWebhook,\n }\n }\n }\n\n // Empty-body deliveries are auto-acked.\n if (isEmptyBody(body)) {\n return { handshake: true, events: [] }\n }\n\n // 2. Signature verification (escape hatch or declarative). Reject on failure \u2014 by RETURNING a 401,\n // never by throwing.\n //\n // A forged delivery is a normal, expected outcome of a public callback URL, not a runtime failure. A\n // throw leaves the pod with a 4xx, which the platform reads as \"the invocation failed\" rather than \"the\n // extension answered 401\" \u2014 so the provider receives a 500. That fails exactly the validation this is\n // for: Xero's Intent to Receive sends a deliberately mis-signed delivery and requires a 401 back.\n //\n // Empty `rawBody` rather than `body`: a rejection carries no content, and `body` is always JSON, so an\n // empty string there would arrive quoted.\n if (!await this.#verify(rawBody, headers, webhookData, ctx)) {\n ctx.logger.warn(`[flow-extension:${ this.extension.id }] webhook signature verification failed \u2014 answering 401`)\n\n return { events: [], responseToWebhook: { httpStatus: 401, rawBody: '' } }\n }\n\n // 3. Escape hatch for irregular/multi-shape payloads \u2014 emits v1 events directly.\n if (this.props.resolveEvents) {\n const result = await this.props.resolveEvents(ctx.bagWith({\n rawBody,\n headers,\n query: invocation.queryParams ?? {},\n body,\n webhookData,\n connectionId: invocation.connectionId,\n }))\n\n return {\n handshake: result.handshake,\n responseToExternalService: result.responseToExternalService,\n responseHeaders: result.responseHeaders,\n responseToWebhook: result.responseToWebhook,\n eventScopeId: result.eventScopeId,\n events: (result.events ?? []).map(event => ({ name: event.id, data: event.providerEventData })),\n }\n }\n\n // 4. Declarative routing: discriminator \u2192 every trigger claiming it; build providerEventData.\n const eventName = readExtract(this.props.extractProviderEventName, body)\n\n if (eventName == null) {\n return { events: [] }\n }\n\n const baseData = this.props.extractProviderEventData\n ? readExtract(this.props.extractProviderEventData, body)\n : body\n const events: { name: string; data: unknown }[] = []\n\n for (const trigger of this.extension.realtimeTriggers()) {\n if (!trigger.claims(eventName as string)) {\n continue\n }\n\n const extra = trigger.extendEventData(body, baseData as Record<string, unknown>)\n\n events.push({ name: trigger.id, data: extra ? { ...(baseData as object), ...extra } : baseData })\n }\n\n const eventScopeId = this.props.scopeAt ? getPath(body, this.props.scopeAt) : undefined\n\n return { events, eventScopeId, connectionId: invocation.connectionId }\n }\n\n // The author's own check wins; otherwise the declarative one; otherwise nothing was asked for.\n async #verify(\n rawBody: string | undefined,\n headers: Record<string, unknown>,\n webhookData: unknown,\n ctx: ExecutionContext\n ): Promise<boolean> {\n if (this.props.verifyRequest) {\n return !!await this.props.verifyRequest(ctx.bagWith({ rawBody, headers, webhookData, config: ctx.config }))\n }\n\n if (this.props.verify) {\n return verifyDeclarative(this.props.verify, rawBody, headers, ctx.config, webhookData)\n }\n\n return true\n }\n\n // Fan one resolved event out over the configured instances of its trigger. An `eventName` this service\n // does not declare is DECLINED outright \u2014 `{ ids: [], enrichedEventData: null }`, no instance offered up\n // and no per-event seam run. That is deliberately not the same case as a trigger which declares no\n // `match`: `matches()` already answers \"fires always\" for that one, so resolve the name FIRST and never\n // let the two share a branch.\n //\n // Declining is the GUARANTEE here, not an accident of a past fix, and it is why this seam is ruled the\n // opposite way to `#toSubTriggers`. This is the DATA PLANE: the platform has already answered the\n // provider and detached this work, so a throw reaches nobody \u2014 and worse, it aborts every remaining event\n // of the same delivery, dropping the good ones beside the stale name.\n async #selectMatched(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n // `eventName` is in practice always present \u2014 RealtimeSelectInvocationSchema declares it\n // `z.string().min(1)`, so SystemMethod.validate rejects a missing one before this runs. The shared\n // invocation bag cannot say so (the other four SYSTEM methods carry no event name), and an absent name\n // is not a trigger id either way, so it folds into the same decline rather than earning a branch.\n const trigger = invocation.eventName ? this.extension.findRealtimeTrigger(invocation.eventName) : undefined\n\n if (!trigger) {\n return { ids: [], enrichedEventData: null }\n }\n\n const eventData = invocation.eventData\n // Read-only here, exactly as on resolve: `match` and `extendResult` may consult what the subscription\n // registered, and neither can write it back \u2014 this seam's answer is ids and enriched data, nothing else.\n const webhookData = invocation.webhookData ?? null\n const ids = (invocation.triggers ?? [])\n .filter(instance => trigger.matches(instance.data ?? {}, eventData, webhookData))\n .map(instance => instance.id)\n\n // extendResult runs ONCE if any instance matched \u2014 the only per-event place that may call the API.\n const enrichedEventData = ids.length && trigger.hasExtendResult()\n ? await trigger.extendResult(eventData, ctx, webhookData)\n : null\n\n return { ids, enrichedEventData }\n }\n}\n", "import { UnknownMethodError } from '../../errors'\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport type { LoaderOwner } from '../loaders/loader-owner'\nimport { ExtensionMethod } from '../method'\nimport type { SharedExtensionMethod } from '../model/model-types'\nimport { toArgs, toBodyParams } from '../model/params-model'\nimport { encodeParams, MethodParams } from '../params'\nimport { getPath } from '../path'\nimport { ResultSpec } from '../result'\nimport type { ProviderPayload } from '../types'\nimport type { RealtimeTriggerProps } from './types'\n\n// A realtime (webhook) trigger (09-realtime-triggers.md). Like a polling trigger it is a published method\n// the console renders as a start node, but is NOT invocable by name \u2014 the runtime reaches it through the\n// realtime SYSTEM seam (see ./realtime-setup.ts), which routes inbound deliveries to it.\n//\n// Its three author hooks answer three different questions, at three different moments:\n// providerEventNames which provider events is this trigger about? (routing, per delivery)\n// matches does THIS configured instance care about it? (fan-out, per instance)\n// extendResult what extra data should the event carry? (once, if anything matched)\n\nexport class RealtimeTriggerMethod extends ExtensionMethod implements LoaderOwner {\n readonly params: MethodParams\n readonly result: ResultSpec\n\n constructor(extension: Extension, private readonly props: RealtimeTriggerProps) {\n super(extension)\n\n this.params = MethodParams.of(props.params, {\n serviceId: extension.id,\n kind: 'realtime trigger',\n itemId: props.id,\n slot: 'params',\n })\n this.result = ResultSpec.from(props.result)\n }\n\n get id(): string {\n return this.props.id\n }\n\n get name(): string {\n return this.props.id\n }\n\n get registerAs(): string {\n return 'REALTIME_TRIGGER'\n }\n\n get category(): string {\n return this.props.category\n }\n\n get oauth2Scopes(): string[] {\n return this.props.oauth2Scopes ?? []\n }\n\n // Not dispatchable by name \u2014 inbound deliveries arrive through the realtime SYSTEM methods.\n execute(): never {\n throw new UnknownMethodError(this.extension.id, this.name)\n }\n\n // \u2500\u2500 routing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // The provider event(s) this trigger claims. The fn form depends on instance params (unusual for routing)\n // \u2014 best-effort with the params given.\n providerEventNames(params: Record<string, unknown> = {}): string[] {\n const declared = this.props.providerEventName\n\n if (typeof declared === 'function') {\n return declared({ params }) ?? []\n }\n\n if (Array.isArray(declared)) {\n return declared\n }\n\n return declared ? [declared] : []\n }\n\n claims(providerEventName: string): boolean {\n return this.providerEventNames().includes(providerEventName)\n }\n\n // Per-trigger enrichment of the shaped event data, before instances are matched against it.\n extendEventData(requestBody: ProviderPayload, providerEventData: ProviderPayload): Record<string, unknown> | undefined {\n return this.props.extendEventData?.({ requestBody, providerEventData })\n }\n\n /**\n * Whether one CONFIGURED INSTANCE of this trigger cares about an event. Declarative form: type-coerced\n * equality per filled param, where an empty param means \"any\" \u2014 that is what lets a user leave a filter\n * blank and receive everything. Predicate form: the author decides. No `match` at all: always fires.\n *\n * `webhookData` is handed to the predicate form to be READ \u2014 an instance filter that depends on what the\n * subscription registered (a tenant id, a resource the webhook was scoped to) has nowhere else to get it.\n * Returning a new document is not a thing this seam can do; only subscribe/refresh/unsubscribe persist.\n */\n matches(\n params: Record<string, unknown>,\n providerEventData: ProviderPayload,\n webhookData: ProviderPayload = null\n ): boolean {\n const match = this.props.match\n\n if (!match) {\n return true\n }\n\n if (typeof match === 'function') {\n return !!match({ params, providerEventData, webhookData })\n }\n\n for (const [paramKey, path] of Object.entries(match)) {\n const paramValue = params[paramKey]\n\n if (paramValue == null || paramValue === '') {\n continue\n }\n\n if (`${ paramValue }` !== `${ getPath(providerEventData, path) }`) {\n return false\n }\n }\n\n return true\n }\n\n // Runs ONCE per event if any instance matched \u2014 the only per-event place that may call the provider API.\n // It reads `webhookData` (an access token or external id the subscription stored) but cannot change it.\n extendResult(\n providerEventData: ProviderPayload,\n ctx: ExecutionContext,\n webhookData: ProviderPayload = null\n ): Promise<unknown> | unknown {\n return this.props.extendResult?.(ctx.bagWith({ providerEventData, webhookData }))\n }\n\n hasExtendResult(): boolean {\n return typeof this.props.extendResult === 'function'\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toModel(): SharedExtensionMethod {\n const [ownStart, ownEnd] = this.props.appearanceColors ?? []\n const [colorStart, colorEnd] = this.extension.appearanceColors\n\n return {\n name: this.id,\n operationName: this.props.label,\n description: this.props.description || '',\n registerAs: this.registerAs,\n category: this.category,\n colorStart: ownStart ?? colorStart,\n colorEnd: ownEnd ?? colorEnd,\n customIcon: this.props.logo ?? '',\n returnType: this.result.returnType,\n queryParams: [],\n bodyParams: toBodyParams(this.params),\n paramsSchema: encodeParams(this.params.scheme),\n metaInfo: { args: toArgs(this.params), ...this.result.toMetaInfo(this.id, this.params) },\n }\n }\n}\n", "import type { ExecutionContext } from './context/execution-context'\nimport type { Extension } from './extension'\nimport { ExtensionMethod } from './method'\nimport { argsFromParams } from './model/method-model'\nimport type { SharedExtensionMethod } from './model/model-types'\nimport { toOpaqueBodyParams } from './model/params-model'\nimport type { ZodSchema } from './params'\nimport { MethodParams } from './params'\nimport type { AnySchema } from './types'\n\n// The runtime-owned methods \u2014 the frozen v1 seam the platform calls rather than a flow: the OAuth connect /\n// callback / refresh steps, the polling tick, and the five realtime webhook lifecycle hooks. An author\n// never writes one; they exist because a feature was set up.\n//\n// Mechanically they are all the same: a runtime-owned params scheme, a SYSTEM model entry, and a handler.\n// Only the handler differs \u2014 so there is ONE class, driven by a spec, and each feature declares its own\n// specs in one place (see each owner's `#registerSystemMethods`). That single row now holds every fact\n// about a SYSTEM method: its name, its input contract, its model shape, and what it does.\n\nexport interface SystemMethodSpec {\n name: string\n /**\n * The params this method takes, as a normal z.object. Today every SYSTEM method happens to declare\n * exactly ONE property (`invocation` / `callbackObject` / `refreshToken`) \u2014 but that is a fact about the\n * current seam, not a constraint of the machinery: a second property needs no change here. Omit entirely\n * for a method that takes no input (getOAuth2ConnectionURL).\n */\n scheme?: AnySchema\n // The v1 `returnType` token. OBJECT for everything but the connect step, which answers a URL.\n returnType?: string\n // Set false for a seam that must stay callable without being advertised (see ExtensionMethod.published).\n published?: boolean\n // Receives the validated params, exactly as an action's handler receives its own.\n run: (params: Record<string, unknown>, ctx: ExecutionContext) => unknown\n}\n\nexport class SystemMethod extends ExtensionMethod {\n readonly params: MethodParams\n\n constructor(extension: Extension, private readonly spec: SystemMethodSpec) {\n super(extension)\n\n this.params = MethodParams.of(spec.scheme, { serviceId: extension.id, kind: 'system method', itemId: spec.name, slot: 'scheme' })\n }\n\n get name(): string {\n return this.spec.name\n }\n\n get registerAs(): string {\n return 'SYSTEM'\n }\n\n get published(): boolean {\n return this.spec.published ?? true\n }\n\n /**\n * FIELD-BY-FIELD validation: every declared param is required, then checked against its OWN schema. The\n * input here is a wrapper carrying named params rather than the params themselves \u2014 `{ invocation }` /\n * `{ callbackObject }` / `{ refreshToken }` are separate method params.\n *\n * Deliberately not one `parse(methodData)` over the whole object, because two failures must stay\n * distinguishable: an ABSENT param is a malformed call (MissingMethodParamError naming the param), while a\n * bad VALUE is a malformed value (InvalidMethodInputError whose issue paths are relative to that param,\n * not to `methodData`). A whole-object parse would flatten both into the second, with `invocation.` in\n * front of every path.\n */\n validate(methodData: Record<string, unknown>): Record<string, unknown> {\n const input = this.input(methodData)\n const parsed: Record<string, unknown> = {}\n\n for (const [name, schema] of this.params.fields()) {\n parsed[name] = input.parseField(name, schema as ZodSchema)\n }\n\n return parsed\n }\n\n execute(params: Record<string, unknown>, ctx: ExecutionContext): unknown {\n return this.spec.run(params, ctx)\n }\n\n toModel(): SharedExtensionMethod {\n const bodyParams = toOpaqueBodyParams(this.params)\n\n return {\n name: this.name,\n operationName: this.name,\n description: '',\n registerAs: this.registerAs,\n category: '',\n colorStart: '',\n colorEnd: '',\n customIcon: undefined,\n returnType: this.spec.returnType ?? 'OBJECT',\n queryParams: [],\n bodyParams,\n metaInfo: { args: argsFromParams(bodyParams), sampleResult: null, sampleResultLoader: null },\n }\n }\n}\n", "import type { ConfigItem } from '../common/types'\nimport { DuplicateItemIdError, OAuthSetupError, RealtimeSetupError, UnknownMethodError } from '../errors'\nimport { ActionMethod } from './actions/action-method'\nimport { ExecutionContext, type ExecutionContextOptions } from './context/execution-context'\nimport { DictionaryMethod } from './dictionaries/dictionary-method'\nimport { DynamicParamsLoaderMethod, SampleResultLoaderMethod } from './loaders/loader-method'\nimport type { LoaderOwner } from './loaders/loader-owner'\nimport type { ExtensionMethod } from './method'\nimport type { SharedExtensionDefinition, SharedExtensionMethod, SharedExtensionServiceInfo } from './model/model-types'\nimport { toConfigItems } from './model/params-model'\nimport { OAuth2 } from './oauth/oauth2'\nimport type { OAuth2Props } from './oauth/types'\nimport type { DictionaryRef } from './params'\nimport { ConfigParams, encodeParams } from './params'\nimport { PollingTriggers } from './polling-triggers/polling-triggers'\nimport { PollingTriggerMethod } from './polling-triggers/trigger-method'\nimport type { PollingTriggerProps } from './polling-triggers/types'\nimport { RealtimeSetup } from './realtime-triggers/realtime-setup'\nimport { RealtimeTriggerMethod } from './realtime-triggers/trigger-method'\nimport type { RealtimeSetupProps, RealtimeTriggerProps } from './realtime-triggers/types'\nimport { SystemMethod, type SystemMethodSpec } from './system-method'\nimport type { ActionProps, DictionaryProps, ExtensionProps } from './types'\n\n// One registered extension: everything a service declared, and everything the runner does with it. The\n// composition root \u2014 `Flowrunner.createExtension(props)` builds one, the registry stores it, and every\n// caller (definition build, config resolution, method dispatch) goes through it rather than reaching into a\n// bag of Maps.\n//\n// Registration happens once, while the service module is being `require`d, and is validated as it goes: ids\n// must be unique across ALL item kinds, a polling trigger must declare exactly one mechanism, and the\n// opt-in features can only be set up once. An authoring mistake therefore surfaces from the first call the\n// console or CLI makes against the extension, naming what has to be fixed.\n\nexport class Extension {\n readonly #props: ExtensionProps\n readonly #config: ConfigParams\n readonly #methods = new Map<string, ExtensionMethod>()\n readonly #pollingTriggers = new PollingTriggers(this)\n readonly #realtimeTriggers = new Map<string, RealtimeTriggerMethod>()\n readonly #usedIds = new Set<string>()\n #oauth?: OAuth2\n #realtime?: RealtimeSetup\n\n constructor(props: ExtensionProps) {\n this.#props = props\n // Eager: `configItems` is validated as the extension registers, like every other declared slot. Leaving\n // it lazy would let a bad one hide behind handlers that never happen to read config.\n this.#config = ConfigParams.of(props.configItems, { serviceId: props.id, kind: 'extension', slot: 'configItems' })\n }\n\n get id(): string {\n return this.#props.id\n }\n\n get props(): ExtensionProps {\n return this.#props\n }\n\n // The declared `configItems`, mapped once per extension rather than per invocation.\n get config(): ConfigParams {\n return this.#config\n }\n\n get oauth(): OAuth2 | undefined {\n return this.#oauth\n }\n\n get realtime(): RealtimeSetup | undefined {\n return this.#realtime\n }\n\n realtimeTriggers(): RealtimeTriggerMethod[] {\n return [...this.#realtimeTriggers.values()]\n }\n\n findRealtimeTrigger(id: string): RealtimeTriggerMethod | undefined {\n return this.#realtimeTriggers.get(id)\n }\n\n get pollingTriggers(): PollingTriggers {\n return this.#pollingTriggers\n }\n\n // The extension-level colours every item falls back to.\n get appearanceColors(): [string, string] {\n const [start = '', end = ''] = this.props.appearanceColors ?? []\n\n return [start, end]\n }\n\n // \u2500\u2500 authoring-time registration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n registerDictionary(props: DictionaryProps): DictionaryRef {\n const dictionary = new DictionaryMethod(this, props)\n\n this.#addMethod(dictionary, 'dictionary')\n\n // The ref threaded into `.dictionary(ref)` on a param; carries the auto-derived dependsOn.\n return { id: props.id, dependsOn: dictionary.dependsOn }\n }\n\n registerAction(props: ActionProps): void {\n const action = new ActionMethod(this, props)\n\n this.#addMethod(action, 'action')\n\n this.#registerSampleResultLoader(action, 'sample-result loader')\n\n // `dynamicParams` \u2192 a PARAM_SCHEMA_DEFINITION method that resolves extra param fields from criteria.\n if (action.hasDynamicParams()) {\n this.#addMethod(new DynamicParamsLoaderMethod(this, action), 'dynamic params loader')\n }\n }\n\n registerPollingTrigger(props: PollingTriggerProps): void {\n // Claim the id before constructing, so a duplicate id is reported ahead of a bad mechanism.\n this.#claimId(props.id, 'polling trigger')\n\n const trigger = new PollingTriggerMethod(this, props)\n\n this.#putMethod(trigger)\n this.#pollingTriggers.add(trigger)\n this.#registerSampleResultLoader(trigger, 'sample-result loader')\n }\n\n registerRealtimeTrigger(props: RealtimeTriggerProps): void {\n this.#claimId(props.id, 'realtime trigger')\n\n const trigger = new RealtimeTriggerMethod(this, props)\n\n this.#putMethod(trigger)\n this.#realtimeTriggers.set(trigger.id, trigger)\n this.#registerSampleResultLoader(trigger, 'sample-result loader')\n }\n\n setupRealtime(props: RealtimeSetupProps): void {\n if (this.#realtime) {\n throw new RealtimeSetupError(this.id, 'setupRealtimeTriggers(...) called more than once')\n }\n\n // The setup validates itself and publishes its SYSTEM methods as it is constructed.\n this.#realtime = new RealtimeSetup(this, props)\n }\n\n setupOAuth2(props: OAuth2Props): void {\n if (this.#oauth) {\n throw new OAuthSetupError(this.id, 'setupOauth2(...) called more than once')\n }\n\n // Like RealtimeSetup, it publishes its SYSTEM methods as it is constructed.\n this.#oauth = new OAuth2(this, props)\n }\n\n // Publish a feature's runtime-owned methods. Called by each subsystem as it is set up, so a SYSTEM method\n // exists exactly when the feature behind it does \u2014 and an id that collides with an author's own item is\n // caught here, loudly, instead of one silently shadowing the other.\n registerSystemMethods(specs: SystemMethodSpec[]): void {\n for (const spec of specs) {\n this.#addMethod(new SystemMethod(this, spec), 'system method')\n }\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // Every method this extension publishes, in registration order.\n methods(): ExtensionMethod[] {\n return [...this.#methods.values()]\n }\n\n findMethod(name: string): ExtensionMethod | undefined {\n return this.#methods.get(name)\n }\n\n getMethod(name: string): ExtensionMethod {\n const method = this.findMethod(name)\n\n if (!method) {\n throw new UnknownMethodError(this.id, name)\n }\n\n return method\n }\n\n createContext(options: ExecutionContextOptions = {}): ExecutionContext {\n return new ExecutionContext(this, options)\n }\n\n // Dispatch: find the method, let it check its own input, run it. Every kind \u2014 action, dictionary,\n // generated loader, SYSTEM seam \u2014 arrives here through the same three steps.\n async run(methodName: string, methodData: Record<string, unknown>, ctx: ExecutionContext): Promise<unknown> {\n const method = this.getMethod(methodName)\n\n return method.execute(method.validate(methodData ?? {}), ctx)\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toConfigItems(): ConfigItem[] {\n return toConfigItems(this.config)\n }\n\n toServiceInfo(): SharedExtensionServiceInfo {\n return {\n serviceClassName: this.props.id,\n integrationName: this.props.name,\n integrationIcon: this.props.logo ?? null,\n description: this.props.description || null,\n integrationTriggersScope: this.#realtime?.scope ?? null,\n requireOAuth: this.#oauth ? true : undefined,\n }\n }\n\n /**\n * The published model \u2014 the v2 analogue of jsdoc-parser's `parseJsDocToServiceJson`, and the same\n * `{ serviceInfo, methodsMap }` shape the console consumes for a v1 service.\n *\n * Every method describes itself, so this is one pass with no per-kind branches: what a service publishes\n * is exactly what it registered.\n */\n toDefinition(): SharedExtensionDefinition {\n const methodsMap: Record<string, SharedExtensionMethod> = {}\n\n for (const method of this.methods()) {\n if (method.published) {\n methodsMap[method.name] = method.toModel()\n }\n }\n\n return {\n runnerVersion: 'v2', //TODO: temp\n serviceInfo: this.toServiceInfo(),\n methodsMap,\n configSchema: encodeParams(this.config.scheme),\n }\n }\n\n // \u2500\u2500 queries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // The `oauth2Scopes` every registered method declares, in registration order. The base set and the\n // dedupe live with the OAuth subsystem that consumes them (see OAuth2.#composeScopes).\n declaredOAuthScopes(): string[] {\n return this.methods().flatMap(method => method.oauth2Scopes)\n }\n\n // \u2500\u2500 private \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // Every registered item is keyed by `id` (= the v1 method name, frozen for back-compat), and the ids must\n // be unique across ALL kinds \u2014 including the loader methods the runtime generates from them.\n #claimId(id: string, kind: string): void {\n if (!id) {\n throw new Error(`[flow-extension:${ this.id }] a ${ kind } was registered without an id`)\n }\n\n if (this.#usedIds.has(id)) {\n throw new DuplicateItemIdError(this.id, id, kind)\n }\n\n this.#usedIds.add(id)\n }\n\n #addMethod(method: ExtensionMethod, kind: string): void {\n this.#claimId(method.name, kind)\n this.#putMethod(method)\n }\n\n #putMethod(method: ExtensionMethod): void {\n this.#methods.set(method.name, method)\n }\n\n // A loader `result` fn \u2192 a SAMPLE_RESULT_LOADER method. Actions and both trigger kinds can declare one,\n // and each satisfies LoaderOwner directly.\n #registerSampleResultLoader(owner: LoaderOwner, kind: string): void {\n if (owner.result.isLoader) {\n this.#addMethod(new SampleResultLoaderMethod(this, owner), kind)\n }\n }\n\n}\n", "import { ExtensionNotRegisteredError } from '../errors'\nimport type { Extension } from './extension'\n\n// The process-wide registry of v2 extensions, keyed by service id. Mirrors the v1 `services` map in\n// v1/namespace.ts: a service module registers once at require time (via Flowrunner.createExtension) and the\n// entry persists across the require cache, so re-requiring the same module is a cheap no-op. Version\n// detection (../index.ts) checks `registry.get(serviceId)` after a module is required \u2014 a hit means v2.\n\nexport class ExtensionRegistry {\n readonly #extensions = new Map<string, Extension>()\n\n register(extension: Extension): void {\n this.#extensions.set(extension.id, extension)\n }\n\n get(id: string): Extension | undefined {\n return this.#extensions.get(id)\n }\n\n all(): Extension[] {\n return [...this.#extensions.values()]\n }\n\n /**\n * The extension for `id`, requiring its module first if it hasn't registered yet. Registration is a\n * require-time side effect and the require cache is shared, so this is a no-op once loaded.\n *\n * The shared namespace must already be installed (../namespace) \u2014 callers reach here via ../index.ts,\n * which imports it.\n */\n load(id: string, entryPointPath: string): Extension {\n if (!this.get(id)) {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require(entryPointPath)\n }\n\n const extension = this.get(id)\n\n if (!extension) {\n throw new ExtensionNotRegisteredError(id, entryPointPath)\n }\n\n return extension\n }\n\n // Test-only: clear the registry between isolated cases.\n reset(): void {\n this.#extensions.clear()\n }\n}\n\nexport const registry = new ExtensionRegistry()\n\n// Function-shaped accessors, kept because they are the package's published surface.\nexport function getExtension(id: string): Extension | undefined {\n return registry.get(id)\n}\n\nexport function getAllExtensions(): Extension[] {\n return registry.all()\n}\n\nexport function resetRegistry(): void {\n registry.reset()\n}\n", "import { Extension } from './extension'\nimport type { OAuth2Props } from './oauth/types'\nimport type { DictionaryRef } from './params'\nimport type { PollingTriggerProps } from './polling-triggers/types'\nimport type { RealtimeSetupProps, RealtimeTriggerProps } from './realtime-triggers/types'\nimport { registry } from './registry'\nimport type {\n ActionProps,\n AnySchema,\n ApiRequestFn,\n DictionaryProps,\n ExtensionApi,\n ExtensionProps,\n ShapeOf,\n} from './types'\n\n// `Flowrunner.createExtension(props)` \u2014 the v2 factory. Builds the Extension, registers it, and returns the\n// `ext` handle: the authoring-facing fa\u00E7ade whose registrars delegate straight to the Extension, which owns\n// the validation and the runtime-generated loader methods (see ./extension.ts).\n\n// Generic so an author's own types reach their handlers: `configItems` / `initContext` / `helpers` /\n// `apiRequest` are inferred here once, and the returned `ext` threads them into every registrar (which\n// then infers its own params). The body works against the erased props, since none of that matters to the\n// runtime \u2014 the single cast on the way out is where the author's shape is re-attached.\nexport function createExtension<\n TConfigSchema extends AnySchema = AnySchema,\n TContext = Record<string, unknown>,\n THelpers = Record<string, unknown>,\n TApiRequest extends ApiRequestFn = ApiRequestFn,\n>(\n props: ExtensionProps<TConfigSchema, TContext, THelpers, TApiRequest>\n): ExtensionApi<ShapeOf<TConfigSchema, TContext, THelpers, TApiRequest>> {\n const extension = new Extension(props as unknown as ExtensionProps)\n\n const api = {\n dictionary(dictionaryProps: DictionaryProps): DictionaryRef {\n return extension.registerDictionary(dictionaryProps)\n },\n\n addAction(actionProps: ActionProps): void {\n extension.registerAction(actionProps)\n },\n\n addPollingTrigger(triggerProps: PollingTriggerProps): void {\n extension.registerPollingTrigger(triggerProps)\n },\n\n setupRealtimeTriggers(realtimeProps: RealtimeSetupProps): void {\n extension.setupRealtime(realtimeProps)\n },\n\n addRealtimeTrigger(triggerProps: RealtimeTriggerProps): void {\n extension.registerRealtimeTrigger(triggerProps)\n },\n\n setupOauth2(oauthProps: OAuth2Props): void {\n extension.setupOAuth2(oauthProps)\n },\n\n extension,\n }\n\n registry.register(extension)\n\n return api as unknown as ExtensionApi<ShapeOf<TConfigSchema, TContext, THelpers, TApiRequest>>\n}\n", "import nodeCrypto from 'crypto'\n\n// Runtime crypto helpers exposed to service code as `Flowrunner.crypto` \u2014 realtime `verify`/`verifyRequest`\n// signature checks (09-realtime-triggers.md). Services can't `require` node modules, so HMAC, constant-time\n// comparison, and timestamp freshness live here.\n\nexport interface FlowrunnerCrypto {\n hmac(algo: string, key: string, data: string, encoding?: 'hex' | 'base64'): string\n timingSafeEqual(a: unknown, b: unknown): boolean\n ageSeconds(timestamp: string | number): number\n}\n\nexport const crypto: FlowrunnerCrypto = {\n hmac(algo, key, data, encoding = 'hex') {\n return nodeCrypto.createHmac(algo, key).update(data ?? '').digest(encoding)\n },\n\n // Constant-time string comparison; false (not throw) on nullish/length-mismatch so callers can `return`.\n timingSafeEqual(a, b) {\n if (typeof a !== 'string' || typeof b !== 'string') {\n return false\n }\n\n const bufferA = Buffer.from(a)\n const bufferB = Buffer.from(b)\n\n if (bufferA.length !== bufferB.length) {\n return false\n }\n\n try {\n return nodeCrypto.timingSafeEqual(bufferA, bufferB)\n } catch {\n return false\n }\n },\n\n // Seconds since `timestamp` (ISO string, or epoch seconds/ms \u2014 magnitude-detected).\n ageSeconds(timestamp) {\n const numeric = typeof timestamp === 'number' ? timestamp : Date.parse(timestamp) || Number(timestamp)\n const milliseconds = numeric < 1e12 ? numeric * 1000 : numeric\n\n return (Date.now() - milliseconds) / 1000\n },\n}\n", "import { type ServiceConfigItemType, ServiceConfigItemTypes, type ServiceConfigsValues } from './constants'\nimport type { ConfigItem } from './types'\n\ntype ConfigValueAdapter = {\n deserialize: (v: unknown) => unknown,\n isEmpty: (v: unknown) => boolean\n}\n\n// Keyed by item type with a mandatory `default` fallback; only types that need\n// special handling are listed, so a lookup by any ServiceConfigItemType may miss\n// and fall through to `default`.\nconst ConfigValueAdapters: Partial<Record<ServiceConfigItemType, ConfigValueAdapter>> & { default: ConfigValueAdapter } = {\n [ServiceConfigItemTypes.BOOL]: {\n deserialize: value => typeof value === 'string' ? value === 'true' : !!value,\n isEmpty: value => typeof value !== 'boolean',\n },\n\n default: {\n deserialize: value => value,\n isEmpty: value => !value,\n },\n}\n\n/**\n * Resolve the effective config values for a service instance: for each declared item take its value from the\n * single `configs` bag, deserialize it with the type adapter, and fall back to the item's default when empty.\n *\n * ONE bag on purpose. `shared` is a UI directive \u2014 it decides who fills a value in and in which dialog \u2014 so\n * it has no business steering resolution. A service installed as a custom extension has no shared tier at\n * all: the customer fills in every item in one dialog. Whoever runs a *shared* extension merges the two\n * tiers before calling in; everyone else passes the single bag they already have.\n */\nexport function prepareServiceConfig(configItems: ConfigItem[], configs: ServiceConfigsValues = {}): ServiceConfigsValues {\n const targetConfig: ServiceConfigsValues = {}\n\n for (const configItem of configItems) {\n const configName = configItem.name\n const configType = configItem.type\n\n const adapter = ConfigValueAdapters[configType] || ConfigValueAdapters.default\n\n targetConfig[configName] = adapter.deserialize(configs[configName])\n\n if (!adapter.isEmpty(targetConfig[configName])) {\n continue\n }\n\n const defaultConfig = adapter.deserialize(configItem.defaultValue)\n\n if (!adapter.isEmpty(defaultConfig)) {\n targetConfig[configName] = defaultConfig\n }\n }\n\n return targetConfig\n}\n", "import { ServiceConfigItemTypes } from '../common/constants'\nimport type { ConfigItem } from '../common/types'\nimport type { ConfigItemSource } from './types'\n\n// Normalize the raw descriptors a v1 service declares via `addService` into the canonical `ConfigItem`\n// shape returned to the console (resolving legacy `hint`/`displayName` aliases and filling defaults).\nexport function normalizeConfigItems(sourceConfigItems?: ConfigItemSource[]): ConfigItem[] {\n return sourceConfigItems?.map(item => ({\n name: item.name,\n type: item.type || ServiceConfigItemTypes.STRING,\n shared: !!item.shared,\n required: !!item.required,\n description: item.description || item.hint || '',\n label: item.label || item.displayName || item.name,\n defaultValue: item.defaultValue,\n options: item.options || [],\n })) || []\n}\n", "import '../namespace'\n\nimport { ServiceConfigItemTypes } from '../common/constants'\nimport type { ConfigItem } from '../common/types'\nimport { normalizeConfigItems } from './config'\nimport { type ServiceClassType } from './constants'\nimport type { ConfigItemSource } from './types'\n\n// The shared global `Flowrunner` is installed by ../namespace (imported above for its side effect). This\n// module owns only the v1 registration seam: `createFlowrunnerSandboxV1` toggles `Flowrunner.ServerCode` for\n// the duration of a v1 require so the required module's `addService(...)` call lands in the `services` map.\n\ninterface RegisteredService {\n ServiceClass: ServiceClassType\n configItems: ConfigItem[]\n}\n\nconst services = new Map<string, RegisteredService>()\n\nexport function createFlowrunnerSandboxV1(serviceId: string, cb: () => void): RegisteredService | undefined {\n global.Flowrunner.ServerCode = {\n addService(ServiceClass: ServiceClassType, sourceConfigItems?: ConfigItemSource[]) {\n services.set(serviceId, {\n ServiceClass,\n configItems: normalizeConfigItems(sourceConfigItems),\n })\n },\n\n ConfigItems: {\n TYPES: ServiceConfigItemTypes,\n },\n }\n\n try {\n cb()\n } finally {\n global.Flowrunner.ServerCode = null\n }\n\n return services.get(serviceId)\n}\n\n", "import { prepareServiceConfig } from '../common/config'\nimport { type ServiceConfigsValues } from '../common/constants'\nimport { FlowrunnerContext, type FlowrunnerContextOptions } from '../common/context'\nimport type { FilesApi } from '../common/context-files'\nimport type { ConfigItem } from '../common/types'\nimport {\n type MethodRequestArgumentsList,\n type MethodRequestArgumentsMap,\n OAUTH_ACCESS_TOKEN_HEADER,\n} from './constants'\nimport { createFlowrunnerSandboxV1 } from './namespace'\n\nfunction requireService(serviceId: string, serviceEntryPointPath: string) {\n const registered = createFlowrunnerSandboxV1(serviceId, () => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require(serviceEntryPointPath)\n })\n\n if (!registered?.ServiceClass) {\n throw new Error(`There is no registered ServiceClass serviceEntryPointPath=\"${ serviceEntryPointPath }\"`)\n }\n\n return registered\n}\n\ntype CreateRuntimeContextData = {\n serverURL: string,\n appId: string,\n apiKey: string,\n //\n runtimeKey: string,\n //\n flowId: string,\n executionId: string\n //\n accessToken?: string\n //\n retrieveNewS3Token: (runtimeKey: string) => Promise<{\n filesS3Token: string\n }>\n //\n createFiles?: (options: FlowrunnerContextOptions) => FilesApi\n\n}\n\n// `flowrunner` is typed by the surface a service actually touches \u2014 `this.flowrunner.Files` \u2014 rather than by\n// the concrete FlowrunnerContext, so a host-supplied client (see `createFiles`) is assignable here too.\ntype FlowrunnerRuntimeContext = {\n flowrunner: { Files: FilesApi }\n httpHeaders: {\n [OAUTH_ACCESS_TOKEN_HEADER]?: string\n }\n}\n\nfunction createRuntimeContext(data: CreateRuntimeContextData): FlowrunnerRuntimeContext {\n const { serverURL, appId, apiKey, runtimeKey, flowId, executionId, accessToken, retrieveNewS3Token } = data\n\n const filesOptions: FlowrunnerContextOptions = {\n serverURL,\n appId,\n apiKey,\n //\n runtimeKey,\n //\n flowId,\n executionId,\n //\n retrieveNewS3Token,\n }\n\n // A v1 service has no `usesFileStorage` opt-in \u2014 `this.flowrunner.Files` is always live \u2014 so a\n // host-supplied client replaces it unconditionally. (v2 consults `createFiles` only when the extension\n // declares `usesFileStorage`, because that is what decides between a real client and the throwing proxy.)\n const flowrunnerContext: FlowrunnerRuntimeContext['flowrunner'] = data.createFiles\n ? { Files: data.createFiles(filesOptions) }\n : new FlowrunnerContext(filesOptions)\n\n const httpHeaders: FlowrunnerRuntimeContext['httpHeaders'] = {}\n\n if (accessToken) {\n httpHeaders[OAUTH_ACCESS_TOKEN_HEADER] = accessToken\n }\n\n return {\n httpHeaders,\n flowrunner: flowrunnerContext,\n }\n}\n\nfunction initServiceInstance(\n serviceId: string,\n serviceEntryPointPath: string,\n configs: ServiceConfigsValues | undefined,\n context: FlowrunnerRuntimeContext\n) {\n const { ServiceClass, configItems } = requireService(serviceId, serviceEntryPointPath)\n\n const config = prepareServiceConfig(configItems, configs)\n\n const service = new ServiceClass(config, context)\n\n Object.assign(service, {\n config,\n flowrunner: context.flowrunner,\n request: {\n context,\n headers: context.httpHeaders,\n },\n })\n\n return service\n}\n\nexport function getServiceConfigs(serviceId: string, serviceEntryPointPath: string): ConfigItem[] {\n const { configItems } = requireService(serviceId, serviceEntryPointPath)\n\n return configItems\n}\n\ntype RunServiceMethodData = {\n serviceId: string,\n serviceEntryPointPath: string,\n configs?: ServiceConfigsValues\n methodName: string\n methodData?: MethodRequestArgumentsMap,\n methodArgs?: MethodRequestArgumentsList\n retrieveNewS3Token: (runtimeKey: string) => Promise<{\n filesS3Token: string\n }>\n // Replaces `this.flowrunner.Files` for this invocation. The default talks to the console over HTTP; a host\n // may build its own against different storage (a legacy-service test mocking the Files API, an e2e harness\n // pointing at a local S3) without the runner or the service knowing.\n createFiles?: (options: FlowrunnerContextOptions) => FilesApi\n executionContext: {\n runtimeKey: string\n accessToken: string\n appId: string\n apiKey: string\n serverURL: string\n flowId: string\n executionId: string\n }\n}\n\nexport async function runServiceMethod(data: RunServiceMethodData): Promise<unknown> {\n const {\n serviceId,\n serviceEntryPointPath,\n configs,\n methodName,\n methodArgs,\n retrieveNewS3Token,\n createFiles,\n } = data\n const { accessToken, runtimeKey, appId, apiKey, serverURL, flowId, executionId } = data.executionContext\n\n const context = createRuntimeContext({\n serverURL,\n appId,\n apiKey,\n //\n runtimeKey,\n //\n flowId,\n executionId,\n //\n accessToken,\n //\n retrieveNewS3Token,\n //\n createFiles,\n })\n\n const serviceInstance = initServiceInstance(serviceId, serviceEntryPointPath, configs, context)\n\n const invoke = (serviceInstance as Record<string, (...args: unknown[]) => unknown>)[methodName]\n\n return invoke.apply(serviceInstance, methodArgs || [])\n}\n\n", "// Public surface of the v2 (declarative, zod-based) extension runtime. Mirrors the v1 entry points\n// (getServiceConfigs / runServiceMethod) plus buildServiceDefinition \u2014 the v2 analogue of jsdoc-parser\n// that produces the same SharedExtensionDefinition model. Version-agnostic callers go through ../index.ts;\n// this module is only reached once a service has been detected as v2.\n\nimport { type ServiceConfigsValues } from '../common/constants'\nimport { FlowrunnerContext, type FlowrunnerContextOptions } from '../common/context'\nimport type { FilesApi } from '../common/context-files'\nimport type { ConfigItem } from '../common/types'\nimport type { SharedExtensionDefinition } from './model/model-types'\nimport { registry } from './registry'\nimport type { Logger } from './types'\n\nexport type { ConfigItem } from '../common/types'\nexport type { SharedExtensionDefinition } from './model/model-types'\n\n// The registry and what it holds. `getExtension` is how ../index.ts detects a v2 service; `resetRegistry`\n// lets a test harness isolate cases (@flowrunner/cli/runtime re-exports it).\nexport { ExecutionContext } from './context/execution-context'\nexport { Extension } from './extension'\nexport { getAllExtensions, getExtension, resetRegistry } from './registry'\n\n// The invocation/result shapes a host may need to type a call against the trigger seams.\nexport type { PollingInvocation, PollingResult } from './polling-triggers/types'\nexport type { RealtimeInvocation } from './realtime-triggers/types'\nexport type { HandlerBag, Logger } from './types'\n\nexport interface RunServiceMethodData {\n serviceId: string\n serviceEntryPointPath: string\n configs?: ServiceConfigsValues\n methodName: string\n methodData?: Record<string, unknown>\n methodArgs?: unknown[]\n logger?: Logger\n retrieveNewS3Token: (runtimeKey: string) => Promise<{ filesS3Token: string }>\n // Replaces the file-service client for this invocation. The default talks to the console over HTTP; a\n // host may build its own against different storage (an e2e harness pointing `ctx.files` at a local S3,\n // say) without the runner or the service knowing. Only consulted when the extension declares\n // `usesFileStorage` \u2014 the throwing proxy is unaffected.\n createFiles?: (options: FlowrunnerContextOptions) => FilesApi\n executionContext: {\n runtimeKey: string\n accessToken: string\n appId: string\n apiKey: string\n serverURL: string\n flowId: string\n executionId: string\n }\n}\n\nexport function getServiceConfigs(serviceId: string, serviceEntryPointPath: string): ConfigItem[] {\n return registry.load(serviceId, serviceEntryPointPath).toConfigItems()\n}\n\nexport function buildServiceDefinition(serviceId: string, serviceEntryPointPath: string): SharedExtensionDefinition {\n return registry.load(serviceId, serviceEntryPointPath).toDefinition()\n}\n\n// The stock file-service client: the console's REST API at `{serverURL}/{appId}/{apiKey}/v1/files`.\nconst defaultCreateFiles = (options: FlowrunnerContextOptions): FilesApi => new FlowrunnerContext(options).Files\n\nexport async function runServiceMethod(data: RunServiceMethodData): Promise<unknown> {\n const { serviceId, serviceEntryPointPath, executionContext, retrieveNewS3Token, methodName } = data\n\n const methodData = data.methodData || {}\n\n const { serverURL, appId, apiKey, runtimeKey, flowId, executionId, accessToken } = executionContext\n\n const extension = registry.load(serviceId, serviceEntryPointPath)\n\n const filesOptions: FlowrunnerContextOptions = {\n serverURL,\n appId,\n apiKey,\n runtimeKey,\n flowId,\n executionId,\n retrieveNewS3Token,\n }\n\n const files = extension.props.usesFileStorage\n ? (data.createFiles ?? defaultCreateFiles)(filesOptions)\n : undefined\n\n const ctx = extension.createContext({ configs: data.configs, accessToken, logger: data.logger, files })\n\n return extension.run(methodName, methodData, ctx)\n}\n", "// Version-agnostic entry point for the flow-extension runner.\n//\n// Consumers import { getServiceConfigs, runServiceMethod } from\n// '@flowrunner/flow-extension-runner' without knowing the extension format version. This module requires\n// the service module once (in the v1 ServerCode sandbox so v1 modules register), then branches on whether\n// the module registered a v2 extension: a hit in the v2 registry \u21D2 v2, otherwise v1.\n\nimport './namespace'\n\nimport * as v1 from './v1'\nimport { createFlowrunnerSandboxV1 } from './v1/namespace'\nimport * as v2 from './v2'\n\nexport * from './errors'\nexport type { RunServiceMethodData } from './v2'\n\n// The file-storage contract and its value shapes, so a host can build its own `ctx.files` for\n// `runServiceMethod({ createFiles })` \u2014 see FilesApi in ./common/context-files.\nexport type { FlowrunnerContextOptions } from './common/context'\nexport type {\n DeleteOptions,\n DeleteResult,\n FileInfo,\n FilesApi,\n GetOptions,\n ListOptions,\n ListResult,\n UploadFileOptions,\n UploadResult,\n UsageResult,\n} from './common/context-files'\nexport { FileScope } from './common/context-files'\n\nexport type ExtensionVersion = 'v1' | 'v2'\n\nexport {\n createFlowrunnerSandboxV1,\n}\n\n// Require the module through the v1 sandbox (harmless for v2 \u2014 it just runs createExtension), then detect.\n// The require is cached, so the subsequent v1/v2 call re-requires for free.\nexport function detectVersion(serviceId: string, serviceEntryPointPath: string): ExtensionVersion {\n createFlowrunnerSandboxV1(serviceId, () => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require(serviceEntryPointPath)\n })\n\n return v2.getExtension(serviceId) ? 'v2' : 'v1'\n}\n\nexport function getServiceConfigs(\n serviceId: string,\n serviceEntryPointPath: string\n): ReturnType<typeof v1.getServiceConfigs> {\n return detectVersion(serviceId, serviceEntryPointPath) === 'v2'\n ? v2.getServiceConfigs(serviceId, serviceEntryPointPath)\n : v1.getServiceConfigs(serviceId, serviceEntryPointPath)\n}\n\nexport async function runServiceMethod(data: v2.RunServiceMethodData): Promise<unknown> {\n const frameworkVersion = detectVersion(data.serviceId, data.serviceEntryPointPath)\n\n const result = frameworkVersion === 'v2'\n ? await v2.runServiceMethod(data)\n : await v1.runServiceMethod(data as Parameters<typeof v1.runServiceMethod>[0])\n\n // console.log('got result:', JSON.stringify({\n // frameworkVersion,\n // serviceId: data.serviceId,\n // methodName: data.methodName,\n // methodData: data.methodData,\n // methodArgs: data.methodArgs,\n // result,\n // }, null, 2))\n\n return result\n}\n\n// Build the SharedExtensionDefinition model (serviceInfo + methodsMap). v2 derives it from the declarative\n// definition; v1 services are modeled by the jsdoc-parser, so this only serves v2 (returns null for v1).\nexport function buildServiceDefinition(\n serviceId: string,\n serviceEntryPointPath: string\n): v2.SharedExtensionDefinition | null {\n return detectVersion(serviceId, serviceEntryPointPath) === 'v2'\n ? v2.buildServiceDefinition(serviceId, serviceEntryPointPath)\n : null\n}\n", "import { type SharedExtensionMethodParam } from '@shared/scheme'\n\nimport type { TypedefsMap } from '../types'\n\nconst SCOPE_FIELD: SharedExtensionMethodParam = {\n name : 'scope',\n type : 'String',\n required : false,\n label : 'Scope',\n description : 'Storage scope: WORKSPACE (shared across flows), FLOW (this flow only), EXECUTION (this run only)',\n uiComponent : { type: 'DROPDOWN', options: { values: ['WORKSPACE', 'FLOW', 'EXECUTION'] } },\n defaultValue: 'FLOW',\n}\n\nexport const filesTypeDefs: TypedefsMap = {\n FilesUploadOptions: [\n SCOPE_FIELD,\n {\n name : 'filename',\n type : 'String',\n required : false,\n label : 'Filename',\n description: 'Custom filename (defaults to the original name if omitted)',\n uiComponent: { type: 'SINGLE_LINE_TEXT' },\n },\n {\n name : 'ttl',\n type : 'Number',\n required : false,\n label : 'URL TTL (seconds)',\n description: 'How long the download URL remains valid',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'objectTtl',\n type : 'Number',\n required : false,\n label : 'File TTL (seconds)',\n description: 'How long the file is kept in storage (omit for permanent storage)',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'overwrite',\n type : 'Boolean',\n required : false,\n label : 'Overwrite existing',\n description: 'Replace the file if one with the same name already exists',\n uiComponent: { type: 'TOGGLE' },\n },\n {\n name : 'generateUrl',\n type : 'Boolean',\n required : false,\n label : 'Generate download URL',\n description : 'Include a pre-signed download URL in the response',\n uiComponent : { type: 'TOGGLE' },\n defaultValue: true,\n },\n ],\n\n FilesListOptions: [\n SCOPE_FIELD,\n {\n name : 'limit',\n type : 'Number',\n required : false,\n label : 'Limit',\n description: 'Maximum number of files to return',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'ttl',\n type : 'Number',\n required : false,\n label : 'URL TTL (seconds)',\n description: 'How long the download URLs remain valid',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'generateUrl',\n type : 'Boolean',\n required : false,\n label : 'Generate download URLs',\n description : 'Include pre-signed download URLs in the response',\n uiComponent : { type: 'TOGGLE' },\n defaultValue: true,\n },\n {\n name : 'cursor',\n type : 'String',\n required : false,\n label : 'Cursor',\n description: 'Pagination cursor from a previous response',\n uiComponent: { type: 'SINGLE_LINE_TEXT' },\n },\n ],\n\n FilesGetOptions: [\n SCOPE_FIELD,\n {\n name : 'ttl',\n type : 'Number',\n required : false,\n label : 'URL TTL (seconds)',\n description: 'How long the download URL remains valid',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'generateUrl',\n type : 'Boolean',\n required : false,\n label : 'Generate download URL',\n description : 'Include a pre-signed download URL in the response',\n uiComponent : { type: 'TOGGLE' },\n defaultValue: true,\n },\n ],\n\n FilesDeleteOptions: [\n SCOPE_FIELD,\n ],\n}\n", "/* eslint-disable @typescript-eslint/no-require-imports */\nimport fs from 'fs'\nimport path from 'path'\n\n// ============================================================================\n// JSDoc programmatic parser (adapted from JS-Code-Runner)\n// ============================================================================\n\nexport interface DocletTag {\n originalTitle: string\n value?: string\n text?: string\n}\n\ninterface DocletParam {\n name: string\n type?: { names?: string[] }\n optional?: boolean\n description?: string\n}\n\ninterface DocletProperty {\n name: string\n type?: { names?: string[] }\n optional?: boolean\n description?: string\n}\n\nexport interface Doclet {\n kind: string\n name: string\n memberof?: string\n scope?: string\n description?: string\n tags?: DocletTag[]\n params?: DocletParam[]\n properties?: DocletProperty[]\n returns?: { type?: { names?: string[] } }[]\n access?: string\n}\n\nfunction resolveJSDocPath(): string {\n const jsDocHolders = require.resolve.paths('jsdoc/lib') || []\n const jsDocPaths = jsDocHolders.map((p: string) => path.join(p, 'jsdoc/lib'))\n\n for (let i = 0; i < jsDocPaths.length; i++) {\n if (fs.existsSync(jsDocPaths[i])) {\n return jsDocPaths[i]\n }\n }\n\n throw new Error('Can not resolve path to JSDoc module.')\n}\n\nconst jsdocPath = resolveJSDocPath()\nconst jsdocModulePath = (mod: string) => path.join(jsdocPath, ...mod.split('/'))\n\nlet _jsdocRequire: NodeRequire\n\nconst jsdocRequire = (modulePath: string) => {\n if (!_jsdocRequire) {\n _jsdocRequire = require('requizzle')({\n infect: true,\n requirePaths: { before: [jsdocPath] },\n })\n\n const Config = _jsdocRequire(jsdocModulePath('jsdoc/config'))\n const env = _jsdocRequire(jsdocModulePath('jsdoc/env'))\n env.conf = new Config().get()\n }\n\n return _jsdocRequire(jsdocModulePath(modulePath))\n}\n\n/**\n * Parse a JS file using jsdoc programmatically and return the doclets array.\n */\nexport function parseJSDoc(filePath: string): Doclet[] {\n const parser = jsdocRequire('jsdoc/src/parser').createParser()\n const handlers = jsdocRequire('jsdoc/src/handlers')\n\n handlers.attachTo(parser)\n\n return parser.parse([filePath])\n}\n", "import {\n type SharedExtensionDefinition,\n type SharedExtensionMetaInfo,\n type SharedExtensionMetaInfoArg,\n type SharedExtensionMethod,\n type SharedExtensionMethodParam,\n type SharedExtensionServiceInfo,\n} from '@shared/scheme'\n\nimport { filesTypeDefs } from './custom-type-defs/files'\nimport type { Doclet, DocletTag } from './lib'\nimport { parseJSDoc } from './lib'\nimport type { TypedefsMap } from './types'\n\n// ============================================================================\n// Internal types\n// ============================================================================\n\ninterface ParsedJSDocsResult {\n serviceInfo: SharedExtensionServiceInfo | null\n methods: MethodInfo[]\n typedefsMap: TypedefsMap\n}\n\ninterface MethodInfo extends Omit<SharedExtensionMethod, 'bodyParams' | 'queryParams' | 'metaInfo'> {\n // name: string\n // description: string\n // returnType: string\n // registerAs: string\n // colorStart: string\n // colorEnd: string\n private: boolean\n // operationName: string\n // customIcon: string\n // category: string\n sampleResult: SharedExtensionMethod['metaInfo']['sampleResult']\n sampleResultLoader: SharedExtensionMethod['metaInfo']['sampleResultLoader']\n route?: string\n routeStr: string\n paramDefs: SharedExtensionMethod['bodyParams']\n}\n\ntype TagCallback = (title: string, value: string, tag: DocletTag) => void\n\n// ============================================================================\n// customTypeDef \u2014 registry of built-in reusable param groups.\n// To add a new domain: create custom-type-defs/<domain>.ts and spread it here.\n// ============================================================================\n\nconst customTypeDef: TypedefsMap = {\n FilesUploadOptions: filesTypeDefs.FilesUploadOptions,\n FilesListOptions: filesTypeDefs.FilesListOptions,\n FilesGetOptions: filesTypeDefs.FilesGetOptions,\n FilesDeleteOptions: filesTypeDefs.FilesDeleteOptions,\n}\n\ntype TagProcessor<T> = (target: T, tagValue: string) => void\n\n// ============================================================================\n// Doclet extraction\n// ============================================================================\n\n/**\n * Find the main service class from doclets.\n * Looks for a class with @integrationName tag, or falls back to the last non-Error class.\n */\nfunction findServiceClassName(doclets: Doclet[]): string | null {\n const withIntegration = doclets\n .find(d => {\n if (d.kind === 'class' && d.tags) {\n return d.tags.find(t => t.originalTitle === 'integrationName')\n }\n })\n\n if (withIntegration) {\n return withIntegration.name\n }\n\n return null\n}\n\n/**\n * Parse a JS file, extract the service class, and return normalized doclets.\n */\nfunction parseJSDocs(filePath: string): ParsedJSDocsResult {\n const doclets = parseJSDoc(filePath)\n const className = findServiceClassName(doclets)\n\n let serviceInfo: SharedExtensionServiceInfo | null = null\n\n const methods: MethodInfo[] = []\n\n const typedefsMap: TypedefsMap = {}\n\n doclets.forEach(d => {\n if (d.kind === 'class' && d.name === className) {\n serviceInfo = composeServiceInfo(d)\n } else if (d.kind === 'function' && d.memberof === className && d.scope === 'instance') {\n methods.push(composeMethod(d))\n } else if (d.kind === 'typedef') {\n const typedefParams = collectTypedef(d)\n\n if (typedefParams) {\n typedefsMap[d.name] = typedefParams\n }\n }\n })\n\n return {\n serviceInfo,\n methods,\n // Extension-defined typedefs override built-ins so authors can customise if needed\n typedefsMap: { ...customTypeDef, ...typedefsMap },\n }\n}\n\nconst ServiceInfoTagsProcessors: Record<string, TagProcessor<SharedExtensionServiceInfo>> = {\n integrationName: (serviceInfo, tagValue) => {\n serviceInfo.integrationName = tagValue || undefined as unknown as string\n },\n\n integrationIcon: (serviceInfo, tagValue) => {\n serviceInfo.integrationIcon = tagValue || null\n },\n\n requireOAuth: serviceInfo => {\n serviceInfo.requireOAuth = true\n },\n\n integrationTriggersScope: (serviceInfo, tagValue) => {\n serviceInfo.integrationTriggersScope = tagValue || null\n },\n}\n\nfunction composeServiceInfo(d: Doclet): SharedExtensionServiceInfo {\n const serviceInfo: SharedExtensionServiceInfo = {\n serviceClassName: d.name,\n integrationName: d.name,\n integrationIcon: null,\n requireOAuth: undefined,\n integrationTriggersScope: null,\n }\n\n iterateTags(d.tags, (tagName, tagValue) => {\n if (ServiceInfoTagsProcessors[tagName]) {\n ServiceInfoTagsProcessors[tagName](serviceInfo, tagValue)\n }\n })\n\n return serviceInfo\n}\n\nfunction iterateTags(tags: DocletTag[] | undefined, cb: TagCallback): void {\n if (tags) {\n tags.forEach(tag => {\n const title = tag.originalTitle\n const value = tag.value || tag.text || ''\n\n cb(title, value, tag)\n })\n }\n}\n\nconst MethodTagsProcessors: Record<string, TagProcessor<MethodInfo>> = {\n paramDef: (methodInfo, tagValue) => {\n if (tagValue) {\n const parsedValue = parseJSON(tagValue)\n\n if (parsedValue) {\n methodInfo.paramDefs.push(parsedValue as SharedExtensionMethodParam)\n }\n }\n },\n\n route: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.route = tagValue\n }\n },\n\n registerAs: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.registerAs = tagValue\n }\n },\n\n operationName: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.operationName = tagValue\n }\n },\n\n customIcon: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.customIcon = tagValue\n }\n },\n\n category: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.category = tagValue\n }\n },\n\n description: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.description = tagValue\n }\n },\n\n appearanceColor: (methodInfo, tagValue) => {\n if (tagValue) {\n const colors = extractColors(tagValue)\n\n methodInfo.colorStart = colors.colorStart\n methodInfo.colorEnd = colors.colorEnd\n }\n },\n\n private: methodInfo => {\n methodInfo.private = true\n },\n\n sampleResult: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.sampleResult = parseJSON(tagValue)\n }\n },\n\n sampleResultLoader: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.sampleResultLoader = parseJSON(tagValue) as SharedExtensionMetaInfo['sampleResultLoader']\n }\n },\n}\n\nfunction composeMethod(m: Doclet): MethodInfo {\n const methodInfo: MethodInfo = {\n name: m.name,\n description: m.description || '',\n returnType: mapReturnType(m.returns?.[0].type?.names?.[0]),\n registerAs: '',\n colorStart: '',\n colorEnd: '',\n private: m.access === 'private',\n operationName: m.name,\n customIcon: '',\n category: '',\n sampleResult: null,\n sampleResultLoader: null,\n routeStr: '',\n paramDefs: [],\n }\n\n if (m.params) {\n m.params.forEach(p => {\n methodInfo.paramDefs.push({\n name: p.name,\n type: p.type?.names?.[0] || 'String',\n required: !p.optional,\n })\n })\n }\n\n iterateTags(m.tags, (tagName, tagValue) => {\n if (MethodTagsProcessors[tagName]) {\n MethodTagsProcessors[tagName](methodInfo, tagValue)\n }\n })\n\n return methodInfo\n}\n\n// ============================================================================\n// Type mapping\n// ============================================================================\n\nconst PRIMITIVES = ['String', 'Object', 'Boolean', 'Number']\n\nconst ParamTypesMap: Record<string, string> = {\n String: 'STRING',\n Object: 'OBJECT',\n Boolean: 'BOOLEAN',\n Number: 'NUMBER',\n}\n\nfunction mapParamType(type: string | undefined): string {\n if (!type) {\n return 'STRING'\n }\n\n if (type.startsWith('Array')) {\n return 'LIST'\n }\n\n return ParamTypesMap[type] || 'STRING'\n}\n\nfunction mapReturnType(type: string | undefined): string {\n if (type) {\n if (type === 'Array' || type.startsWith('Array.') || type.startsWith('Array<')) return 'LIST'\n if (type === 'Object') return 'OBJECT'\n if (type === 'String') return 'STRING'\n }\n\n return 'VOID'\n}\n\n// ============================================================================\n// Typedef map (from @paramDef tags on typedefs)\n// ============================================================================\n\nfunction collectTypedef(d: Doclet): SharedExtensionMethodParam[] | undefined {\n const defs: SharedExtensionMethodParam[] = []\n\n iterateTags(d.tags, (title, value) => {\n if (title === 'paramDef') {\n const parsedValue = parseJSON(value)\n\n if (parsedValue) {\n defs.push(parsedValue as SharedExtensionMethodParam)\n }\n }\n })\n\n if (d.properties) {\n d.properties.forEach(property => {\n // JSDoc may omit the type on a @property line \u2014 preserved as-is at runtime\n const type = property?.type?.names?.[0] as string\n\n defs.push({\n name: property.name,\n required: !property.optional,\n description: property.description,\n type,\n })\n })\n }\n\n if (defs.length > 0) {\n return defs\n }\n}\n\n// ============================================================================\n// Param building (resolves typedefs)\n// ============================================================================\n\nfunction buildParam(paramDef: SharedExtensionMethodParam, typedefsMap: TypedefsMap, nested = false): SharedExtensionMethodParam {\n const isCustomType = !nested &&\n paramDef.type &&\n !PRIMITIVES.includes(paramDef.type) &&\n !paramDef.type.startsWith('Array')\n\n let properties: SharedExtensionMethodParam[] | undefined\n\n if (isCustomType && typedefsMap[paramDef.type!]) {\n let subDefs = typedefsMap[paramDef.type!]\n\n if (paramDef.include?.length) {\n const includeSet = new Set(paramDef.include)\n\n subDefs = subDefs.filter(sd => includeSet.has(sd.name))\n }\n\n if (subDefs.length > 0) {\n properties = subDefs.map(sp => buildParam(sp, typedefsMap, true))\n }\n }\n\n const param: SharedExtensionMethodParam = {\n name: paramDef.name,\n required: paramDef.required || false,\n description: paramDef.description || '',\n type: isCustomType ? 'OBJECT' : mapParamType(paramDef.type),\n }\n\n if (nested) {\n if (paramDef.label !== undefined) {\n param.label = paramDef.label\n }\n\n if (paramDef.uiComponent !== undefined) {\n param.uiComponent = paramDef.uiComponent\n }\n\n if (paramDef.dependsOn !== undefined) {\n param.dependsOn = paramDef.dependsOn\n }\n\n if (paramDef.dictionary !== undefined) {\n param.dictionary = paramDef.dictionary\n }\n\n if (paramDef.defaultValue !== undefined) {\n param.defaultValue = paramDef.defaultValue\n }\n }\n\n if (properties && properties.length > 0) {\n param.properties = properties\n }\n\n if (param.type === 'LIST') {\n param.items = { type: 'OBJECT' }\n }\n\n return param\n}\n\n// ============================================================================\n// MetaInfo args\n// ============================================================================\n\nfunction buildMetaInfoArgs(paramDefs: SharedExtensionMethodParam[], typedefsMap: TypedefsMap): Record<string, SharedExtensionMetaInfoArg> {\n const args: Record<string, SharedExtensionMetaInfoArg> = {}\n\n for (const pd of paramDefs) {\n const isCustomType = pd.type &&\n !PRIMITIVES.includes(pd.type) &&\n !pd.type.startsWith('Array')\n\n if (isCustomType && typedefsMap[pd.type!]) {\n const entry: SharedExtensionMetaInfoArg = {}\n if (pd.label) entry.label = pd.label\n args[pd.name] = entry\n continue\n }\n\n const entry: SharedExtensionMetaInfoArg = {}\n\n if (pd.label) entry.label = pd.label\n if (pd.dictionary) entry.dictionary = pd.dictionary\n if (pd.dependsOn && pd.dependsOn.length > 0) entry.dependsOn = pd.dependsOn\n if (pd.uiComponent) entry.uiComponent = pd.uiComponent\n\n args[pd.name] = entry\n }\n\n return args\n}\n\n// ============================================================================\n// Colors\n// ============================================================================\n\nfunction extractColors(colorStr: string): { colorStart: string; colorEnd: string } {\n if (!colorStr) {\n return { colorStart: '', colorEnd: '' }\n }\n\n const colors = colorStr.split(/[,\\s]+/).map(c => c.trim()).filter(Boolean)\n\n return {\n colorStart: colors[0] || '',\n colorEnd: colors[1] || colors[0] || '',\n }\n}\n\n// ============================================================================\n// Service JSON builder \u2014 converts normalized parseJSDocs output to service JSON\n// ============================================================================\n\nfunction parseJSON(str: string): unknown {\n try {\n return JSON.parse(str)\n } catch {\n return null\n }\n}\n\nexport function parseJsDocToServiceJson(entryPoint: string): SharedExtensionDefinition {\n const { serviceInfo, methods, typedefsMap } = parseJSDocs(entryPoint)\n\n const methodsMap: SharedExtensionDefinition['methodsMap'] = {}\n\n for (const method of methods) {\n if (method.private) {\n continue\n }\n\n const {\n name,\n route,\n registerAs,\n colorStart,\n colorEnd,\n operationName,\n customIcon,\n category,\n description,\n sampleResult,\n sampleResultLoader,\n paramDefs,\n returnType,\n } = method\n\n const isSystem = registerAs === 'SYSTEM'\n\n // Determine HTTP method from @route for param placement\n const httpMethod = route\n ? route.split(/\\s+/)[0].toUpperCase()\n : name.startsWith('get') ? 'GET' : 'POST'\n\n const isQueryPlacement = httpMethod === 'GET'\n\n // Build params\n const params = paramDefs.map(pd => buildParam(pd, typedefsMap))\n\n const queryParams = isQueryPlacement ? params : []\n const bodyParams = isQueryPlacement ? [] : params\n\n // Build metaInfo \u2014 only from @paramDef, not from standard @param fallback\n const metaInfoArgs = paramDefs.length > 0\n ? buildMetaInfoArgs(paramDefs, typedefsMap)\n : {}\n\n methodsMap[name] = {\n colorStart,\n colorEnd,\n queryParams, // todo remove me\n bodyParams,\n customIcon: isSystem ? undefined : customIcon,\n registerAs,\n category,\n metaInfo: {\n args: metaInfoArgs,\n sampleResult: isSystem ? undefined : sampleResult,\n sampleResultLoader: (isSystem ? undefined : sampleResultLoader) as SharedExtensionMethod['metaInfo']['sampleResultLoader'],\n },\n returnType,\n description,\n operationName,\n name,\n }\n }\n\n return {\n runnerVersion: 'v1', //TODO: temp\n methodsMap,\n serviceInfo: serviceInfo!,\n }\n}\n", "import { createHash } from 'crypto'\nimport fs from 'fs'\nimport path from 'path'\n\nimport { HASH_EXCLUDED_FOLDERS } from '../../constants'\n\n// The version of a service is a hash of the service, and of nothing else.\n//\n// That is what makes it comparable as well as unique: two checkouts of the same service hash the same\n// wherever they live, so `pull` can tell \"already up to date\" from \"differs\" without downloading anything \u2014\n// and a change to a sibling service, or to the project around it, cannot move it.\n//\n// `node_modules` is packed but not hashed. The service's own `package-lock.json` is hashed and says\n// everything about the dependency tree that matters, so a bump still produces a new version \u2014 which it must,\n// since the pod caches by this hash and the tree ships inside the package.\n//\n// Paths stay relative to the service root: the same sources unpacked anywhere else must hash the same.\n\nexport async function computeServiceHash(projectRoot: string, serviceId: string): Promise<string> {\n const hash = createHash('sha256')\n const serviceDir = path.resolve(projectRoot, 'services', serviceId)\n\n const files: string[] = []\n\n collectFiles(serviceDir, '', files)\n files.sort()\n\n for (const file of files) {\n hash.update(file)\n hash.update(fs.readFileSync(path.resolve(serviceDir, file)))\n }\n\n return hash.digest('hex')\n}\n\n/** Walks `dir` and appends every file to `files`, relative to the service root. */\nfunction collectFiles(serviceDir: string, relativeDir: string, files: string[]): void {\n const entries = fs.readdirSync(path.resolve(serviceDir, relativeDir), { withFileTypes: true })\n\n for (const entry of entries) {\n if (HASH_EXCLUDED_FOLDERS.includes(entry.name)) {\n continue\n }\n\n const relativePath = relativeDir ? path.join(relativeDir, entry.name) : entry.name\n\n if (!entry.isSymbolicLink()) {\n if (entry.isDirectory()) {\n collectFiles(serviceDir, relativePath, files)\n } else {\n files.push(relativePath)\n }\n }\n }\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { DiscoveredService } from './discover-services'\n\nexport interface PublicFile {\n serviceId: string\n /** Path relative to public/, e.g. \"icon.webp\" */\n relativePath: string\n buffer: Buffer\n}\n\nexport interface PublicFilesResult {\n files: PublicFile[]\n /** Icons a service declares that are not on disk \u2014 the deploy goes ahead without them. */\n missing: { serviceId: string; relativePath: string }[]\n}\n\n/**\n * Collects all public files referenced by the given service definitions (e.g. integrationIcon).\n * Icon paths in JSDoc use a leading slash relative to public/ (e.g. \"/icon.webp\").\n */\nexport function collectPublicFiles(\n services: DiscoveredService[],\n projectRoot: string = process.cwd()\n): PublicFilesResult {\n const files: PublicFile[] = []\n const missing: { serviceId: string; relativePath: string }[] = []\n\n for (const service of services) {\n // Per service, not per project: icons live in `services/<id>/public/`. Guarding on a root `public/`\n // directory instead used to drop every icon in a project that has no such folder.\n const servicePublicDir = path.resolve(projectRoot, 'services', service.serviceId, 'public')\n\n if (!fs.existsSync(servicePublicDir)) {\n continue\n }\n\n const iconPath = service.serviceInfo.integrationIcon\n\n if (!iconPath) {\n continue\n }\n\n // Strip leading slash \u2014 \"/icon.webp\" \u2192 \"icon.webp\"\n const relativePath = iconPath.replace(/^\\//, '')\n const fullPath = path.resolve(servicePublicDir, relativePath)\n\n // Confine the resolved path to public/. The separator is what makes this a containment check rather than\n // a prefix match: without it, `services/<id>/public-anything/` also starts with the directory name.\n if (!fullPath.startsWith(servicePublicDir + path.sep)) {\n continue\n }\n\n if (!fs.existsSync(fullPath)) {\n missing.push({ serviceId: service.serviceId, relativePath })\n\n continue\n }\n\n files.push({\n relativePath,\n serviceId: service.serviceId,\n buffer : fs.readFileSync(fullPath),\n })\n }\n\n return { files, missing }\n}\n", "import { SelectionRequiredError, UnknownServiceError } from '../../errors'\n\n// Which of the project's services a command is about.\n//\n// A deploy touches only the services it names, so \"everything\" has to be asked for. The one exception is a\n// project with a single service, where there is nothing to disambiguate.\n//\n// Generic over anything with a `serviceId` so the same rules cover a discovered service, a planned one, and\n// a service listed by the workspace \u2014 the question is the same in all three cases.\n\nexport interface Selection {\n /** Explicit ids. Wins over `all`. */\n serviceIds?: string[]\n /** Take every candidate. */\n all?: boolean\n}\n\nexport function selectServices<T extends { serviceId: string }>(\n available: T[],\n selection: Selection = {}\n): T[] {\n const ids = available.map(entry => entry.serviceId)\n\n if (selection.serviceIds?.length) {\n return selection.serviceIds.map(serviceId => {\n const match = available.find(entry => entry.serviceId === serviceId)\n\n if (!match) {\n throw new UnknownServiceError(serviceId, ids)\n }\n\n return match\n })\n }\n\n if (selection.all || available.length === 1) {\n return available\n }\n\n throw new SelectionRequiredError(ids)\n}\n", "import archiver from 'archiver'\nimport path from 'path'\n\n// The archive the pod unpacks, and it IS the service folder:\n//\n// package/src/index.js \u2190 the service's source\n// package/public/icon.webp\n// package/package.json \u2190 the service's own manifest\n// package/package-lock.json\n// package/node_modules/** \u2190 the service's own dependencies\n//\n// So `serviceFilePath` is relative to the service ('src/index.js'), and `require` resolves by walking up\n// from `package/src/` to `package/node_modules`. Nothing from the project root is in here.\n\nexport async function createServiceZip(\n definition: object,\n projectRoot: string,\n serviceId: string\n): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const archive = archiver('zip', { zlib: { level: 9 } })\n const chunks: Buffer[] = []\n\n archive.on('data', (chunk: Buffer) => chunks.push(chunk))\n archive.on('end', () => resolve(Buffer.concat(chunks)))\n archive.on('error', reject)\n\n // Everything the service folder holds, `node_modules` included \u2014 the pod installs nothing.\n archive.directory(`${ path.resolve(projectRoot, 'services', serviceId) }/`, 'package')\n\n // Add definition.json next to package/ (for debugging/testing)\n archive.append(JSON.stringify(definition, null, 2), { name: 'definition.json' })\n\n archive.finalize()\n })\n}\n", "import { execFileSync } from 'child_process'\nimport fs from 'fs'\nimport path from 'path'\n\nimport {\n CONFIG_FILE,\n PLACEHOLDER_SCRIPTS,\n TEST_DEV_DEPENDENCIES,\n TEST_GITIGNORE_ENTRIES,\n TEST_SCRIPTS,\n TOKEN_DIR,\n} from '../../constants'\nimport { PromptAbortedError, PromptRequiredError } from '../../errors'\nimport { ensureServerUrl } from '../../project/config'\nimport { packageRoot } from '../../templates/package-root'\nimport { PORTABLE_CLI_COMMAND } from '../../utils/invocation'\nimport { resolveServerTarget } from '../server-target'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport type { CreateServiceOptions, ScaffoldedService } from './create-service'\nimport { resolveTemplateId, scaffoldFromTemplate } from './create-service'\nimport { writeTestingFiles } from './testing'\n\n// `init` bootstraps the project the other commands assume: an npm package with the CLI as a devDependency,\n// a `flowrunner.json` naming a server, a `.gitignore` that keeps the token out of git, and the unit-test\n// harness a service is written against (see `testing.ts`).\n//\n// Nothing here overwrites. The command is meant to be safe to run in a directory that already has files \u2014\n// adding FlowRunner to an existing repository is the same operation as starting from nothing, minus the\n// files that are already there.\n\nexport type InitEvent =\n | { type: 'target'; projectRoot: string; lines: string[] }\n | { type: 'files'; created: string[]; skipped: string[]; serverUrl: string }\n | { type: 'repository'; committed: boolean }\n | { type: 'cancelled' }\n | { type: 'warning'; message: string }\n\nexport interface InitOptions extends Omit<CreateServiceOptions, 'onEvent'>, OperationOptions<InitEvent> {\n /** A template to scaffold a first service from. Omitted creates just the project. */\n template?: string\n /**\n * Written into `flowrunner.json`; defaults to the CLI's own default cluster.\n *\n * A cluster name (`prod`/`dev`/`local`) or a full URL.\n */\n server?: string\n /** Set false to skip `npm install`. */\n install?: boolean\n /**\n * Set false to skip the unit-test harness \u2014 the sandbox, the jest config, and their dependencies.\n *\n * For a project that already has a test runner it does not want two of.\n */\n tests?: boolean\n /** Set false to skip initialising a git repository and making the first commit. */\n git?: boolean\n /**\n * Confirm writing into a directory that already holds something.\n *\n * `init` never overwrites, but landing a project on top of an unrelated one \u2014 a mistyped `--dir`, a\n * stray `..` \u2014 is worth a second look. Omitted means nothing can be asked, so a directory that needs\n * confirming throws instead.\n */\n onConfirmTarget?: (target: TargetDescription) => Promise<boolean>\n /** Progress from the service scaffold, when a template was given. */\n onServiceEvent?: CreateServiceOptions['onEvent']\n}\n\nexport interface TargetDescription {\n projectRoot: string\n lines: string[]\n defaultYes: boolean\n}\n\nexport interface InitResult {\n projectRoot: string\n /** The target was not confirmed, so nothing was written. */\n cancelled: boolean\n created: string[]\n skipped: string[]\n serverUrl: string\n /** The harness files that were written, relative to the project root. Empty under `tests: false`. */\n testingFiles: string[]\n service?: ScaffoldedService\n installed: boolean\n /** 'created' \u2014 a new repository; 'existing' \u2014 left alone; 'skipped' \u2014 `--no-git`; 'failed' \u2014 git refused. */\n repository: 'created' | 'existing' | 'skipped' | 'failed'\n committed: boolean\n}\n\nconst GITIGNORE_ENTRIES = ['node_modules/', `${ TOKEN_DIR }/`, ...TEST_GITIGNORE_ENTRIES]\n\n/** The package `init` writes into `devDependencies`, and the pre-rename name a project may already hold. */\nconst CLI_PACKAGE = '@flowrunner/cli'\nconst CLI_PACKAGE_NAMES = [CLI_PACKAGE, 'flowrunner-cli']\n\n/** Reports something that went wrong without stopping the init. */\ntype Warn = (message: string) => void\n\n/** The CLI's own version, so a generated project pins the version that generated it. */\nfunction cliVersion(): string {\n return JSON.parse(fs.readFileSync(path.join(packageRoot(), 'package.json'), 'utf-8')).version\n}\n\n/** A directory name turned into something npm will accept as a package name. */\nfunction packageNameFrom(directory: string): string {\n const name = path.basename(path.resolve(directory))\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^[._-]+|[-._]+$/g, '')\n\n return name || 'flowrunner-extensions'\n}\n\n/**\n * Add every entry of `additions` that the section does not already have, and report whether anything\n * changed.\n *\n * \"Already have\" is by key, never by value: a project pinning jest 29, or defining its own `test` script\n * that runs something else first, has made a decision \u2014 and `init` is not the command that revisits it.\n *\n * `placeholders` is the one exception, and it is not a value judgement: `npm init -y` writes a `test` script\n * that exits 1, which is a stand-in for the absence of one rather than anything the project chose.\n */\nfunction addMissing(\n section: Record<string, string>,\n additions: Record<string, string>,\n placeholders: Record<string, string> = {}\n): boolean {\n let changed = false\n\n for (const [name, value] of Object.entries(additions)) {\n if (section[name] === undefined || section[name] === placeholders[name]) {\n section[name] = value\n changed = true\n }\n }\n\n return changed\n}\n\nfunction writePackageJson(projectRoot: string, tests: boolean): 'created' | 'updated' | 'skipped' {\n const fullPath = path.join(projectRoot, 'package.json')\n const version = cliVersion()\n\n const devDependencies = { [CLI_PACKAGE]: version, ...(tests ? TEST_DEV_DEPENDENCIES : {}) }\n const scripts = { deploy: 'flowrunner deploy --all', ...(tests ? TEST_SCRIPTS : {}) }\n\n if (!fs.existsSync(fullPath)) {\n const manifest = {\n name : packageNameFrom(projectRoot),\n version : '0.0.1',\n private : true,\n description: 'FlowRunner custom extensions.',\n scripts,\n devDependencies,\n }\n\n fs.writeFileSync(fullPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8')\n\n return 'created'\n }\n\n // An existing project keeps its own manifest, including a version of the CLI or of jest it has\n // deliberately pinned. What is worth adding is what the project cannot work without: the CLI itself,\n // without which `npx flowrunner` resolves to whatever is globally installed \u2014 or to nothing \u2014 and the\n // packages the harness files just copied in would fail to require.\n const manifest = JSON.parse(fs.readFileSync(fullPath, 'utf-8'))\n\n // A CLI the project already declares is left exactly where it is. Which section it sits in is the\n // project's own decision, and listing it twice is how npm ends up resolving two copies \u2014 which is also\n // why the pre-rename name counts: adding `@flowrunner/cli` beside an existing `flowrunner-cli` would\n // install both and leave the launcher choosing between them.\n const alreadyDeclared = CLI_PACKAGE_NAMES.some(name =>\n manifest.dependencies?.[name] || manifest.devDependencies?.[name])\n\n const additions = alreadyDeclared\n ? Object.fromEntries(Object.entries(devDependencies).filter(([name]) => name !== CLI_PACKAGE))\n : devDependencies\n\n manifest.devDependencies ??= {}\n manifest.scripts ??= {}\n\n // Both run \u2014 `.some()` on an array, not `||` \u2014 so a manifest needing only the scripts still gets them.\n const changed = [\n addMissing(manifest.devDependencies, additions),\n addMissing(manifest.scripts, tests ? TEST_SCRIPTS : {}, PLACEHOLDER_SCRIPTS),\n ].some(Boolean)\n\n if (!changed) {\n return 'skipped'\n }\n\n fs.writeFileSync(fullPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8')\n\n return 'updated'\n}\n\nfunction writeGitignore(projectRoot: string): 'created' | 'updated' | 'skipped' {\n const fullPath = path.join(projectRoot, '.gitignore')\n\n if (!fs.existsSync(fullPath)) {\n fs.writeFileSync(fullPath, GITIGNORE_ENTRIES.join('\\n') + '\\n', 'utf-8')\n\n return 'created'\n }\n\n const content = fs.readFileSync(fullPath, 'utf-8')\n const lines = content.split('\\n').map(line => line.trim())\n // A bare `node_modules` covers `node_modules/`; compare on the stem so an existing entry is respected.\n const missing = GITIGNORE_ENTRIES.filter(entry => !lines.includes(entry) && !lines.includes(entry.replace(/\\/$/, '')))\n\n if (missing.length === 0) {\n return 'skipped'\n }\n\n fs.appendFileSync(fullPath, `${ content.endsWith('\\n') ? '' : '\\n' }${ missing.join('\\n') }\\n`)\n\n return 'updated'\n}\n\nconst README = (name: string) => `# ${ name }\n\nFlowRunner custom extensions for this workspace.\n\nEach folder under \\`services/\\` is one extension and one npm package: it has its own \\`package.json\\` and its\nown \\`node_modules\\`, so \\`npm install\\` for a service is run **inside that service's folder**. It is deployed\nand versioned on its own, and deploying one leaves every other service in the workspace untouched \u2014 which is\nwhat lets several projects deploy into the same workspace.\n\n\\`\\`\\`bash\n${ PORTABLE_CLI_COMMAND } cs # scaffold another service\n${ PORTABLE_CLI_COMMAND } login # authorize against the console (once)\n${ PORTABLE_CLI_COMMAND } deploy -s <id># build one service's definition and upload it (--all for every one)\n${ PORTABLE_CLI_COMMAND } pull # bring the workspace's services down into services/\n${ PORTABLE_CLI_COMMAND } init-claude # wire the FlowRunner agents into Claude Code\n\ncd services/<id> && npm install # add a dependency to one service\nnpm test # run the unit suites in services/*/tests/\n\\`\\`\\`\n\nWith \\`npm i -g @flowrunner/cli\\` you can drop the \\`npx\\` and just write \\`flowrunner cs\\`. The global copy only\nlaunches the one in this project's \\`node_modules\\`, so the version pinned in \\`package.json\\` is still the one\nthat runs.\n\nTo move this project to a newer CLI, upgrade the dependency and commit it \u2014 that is what decides which code\nruns, for you and for CI:\n\n\\`\\`\\`bash\nnpm i -D @flowrunner/cli@<version>\n\\`\\`\\`\n\nUpdating the global copy (\\`npm i -g @flowrunner/cli@latest\\`) is rarely needed and changes nothing here.\n\nTests run each service the way the platform does, with HTTP intercepted at the socket \u2014 see\n\\`sandbox/index.js\\`, which \\`${ PORTABLE_CLI_COMMAND } init\\` copied here for you to edit.\n\nThe authoring reference the CLI ships lives in\n\\`node_modules/@flowrunner/cli/ai-docs/instructions/service-code-format/\\`. Point your AI agent at it \u2014 or run\n\\`${ PORTABLE_CLI_COMMAND } init-claude\\` and Claude Code is wired up for you.\n\n\\`flowrunner.json\\` names the server and the workspace and belongs in git.\n\\`.flowrunner/token\\` is the deploy token and must not.\n`\n\nfunction writeReadme(projectRoot: string): 'created' | 'skipped' {\n const fullPath = path.join(projectRoot, 'README.md')\n\n if (fs.existsSync(fullPath)) {\n return 'skipped'\n }\n\n fs.writeFileSync(fullPath, README(packageNameFrom(projectRoot)), 'utf-8')\n\n return 'created'\n}\n\nfunction git(projectRoot: string, args: string[]): void {\n execFileSync('git', args, { cwd: projectRoot, stdio: 'pipe' })\n}\n\n/** Whether the directory is already tracked \u2014 by its own repository or by one further up. */\nfunction insideRepository(projectRoot: string): boolean {\n try {\n git(projectRoot, ['rev-parse', '--is-inside-work-tree'])\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Start a repository, unless the directory is already in one.\n *\n * An existing repository is left completely alone \u2014 `init` has no business running `git init` inside a\n * monorepo subdirectory, and it must never touch a working tree that may hold someone's unrelated changes.\n */\nfunction gitInit(projectRoot: string, warn: Warn): 'created' | 'existing' | 'failed' {\n if (insideRepository(projectRoot)) {\n return 'existing'\n }\n\n try {\n // `-b main` also silences git's default-branch hint. Older gits do not know the flag.\n try {\n git(projectRoot, ['init', '-b', 'main'])\n } catch {\n git(projectRoot, ['init'])\n }\n\n return 'created'\n } catch {\n warn('git init failed \u2014 is git installed? The project files are fine either way.')\n\n return 'failed'\n }\n}\n\n/**\n * The first commit, made after `npm install` so the lockfile is part of it.\n *\n * Only ever runs in a repository this command just created, where staging everything is safe by\n * construction: there is nothing else in it.\n */\nfunction gitCommit(projectRoot: string, warn: Warn): boolean {\n try {\n git(projectRoot, ['add', '-A'])\n git(projectRoot, ['commit', '-m', 'Initial commit'])\n\n return true\n } catch {\n // Most often an unconfigured user.name / user.email. Setting one ourselves would stamp an identity the\n // user never chose onto their own history, so the files stay staged and they decide.\n warn('git commit failed \u2014 the files are staged; commit them once git knows who you are.')\n\n return false\n }\n}\n\nfunction npmInstall(projectRoot: string, warn: Warn): boolean {\n const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'\n\n try {\n execFileSync(npm, ['install'], { cwd: projectRoot, stdio: 'inherit' })\n\n return true\n } catch {\n // The project files are already correct, so a failed install is a warning and not a failed init: the\n // user can run `npm install` themselves once they have fixed whatever npm complained about.\n warn('npm install failed \u2014 run it yourself in the project directory.')\n\n return false\n }\n}\n\n/**\n * What the user is about to do to a directory, in the terms that would make them notice a mistake: the\n * absolute path, whether it exists, whether anything is in it, and whether it is already a project.\n */\nexport function describeTarget(projectRoot: string): TargetDescription {\n if (!fs.existsSync(projectRoot)) {\n return { projectRoot, lines: ['a new directory'], defaultYes: true }\n }\n\n if (!fs.statSync(projectRoot).isDirectory()) {\n return { projectRoot, lines: ['not a directory'], defaultYes: false }\n }\n\n const entries = fs.readdirSync(projectRoot).filter(entry => entry !== '.git')\n\n if (entries.length === 0) {\n return { projectRoot, lines: ['an empty directory'], defaultYes: true }\n }\n\n const lines = [`an existing directory \u2014 ${ entries.length } ${ entries.length === 1 ? 'entry' : 'entries' }`]\n\n if (entries.includes('package.json')) {\n lines.push('already an npm project \u2014 its package.json will be kept, with the CLI added as a devDependency')\n }\n\n if (entries.includes('services')) {\n lines.push('already has services/')\n }\n\n if (insideRepository(projectRoot)) {\n lines.push('already tracked by git \u2014 no repository will be created and nothing will be committed')\n }\n\n // Anything already in there is a reason to look twice: `init -d ..` or a mistyped path lands here, and\n // the files this writes would then join a project that never asked for them.\n return { projectRoot, lines, defaultYes: false }\n}\n\n/** Create the project the other operations assume, optionally with a first service in it. */\nexport async function init(options: InitOptions = {}): Promise<InitResult> {\n const projectRoot = path.resolve(options.cwd ?? '.')\n const emit = emitter(options)\n const warn = (message: string) => emit({ type: 'warning', message })\n\n // Both resolved before anything is written, so an unknown template or an unknown server fails without\n // leaving a half-made project behind.\n const template = options.template ? resolveTemplateId(options.template) : null\n const requestedServerUrl = options.server ? resolveServerTarget(options.server) : undefined\n\n const target = describeTarget(projectRoot)\n\n emit({ type: 'target', projectRoot, lines: target.lines })\n\n // A directory that already holds something, and no way to ask about it: neither answer can be assumed.\n // Writing would be a silent surprise, and doing nothing would be a silent no-op \u2014 so say what is needed.\n if (!options.acceptDefaults && !options.onConfirmTarget && !target.defaultYes) {\n throw new PromptRequiredError(\n 'confirm-target',\n `${ projectRoot } already has files in it, and there is no way to confirm writing a project there.`\n )\n }\n\n // `acceptDefaults` already means \"ask nothing\".\n if (!options.acceptDefaults && options.onConfirmTarget && !await options.onConfirmTarget(target)) {\n emit({ type: 'cancelled' })\n\n return {\n projectRoot,\n cancelled : true,\n created : [],\n skipped : [],\n serverUrl : '',\n testingFiles: [],\n installed : false,\n repository : 'skipped',\n committed : false,\n }\n }\n\n if (!fs.existsSync(projectRoot)) {\n fs.mkdirSync(projectRoot, { recursive: true })\n }\n\n if (!fs.statSync(projectRoot).isDirectory()) {\n throw new PromptAbortedError(`${ projectRoot } is not a directory.`)\n }\n\n const created: string[] = []\n const skipped: string[] = []\n\n const record = (file: string, outcome: 'created' | 'updated' | 'skipped') => {\n (outcome === 'skipped' ? skipped : created).push(outcome === 'updated' ? `${ file } (updated)` : file)\n }\n\n const tests = options.tests !== false\n\n record('package.json', writePackageJson(projectRoot, tests))\n record('.gitignore', writeGitignore(projectRoot))\n\n const server = ensureServerUrl(projectRoot, requestedServerUrl)\n\n record(CONFIG_FILE, server.created ? 'created' : server.updated ? 'updated' : 'skipped')\n record('README.md', writeReadme(projectRoot))\n\n // The harness is part of the project rather than something bolted on afterwards, so it is written with\n // the rest of the scaffolding and reported in the same list.\n const testing = tests ? writeTestingFiles(projectRoot) : { created: [], skipped: [] }\n\n testing.created.forEach(file => record(file, 'created'))\n testing.skipped.forEach(file => record(file, 'skipped'))\n\n emit({ type: 'files', created, skipped, serverUrl: server.serverUrl })\n\n const service = template\n ? await scaffoldFromTemplate(template, { ...options, onEvent: options.onServiceEvent }, projectRoot)\n : undefined\n\n // Before the install, so a repository exists to commit into; the commit itself waits until after it, so\n // package-lock.json lands in the first commit rather than as an immediate diff.\n const repository = options.git === false ? 'skipped' : gitInit(projectRoot, warn)\n const installed = options.install === false ? false : npmInstall(projectRoot, warn)\n const committed = repository === 'created' && gitCommit(projectRoot, warn)\n\n if (repository === 'created') {\n emit({ type: 'repository', committed })\n }\n\n return {\n projectRoot,\n cancelled : false,\n created,\n skipped,\n serverUrl : server.serverUrl,\n testingFiles: testing.created,\n service,\n installed,\n repository,\n committed,\n }\n}\n\nexport type { TestingFilesResult } from './testing'\nexport { testingFilesDirectory, writeTestingFiles } from './testing'\n", "import fs from 'fs'\nimport path from 'path'\n\n// The CLI runs from two places with different depths \u2014 bundled at `dist/index.js`, and straight from\n// `src/**` via tsx when `bin/flowrunner.js` finds the TypeScript entry (dev mode / npm link). Neither a\n// fixed `../` count nor `process.cwd()` (the *target* project) locates the shipped `templates/` folder, so\n// walk up to the package that owns this file.\n\n// Either name identifies our own package: the CLI moved to the `@flowrunner` org, and a copy installed\n// under the old name must still locate its own `templates/` and `ai-docs/`.\nconst PACKAGE_NAMES = ['@flowrunner/cli', 'flowrunner-cli']\n\nlet cached: string | null = null\n\nfunction findPackageRoot(): string {\n let dir = __dirname\n\n while (true) {\n const manifest = path.join(dir, 'package.json')\n\n if (fs.existsSync(manifest)) {\n try {\n if (PACKAGE_NAMES.includes(JSON.parse(fs.readFileSync(manifest, 'utf-8')).name)) {\n return dir\n }\n } catch {\n // A malformed package.json on the way up is not ours to complain about \u2014 keep walking.\n }\n }\n\n const parent = path.dirname(dir)\n\n if (parent === dir) {\n throw new Error(`Could not locate the \"${ PACKAGE_NAMES[0] }\" package root above ${ __dirname }`)\n }\n\n dir = parent\n }\n}\n\nexport function packageRoot(): string {\n cached ??= findPackageRoot()\n\n return cached\n}\n\n/** Absolute path of the shipped template content (`packages/cli/templates`). */\nexport function templatesRoot(): string {\n return path.join(packageRoot(), 'templates')\n}\n", "import fs from 'fs'\nimport path from 'path'\n\n// How the CLI tells a user to invoke it.\n//\n// `node_modules/.bin` is on PATH only inside npm's own lifecycle \u2014 `npm run`, `npm exec`, `npx` \u2014 never in\n// an interactive shell. So a bare `flowrunner \u2026` runs only when a GLOBAL install put it on PATH, and a\n// project that has the CLI as a dependency and nothing else answers `command not found`. That is the whole\n// bug: the hint was written by people who had a global install, for people who do not.\n//\n// Some terminals muddy this further by injecting `node_modules/.bin` themselves (JetBrains IDEs do), which\n// is why \"it works for me\" is not evidence either way.\n\n/**\n * The invocation for text written to FILES.\n *\n * A README is committed and read on machines other than the one that generated it, so it cannot encode this\n * machine's PATH. `npx` resolves `node_modules/.bin` first and falls back to PATH, so it is right for a\n * local install, a global one, and CI alike.\n */\nexport const PORTABLE_CLI_COMMAND = 'npx flowrunner'\n\n// npm installs global bins alongside the running node binary, so this one `existsSync` answers \"is there a\n// global flowrunner\" without spawning `npm prefix -g`.\nconst GLOBAL_BIN_NAMES = process.platform === 'win32'\n ? ['flowrunner.cmd', 'flowrunner.exe', 'flowrunner']\n : ['flowrunner']\n\nlet resolved: boolean | undefined\n\n/**\n * Whether a global install has put `flowrunner` on PATH.\n *\n * This is what makes the bare command usable at all \u2014 and, with the launcher in `bin/resolve-local.js`,\n * what lets it hand over to the project's own copy.\n */\nexport function hasGlobalInstall(): boolean {\n if (resolved === undefined) {\n const binDirectory = path.dirname(process.execPath)\n\n resolved = GLOBAL_BIN_NAMES.some(name => fs.existsSync(path.join(binDirectory, name)))\n }\n\n return resolved\n}\n\n/**\n * The invocation to PRINT, for the person at this keyboard right now.\n *\n * Bare when a global install makes it resolvable, `npx flowrunner` otherwise \u2014 so every hint the CLI prints\n * is one the reader can actually paste. Wrong only in the safe direction: a terminal that injects\n * `node_modules/.bin` gets the `npx` form, which still runs. It never prints a bare command that fails.\n *\n * Both forms run the same code: the bare one goes through the global launcher, which delegates to the\n * project's copy, and `npx` resolves that copy directly.\n */\nexport function cliCommand(): string {\n return hasGlobalInstall() ? 'flowrunner' : PORTABLE_CLI_COMMAND\n}\n\n/** Testing seam: the answer is cached because it cannot change within one run. */\nexport function resetCliCommandCache(): void {\n resolved = undefined\n}\n", "import type { ClusterName } from '../constants'\nimport { CLUSTERS } from '../constants'\nimport { UnknownServerError } from '../errors'\n\n// Turning what someone typed \u2014 `dev`, or a URL \u2014 into a server address. Shared by every command that takes\n// a server: `use`, and the `--server` option on `init` and `login`.\n\nexport const CLUSTER_NAMES = Object.keys(CLUSTERS) as ClusterName[]\n\n/** Trailing slashes are noise: the same server typed two ways must compare equal. */\nexport function normalizeServerUrl(serverUrl: string): string {\n return serverUrl.replace(/\\/+$/, '')\n}\n\n/** Which cluster a URL is, or null when it is not one of ours. */\nexport function clusterFor(serverUrl: string): ClusterName | null {\n const normalized = normalizeServerUrl(serverUrl)\n\n return CLUSTER_NAMES.find(name => CLUSTERS[name] === normalized) ?? null\n}\n\n/**\n * Resolve `prod` / `dev` / `local`, or an explicit URL, to a server URL.\n *\n * Anything that is not a known name and does not look like a URL is refused rather than passed through: a\n * mistyped `prd` would otherwise be stored as a server address and fail much later, against a host that\n * does not exist.\n */\nexport function resolveServerTarget(target: string): string {\n const known = CLUSTERS[target as ClusterName]\n\n if (known) {\n return known\n }\n\n if (/^https?:\\/\\//i.test(target)) {\n return normalizeServerUrl(target)\n }\n\n throw new UnknownServerError(target, [...CLUSTER_NAMES, 'or a full http(s):// URL'])\n}\n", "import path from 'path'\n\nimport { TemplateNotFoundError } from '../../errors'\nimport type { Answers, Template } from '../../templates/manifest'\nimport { DEFAULT_TEMPLATE_ALIAS, findTemplate, listTemplates } from '../../templates/registry'\nimport { scaffoldService } from '../../templates/scaffold'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport type { Ask } from './answers'\nimport { resolveAnswers } from './answers'\n\n// Scaffolding one service into an existing project.\n\nexport type CreateServiceEvent =\n | { type: 'template'; template: Template }\n | { type: 'created-services-directory' }\n | { type: 'created'; relativePath: string; files: string[] }\n\nexport interface CreateServiceOptions extends OperationOptions<CreateServiceEvent> {\n /** Answers the template's prompts, keyed by prompt name. `id` and `name` are expected by every template. */\n answers?: Answers\n /** Take every default rather than asking. */\n acceptDefaults?: boolean\n /** How to ask for anything still unanswered. Omitted means an unanswered prompt throws. */\n ask?: Ask\n}\n\nexport interface ScaffoldedService {\n serviceId: string\n serviceDirectory: string\n /** `serviceDirectory` relative to the project root, for printing. */\n relativePath: string\n files: string[]\n}\n\n/** Resolves a template id \u2014 the `demo` alias included \u2014 or throws naming what is available. */\nexport function resolveTemplateId(templateId: string, templates: Template[] = listTemplates()): Template {\n const template = findTemplate(templateId)\n\n if (!template) {\n throw new TemplateNotFoundError(\n templateId,\n [...templates.map(entry => entry.manifest.id), DEFAULT_TEMPLATE_ALIAS]\n )\n }\n\n return template\n}\n\n/**\n * Ask the template's questions and write the service \u2014 the part `createService` and `init` share.\n *\n * Reports the files it created; the caller owns the \"next steps\" it prints afterwards, since those differ\n * between scaffolding into an existing project and bootstrapping a new one.\n */\nexport async function scaffoldFromTemplate(\n template: Template,\n options: CreateServiceOptions = {},\n projectRoot: string = options.cwd ?? process.cwd()\n): Promise<ScaffoldedService> {\n const emit = emitter(options)\n\n emit({ type: 'template', template })\n\n const answers = await resolveAnswers(template.manifest.prompts, {\n prefilled : options.answers,\n constants : template.manifest.values,\n acceptDefaults: options.acceptDefaults,\n ask : options.ask,\n projectRoot,\n })\n\n // Every template is expected to collect the service id under this name \u2014 it is what the folder is\n // called and what `createExtension({ id })` freezes.\n const serviceId = String(answers.id)\n\n const { serviceDirectory, files, createdServicesDirectory } =\n scaffoldService(template, answers, serviceId, projectRoot)\n\n const relativePath = path.relative(projectRoot, serviceDirectory) || serviceDirectory\n const written = files.map(file => file.relativePath)\n\n if (createdServicesDirectory) {\n emit({ type: 'created-services-directory' })\n }\n\n emit({ type: 'created', relativePath, files: written })\n\n return { serviceId, serviceDirectory, relativePath, files: written }\n}\n\n/** Scaffold a service from the named template into the project. */\nexport async function createService(\n templateId: string,\n options: CreateServiceOptions = {}\n): Promise<ScaffoldedService> {\n return scaffoldFromTemplate(resolveTemplateId(templateId), options, options.cwd ?? process.cwd())\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { Template } from './manifest'\nimport { TemplateManifestSchema } from './manifest'\nimport { templatesRoot } from './package-root'\n\n// Templates are discovered from `templates/*/template.json`, so adding one is still just dropping in a\n// folder. Which of them is the *default* is decided here, by a single id \u2014 deliberately not a `default:\n// true` flag on each manifest, because two manifests could both set that and the winner would come down to\n// directory order.\n\nconst MANIFEST_FILE = 'template.json'\n\n/** The template `flowrunner cs demo` resolves to, and the one that heads the interactive picker. */\nexport const DEFAULT_TEMPLATE_ID = 'demo-todo-list'\n\n/**\n * A stable shorthand for \"whichever template is the default one\", so `flowrunner cs demo` keeps working\n * if the default moves. The default template's own id still resolves normally.\n */\nexport const DEFAULT_TEMPLATE_ALIAS = 'demo'\n\n// A manifest is checked the moment it is read, not when a file is finally written: a template that declares\n// a missing source or a `to` path escaping the service directory is broken for everyone, and finding that\n// out halfway through a render leaves the target project in a state the user has to clean up by hand.\nfunction loadTemplate(directory: string): Template {\n const manifestPath = path.join(directory, MANIFEST_FILE)\n\n let raw: unknown\n\n try {\n raw = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'))\n } catch (error) {\n throw new Error(`Template manifest ${ manifestPath } is not readable JSON: ${ (error as Error).message }`)\n }\n\n const parsed = TemplateManifestSchema.safeParse(raw)\n\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map(issue => ` ${ issue.path.join('.') || '<root>' }: ${ issue.message }`)\n .join('\\n')\n\n throw new Error(`Template manifest ${ manifestPath } is invalid:\\n${ issues }`)\n }\n\n const manifest = parsed.data\n\n // The folder is how a template is found; the manifest id is how it is addressed. A mismatch would make\n // `cs <folder>` fail while the template looks perfectly present on disk.\n if (manifest.id !== path.basename(directory)) {\n throw new Error(`Template in ${ directory } declares id \"${ manifest.id }\" \u2014 it must match the folder name`)\n }\n\n for (const prompt of manifest.prompts) {\n if (prompt.type === 'choice' && !prompt.options.some(option => option.value === prompt.default)) {\n throw new Error(`Template \"${ manifest.id }\" prompt \"${ prompt.name }\" defaults to \"${ prompt.default }\", ` +\n `which is not one of its options (${ prompt.options.map(option => option.value).join(', ') })`)\n }\n }\n\n const filesRoot = path.join(directory, 'files')\n\n for (const file of manifest.files) {\n const source = path.resolve(filesRoot, file.from)\n\n if (!source.startsWith(filesRoot + path.sep)) {\n throw new Error(`Template \"${ manifest.id }\" declares a source outside files/: ${ file.from }`)\n }\n\n if (!fs.existsSync(source)) {\n throw new Error(`Template \"${ manifest.id }\" declares a missing source file: files/${ file.from }`)\n }\n\n // The real destination is per-service, but whether it can escape is decided by the manifest alone.\n const destination = path.normalize(file.to)\n\n if (path.isAbsolute(destination) || destination.split(/[\\\\/]/).includes('..')) {\n throw new Error(`Template \"${ manifest.id }\" declares a destination outside the service folder: ${ file.to }`)\n }\n\n const gate = file.when &&\n (manifest.prompts.some(prompt => prompt.type === 'boolean' && prompt.name === file.when) ||\n typeof manifest.values[file.when] === 'boolean')\n\n if (file.when && !gate) {\n throw new Error(`Template \"${ manifest.id }\" gates files/${ file.from } on \"${ file.when }\", ` +\n 'which is neither a boolean prompt nor a boolean entry in `values`')\n }\n }\n\n return { manifest, directory, isDefault: manifest.id === DEFAULT_TEMPLATE_ID }\n}\n\n/** Every template shipped with the CLI \u2014 the default one first, then alphabetically. */\nexport function listTemplates(): Template[] {\n const root = templatesRoot()\n\n if (!fs.existsSync(root)) {\n return []\n }\n\n const templates = fs\n .readdirSync(root, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && fs.existsSync(path.join(root, entry.name, MANIFEST_FILE)))\n .map(entry => loadTemplate(path.join(root, entry.name)))\n\n // Catches a rename or a deletion of the default template, rather than quietly leaving `cs demo` broken.\n if (templates.length > 0 && !templates.some(template => template.isDefault)) {\n throw new Error(`DEFAULT_TEMPLATE_ID is \"${ DEFAULT_TEMPLATE_ID }\", but no template with that id is bundled`)\n }\n\n return templates.sort((a, b) => Number(b.isDefault) - Number(a.isDefault) ||\n a.manifest.id.localeCompare(b.manifest.id))\n}\n\nexport function defaultTemplate(): Template | null {\n return listTemplates().find(template => template.isDefault) ?? null\n}\n\n/** Resolves a template id, or the `demo` alias, to a template. */\nexport function findTemplate(id: string): Template | null {\n const templates = listTemplates()\n const match = templates.find(template => template.manifest.id === id)\n\n if (match) {\n return match\n }\n\n return id === DEFAULT_TEMPLATE_ALIAS\n ? templates.find(template => template.isDefault) ?? null\n : null\n}\n", "import fs from 'fs'\nimport { z } from 'zod'\n\nimport { serviceDirectory } from './paths'\n\n// A template is data, not code: `template.json` declares what the template asks the user, what it fixes for\n// them, and which files it writes \u2014 so adding a template never touches `src/`. Everything a manifest can\n// express is validated here; in particular `validate` names a built-in rule rather than shipping a pattern,\n// so a template cannot widen what counts as a legal service id.\n\nexport const SERVICE_ID_PATTERN = /^[a-z][a-z0-9-]*$/\n\n/**\n * The closest legal service id to free text: \"Token Generator\" \u2192 \"token-generator\", \"Caf\u00E9_Bot.v2\" \u2192\n * \"cafe-bot-v2\". Accents are folded, every run of anything else becomes one dash, and leading digits are\n * dropped because an id must start with a letter. Returns '' when nothing usable is left (\"\u65E5\u672C\u8A9E\"), so the\n * caller decides the fallback rather than this inventing one.\n */\nexport function toServiceId(value: string): string {\n return value\n .normalize('NFKD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^[^a-z]+/, '')\n .replace(/-+$/, '')\n}\n\n/**\n * `id` itself when no service uses it, otherwise the first free `id-2`, `id-3`, \u2026 \u2014 for a *suggested* id\n * only. An id the user typed or passed as a flag is never renamed behind their back; it is rejected as taken.\n */\nexport function availableServiceId(id: string, projectRoot: string): string {\n let candidate = id\n\n for (let suffix = 2; fs.existsSync(serviceDirectory(candidate, projectRoot)); suffix++) {\n candidate = `${ id }-${ suffix }`\n }\n\n return candidate\n}\n\nexport interface ValidationContext {\n /** The project being scaffolded into \u2014 an id is only \"taken\" relative to one project. */\n projectRoot: string\n}\n\n/** Returns an error message, or null when the value is acceptable. */\nexport type Validator = (value: string, context: ValidationContext) => string | null\n\nexport const VALIDATORS = {\n // Both halves of \"is this a usable id\" live together, so the prompt can re-ask on either. Availability is\n // checked here rather than at write time so the user finds out while they are still on that question.\n serviceId: (value, context) => {\n if (!SERVICE_ID_PATTERN.test(value)) {\n return 'must start with a lowercase letter and contain only lowercase letters, digits and dashes ' +\n '\u2014 it becomes the folder name and the service id, which is frozen once deployed'\n }\n\n if (fs.existsSync(serviceDirectory(value, context.projectRoot))) {\n return `is already taken \u2014 services/${ value } exists in this project`\n }\n\n return null\n },\n nonEmpty: value => (value.trim().length > 0 ? null : 'must not be empty'),\n} satisfies Record<string, Validator>\n\nexport type ValidatorName = keyof typeof VALIDATORS\n\n/**\n * Rules that can also repair a value, keyed like VALIDATORS. Applied only to what a person types at the\n * prompt \u2014 where they see the result echoed back \u2014 never to a flag, which a script expects to be taken\n * exactly as given or refused.\n */\nexport const NORMALIZERS: Partial<Record<ValidatorName, (value: string) => string>> = {\n serviceId: toServiceId,\n}\n\nconst VALIDATOR_NAMES = Object.keys(VALIDATORS) as [ValidatorName, ...ValidatorName[]]\n\nconst StringPromptSchema = z.object({\n name : z.string().min(1),\n label : z.string().min(1),\n type : z.literal('string'),\n hint : z.string().optional(),\n // May interpolate a value fixed by `values`, a value supplied up front (flag or `--set`), or an answer\n // collected *earlier* in the list: \"{{id}}\", \"{{name|serviceId}}\". A list is a chain of candidates: the\n // first whose placeholders all resolve to something non-empty wins \u2014 `[\"{{id|titleCase}}\", \"My Service\"]`\n // follows an `--id` flag when there is one and falls back to the literal when there is not.\n default : z.union([z.string(), z.array(z.string()).min(1)]).default(''),\n validate: z.enum(VALIDATOR_NAMES).optional(),\n})\n\nconst BooleanPromptSchema = z.object({\n name : z.string().min(1),\n label : z.string().min(1),\n type : z.literal('boolean'),\n hint : z.string().optional(),\n default: z.boolean().default(false),\n})\n\n// `default` must name one of the options \u2014 checked in the registry rather than here, because a refined\n// schema cannot sit inside a discriminated union.\nconst ChoicePromptSchema = z.object({\n name : z.string().min(1),\n label : z.string().min(1),\n type : z.literal('choice'),\n hint : z.string().optional(),\n default: z.string().min(1),\n options: z.array(z.object({\n value : z.string().min(1),\n label : z.string().min(1),\n description: z.string().optional(),\n })).min(2),\n})\n\nexport const PromptSchema = z.discriminatedUnion('type', [\n StringPromptSchema,\n BooleanPromptSchema,\n ChoicePromptSchema,\n])\n\nexport const TemplateFileSchema = z.object({\n from: z.string().min(1),\n to : z.string().min(1),\n /** Name of a boolean answer; the file is written only when that answer is true. */\n when: z.string().min(1).optional(),\n})\n\nexport const TemplateManifestSchema = z.object({\n id : z.string().regex(SERVICE_ID_PATTERN),\n label : z.string().min(1),\n description: z.string().min(1),\n prompts : z.array(PromptSchema).min(1),\n /**\n * Answers the template fixes instead of asking for. Available to the file templates exactly like a\n * prompted answer, and still overridable with `--set name=value`.\n */\n values : z.record(z.string(), z.union([z.string(), z.boolean()])).default({}),\n files : z.array(TemplateFileSchema).min(1),\n})\n\nexport type Prompt = z.infer<typeof PromptSchema>\nexport type TemplateFile = z.infer<typeof TemplateFileSchema>\nexport type TemplateManifest = z.infer<typeof TemplateManifestSchema>\n\nexport type Answers = Record<string, string | boolean>\n\n/** A manifest plus where it was loaded from, so file paths resolve against the right template. */\nexport interface Template {\n manifest: TemplateManifest\n /** Absolute path of the template directory (the one holding `template.json`). */\n directory: string\n /** Whether this is the default template. Decided by the registry, not declared by the manifest. */\n isDefault: boolean\n}\n\n", "import path from 'path'\n\n// Where a service lands in the target project. Shared by the id validator (which has to know whether an id\n// is already taken while the user is still typing it) and the scaffolder (which writes there).\n\nexport const SERVICES_DIRECTORY = 'services'\n\nexport function servicesDirectory(projectRoot: string = process.cwd()): string {\n return path.join(projectRoot, SERVICES_DIRECTORY)\n}\n\nexport function serviceDirectory(serviceId: string, projectRoot: string = process.cwd()): string {\n return path.join(servicesDirectory(projectRoot), serviceId)\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { Answers, Template } from './manifest'\nimport { serviceDirectory as resolveServiceDirectory, servicesDirectory } from './paths'\nimport { render } from './render'\n\n// Files whose bytes must survive untouched. Everything else is rendered as UTF-8 text \u2014 a template is\n// overwhelmingly source, and an icon is the one thing likely to be binary.\nconst BINARY_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.zip', '.woff', '.woff2'])\n\nexport interface RenderedFile {\n /** Path relative to the service directory, e.g. `src/index.js`. */\n relativePath: string\n contents: Buffer\n}\n\nexport interface ScaffoldResult {\n serviceDirectory: string\n files: RenderedFile[]\n createdServicesDirectory: boolean\n}\n\n/**\n * Render every file the template declares, in memory.\n *\n * Nothing touches disk here: a bad placeholder or an unknown flag must fail before the first `mkdir`, or\n * the user is left cleaning up a half-written service directory by hand.\n */\nexport function renderTemplate(template: Template, answers: Answers): RenderedFile[] {\n const filesRoot = path.join(template.directory, 'files')\n const rendered: RenderedFile[] = []\n\n for (const file of template.manifest.files) {\n if (file.when && !answers[file.when]) {\n continue\n }\n\n const source = path.join(filesRoot, file.from)\n const relativePath = render(file.to, answers, `destination of ${ file.from }`)\n\n if (BINARY_EXTENSIONS.has(path.extname(file.from).toLowerCase())) {\n rendered.push({ relativePath, contents: fs.readFileSync(source) })\n\n continue\n }\n\n const contents = render(fs.readFileSync(source, 'utf-8'), answers, `${ template.manifest.id }/files/${ file.from }`)\n\n rendered.push({ relativePath, contents: Buffer.from(contents, 'utf-8') })\n }\n\n return rendered\n}\n\n/**\n * Write a rendered template into `services/<serviceId>/` under `projectRoot`.\n *\n * Refuses an existing service directory outright \u2014 overwriting one would silently discard work, and the\n * service id is frozen once deployed, so a collision is far more likely to be a mistake than an intent.\n */\nexport function scaffoldService(\n template: Template,\n answers: Answers,\n serviceId: string,\n projectRoot: string = process.cwd()\n): ScaffoldResult {\n const files = renderTemplate(template, answers)\n\n const servicesRoot = servicesDirectory(projectRoot)\n const serviceDirectory = resolveServiceDirectory(serviceId, projectRoot)\n\n // The id prompt already refuses a taken id; this is the last line of defence for `--id` on a racing or\n // scripted run, and it keeps `scaffoldService` safe to call on its own.\n if (fs.existsSync(serviceDirectory)) {\n throw new Error(`services/${ serviceId } already exists \u2014 pick another service id, or remove it first.`)\n }\n\n // Second containment check, now against the real destination. The manifest was validated at load time;\n // this catches a `to` path made unsafe by interpolation.\n for (const file of files) {\n const target = path.resolve(serviceDirectory, file.relativePath)\n\n if (target !== serviceDirectory && !target.startsWith(serviceDirectory + path.sep)) {\n throw new Error(`Template \"${ template.manifest.id }\" resolved a path outside the service folder: ${ file.relativePath }`)\n }\n }\n\n const createdServicesDirectory = !fs.existsSync(servicesRoot)\n\n for (const file of files) {\n const target = path.join(serviceDirectory, file.relativePath)\n\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(target, file.contents)\n }\n\n return { serviceDirectory, files, createdServicesDirectory }\n}\n", "import type { Answers } from './manifest'\nimport { toServiceId } from './manifest'\n\n// Template files are stored under their real names (`index.js`, not `index.js.tpl`) so they stay readable\n// and syntax-highlighted while being edited. That constrains the substitution syntax: `{{name}}` only ever\n// appears inside a string literal, and anything structural is gated by a *line comment* pair, which keeps\n// the raw template valid JavaScript.\n//\n// // {{#if useFilesApi}}\n// usesFileStorage: true,\n// // {{/if}}\n//\n// A block may also test a specific value, for answers that are not booleans:\n//\n// // {{#if configMode=full}}\n\nconst PLACEHOLDER = /\\{\\{\\s*([a-zA-Z0-9_]+)\\s*(?:\\|\\s*([a-zA-Z0-9_]+)\\s*)?\\}\\}/g\nconst IF_OPEN = /^\\s*(?:\\/\\/|#|<!--)\\s*\\{\\{#if\\s+([a-zA-Z0-9_]+)\\s*(?:=\\s*([a-zA-Z0-9_.-]+)\\s*)?\\}\\}/\nconst IF_CLOSE = /^\\s*(?:\\/\\/|#|<!--)\\s*\\{\\{\\/if\\s*\\}\\}/\n\nconst FILTERS: Record<string, (value: string) => string> = {\n titleCase: value => value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' '),\n upperCase: value => value.toUpperCase(),\n lowerCase: value => value.toLowerCase(),\n serviceId: toServiceId,\n}\n\nexport function applyFilter(name: string, value: string): string {\n const filter = FILTERS[name]\n\n if (!filter) {\n throw new Error(`Unknown template filter \"${ name }\" \u2014 known filters: ${ Object.keys(FILTERS).join(', ') }`)\n }\n\n return filter(value)\n}\n\n/**\n * Substitute `{{name}}` / `{{name|filter}}` against the answers.\n *\n * An unknown key is an error rather than an empty string: a typo in a template would otherwise ship a\n * silently broken service, and the generated file is the thing a user reads to learn the format.\n */\n/** Whether every placeholder in `source` names a known answer \u2014 i.e. whether `interpolate` would succeed. */\nexport function canInterpolate(source: string, answers: Answers): boolean {\n return [...source.matchAll(PLACEHOLDER)].every(([, name]) => name in answers)\n}\n\nexport function interpolate(source: string, answers: Answers, origin: string): string {\n return source.replace(PLACEHOLDER, (_match, name: string, filter?: string) => {\n if (!(name in answers)) {\n throw new Error(`Unresolved placeholder \"{{${ name }}}\" in ${ origin }`)\n }\n\n const value = String(answers[name])\n\n return filter ? applyFilter(filter, value) : value\n })\n}\n\n/** Drop the lines inside `{{#if flag}}` blocks whose flag is falsy, and the marker lines themselves. */\nexport function stripConditionals(source: string, answers: Answers, origin: string): string {\n const lines = source.split('\\n')\n const output: string[] = []\n const stack: { name: string, keep: boolean }[] = []\n\n for (const [index, line] of lines.entries()) {\n const open = IF_OPEN.exec(line)\n\n if (open) {\n const [, name, expected] = open\n\n if (!(name in answers)) {\n throw new Error(`Unknown flag \"${ name }\" in {{#if}} at ${ origin }:${ index + 1 }`)\n }\n\n // `{{#if name}}` is truthiness; `{{#if name=value}}` compares, for choice answers.\n const matches = expected === undefined\n ? Boolean(answers[name])\n : String(answers[name]) === expected\n\n // A nested block inside a dropped one stays dropped regardless of its own flag.\n stack.push({ name, keep: matches && stack.every(frame => frame.keep) })\n\n continue\n }\n\n if (IF_CLOSE.test(line)) {\n if (!stack.pop()) {\n throw new Error(`Unmatched {{/if}} at ${ origin }:${ index + 1 }`)\n }\n\n continue\n }\n\n if (stack.every(frame => frame.keep)) {\n output.push(line)\n }\n }\n\n if (stack.length > 0) {\n throw new Error(`Unclosed {{#if ${ stack[stack.length - 1].name }}} in ${ origin }`)\n }\n\n return output.join('\\n')\n}\n\n/** Full render of one template file: conditionals first, so a dropped block's placeholders never resolve. */\nexport function render(source: string, answers: Answers, origin: string): string {\n return interpolate(stripConditionals(source, answers, origin), answers, origin)\n}\n", "import { PromptAbortedError, PromptRequiredError } from '../../errors'\nimport type { Answers, Prompt, ValidationContext } from '../../templates/manifest'\nimport { availableServiceId, NORMALIZERS, VALIDATORS } from '../../templates/manifest'\nimport { canInterpolate, interpolate } from '../../templates/render'\n\n// Turning a template's declared prompts into a complete set of answers, without asking anybody anything.\n//\n// Everything that can be decided from what the caller already supplied \u2014 a prefill, a fixed value, a\n// default \u2014 is decided here. Only a prompt with no answer left needs a human, and that goes out through\n// `ask`. A caller with no `ask` gets PromptRequiredError naming the prompt, which is what makes a scripted\n// or programmatic scaffold possible: supply every answer and nothing ever needs a terminal.\n\n/** Shared with the standalone confirmations in `cli/prompts/confirm`, so both read a yes/no the same way. */\nexport const TRUTHY = ['y', 'yes', 'true', '1']\nexport const FALSY = ['n', 'no', 'false', '0']\n\nexport interface AskRequest {\n prompt: Prompt\n /** What the answer would be if the user just pressed Enter. */\n fallback: string | boolean\n /** Returns a message to show before asking again, or null when the value is acceptable. */\n validate: (value: string) => string | null\n /**\n * Repairs what the user typed into the closest acceptable value (\"Token Generator\" \u2192 \"token-generator\"),\n * or returns it unchanged. Run before `validate`; the asker should show the user a value it changed.\n */\n normalize: (value: string) => string\n}\n\nexport type Ask = (request: AskRequest) => Promise<string | boolean>\n\nexport interface ResolveAnswersOptions {\n /** Pre-supplied answers (CLI flags). A prompt with a prefill is not asked. */\n prefilled?: Answers\n /** Answers the template fixes rather than asking for \u2014 see `values` in the manifest. */\n constants?: Answers\n /** Ask nothing; take every default. */\n acceptDefaults?: boolean\n /** The project being scaffolded into; validators need it to tell whether an id is taken. */\n projectRoot?: string\n /** How to ask a human. Omitted means nothing can be asked, and an unanswered prompt is an error. */\n ask?: Ask\n}\n\n/**\n * Resolve a prompt's declared default, which may interpolate the answers known so far.\n *\n * A list default is tried in order and the first candidate that resolves to something non-empty wins. When\n * none does, the last one is interpolated anyway \u2014 an unresolvable placeholder then fails with the same\n * error a single-string default would, rather than being swallowed into an empty answer.\n */\nexport function resolveDefault(prompt: Prompt, answers: Answers): string | boolean {\n if (prompt.type === 'boolean' || prompt.type === 'choice') {\n return prompt.default\n }\n\n const origin = `default of \"${ prompt.name }\"`\n const candidates = Array.isArray(prompt.default) ? prompt.default : [prompt.default]\n\n for (const candidate of candidates) {\n const value = canInterpolate(candidate, answers) ? interpolate(candidate, answers, origin) : ''\n\n if (value) {\n return value\n }\n }\n\n return interpolate(candidates[candidates.length - 1], answers, origin)\n}\n\n/**\n * A prefill arrives as a raw string when it came from a flag; anything boolean has to interpret it.\n *\n * Skipping this for a fixed value would be quietly wrong rather than merely untidy: `--set flag=false`\n * would store the STRING \"false\", which is truthy, and the `{{#if flag}}` block would survive.\n */\nexport function coerceBoolean(label: string, value: string | boolean): boolean {\n if (typeof value === 'boolean') {\n return value\n }\n\n const normalized = value.trim().toLowerCase()\n\n if (TRUTHY.includes(normalized)) {\n return true\n }\n\n if (FALSY.includes(normalized)) {\n return false\n }\n\n throw new PromptAbortedError(`${ label }: expected true or false, got \"${ value }\"`)\n}\n\nfunction validator(prompt: Prompt, context: ValidationContext): (value: string) => string | null {\n return value => {\n if (prompt.type !== 'string' || !prompt.validate) {\n return null\n }\n\n const failure = VALIDATORS[prompt.validate](value, context)\n\n return failure && `${ prompt.label } ${ failure }`\n }\n}\n\nfunction normalizer(prompt: Prompt): (value: string) => string {\n const normalize = prompt.type === 'string' && prompt.validate ? NORMALIZERS[prompt.validate] : undefined\n\n return normalize ?? (value => value)\n}\n\n/**\n * The default offered to a person. A suggested service id that is already taken is moved on to the next\n * free one, so Enter still works on a second scaffold in the same project. Only the *offer* changes:\n * under `--yes` nobody sees it, so a taken default is still refused there rather than quietly renamed.\n */\nfunction offeredDefault(prompt: Prompt, fallback: string | boolean, context: ValidationContext): string | boolean {\n if (prompt.type === 'string' && prompt.validate === 'serviceId' && typeof fallback === 'string' && fallback) {\n return availableServiceId(fallback, context.projectRoot)\n }\n\n return fallback\n}\n\n/** Run a template's declared prompts in order, honouring prefills and `--yes`. */\nexport async function resolveAnswers(\n prompts: Prompt[],\n {\n prefilled = {},\n constants = {},\n acceptDefaults = false,\n projectRoot = process.cwd(),\n ask,\n }: ResolveAnswersOptions = {}\n): Promise<Answers> {\n const context: ValidationContext = { projectRoot }\n // Fixed values first, so a prompt default may interpolate one; a prompt of the same name wins over it.\n const answers: Answers = { ...constants }\n // What the caller supplied for prompts is known before anything is asked, so it is visible to the\n // defaults of *earlier* prompts too: the name is asked before the id, yet `--id acme-crm` should still\n // make \"Acme Crm\" the name on offer. Each prefill is still validated when its own prompt comes up.\n const prefilledDefaults: Answers = {}\n\n // A prefill naming neither a prompt nor a fixed value is a typo, not a no-op \u2014 silently ignoring it\n // would hand the user a service that quietly differs from what they asked for.\n const known = [...prompts.map(prompt => prompt.name), ...Object.keys(constants)]\n const unknown = Object.keys(prefilled).filter(name => !known.includes(name))\n\n if (unknown.length > 0) {\n throw new PromptAbortedError(\n `This template has no setting named ${ unknown.map(name => `\"${ name }\"`).join(', ') }. ` +\n `It accepts: ${ known.join(', ') }`\n )\n }\n\n for (const prompt of prompts) {\n if (prompt.name in prefilled && prompt.type === 'string') {\n prefilledDefaults[prompt.name] = String(prefilled[prompt.name])\n }\n }\n\n for (const prompt of prompts) {\n const fallback = resolveDefault(prompt, { ...prefilledDefaults, ...answers })\n const validate = validator(prompt, context)\n\n if (prompt.name in prefilled) {\n const supplied = prefilled[prompt.name]\n\n if (prompt.type === 'boolean') {\n answers[prompt.name] = coerceBoolean(prompt.label, supplied)\n\n continue\n }\n\n if (prompt.type === 'choice') {\n const values = prompt.options.map(option => option.value)\n\n if (!values.includes(String(supplied))) {\n throw new PromptAbortedError(`${ prompt.label }: \"${ supplied }\" is not one of ${ values.join(', ') }`)\n }\n\n answers[prompt.name] = String(supplied)\n\n continue\n }\n\n const failure = validate(String(supplied))\n\n if (failure) {\n throw new PromptAbortedError(failure)\n }\n\n answers[prompt.name] = String(supplied)\n\n continue\n }\n\n if (acceptDefaults) {\n // Validated like any other answer: under `--yes` a default service id can still be taken, and the\n // failure should read the same as it would have when typed.\n const failure = typeof fallback === 'string' ? validate(fallback) : null\n\n if (failure) {\n throw new PromptAbortedError(failure)\n }\n\n answers[prompt.name] = fallback\n\n continue\n }\n\n if (!ask) {\n throw new PromptRequiredError(\n prompt.name,\n `\"${ prompt.name }\" has no answer and there is no way to ask for one. ` +\n 'Supply it up front, or accept the defaults.'\n )\n }\n\n answers[prompt.name] = await ask({\n prompt,\n fallback : offeredDefault(prompt, fallback, context),\n validate,\n normalize: normalizer(prompt),\n })\n }\n\n // A `--set` for a fixed value overrides it; prompts have already had their turn above. The manifest's\n // own value tells us the intended type, so a boolean stays a boolean.\n for (const [name, value] of Object.entries(prefilled)) {\n if (prompts.some(prompt => prompt.name === name)) {\n continue\n }\n\n answers[name] = typeof constants[name] === 'boolean' ? coerceBoolean(name, value) : value\n }\n\n return answers\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport { PROJECT_FILES_DIRECTORY, TESTING_FILES } from '../../constants'\nimport { packageRoot } from '../../templates/package-root'\n\n// Copying the unit-test harness into a project.\n//\n// The harness is *copied*, not imported from the installed package, and that is the whole design. A test\n// harness is something a project owns: a service wrapping an awkward SDK needs a shim inside the HTTP mock,\n// and a project with its own conventions will want its own `jest.config.js`. A copy can be read and edited;\n// a module behind a package export cannot. The cost is that a copy does not move with the CLI \u2014 which is\n// why `init` is additive and safe to re-run, and why a project created before this existed picks the\n// harness up by running `flowrunner init` again.\n//\n// Nothing is overwritten, for the same reason as everywhere else in `init`: a customer's edit to their own\n// jest config must survive a command they ran for an unrelated reason.\n\nexport interface TestingFilesResult {\n created: string[]\n skipped: string[]\n}\n\n/** Where the shipped harness lives inside the installed package. */\nexport function testingFilesDirectory(): string {\n return path.join(packageRoot(), PROJECT_FILES_DIRECTORY)\n}\n\n/**\n * Copy the harness into `projectRoot`, leaving any file that is already there alone.\n *\n * Reports what it did per file so `init` can print the same `+ file` / `file \u2014 already there` lines it\n * prints for everything else it writes.\n */\nexport function writeTestingFiles(projectRoot: string): TestingFilesResult {\n const source = testingFilesDirectory()\n\n const created: string[] = []\n const skipped: string[] = []\n\n for (const file of TESTING_FILES) {\n const target = path.join(projectRoot, file)\n\n if (fs.existsSync(target)) {\n skipped.push(file)\n\n continue\n }\n\n const contents = fs.readFileSync(path.join(source, file))\n\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(target, contents)\n\n created.push(file)\n }\n\n return { created, skipped }\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { ProviderLayout } from '../../constants'\nimport {\n AI_PROVIDERS_DIRECTORY,\n CLAUDE_PROVIDER,\n ORCHESTRATOR_SEGMENT_FILE,\n PROVIDER_AGENTS_DIRECTORY,\n PROVIDERS,\n} from '../../constants'\nimport { AiDocsMissingError } from '../../errors'\nimport { packageRoot } from '../../templates/package-root'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport type { SegmentOutcome } from './segment'\nimport { mergeSegment } from './segment'\n\n// `init-claude` connects a project to the FlowRunner agent instructions the CLI ships.\n//\n// Which files it writes, and where, comes from the provider layout in `constants/providers.ts` \u2014 Claude Code\n// reads `CLAUDE.md` and not `AGENTS.md`, and the next provider will differ again, so that knowledge is data\n// rather than something `init` could write once for everyone.\n//\n// Two halves, and they differ in who owns the file. The agent definitions under the provider's agents\n// directory are the CLI's: they are named `flowrunner-service-*`, they mean nothing without the instructions\n// they point at, and refreshing them on every run is the point of the command \u2014 so they are overwritten. The\n// provider's instructions file is the project's, and only the region between the CLI's own markers is ever\n// rewritten (see `segment.ts`).\n\nexport type InitClaudeEvent =\n | { type: 'agents'; directory: string; created: string[]; updated: string[]; unchanged: string[] }\n | { type: 'segment'; file: string; outcome: SegmentOutcome }\n | { type: 'warning'; message: string }\n\nexport type InitClaudeOptions = OperationOptions<InitClaudeEvent>\n\nexport interface InitClaudeResult {\n projectRoot: string\n /** Absolute path of the provider's agents directory. */\n agentsDirectory: string\n /** Agent file names, relative to `agentsDirectory`. */\n created: string[]\n updated: string[]\n unchanged: string[]\n /** Absolute path of the provider's instructions file. */\n claudeFile: string\n segment: SegmentOutcome\n}\n\n/** Where the packed docs for a provider live inside the installed package. */\nexport function providerDirectory(provider: string = CLAUDE_PROVIDER): string {\n return path.join(packageRoot(), AI_PROVIDERS_DIRECTORY, provider)\n}\n\n/**\n * The agent definitions the installed package ships, sorted so the reported list is stable.\n *\n * Only top-level `.md` files: an agent definition is one file, and anything else in there is not one.\n */\nfunction packedAgents(directory: string): string[] {\n if (!fs.existsSync(directory)) {\n return []\n }\n\n return fs.readdirSync(directory, { withFileTypes: true })\n .filter(entry => entry.isFile() && entry.name.endsWith('.md'))\n .map(entry => entry.name)\n .sort()\n}\n\n/**\n * Write the shipped agent definitions into `.claude/agents/`.\n *\n * Overwrites. These files are CLI-owned \u2014 a customer editing one would have it replaced by the next\n * `init-claude`, which is the same deal as any other generated file, and the alternative (skip what exists)\n * makes the command unable to ship a fix. Identical content is reported as `unchanged` rather than written,\n * so a re-run does not churn mtimes for no reason.\n */\nfunction writeAgents(sourceDirectory: string, projectRoot: string, layout: ProviderLayout): {\n directory: string\n created: string[]\n updated: string[]\n unchanged: string[]\n warnings: string[]\n} {\n const directory = path.join(projectRoot, layout.agentsDirectory)\n const agents = packedAgents(sourceDirectory)\n\n const created: string[] = []\n const updated: string[] = []\n const unchanged: string[] = []\n const warnings: string[] = []\n\n if (agents.length === 0) {\n warnings.push(`The installed CLI ships no agent definitions in ${ PROVIDER_AGENTS_DIRECTORY }/ \u2014 none were written.`)\n\n return { directory, created, updated, unchanged, warnings }\n }\n\n fs.mkdirSync(directory, { recursive: true })\n\n for (const agent of agents) {\n const contents = fs.readFileSync(path.join(sourceDirectory, agent), 'utf-8')\n const target = path.join(directory, agent)\n\n if (contents.length === 0) {\n // Shipped-but-unwritten: the file still lands, so the wiring is in place and filling it later is a\n // CLI upgrade rather than another manual step. Saying so is what stops it looking like a broken agent.\n warnings.push(`${ agent } is empty in the installed CLI \u2014 written as an empty file.`)\n }\n\n if (!fs.existsSync(target)) {\n fs.writeFileSync(target, contents, 'utf-8')\n created.push(agent)\n\n continue\n }\n\n if (fs.readFileSync(target, 'utf-8') === contents) {\n unchanged.push(agent)\n\n continue\n }\n\n fs.writeFileSync(target, contents, 'utf-8')\n updated.push(agent)\n }\n\n return { directory, created, updated, unchanged, warnings }\n}\n\n/** Merge the orchestrator segment into the provider's own instructions file. */\nfunction writeSegment(sourceDirectory: string, projectRoot: string, layout: ProviderLayout): {\n file: string\n outcome: SegmentOutcome\n warnings: string[]\n} {\n const file = path.join(projectRoot, layout.instructionsFile)\n const source = path.join(sourceDirectory, ORCHESTRATOR_SEGMENT_FILE)\n const warnings: string[] = []\n\n if (!fs.existsSync(source)) {\n warnings.push(`The installed CLI ships no ${ ORCHESTRATOR_SEGMENT_FILE } \u2014 ${ layout.instructionsFile } was left alone.`)\n\n return { file, outcome: 'unchanged', warnings }\n }\n\n const segment = fs.readFileSync(source, 'utf-8')\n\n if (segment.trim().length === 0) {\n warnings.push(`${ ORCHESTRATOR_SEGMENT_FILE } is empty in the installed CLI \u2014 the marked block is empty.`)\n }\n\n const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf-8') : null\n const merged = mergeSegment(current, segment, layout.instructionsFile)\n\n if (merged.outcome !== 'unchanged') {\n fs.writeFileSync(file, merged.contents, 'utf-8')\n }\n\n return { file, outcome: merged.outcome, warnings }\n}\n\n/**\n * Wire the shipped FlowRunner agent instructions into a project's Claude setup.\n *\n * Deliberately does not require a FlowRunner project: someone can reasonably run this in a repo before\n * `init`, and refusing would be a rule with nothing behind it \u2014 nothing here reads `flowrunner.json`.\n */\nexport async function initClaude(options: InitClaudeOptions = {}): Promise<InitClaudeResult> {\n const projectRoot = path.resolve(options.cwd ?? '.')\n const emit = emitter(options)\n // Each event first, then the warnings about it: a warning printed before its own heading reads as a\n // warning about whatever came before.\n const warnAll = (messages: string[]) => messages.forEach(message => emit({ type: 'warning', message }))\n\n const layout = PROVIDERS[CLAUDE_PROVIDER]\n const sourceDirectory = providerDirectory(layout.id)\n\n if (!fs.existsSync(sourceDirectory)) {\n throw new AiDocsMissingError(path.join(AI_PROVIDERS_DIRECTORY, CLAUDE_PROVIDER))\n }\n\n if (!fs.existsSync(projectRoot)) {\n fs.mkdirSync(projectRoot, { recursive: true })\n }\n\n const agents = writeAgents(path.join(sourceDirectory, PROVIDER_AGENTS_DIRECTORY), projectRoot, layout)\n\n emit({\n type : 'agents',\n directory: agents.directory,\n created : agents.created,\n updated : agents.updated,\n unchanged: agents.unchanged,\n })\n\n warnAll(agents.warnings)\n\n const segment = writeSegment(sourceDirectory, projectRoot, layout)\n\n emit({ type: 'segment', file: segment.file, outcome: segment.outcome })\n\n warnAll(segment.warnings)\n\n return {\n projectRoot,\n agentsDirectory: agents.directory,\n created : agents.created,\n updated : agents.updated,\n unchanged : agents.unchanged,\n claudeFile : segment.file,\n segment : segment.outcome,\n }\n}\n\nexport type { MergeResult, SegmentOutcome } from './segment'\nexport { BEGIN_MARKER, END_MARKER, mergeSegment } from './segment'\n", "// Merging one block of text into a file somebody else owns.\n//\n// `CLAUDE.md` belongs to the project, not to this CLI. It will hold a team's own instructions, and it will\n// be edited by hand between runs \u2014 so the segment cannot simply be written, and it cannot be appended twice.\n// Markers give the CLI a region it owns inside a file it does not: everything between them is replaced on\n// every run, everything outside them is never touched.\n\n// The exact strings matter: projects generated before this command carry these markers already, so matching\n// them is what makes `init-claude` *replace* an existing block there rather than append a second one.\nexport const BEGIN_MARKER = '<!-- flowrunner-cli:ai:start -->'\nexport const END_MARKER = '<!-- flowrunner-cli:ai:end -->'\n\n/**\n * What happened to the file.\n *\n * `inserted` and `replaced` are kept apart because they answer different questions: the first says the CLI\n * added something to a file that was already there, the second says it refreshed what it had added before.\n */\nexport type SegmentOutcome = 'created' | 'inserted' | 'replaced' | 'unchanged'\n\nexport interface MergeResult {\n contents: string\n outcome: SegmentOutcome\n}\n\n/** The owned region, marker lines included. */\nfunction block(segment: string): string {\n return `${ BEGIN_MARKER }\\n${ segment.trimEnd() }\\n${ END_MARKER }\\n`\n}\n\n/**\n * Compute the new contents of an instructions file with `segment` merged into it.\n *\n * Pure \u2014 takes the current contents (`null` when the file does not exist) and returns the new ones, so the\n * decision of what to write is testable without a filesystem, and the caller stays the only thing that\n * touches disk.\n *\n * An unbalanced marker pair throws. A half-marked file is either a bad hand-edit or a merge conflict\n * someone resolved wrongly, and both readings of \"repair it\" \u2014 treat the file as unmarked and append a\n * second block, or guess where the missing marker went \u2014 silently damage the user's own instructions.\n */\nexport function mergeSegment(current: string | null, segment: string, file: string): MergeResult {\n const marked = block(segment)\n\n if (current === null) {\n return { contents: marked, outcome: 'created' }\n }\n\n const begin = current.indexOf(BEGIN_MARKER)\n const end = current.indexOf(END_MARKER)\n\n if (begin === -1 && end === -1) {\n // A blank line between their content and ours, and never a second one.\n const separator = current.length === 0 ? '' : current.endsWith('\\n\\n') ? '' : current.endsWith('\\n') ? '\\n' : '\\n\\n'\n\n return { contents: `${ current }${ separator }${ marked }`, outcome: 'inserted' }\n }\n\n if (begin === -1 || end === -1 || end < begin) {\n throw new Error(\n `${ file } has an unbalanced flowrunner-cli marker pair. ` +\n `Restore both \"${ BEGIN_MARKER }\" and \"${ END_MARKER }\", or delete them and run this again.`\n )\n }\n\n const before = current.slice(0, begin)\n const after = current.slice(end + END_MARKER.length).replace(/^\\n/, '')\n const contents = `${ before }${ marked }${ after }`\n\n return { contents, outcome: contents === current ? 'unchanged' : 'replaced' }\n}\n", "import http from 'http'\n\nimport { callbackRoute } from './routes/callback'\nimport type { Route } from './types'\n\n// The CLI's own HTTP server. Today it exists for one reason \u2014 receiving the authorization redirect that a\n// browser cannot deliver any other way \u2014 but it is a route table rather than a single handler, so the next\n// thing that needs a local endpoint adds a file under `routes/` and one entry to the array.\n//\n// It always listens on a random free port on localhost. A fixed port would collide with whatever else the\n// developer is running, and binding anywhere but localhost would put an open endpoint on their network.\n\nexport { callbackRoute } from './routes/callback'\nexport type { Route, RouteContext } from './types'\n\nexport interface LocalServer {\n port: number\n close: () => void\n}\n\nexport function startLocalServer(routes: Route[]): Promise<LocalServer> {\n return new Promise((resolve, reject) => {\n const server = http.createServer((req, res) => {\n const url = new URL(req.url || '/', 'http://localhost')\n const route = routes.find(entry => entry.method === req.method && entry.path === url.pathname)\n\n if (!route) {\n res.writeHead(404)\n res.end()\n\n return\n }\n\n route.handle({ req, res, url })\n })\n\n server.listen(0, 'localhost', () => {\n const address = server.address()\n\n if (!address || typeof address === 'string') {\n reject(new Error('Failed to start the local callback server'))\n\n return\n }\n\n resolve({\n port: address.port,\n // `close()` alone only stops listening: the browser's keep-alive socket would hold the event loop\n // open, which is survivable for a command that exits straight after but not for one that carries on\n // into a deploy.\n close: () => {\n server.closeAllConnections?.()\n server.close()\n },\n })\n })\n\n server.on('error', reject)\n })\n}\n\nexport interface CallbackServer extends LocalServer {\n /** Resolves with the exchange code the console redirects back with. */\n waitForCode: () => Promise<string>\n}\n\n/** The one composition the login needs: a server whose only route is the authorization callback. */\nexport async function startCallbackServer(): Promise<CallbackServer> {\n const { route, waitForCode } = callbackRoute()\n const server = await startLocalServer([route])\n\n return { ...server, waitForCode }\n}\n", "// The two pages the browser lands on at the end of an authorization. They are the last thing the user sees\n// before switching back to the terminal, so they say which window to close and nothing else.\n\nconst PAGE_STYLES = `\n *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }\n body { font-family: Inter, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif; font-size: 14px; background: #F3F4F6; color: #111827; display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 16px; }\n .card { background: #fff; border-radius: 16px; box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075); width: 100%; max-width: 420px; padding: 32px; text-align: center; }\n .brand { font-size: 20px; font-weight: 700; color: #7f7fed; margin-bottom: 24px; }\n .icon { width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px; font-size: 24px; }\n .icon-success { background: rgba(16,185,129,0.1); color: #10B981; }\n .icon-error { background: rgba(220,38,38,0.1); color: #DC2626; }\n h1 { font-size: 20px; font-weight: 600; margin-bottom: 8px; }\n p { font-size: 14px; color: #6B7280; line-height: 1.5; }\n p + p { margin-top: 4px; }\n`\n\nexport const SUCCESS_HTML = `<!DOCTYPE html>\n<html><head><meta charset=\"UTF-8\"><title>Authorized \u2014 FlowRunner CLI</title>\n<style>${PAGE_STYLES}</style>\n</head><body>\n<div class=\"card\">\n <div class=\"brand\">FlowRunner</div>\n <div class=\"icon icon-success\">&#10003;</div>\n <h1>Authorization Successful</h1>\n <p>You can close this window and return to the terminal.</p>\n</div>\n</body></html>`\n\nexport const ERROR_HTML = (error: string) => `<!DOCTYPE html>\n<html><head><meta charset=\"UTF-8\"><title>Authorization Failed \u2014 FlowRunner CLI</title>\n<style>${PAGE_STYLES}</style>\n</head><body>\n<div class=\"card\">\n <div class=\"brand\">FlowRunner</div>\n <div class=\"icon icon-error\">&#10007;</div>\n <h1>Authorization Failed</h1>\n <p>${error}</p>\n <p>You can close this window and try again.</p>\n</div>\n</body></html>`\n", "import { ERROR_HTML, SUCCESS_HTML } from '../pages'\nimport type { Route } from '../types'\n\n// Where the console sends the browser once the user has authorized the CLI and picked a workspace. The\n// request carries either an exchange code or an error; both end the wait, and both render a page telling\n// the user they can close the window.\n\nexport interface CallbackRoute {\n route: Route\n waitForCode: () => Promise<string>\n}\n\nexport function callbackRoute(path = '/callback'): CallbackRoute {\n let resolveCode: ((code: string) => void) | null = null\n let rejectCode: ((error: Error) => void) | null = null\n\n const respond = (route: Parameters<Route['handle']>[0], html: string) => {\n route.res.writeHead(200, { 'Content-Type': 'text/html' })\n route.res.end(html)\n }\n\n const route: Route = {\n method: 'GET',\n path,\n handle: context => {\n const code = context.url.searchParams.get('code')\n const error = context.url.searchParams.get('error')\n\n if (error) {\n respond(context, ERROR_HTML(error))\n rejectCode?.(new Error(error))\n\n return\n }\n\n if (!code) {\n respond(context, ERROR_HTML('Missing exchange code'))\n rejectCode?.(new Error('Missing exchange code'))\n\n return\n }\n\n respond(context, SUCCESS_HTML)\n resolveCode?.(code)\n },\n }\n\n return {\n route,\n waitForCode: () => new Promise<string>((resolve, reject) => {\n resolveCode = resolve\n rejectCode = reject\n }),\n }\n}\n", "/** Hand a URL to whatever the operating system considers the browser. */\nexport function openBrowser(url: string): void {\n // eslint-disable-next-line @typescript-eslint/consistent-type-imports\n const { exec } = require('child_process') as typeof import('child_process')\n\n const command = process.platform === 'darwin'\n ? `open \"${ url }\"`\n : process.platform === 'win32'\n ? `start \"${ url }\"`\n : `xdg-open \"${ url }\"`\n\n // Detached from this process's lifetime: whether the browser is still open has nothing to do with whether\n // the CLI is finished, and an unreaped child handle would keep it running.\n exec(command).unref()\n}\n", "import { authorizeUrl, exchangeCodeForToken } from '../api/console-client'\nimport { LoginTimeoutError } from '../errors'\nimport { saveAuth } from '../project/auth'\nimport { getServerUrl, getWorkspaceId } from '../project/config'\nimport { startCallbackServer } from '../server'\nimport { openBrowser } from '../utils/open-browser'\nimport { normalizeServerUrl, resolveServerTarget } from './server-target'\nimport type { OperationOptions } from './types'\nimport { emitter } from './types'\n\n// Connecting a project to a workspace: stand up a local callback server, send the user to the console to\n// authorize, trade the code it redirects back with for a deploy token, write both down.\n//\n// The browser is the part that makes this awkward to automate, so it is behind `openUrl`: the default hands\n// the URL to the operating system, and a caller that wants to do something else \u2014 print it, drive a headless\n// browser, ignore it \u2014 passes their own and reads the URL off the `authorize` event.\n\nconst DEFAULT_TIMEOUT_MS = 2 * 60 * 1000\n\nexport type LoginEvent =\n | { type: 'connecting'; serverUrl: string }\n | { type: 'authorize'; url: string }\n | { type: 'waiting' }\n | { type: 'exchanging' }\n | { type: 'connected'; serverUrl: string; workspaceId: string; workspaceName: string }\n\nexport interface LoginOptions extends OperationOptions<LoginEvent> {\n /** Overrides the server in `flowrunner.json`. A cluster name (`prod`/`dev`/`local`) or a full URL. */\n server?: string\n /** How long to wait for the browser round-trip. */\n timeoutMs?: number\n /**\n * Called with the authorization URL after it is known and before `openUrl` runs.\n *\n * The CLI waits for Enter here when the login is a step inside another command: a browser window taking\n * focus out of nowhere, mid-deploy, is startling in a way that one typed `flowrunner login` is not.\n */\n onBeforeOpen?: (url: string) => Promise<void>\n /** How the user gets the URL. Defaults to opening their browser. */\n openUrl?: (url: string) => void | Promise<void>\n}\n\nexport interface LoginResult {\n serverUrl: string\n workspaceId: string\n workspaceName: string\n}\n\nexport async function login(options: LoginOptions = {}): Promise<LoginResult> {\n const projectRoot = options.cwd ?? process.cwd()\n const emit = emitter(options)\n\n // Never empty: `getServerUrl` falls back to the environment and then to DEFAULT_SERVER_URL, so a project\n // that has never been logged in \u2014 one with no flowrunner.json at all \u2014 still has somewhere to go.\n const serverUrl = options.server\n ? resolveServerTarget(options.server)\n : normalizeServerUrl(getServerUrl(projectRoot))\n\n // Pre-selects the workspace the project is already attached to. The page still offers \"use another\n // workspace\", so `flowrunner login` is also how you move a connected project somewhere else.\n const existingWorkspaceId = getWorkspaceId(projectRoot)\n\n emit({ type: 'connecting', serverUrl })\n\n const server = await startCallbackServer()\n const callbackUrl = `http://localhost:${ server.port }/callback`\n\n try {\n const authUrl = authorizeUrl({ serverUrl, callbackUrl, workspaceId: existingWorkspaceId })\n\n emit({ type: 'authorize', url: authUrl })\n\n await options.onBeforeOpen?.(authUrl)\n await (options.openUrl ?? openBrowser)(authUrl)\n\n emit({ type: 'waiting' })\n\n // The timer has to be cleared, not just lost: a pending two-minute timeout keeps the event loop alive,\n // so the CLI would sit there doing nothing after a successful login \u2014 invisible while this command\n // ended in `process.exit`, and a hang once a deploy runs after it.\n let timeout: NodeJS.Timeout | undefined\n\n const exchangeCode = await Promise.race([\n server.waitForCode(),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new LoginTimeoutError()), options.timeoutMs ?? DEFAULT_TIMEOUT_MS)\n }),\n ]).finally(() => clearTimeout(timeout))\n\n emit({ type: 'exchanging' })\n\n const { token, workspaceId, workspaceName } = await exchangeCodeForToken(serverUrl, exchangeCode)\n\n saveAuth({ serverUrl, workspaceId, deployToken: token, workspaceName }, projectRoot)\n\n emit({ type: 'connected', serverUrl, workspaceId, workspaceName: workspaceName || '' })\n\n return { serverUrl, workspaceId, workspaceName: workspaceName || '' }\n } finally {\n server.close()\n }\n}\n", "import { revokeToken } from '../api/console-client'\nimport { clearAuth, loadAuth } from '../project/auth'\nimport type { OperationOptions } from './types'\nimport { emitter } from './types'\n\nexport type LogoutEvent =\n /** Emitted once there is something to log out of, before the revoke goes over the network. */\n | { type: 'starting'; serverUrl: string }\n | { type: 'revoked' }\n | { type: 'cleared' }\n\nexport type LogoutOptions = OperationOptions<LogoutEvent>\n\nexport interface LogoutResult {\n /** False when there was nothing to log out of \u2014 not an error, just nothing to do. */\n wasLoggedIn: boolean\n /** The server the revoked token belonged to, when there was one. */\n serverUrl?: string\n}\n\nexport async function logout(options: LogoutOptions = {}): Promise<LogoutResult> {\n const projectRoot = options.cwd ?? process.cwd()\n const emit = emitter(options)\n const stored = loadAuth(projectRoot)\n\n if (!stored) {\n return { wasLoggedIn: false }\n }\n\n emit({ type: 'starting', serverUrl: stored.serverUrl })\n\n // Best effort, and deliberately not fatal: the local token is being deleted either way, and a revoke that\n // never reached the server is not a reason to leave the user still looking logged in.\n await revokeToken(stored.serverUrl, stored.deployToken)\n\n emit({ type: 'revoked' })\n\n clearAuth(projectRoot)\n\n emit({ type: 'cleared' })\n\n return { wasLoggedIn: true, serverUrl: stored.serverUrl }\n}\n", "import AdmZip from 'adm-zip'\nimport fs from 'fs'\nimport path from 'path'\n\nimport type { RemoteService } from '../../api/console-client'\nimport { downloadRemoteService, listRemoteServices } from '../../api/console-client'\nimport {\n HttpError,\n NotLoggedInError,\n NoWorkspaceError,\n SelectionRequiredError,\n TokenExpiredError,\n UnknownServiceError,\n} from '../../errors'\nimport type { AuthGap, StoredAuth } from '../../project/auth'\nimport { authGap, loadAuth } from '../../project/auth'\nimport { computeServiceHash } from '../deploy/hash'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport { declaredDependencies, extractService, isSafeServiceId } from './extract'\n\nexport { declaredDependencies, extractService, isSafeServiceId } from './extract'\n\n// Pulling: bring the workspace's services down into this project so they can be edited and deployed back.\n//\n// The mirror image of deploying, and it has to be, now that a workspace collects services from any number of\n// projects: a fresh checkout can connect to a workspace and get whatever is live there, whoever deployed it.\n//\n// A service is self-contained, so what lands on disk is nearly the whole archive \u2014 source, icons, and the\n// service's own `package.json`. Only `node_modules` stays behind, because `npm install` rebuilds it; a\n// service that declares dependencies is reported as needing one rather than having it run for it.\n\n/**\n * What the local copy of a service is, relative to the deployed one.\n *\n * Decided on `sourceHash`, which covers the service folder and nothing else \u2014 so the answer holds wherever\n * the service is checked out, and \"same version\" and \"same code\" are the same question.\n */\nexport type LocalState = 'absent' | 'same' | 'different'\n\nexport type PullEvent =\n | { type: 'listed'; services: RemoteService[]; workspace: Workspace }\n | { type: 'selected'; services: RemoteService[] }\n | { type: 'up-to-date'; serviceId: string; sourceHash: string }\n | { type: 'skipped'; serviceId: string; reason: string }\n | { type: 'pulled'; serviceId: string; sourceHash: string; files: number; directory: string }\n | { type: 'install-needed'; serviceId: string; dependencies: string[] }\n\nexport interface Workspace {\n workspaceId: string\n workspaceName: string\n}\n\nexport interface PullOptions extends OperationOptions<PullEvent> {\n /** Service ids to pull. Wins over `all`. */\n serviceIds?: string[]\n /** Pull every service in the workspace. */\n all?: boolean\n /** Overwrite `services/<id>/` when it already exists. Without this, existing folders are left alone. */\n force?: boolean\n onAuthRequired?: (gap: AuthGap) => Promise<void>\n onSelectionRequired?: (available: RemoteService[]) => Promise<{ serviceIds?: string[]; all?: boolean }>\n}\n\nexport interface PulledService {\n serviceId: string\n serviceName: string\n sourceHash: string\n files: number\n directory: string\n /** What the service declares. Non-empty means `npm install` is needed in its folder before it will run. */\n dependencies: string[]\n}\n\nexport interface PullResult {\n workspace: Workspace\n serverUrl: string\n /** Services written to disk. */\n services: PulledService[]\n /** Already identical to what is deployed \u2014 nothing to download, nothing to write. */\n upToDate: { serviceId: string; serviceName: string; sourceHash: string }[]\n /** Selected but not written: a local copy that differs, without `--force`. */\n skipped: { serviceId: string; reason: string }[]\n}\n\n/**\n * How the local `services/<id>/` compares to the deployed service.\n *\n * A folder that is not there is `absent`; anything else is decided on the hash a deploy would produce.\n */\nexport async function localState(\n projectRoot: string,\n service: RemoteService\n): Promise<LocalState> {\n if (!fs.existsSync(path.resolve(projectRoot, 'services', service.serviceId))) {\n return 'absent'\n }\n\n // A folder we cannot hash (unreadable, or something that is not a service) is treated as different, so the\n // pull refuses to overwrite it rather than assuming it is safe to replace.\n try {\n return await computeServiceHash(projectRoot, service.serviceId) === service.sourceHash ? 'same' : 'different'\n } catch {\n return 'different'\n }\n}\n\nasync function resolveAuth(projectRoot: string, onAuthRequired?: PullOptions['onAuthRequired']): Promise<StoredAuth> {\n const stored = loadAuth(projectRoot)\n const gap = authGap(stored)\n\n if (!gap) {\n return stored as StoredAuth\n }\n\n if (!onAuthRequired) {\n throw gap === 'not-logged-in' ? new NotLoggedInError() : new NoWorkspaceError()\n }\n\n await onAuthRequired(gap)\n\n const refreshed = loadAuth(projectRoot)\n const remaining = authGap(refreshed)\n\n if (remaining) {\n throw remaining === 'not-logged-in' ? new NotLoggedInError() : new NoWorkspaceError()\n }\n\n return refreshed as StoredAuth\n}\n\nexport async function pull(options: PullOptions = {}): Promise<PullResult> {\n const projectRoot = options.cwd ?? process.cwd()\n const emit = emitter(options)\n\n const { serverUrl, workspaceId, workspaceName, deployToken } = await resolveAuth(projectRoot, options.onAuthRequired)\n const credentials = { serverUrl, workspaceId, deployToken }\n\n const available = await guard(() => listRemoteServices(credentials))\n\n emit({ type: 'listed', services: available, workspace: { workspaceId, workspaceName } })\n\n const selected = await resolveSelection(available, options)\n\n emit({ type: 'selected', services: selected })\n\n const pulled: PulledService[] = []\n const upToDate: PullResult['upToDate'] = []\n const skipped: { serviceId: string; reason: string }[] = []\n\n for (const service of selected) {\n // The id decides where this writes, and it came from the server.\n if (!isSafeServiceId(service.serviceId)) {\n const reason = `\"${ service.serviceId }\" is not a usable folder name`\n\n skipped.push({ serviceId: service.serviceId, reason })\n emit({ type: 'skipped', serviceId: service.serviceId, reason })\n\n continue\n }\n\n const directory = path.resolve(projectRoot, 'services', service.serviceId)\n const state = await localState(projectRoot, service)\n\n // Identical code needs no download and no write \u2014 and `--force` changes nothing, since there is nothing\n // to overwrite it with. Reported rather than silently omitted: \"I checked, and it matches\" is an answer.\n if (state === 'same') {\n upToDate.push({\n serviceId : service.serviceId,\n serviceName: service.serviceName,\n sourceHash : service.sourceHash,\n })\n emit({ type: 'up-to-date', serviceId: service.serviceId, sourceHash: service.sourceHash })\n\n continue\n }\n\n if (state === 'different' && !options.force) {\n const reason = `services/${ service.serviceId }/ differs from the deployed version`\n\n skipped.push({ serviceId: service.serviceId, reason })\n emit({ type: 'skipped', serviceId: service.serviceId, reason })\n\n continue\n }\n\n const exists = state === 'different'\n const zipBuffer = await guard(() => downloadRemoteService(credentials, service.serviceId))\n const archive = new AdmZip(zipBuffer)\n\n // --force replaces rather than merges. Extracting over the top would leave behind files the remote\n // version no longer has, and the next deploy would quietly ship them \u2014 a version matching nothing.\n if (exists) {\n fs.rmSync(directory, { recursive: true, force: true })\n }\n\n const files = extractService(archive, directory)\n const dependencies = declaredDependencies(archive)\n\n emit({ type: 'pulled', serviceId: service.serviceId, sourceHash: service.sourceHash, files, directory })\n\n if (dependencies.length > 0) {\n emit({ type: 'install-needed', serviceId: service.serviceId, dependencies })\n }\n\n pulled.push({\n serviceId : service.serviceId,\n serviceName: service.serviceName,\n sourceHash : service.sourceHash,\n files,\n directory,\n dependencies,\n })\n }\n\n return { workspace: { workspaceId, workspaceName }, serverUrl, services: pulled, upToDate, skipped }\n}\n\nasync function resolveSelection(\n available: RemoteService[],\n options: PullOptions\n): Promise<RemoteService[]> {\n const ids = available.map(service => service.serviceId)\n\n const pick = (selection: { serviceIds?: string[]; all?: boolean }): RemoteService[] => {\n if (selection.serviceIds?.length) {\n return selection.serviceIds.map(serviceId => {\n const match = available.find(service => service.serviceId === serviceId)\n\n if (!match) {\n throw new UnknownServiceError(serviceId, ids)\n }\n\n return match\n })\n }\n\n if (selection.all || available.length <= 1) {\n return available\n }\n\n throw new SelectionRequiredError(ids, 'This workspace has more than one service, so the pull needs to know which.')\n }\n\n try {\n return pick(options)\n } catch (error) {\n if (!options.onSelectionRequired || (error as { code?: string }).code !== 'FR_SELECTION_REQUIRED') {\n throw error\n }\n\n return pick(await options.onSelectionRequired(available))\n }\n}\n\n/** Turns a rejected token into the same error the deploy path raises, so the advice is one sentence. */\nasync function guard<T>(call: () => Promise<T>): Promise<T> {\n try {\n return await call()\n } catch (error) {\n if (error instanceof HttpError && (error.status === 401 || error.body.includes('CLI_TOKEN_EXPIRED'))) {\n throw new TokenExpiredError()\n }\n\n throw error\n }\n}\n", "import type AdmZip from 'adm-zip'\nimport fs from 'fs'\nimport path from 'path'\n\nimport { HASH_EXCLUDED_FOLDERS } from '../../constants'\n\n// Turning a downloaded package back into a service folder.\n//\n// The archive's `package/` root IS the service, so nearly all of it belongs on disk \u2014 its source, its icons,\n// and its own `package.json`. The one thing left behind is `node_modules`: it is generated, it is the bulk of\n// the download, and `npm install` in the service folder rebuilds it from the lockfile that did come across.\n\nconst PACKAGE_PREFIX = 'package/'\n\n/** A service id is a folder name and nothing else \u2014 no separators, no `..`, no absolute path. */\nconst SAFE_SERVICE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/**\n * Whether `serviceId` is safe to use as a path segment.\n *\n * The id arrives from the server, so it is input: `../../etc` as a service id would otherwise decide where\n * this command writes.\n */\nexport function isSafeServiceId(serviceId: string): boolean {\n return SAFE_SERVICE_ID.test(serviceId) && serviceId !== '.' && serviceId !== '..'\n}\n\n/** Everything in the archive that is worth writing \u2014 the service, minus what `npm install` regenerates. */\nfunction serviceEntries(archive: AdmZip): AdmZip.IZipEntry[] {\n return archive.getEntries().filter(entry => {\n if (entry.isDirectory || !entry.entryName.startsWith(PACKAGE_PREFIX)) {\n return false\n }\n\n const [top] = entry.entryName.slice(PACKAGE_PREFIX.length).split('/')\n\n return !HASH_EXCLUDED_FOLDERS.includes(top)\n })\n}\n\n/**\n * Write the service's files into `directory`, returning how many were written.\n *\n * Entry names are confined to the target directory before anything is written: an archive is input, and a\n * `../` in a path is the oldest way to get a file written somewhere it was never meant to go.\n */\nexport function extractService(archive: AdmZip, directory: string): number {\n let written = 0\n\n for (const entry of serviceEntries(archive)) {\n const relativePath = entry.entryName.slice(PACKAGE_PREFIX.length)\n const target = path.resolve(directory, relativePath)\n\n if (target !== directory && !target.startsWith(directory + path.sep)) {\n continue\n }\n\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(target, entry.getData())\n\n written++\n }\n\n return written\n}\n\n/**\n * The dependencies the pulled service declares, if any.\n *\n * `node_modules` is not extracted, so a service that declares anything needs an install before it will run.\n * Reported rather than installed: running a package manager on someone's behalf, in a folder they have not\n * looked at yet, is a bigger act than unpacking it.\n */\nexport function declaredDependencies(archive: AdmZip): string[] {\n const raw = archive.getEntry(`${ PACKAGE_PREFIX }package.json`)?.getData().toString('utf-8')\n\n if (!raw) {\n return []\n }\n\n try {\n const manifest = JSON.parse(raw) as { dependencies?: Record<string, string> }\n\n return Object.keys(manifest.dependencies ?? {})\n } catch {\n // A manifest that will not parse tells us nothing, and must not fail a pull that already succeeded.\n return []\n }\n}\n", "import fs from 'fs'\n\nimport type { ClusterName } from '../constants'\nimport { NotAProjectError } from '../errors'\nimport { clearAuth, loadAuth } from '../project/auth'\nimport { configPath, readConfig, writeConfig } from '../project/config'\nimport { clusterFor, normalizeServerUrl, resolveServerTarget } from './server-target'\nimport type { OperationOptions } from './types'\n\n// Pointing a project at a different Flowrunner cluster.\n//\n// The reason this is a command rather than \"edit flowrunner.json\" is the login. A deploy token is issued by\n// one server and a workspace id only exists on that server, so a project carrying both across a switch is\n// carrying credentials that cannot work \u2014 and the failure would arrive later, as a 401 in the middle of a\n// deploy, rather than here where the cause is obvious. Switching therefore detaches both.\n\nexport { CLUSTER_NAMES, clusterFor, normalizeServerUrl, resolveServerTarget } from './server-target'\n\nexport interface UseServerResult {\n /** The cluster switched to, or null for a URL that is not one of ours. */\n cluster: ClusterName | null\n serverUrl: string\n previousServerUrl: string\n /** False when the project was already pointed at this server \u2014 nothing was touched. */\n changed: boolean\n /** A login existed for the previous server and was detached. */\n clearedLogin: boolean\n /** The workspace that was detached, if there was one. */\n clearedWorkspaceId: string\n}\n\n/** Point the project at `target`, detaching any login that belonged to the server it was on. */\nexport function useServer(target: string, options: OperationOptions = {}): UseServerResult {\n const projectRoot = options.cwd ?? process.cwd()\n\n if (!fs.existsSync(configPath(projectRoot))) {\n throw new NotAProjectError()\n }\n\n const serverUrl = resolveServerTarget(target)\n const config = readConfig(projectRoot)\n const previousServerUrl = normalizeServerUrl(config.serverUrl ?? '')\n\n // Switching to the server you are already on must not log you out \u2014 that would make an idempotent\n // command destructive, and `use dev` is exactly the thing someone types to check where they are.\n if (previousServerUrl === serverUrl) {\n return {\n cluster : clusterFor(serverUrl),\n serverUrl,\n previousServerUrl,\n changed : false,\n clearedLogin : false,\n clearedWorkspaceId: '',\n }\n }\n\n const clearedLogin = Boolean(loadAuth(projectRoot))\n const clearedWorkspaceId = config.workspaceId ?? ''\n\n // The workspace and the name go with the old server; only `serverUrl` survives the switch.\n const { workspaceId: _workspaceId, workspaceName: _workspaceName, ...rest } = config\n\n writeConfig({ ...rest, serverUrl }, projectRoot)\n clearAuth(projectRoot)\n\n return {\n cluster: clusterFor(serverUrl),\n serverUrl,\n previousServerUrl,\n changed: true,\n clearedLogin,\n clearedWorkspaceId,\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,wDAAAA,UAAA;AAAA;AAEA,WAAO,eAAeA,UAAS,cAAc;AAAA,MAC3C,OAAO;AAAA,IACT,CAAC;AACD,IAAAA,SAAQ,iBAAiB;AACzB,IAAAA,SAAQ,YAAY;AACpB,IAAAA,SAAQ,cAAc;AACtB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I,sBAAsB,WAAW;AACnC,WAAO;AAAA,MACL,SAAoB,WAAW,SAAS;AAAA,MACxC;AAAA,MACA;AAAA,MACA,SAAoB;AAAA,MACpB,cAAoB;AAAA,MACpB,oBAAoB;AAAA,IACtB;AAAA,EACF;AAEA,QAAM,eAAe,QAAQ,SAAS,WAAW,CAAC;AAClD,QAAM,qBAAqB,OAAO,eAAe;AAGjD,QAAM,EAAE,aAAa,cAAc,eAAe,gBAAgB,GAAG,KAAK,IAAI;AAE9E,cAAY,EAAE,GAAG,MAAM,UAAU,GAAG,WAAW;AAC/C,YAAU,WAAW;AAErB,SAAO;AAAA,IACL,SAAS,WAAW,SAAS;AAAA,IAC7B;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.blobToFormPart = blobToFormPart;\nexports.castArray = void 0;\nexports.decodeBytes = decodeBytes;\nexports.ensureEncoding = ensureEncoding;\nexports.getFormData = getFormData;\nexports.isWebFormData = exports.isStream = exports.isObject = exports.isNodeJS = exports.isFormData = exports.isBytes = exports.isBrowser = exports.isBlob = void 0;\nexports.normalizeFormPart = normalizeFormPart;\nexports.normalizeTrailingSlashInPath = normalizeTrailingSlashInPath;\nexports.setFormData = setFormData;\nexports.toBytes = toBytes;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\n/**\n * Casts `value` as an array if it's not one.\n * Equivalent to lodash/castArray\n */\nvar castArray = exports.castArray = function castArray(value) {\n return Array.isArray(value) ? value : [value];\n};\nvar isObject = exports.isObject = function isObject(value) {\n return null != value && _typeof(value) === 'object';\n};\nvar isFormData = exports.isFormData = function isFormData(value) {\n if (!value) {\n return false;\n }\n var FormData = getFormData();\n if (value instanceof FormData) {\n return true;\n }\n return value && value.constructor && value.constructor.toString().trim().indexOf('function FormData') === 0;\n};\nvar isStream = exports.isStream = function isStream(value) {\n var stream = require('stream');\n return value instanceof stream.Stream;\n};\nvar isNodeJS = exports.isNodeJS = function isNodeJS() {\n return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n};\nvar isBrowser = exports.isBrowser = function isBrowser() {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n};\nvar CustomFormData = null;\nfunction getFormData() {\n if (CustomFormData) {\n return CustomFormData;\n }\n return isNodeJS() || typeof FormData === 'undefined' ? require('form-data') : FormData;\n}\nfunction setFormData(value) {\n CustomFormData = value;\n}\n\n// @ : / # ? = $ & +\nvar SAFE_CHAR_CODES = ['%40', '%3A', '%2F', '%23', '%3F', '%3D', '%24', '%26', '%2B'];\nfunction safeEscape(str, charCodes) {\n var _char = charCodes[0];\n if (_char) {\n var tokens = str.split(_char).map(function (p) {\n return safeEscape(p, charCodes.slice(1));\n });\n return tokens.join(_char);\n }\n return encodeURI(str);\n}\nfunction ensureComponentEncoding(uriComponent) {\n if (uriComponent === decodeURI(uriComponent)) {\n return safeEscape(uriComponent, [].concat(SAFE_CHAR_CODES));\n }\n return uriComponent;\n}\nfunction encodePath(path) {\n return path.split('/').map(ensureComponentEncoding).join('/');\n}\nfunction ensureEncoding(path) {\n try {\n var url = new URL(path);\n return url.origin + encodePath(normalizeTrailingSlashInPath(path, url)) + url.search;\n } catch (_unused) {\n return encodePath(path);\n }\n}\nfunction normalizeTrailingSlashInPath(originPath, _ref) {\n var pathname = _ref.pathname;\n if (originPath.includes('?')) {\n originPath = originPath.split('?')[0];\n }\n var keepTrailingSlash = originPath.endsWith('/');\n return !keepTrailingSlash && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;\n}\nvar isBytes = exports.isBytes = function isBytes(value) {\n return typeof Uint8Array !== 'undefined' && value instanceof Uint8Array;\n};\n\n/**\n * Normalizes a raw response body to bytes.\n *\n * A Buffer is a Uint8Array, so the check a caller needs is `instanceof Uint8Array` in both\n * environments, and the value we already have is handed back as is - no copy, these are file\n * payloads and a single one is routinely tens of MB.\n *\n * Everything else can only come from an empty response or from a replaced `Request.send`,\n * both of them cheap to convert. Anything that is not convertible is a broken contract and\n * throws rather than silently uploading wrong bytes.\n *\n * @param {*} value\n * @returns {Buffer|Uint8Array}\n */\nfunction toBytes(value) {\n if (isBytes(value)) {\n return value;\n }\n var hasBuffer = typeof Buffer !== 'undefined' && typeof Buffer.from === 'function';\n if (value === undefined || value === null || value === '') {\n return hasBuffer ? Buffer.alloc(0) : new Uint8Array(0);\n }\n if (typeof value === 'string') {\n return hasBuffer ? Buffer.from(value, 'utf8') : new TextEncoder().encode(value);\n }\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return hasBuffer ? Buffer.from(value) : new Uint8Array(value);\n }\n throw new Error('The response body can not be represented as bytes, ' + \"received \".concat(value === null ? 'null' : _typeof(value), \". \") + 'This happens when \"Request.send\" is replaced with an implementation ' + 'that does not return the raw body for a request made with \"toBuffer()\".');\n}\n\n/**\n * Decodes bytes to utf8 text, anything which is not bytes is passed through.\n *\n * Used for the error body of a raw request: a browser gets it as a Uint8Array, because\n * `responseType` is set for the whole response, and `String()` on a Uint8Array joins the byte\n * values with commas instead of decoding them\n *\n * @param {*} value\n * @returns {*}\n */\nfunction decodeBytes(value) {\n if (!isBytes(value)) {\n return value;\n }\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return value.toString('utf8');\n }\n if (typeof TextDecoder !== 'undefined') {\n return new TextDecoder('utf8').decode(value);\n }\n return value;\n}\n\n/**\n * A Blob or a File, duck typed so that an instance coming from another realm is recognized too\n */\nvar isBlob = exports.isBlob = function isBlob(value) {\n return !!value && _typeof(value) === 'object' && typeof value.stream === 'function' && typeof value.arrayBuffer === 'function' && typeof value.size === 'number';\n};\n\n/**\n * The FormData of the WHATWG spec - the Node 18+ global one, or the browser one.\n *\n * The `form-data` npm package, which is what `Request.FormData` is in Node js, is a different\n * class with a different API and it is recognized by `isFormData`\n */\nvar isWebFormData = exports.isWebFormData = function isWebFormData(value) {\n return !!value && typeof value.append === 'function' && typeof value.getAll === 'function' && typeof value.forEach === 'function' && typeof value.getHeaders !== 'function';\n};\n\n/**\n * Turns a Blob or a File into something the `form-data` package can stream.\n *\n * The package accepts a Buffer or a stream and treats any other object as stream like, which\n * makes it throw \"source.on is not a function\" from inside `combined-stream` at append time.\n * A web stream is not that either, `Readable.fromWeb` bridges the two.\n *\n * `knownLength` is what keeps `form.getLength()` synchronous and the content-length header\n * correct, and the filename follows what a browser sends for a nameless Blob\n *\n * @param {Blob|File} blob\n * @returns {{ value: Object, options: Object }}\n */\nfunction blobToFormPart(blob) {\n var _require = require('stream'),\n Readable = _require.Readable;\n if (typeof Readable.fromWeb !== 'function') {\n throw new Error('A Blob can only be added to a form on Node 18 or newer, ' + 'pass a Buffer or a stream instead.');\n }\n var options = {\n knownLength: blob.size,\n filename: blob.name || 'blob'\n };\n if (blob.type) {\n options.contentType = blob.type;\n }\n return {\n value: Readable.fromWeb(blob.stream()),\n options: options\n };\n}\n\n/**\n * Prepares a value for `FormData#append` of the `form-data` package.\n *\n * Everything the package can not stream is either converted here or reported with an error which\n * names the field, instead of the \"source.on is not a function\"/\"Illegal invocation\" thrown from\n * deep inside `combined-stream` with nothing pointing at the value which caused it\n *\n * @param {String} key\n * @param {*} value\n * @returns {{ value: *, options: Object|undefined }}\n */\nfunction normalizeFormPart(key, value) {\n if (isBlob(value)) {\n return blobToFormPart(value);\n }\n if (isBytes(value) && typeof Buffer !== 'undefined' && !Buffer.isBuffer(value)) {\n // a Uint8Array is not a Buffer and the package treats it as a stream, the view is\n // wrapped without copying the bytes\n return {\n value: Buffer.from(value.buffer, value.byteOffset, value.byteLength)\n };\n }\n if (isObject(value) && !isStream(value) && !(typeof Buffer !== 'undefined' && Buffer.isBuffer(value))) {\n throw new Error(\"The form field \\\"\".concat(key, \"\\\" can not be sent, \") + \"expected a Buffer, a stream, a Blob or a primitive value, received \".concat(describeValue(value), \".\"));\n }\n return {\n value: value\n };\n}\nfunction describeValue(value) {\n if (Array.isArray(value)) {\n return 'an Array';\n }\n var name = value.constructor && value.constructor.name;\n return name ? \"an instance of \".concat(name) : 'an object';\n}", "\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.TLSError = exports.ResponseError = void 0;\nexports.toTLSError = toTLSError;\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\nfunction _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nvar ResponseError = exports.ResponseError = /*#__PURE__*/function (_Error) {\n _inherits(ResponseError, _Error);\n var _super = _createSuper(ResponseError);\n function ResponseError(response) {\n var _this;\n _classCallCheck(this, ResponseError);\n _this = _super.call(this);\n var error = parseError(response);\n _this.message = error.message || error;\n _this.code = error.code;\n _this.status = response.status;\n _this.headers = response.headers;\n _this.body = response.body;\n return _this;\n }\n return _createClass(ResponseError);\n}( /*#__PURE__*/_wrapNativeSuper(Error));\nfunction parseError(res) {\n if (res.status === 502) {\n return 'No connection with server';\n }\n return res.body || \"Status Code \".concat(res.status, \" (\").concat(res.statusText, \")\");\n}\n\n/**\n * An error which is raised when a TLS connection can not be established.\n *\n * A raw TLS failure surfaces as an opaque socket error (ECONNRESET, EPROTO, an OpenSSL code),\n * which makes the most common operational failures - a missing, rejected or expired client\n * certificate - indistinguishable from a network problem.\n *\n * Never put any part of the certificate, the private key or the passphrase into the message,\n * the reasons below are the only text this error is built from.\n */\nvar TLSError = exports.TLSError = /*#__PURE__*/function (_Error2) {\n _inherits(TLSError, _Error2);\n var _super2 = _createSuper(TLSError);\n function TLSError(reason, cause) {\n var _this2;\n _classCallCheck(this, TLSError);\n _this2 = _super2.call(this, cause && cause.code ? \"\".concat(reason, \" (\").concat(cause.code, \")\") : reason);\n _this2.name = 'TLSError';\n _this2.code = cause && cause.code || 'TLS_ERROR';\n if (cause) {\n _this2.cause = cause;\n }\n return _this2;\n }\n return _createClass(TLSError);\n}( /*#__PURE__*/_wrapNativeSuper(Error)); // the local certificate/key material can not even be loaded, the connection is never attempted\nvar SECURE_CONTEXT_REASONS = [{\n match: /bad decrypt|bad password read|wrong final block length/i,\n reason: 'The private key could not be decrypted, the passphrase is missing or incorrect.'\n}, {\n match: /no start line|not enough data|PEM_read_bio|DECODER routines/i,\n reason: 'The client certificate or the private key is not valid PEM.'\n}, {\n match: /key values mismatch/i,\n reason: 'The private key does not match the client certificate.'\n}];\n\n// the server refused our client certificate during the handshake\nvar HANDSHAKE_ALERT_REASONS = [{\n // the server demands a client certificate before it looks at anything else, including auth\n match: /certificate[ _]required/i,\n reason: 'The server requires a client certificate and none was supplied.'\n}, {\n match: /certificate expired/i,\n reason: 'The server rejected the client certificate because it has expired.'\n}, {\n match: /certificate revoked/i,\n reason: 'The server rejected the client certificate because it has been revoked.'\n}, {\n match: /unknown ca/i,\n reason: 'The server does not trust the authority which issued the client certificate.'\n}, {\n match: /(bad|unsupported|unknown|no) certificate/i,\n reason: 'The server rejected the client certificate.'\n}, {\n match: /handshake failure/i,\n reason: 'The server rejected the TLS handshake, the client certificate is missing or was rejected.'\n}];\n\n// the certificate presented by the server could not be verified\nvar NO_CA_REASON = 'The server certificate could not be verified, a CA bundle may be required.';\nvar PEER_CERTIFICATE_REASONS = {\n CERT_HAS_EXPIRED: 'The server certificate has expired.',\n CERT_NOT_YET_VALID: 'The server certificate is not valid yet.',\n SELF_SIGNED_CERT_IN_CHAIN: 'The server certificate chain is self signed, a CA bundle may be required.',\n DEPTH_ZERO_SELF_SIGNED_CERT: 'The server certificate is self signed, a CA bundle may be required.',\n ERR_TLS_CERT_ALTNAME_INVALID: 'The server certificate does not match the requested host.',\n UNABLE_TO_VERIFY_LEAF_SIGNATURE: NO_CA_REASON,\n UNABLE_TO_GET_ISSUER_CERT_LOCALLY: NO_CA_REASON\n};\nfunction findReason(reasons, text) {\n var found = reasons.find(function (_ref) {\n var match = _ref.match;\n return match.test(text);\n });\n return found && found.reason;\n}\nfunction findPeerCertificateReason(code) {\n return code && PEER_CERTIFICATE_REASONS.hasOwnProperty(code) ? PEER_CERTIFICATE_REASONS[code] : undefined;\n}\n\n/**\n * Converts a low level socket/OpenSSL failure into a TLSError with an actionable message.\n *\n * @param {Error} error the error raised by the http client\n * @param {Boolean} withClientCert whether a client certificate was supplied for this request\n * @returns {TLSError|null} null when the error is not TLS related and should be reported as is\n */\nfunction toTLSError(error, withClientCert) {\n if (!error) {\n return null;\n }\n var text = \"\".concat(error.code || '', \" \").concat(error.message || '');\n var reason = findPeerCertificateReason(error.code) || findReason(SECURE_CONTEXT_REASONS, text) || findReason(HANDSHAKE_ALERT_REASONS, text);\n if (reason) {\n return new TLSError(reason, error);\n }\n\n // a server which demands a client certificate usually just drops the connection when it does not\n // get one it accepts, there is no alert to read, so this is the best guess we can offer\n if (withClientCert && (error.code === 'ECONNRESET' || error.code === 'EPROTO')) {\n return new TLSError('The connection was closed during the TLS handshake, ' + 'the client certificate was most likely missing, rejected or expired.', error);\n }\n return null;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.sendNodeAPIRequest = sendNodeAPIRequest;\nvar _utils = require(\"./utils\");\nvar _error = require(\"./error\");\nfunction sendNodeAPIRequest(path, method, headers, body, encoding, timeout, withCredentials, tlsOptions) {\n return new Promise(function (resolve, reject) {\n var u = require('url').parse(path);\n var form = (0, _utils.isFormData)(body) && body;\n var https = u.protocol === 'https:';\n var options = {\n host: u.hostname,\n port: u.port || (https ? 443 : 80),\n path: (0, _utils.normalizeTrailingSlashInPath)(path, u) + (u.search || ''),\n method: method,\n headers: headers,\n timeout: timeout\n };\n if (typeof withCredentials === 'boolean') {\n options.withCredentials = withCredentials;\n }\n var withClientCert = !!(tlsOptions && (tlsOptions.cert || tlsOptions.key));\n if (tlsOptions) {\n if (!https) {\n // going ahead would silently drop the certificate and send the request in plain text,\n // there is no mutual TLS without TLS\n return reject(new _error.TLSError('A client certificate can only be used with an https:// URL.'));\n }\n Object.assign(options, tlsOptions);\n }\n\n // a TLS failure arrives here as an opaque socket/OpenSSL error, translate the ones we recognize\n var rejectWithError = function rejectWithError(error) {\n return reject((0, _error.toTLSError)(error, withClientCert) || error);\n };\n var _send = function _send() {\n var Buffer = require('buffer').Buffer;\n var httpClient = require(https ? 'https' : 'http');\n var req = httpClient.request(options, function (res) {\n var strings = [];\n var buffers = [];\n var bufferLength = 0;\n var body = '';\n var status = res.statusCode,\n statusText = res.statusMessage,\n headers = res.headers;\n res.on('data', function (chunk) {\n if (!Buffer.isBuffer(chunk)) {\n strings.push(chunk);\n } else if (chunk.length) {\n bufferLength += chunk.length;\n buffers.push(chunk);\n }\n });\n res.on('end', function () {\n if (bufferLength) {\n body = Buffer.concat(buffers, bufferLength);\n if (encoding != null) {\n body = body.toString(encoding);\n }\n } else if (strings.length) {\n body = strings.join();\n } else if (encoding == null) {\n // a raw request asked for bytes, and a 0 byte response is an empty buffer,\n // not the empty string the body is initialized with\n body = Buffer.alloc(0);\n }\n resolve({\n status: status,\n statusText: statusText,\n headers: headers,\n body: body\n });\n });\n res.on('error', rejectWithError);\n });\n req.on('error', rejectWithError);\n req.on('timeout', function () {\n req.destroy(new Error('Connection aborted due to timeout'));\n });\n if (body) {\n if ((0, _utils.isStream)(body)) {\n body.pipe(req);\n return;\n }\n req.write(body);\n }\n req.end();\n };\n\n // an unusable certificate/key/passphrase makes https.request() throw synchronously, and for a\n // form body _send() runs from a callback where a throw would escape the promise altogether\n var send = function send() {\n try {\n _send();\n } catch (error) {\n rejectWithError(error);\n }\n };\n if (form) {\n Object.assign(options.headers, form.getHeaders());\n form.getLength(function (err, length) {\n if (!err && !isNaN(length)) {\n options.headers['content-length'] = length;\n }\n send();\n });\n } else {\n if (body && !options.headers['content-length']) {\n var Buffer = require('buffer').Buffer;\n options.headers['content-length'] = Buffer.byteLength(body);\n }\n send();\n }\n });\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar EventEmitter = exports[\"default\"] = /*#__PURE__*/function () {\n function EventEmitter() {\n _classCallCheck(this, EventEmitter);\n this.events = {};\n }\n _createClass(EventEmitter, [{\n key: \"on\",\n value: function on(eventName, callback) {\n this.events[eventName] = this.events[eventName] || [];\n this.events[eventName].push(callback);\n return this;\n }\n }, {\n key: \"off\",\n value: function off(eventName, callback) {\n if (!eventName) {\n this.events = {};\n } else if (this.events[eventName]) {\n if (callback) {\n this.events[eventName] = this.events[eventName].filter(function (c) {\n return c !== callback;\n });\n } else {\n delete this.events[eventName];\n }\n }\n return this;\n }\n }, {\n key: \"emit\",\n value: function emit(eventName) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n if (this.events[eventName]) {\n this.events[eventName].forEach(function (callback) {\n return callback.apply(void 0, args);\n });\n }\n }\n }]);\n return EventEmitter;\n}();", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.stringify = void 0;\nvar _utils = require(\"./utils\");\n/**\n * Produces a URL query string from a given obj by iterating through the object's \"own properties\".\n * @param {Object} obj\n * @returns {string}\n */\nvar stringify = exports.stringify = function stringify(obj) {\n var tokens = [];\n Object.keys(obj).forEach(function (key) {\n var value = obj[key];\n if (value !== undefined) {\n (0, _utils.castArray)(value).forEach(function (value) {\n tokens.push(\"\".concat(encodeURIComponent(key), \"=\").concat(encodeURIComponent(value)));\n });\n }\n });\n return tokens.join('&');\n};", "\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.Request = void 0;\nvar _eventEmitter = _interopRequireDefault(require(\"./event-emitter\"));\nvar qs = _interopRequireWildcard(require(\"./qs\"));\nvar _utils = require(\"./utils\");\nvar _error = require(\"./error\");\nfunction _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== \"function\") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }\nfunction _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") { return { \"default\": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj[\"default\"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nvar CONTENT_TYPE_HEADER = 'Content-Type';\n\n// the only TLS options a caller may pass, everything else (rejectUnauthorized and friends) is\n// dropped on purpose so that a config blob can not weaken the connection by accident\nvar TLS_OPTION_KEYS = ['cert', 'key', 'passphrase', 'ca'];\nvar REQUEST_EVENT = 'request';\nvar RESPONSE_EVENT = 'response';\nvar ERROR_EVENT = 'error';\nvar DONE_EVENT = 'done';\nvar Request = exports.Request = /*#__PURE__*/function (_EventEmitter) {\n _inherits(Request, _EventEmitter);\n var _super = _createSuper(Request);\n function Request(path, method, body) {\n var _this;\n _classCallCheck(this, Request);\n _this = _super.call(this);\n _this.method = method;\n _this.path = (0, _utils.ensureEncoding)(path);\n _this.body = body;\n _this.unwrap = true;\n _this.raw = false;\n _this.headers = {};\n _this.queryParams = {};\n _this.encoding = 'utf8';\n _this.timeout = 0;\n _this.withCredentials = null;\n\n // the private key is credential material, a non enumerable property keeps it out of\n // console.log(request)/JSON.stringify(request) in whatever logging a caller has around\n Object.defineProperty(_assertThisInitialized(_this), 'tlsOptions', {\n value: undefined,\n writable: true,\n enumerable: false,\n configurable: true\n });\n return _this;\n }\n\n /**\n * Sets a header\n *\n * @param {String|Object} key or map of headers\n * @param {String} [value]\n * @returns {Request}\n */\n _createClass(Request, [{\n key: \"set\",\n value: function set(key, value) {\n if ((0, _utils.isObject)(key)) {\n for (var headerName in key) {\n this.set(headerName, key[headerName]);\n }\n } else if (typeof value !== 'undefined') {\n this.headers[key] = value;\n }\n return this;\n }\n\n /**\n * Shortcut for req.set('Authorization', `Basic ${basicAuth.token}`)\n *\n * @param {Object} [basicAuth]\n * @param {String} basicAuth.token\n * @returns {Request}\n */\n }, {\n key: \"basicAuth\",\n value: function basicAuth(_basicAuth) {\n if (_basicAuth) {\n this.set({\n Authorization: \"Basic \".concat(_basicAuth.token)\n });\n }\n return this;\n }\n\n /**\n * Shortcut for req.set('auth-key', authKey)\n *\n * @param {String} [authKey]\n * @returns {Request}\n */\n }, {\n key: \"authKey\",\n value: function authKey(_authKey) {\n if (_authKey) {\n this.set({\n 'auth-key': _authKey\n });\n }\n return this;\n }\n\n /**\n * Attaches a TLS client certificate and private key to the request (mutual TLS).\n *\n * Works only for Node js, in a browser the client certificate is chosen by the browser itself.\n *\n * Calling the method several times merges the options, so the certificate and the key may come\n * from different places. Options other than the ones listed below are ignored.\n *\n * @param {Object} [tlsOptions]\n * @param {String|Buffer|Array} tlsOptions.cert PEM encoded client certificate (or chain)\n * @param {String|Buffer|Array} tlsOptions.key PEM encoded private key\n * @param {String} [tlsOptions.passphrase] passphrase of an encrypted private key\n * @param {String|Buffer|Array} [tlsOptions.ca] PEM encoded CA bundle to verify the server with\n * @returns {Request}\n */\n }, {\n key: \"cert\",\n value: function cert(tlsOptions) {\n var options = tlsOptions && pickTLSOptions(tlsOptions);\n if (options && Object.keys(options).length) {\n this.tlsOptions = _objectSpread(_objectSpread({}, this.tlsOptions), options);\n }\n return this;\n }\n\n /**\n * @param {Object} queryParams\n * @returns {Request}\n */\n }, {\n key: \"query\",\n value: function query(queryParams) {\n Object.assign(this.queryParams, queryParams);\n return this;\n }\n\n /**\n * Sets a multipart form as the request body.\n *\n * Accepts an instance of `Request.FormData`, a WHATWG `FormData` (the Node 18+ global one) and\n * a plain object. A Blob or a File, which the `form-data` package can not stream on its own,\n * is converted, and a value it can not send at all is reported with an error naming the field.\n *\n * @param {Object} form\n * @returns {Request}\n */\n }, {\n key: \"form\",\n value: function form(_form) {\n if (_form) {\n if ((0, _utils.isFormData)(_form)) {\n this.body = _form;\n } else if ((0, _utils.isWebFormData)(_form)) {\n this.body = toRequestFormData(_form);\n } else {\n var formData = new Request.FormData();\n var _loop = function _loop(formKey) {\n if (formKey) {\n (0, _utils.castArray)(_form[formKey]).forEach(function (formValue) {\n if (formValue && formValue.hasOwnProperty('value') && formValue.hasOwnProperty('options')) {\n appendFormPart(formData, formKey, formValue.value, formValue.options);\n } else {\n appendFormPart(formData, formKey, formValue);\n }\n });\n }\n };\n for (var formKey in _form) {\n _loop(formKey);\n }\n this.body = formData;\n }\n }\n return this;\n }\n\n /**\n * Shortcut for req.set('Content-Type', value)\n *\n * @param {String} contentType\n * @returns {Request}\n */\n }, {\n key: \"type\",\n value: function type(contentType) {\n this.set(CONTENT_TYPE_HEADER, contentType);\n return this;\n }\n\n /**\n * Should we unwrap the response and return only body. true by default\n * @param {Boolean} unwrap\n * @returns {Request}\n */\n }, {\n key: \"unwrapBody\",\n value: function unwrapBody(unwrap) {\n this.unwrap = unwrap;\n return this;\n }\n\n /**\n * set encoding to response\n * works only for Node js\n *\n * @param {String} encoding\n * @returns {Request}\n */\n }, {\n key: \"setEncoding\",\n value: function setEncoding(encoding) {\n this.encoding = encoding;\n return this;\n }\n\n /**\n * Sends the request and resolves the response body as raw bytes.\n *\n * Unlike `setEncoding(null)` the result is guaranteed: a `Buffer` in Node js, a `Uint8Array`\n * in a browser (a Buffer is a Uint8Array, so `instanceof Uint8Array` holds in both), an empty\n * one for a 0 byte response, and never a value that `JSON.parse` got to first.\n *\n * The method is terminal, it implies a raw transfer and overrides whatever `setEncoding` was\n * given before it, so there is no need to call `setEncoding(null)` as well.\n *\n * An unsuccessful response is rejected the same way as for any other request, with the error\n * body still JSON parsed when it is JSON - a vendor answers a failed binary download with a\n * JSON error and `error.body.message` has to keep working.\n *\n * @returns {Promise<Buffer|Uint8Array>}\n */\n }, {\n key: \"toBuffer\",\n value: function toBuffer() {\n this.raw = true;\n this.encoding = null;\n this.promise = this.promise || this.send(this.body);\n return this.promise;\n }\n\n /**\n * set withCredentials option\n *\n * @param {Boolean} value\n * @returns {Request}\n */\n }, {\n key: \"setWithCredentials\",\n value: function setWithCredentials(value) {\n this.withCredentials = value;\n return this;\n }\n\n /**\n * A number specifying request timeout in milliseconds.\n * @param {Number} ms\n * @returns {Request}\n */\n }, {\n key: \"setTimeout\",\n value: function setTimeout(ms) {\n this.timeout = ms;\n return this;\n }\n\n /**\n * Sends the request\n *\n * @param {Object} body\n * @returns {Promise}\n */\n }, {\n key: \"send\",\n value: function send(body) {\n var _this2 = this;\n this.emit(REQUEST_EVENT, this);\n var path = this.path;\n var queryString = qs.stringify(this.queryParams);\n if (queryString) {\n path += '?' + queryString;\n }\n if (!(0, _utils.isFormData)(body) && (0, _utils.isWebFormData)(body)) {\n body = toRequestFormData(body);\n }\n var type = this.headers[CONTENT_TYPE_HEADER];\n if (!type && (0, _utils.isObject)(body) && !(0, _utils.isFormData)(body)) {\n this.type('application/json');\n }\n if (body) {\n var isJSON = this.headers[CONTENT_TYPE_HEADER] === 'application/json';\n body = isJSON && typeof body !== 'string' ? JSON.stringify(body) : body;\n }\n var unwrapBody = function unwrapBody(res) {\n return _this2.unwrap ? res.body : res;\n };\n if (Request.verbose) {\n console.log(this.method.toUpperCase(), decodeURIComponent(path), body, this.headers);\n }\n var withCredentials = typeof this.withCredentials === 'boolean' ? this.withCredentials : Request.withCredentials;\n var syncError = new Error();\n var request = Request.send(path, this.method.toUpperCase(), this.headers, body, this.encoding, this.timeout, withCredentials, this.tlsOptions).then(function (res) {\n return parseBody(res, _this2.raw);\n }).then(function (res) {\n return ensureRawBody(res, _this2.raw);\n }).then(checkStatus).then(unwrapBody)[\"catch\"](function (error) {\n error.stack = \"\".concat(error.stack).concat(syncError.stack);\n throw error;\n });\n request.then(function (result) {\n _this2.emit(RESPONSE_EVENT, result);\n _this2.emit(DONE_EVENT, null, result);\n })[\"catch\"](function (error) {\n _this2.emit(ERROR_EVENT, error);\n _this2.emit(DONE_EVENT, error);\n });\n return request;\n }\n\n /**\n * If you are too lazy to use method 'send', don't use it and stay cool :)\n *\n * @param {Function} successHandler\n * @param {Function} errorHandler\n * @returns {Promise}\n */\n }, {\n key: \"then\",\n value: function then(successHandler, errorHandler) {\n this.promise = this.promise || this.send(this.body);\n return this.promise.then(successHandler, errorHandler);\n }\n\n /**\n * @param {Function} errorHandler\n * @returns {Promise}\n */\n }, {\n key: \"catch\",\n value: function _catch(errorHandler) {\n this.promise = this.promise || this.send(this.body);\n return this.promise[\"catch\"](errorHandler);\n }\n }]);\n return Request;\n}(_eventEmitter[\"default\"]);\n/**\n * Keeps only the known TLS options and skips the empty ones,\n * `undefined` values would otherwise overwrite already collected options on a merge\n */\nfunction pickTLSOptions(tlsOptions) {\n var result = {};\n TLS_OPTION_KEYS.forEach(function (key) {\n if (tlsOptions[key] !== undefined && tlsOptions[key] !== null) {\n result[key] = tlsOptions[key];\n }\n });\n return result;\n}\n\n/**\n * Copies a WHATWG FormData into a `Request.FormData`.\n *\n * Iterating with `for (var key in webFormData)` , which is what a plain object gets, walks the\n * enumerable WebIDL operations of the prototype and appends `append`, `get`, `set`, `forEach` ...\n * as form parts, and streaming then calls one of them unbound\n */\nfunction toRequestFormData(webFormData) {\n var formData = new Request.FormData();\n webFormData.forEach(function (value, key) {\n return appendFormPart(formData, key, value);\n });\n return formData;\n}\nfunction appendFormPart(formData, key, value, options) {\n if (typeof formData.getHeaders !== 'function') {\n // a browser FormData, it takes a Blob, a File and a typed array natively\n return options ? formData.append(key, value, options) : formData.append(key, value);\n }\n var part = (0, _utils.normalizeFormPart)(key, value);\n var partOptions = _objectSpread(_objectSpread({}, part.options), options);\n if (Object.keys(partOptions).length) {\n formData.append(key, part.value, partOptions);\n } else {\n formData.append(key, part.value);\n }\n}\nfunction isSuccessStatus(status) {\n return status >= 200 && status < 300;\n}\n\n/**\n * `JSON.parse` coerces its argument with `String()`, so it destroys a body that was asked for as\n * raw bytes whenever those bytes happen to be valid JSON. A raw request skips it for a successful\n * response only, an error body keeps being parsed as it always was.\n */\nfunction parseBody(res, raw) {\n if (raw && isSuccessStatus(res.status)) {\n return res;\n }\n try {\n return _objectSpread(_objectSpread({}, res), {}, {\n body: JSON.parse(raw ? (0, _utils.decodeBytes)(res.body) : res.body)\n });\n } catch (e) {\n return res;\n }\n}\nfunction ensureRawBody(res, raw) {\n return raw && isSuccessStatus(res.status) ? _objectSpread(_objectSpread({}, res), {}, {\n body: (0, _utils.toBytes)(res.body)\n }) : res;\n}\n\n/**\n * Checks if a network request came back fine, and throws an error if not\n *\n * @param {object} response A response from a network request\n *\n * @return {object|undefined} Returns either the response, or throws an error\n */\nfunction checkStatus(response) {\n if (isSuccessStatus(response.status)) {\n return response;\n }\n throw new _error.ResponseError(response);\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.sendXmlHttpRequest = sendXmlHttpRequest;\nvar _request2 = require(\"./request\");\nfunction sendXmlHttpRequest(path, method, headers, body, encoding, timeout, withCredentials) {\n return new Promise(function sendRequest(resolve, reject) {\n var request = new _request2.Request.XMLHttpRequest();\n request.timeout = timeout;\n if (!encoding) {\n request.responseType = 'arraybuffer';\n }\n request.open(method.toUpperCase(), path, true);\n if (typeof withCredentials === 'boolean') {\n request.withCredentials = withCredentials;\n }\n request.onload = function handleLoadEvent() {\n var headers = parseHeaders(request.getAllResponseHeaders());\n var _request = request,\n status = _request.status,\n statusText = _request.statusText;\n var result = {\n status: status,\n statusText: statusText,\n headers: headers\n };\n if (encoding) {\n // `responseType` was left as the default one for any encoding, XMLHttpRequest has no way\n // to decode an arbitrary charset, so the body is the text the browser decoded for us.\n // Wrapping that string into a Uint8Array, as it used to be for a non utf8 encoding,\n // produced an empty array and lost the response entirely\n result.body = request.response || request.responseText;\n } else {\n // `responseType` is 'arraybuffer' here, a 0 byte response has to stay bytes as well\n result.body = request.response ? new Uint8Array(request.response) : new Uint8Array(0);\n }\n resolve(result);\n request = null;\n };\n request.onerror = function handleErrorEvent() {\n reject(new Error('Network Error'));\n request = null;\n };\n request.ontimeout = function handleTimeout() {\n reject(new Error('Connection aborted due to timeout'));\n request = null;\n };\n Object.keys(headers).forEach(function (key) {\n request.setRequestHeader(key, headers[key]);\n });\n request.send(body);\n });\n}\nfunction parseHeaders(headersString) {\n var parsed = {};\n if (!headersString) {\n return parsed;\n }\n headersString.split('\\n').forEach(function (line) {\n var i = line.indexOf(':');\n var key = line.substr(0, i).trim();\n var val = line.substr(i + 1).trim();\n if (key) {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n return parsed;\n}", "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar _clientNode = require(\"./client-node\");\nvar _clientBrowser = require(\"./client-browser\");\nvar _request = require(\"./request\");\nvar _utils = require(\"./utils\");\nObject.defineProperty(_request.Request, 'FormData', {\n get: function get() {\n return (0, _utils.getFormData)();\n },\n set: function set(value) {\n (0, _utils.setFormData)(value);\n }\n});\n_request.Request.XMLHttpRequest = typeof XMLHttpRequest !== 'undefined' ? XMLHttpRequest : undefined;\n\n// `tlsOptions` is meaningful for the Node client only, XMLHttpRequest gives no control over the\n// client certificate - a browser picks it from the OS/browser keystore when a server asks for one\n_request.Request.send = function (path, method, headers, body, encoding, timeout, withCredentials, tlsOptions) {\n var sender = typeof _request.Request.XMLHttpRequest !== 'undefined' ? _clientBrowser.sendXmlHttpRequest : _clientNode.sendNodeAPIRequest;\n return sender(path, method, headers, body, encoding, timeout, withCredentials, tlsOptions);\n};\n_request.Request.verbose = false;\n_request.Request.withCredentials = false;\n_request.Request.methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];\n_request.Request.methods.forEach(function (method) {\n _request.Request[method] = function (path, body) {\n return new _request.Request(path, method, body);\n };\n});\nexports = module.exports = _request.Request;\nvar _default = exports[\"default\"] = _request.Request;", "module.exports = {\n /* The local file header */\n LOCHDR : 30, // LOC header size\n LOCSIG : 0x04034b50, // \"PK\\003\\004\"\n LOCVER : 4,\t// version needed to extract\n LOCFLG : 6, // general purpose bit flag\n LOCHOW : 8, // compression method\n LOCTIM : 10, // modification time (2 bytes time, 2 bytes date)\n LOCCRC : 14, // uncompressed file crc-32 value\n LOCSIZ : 18, // compressed size\n LOCLEN : 22, // uncompressed size\n LOCNAM : 26, // filename length\n LOCEXT : 28, // extra field length\n\n /* The Data descriptor */\n EXTSIG : 0x08074b50, // \"PK\\007\\008\"\n EXTHDR : 16, // EXT header size\n EXTCRC : 4, // uncompressed file crc-32 value\n EXTSIZ : 8, // compressed size\n EXTLEN : 12, // uncompressed size\n\n /* The central directory file header */\n CENHDR : 46, // CEN header size\n CENSIG : 0x02014b50, // \"PK\\001\\002\"\n CENVEM : 4, // version made by\n CENVER : 6, // version needed to extract\n CENFLG : 8, // encrypt, decrypt flags\n CENHOW : 10, // compression method\n CENTIM : 12, // modification time (2 bytes time, 2 bytes date)\n CENCRC : 16, // uncompressed file crc-32 value\n CENSIZ : 20, // compressed size\n CENLEN : 24, // uncompressed size\n CENNAM : 28, // filename length\n CENEXT : 30, // extra field length\n CENCOM : 32, // file comment length\n CENDSK : 34, // volume number start\n CENATT : 36, // internal file attributes\n CENATX : 38, // external file attributes (host system dependent)\n CENOFF : 42, // LOC header offset\n\n /* The entries in the end of central directory */\n ENDHDR : 22, // END header size\n ENDSIG : 0x06054b50, // \"PK\\005\\006\"\n ENDSUB : 8, // number of entries on this disk\n ENDTOT : 10, // total number of entries\n ENDSIZ : 12, // central directory size in bytes\n ENDOFF : 16, // offset of first CEN header\n ENDCOM : 20, // zip file comment length\n\n END64HDR : 20, // zip64 END header size\n END64SIG : 0x07064b50, // zip64 Locator signature, \"PK\\006\\007\"\n END64START : 4, // number of the disk with the start of the zip64\n END64OFF : 8, // relative offset of the zip64 end of central directory\n END64NUMDISKS : 16, // total number of disks\n\n ZIP64SIG : 0x06064b50, // zip64 signature, \"PK\\006\\006\"\n ZIP64HDR : 56, // zip64 record minimum size\n ZIP64LEAD : 12, // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE\n ZIP64SIZE : 4, // zip64 size of the central directory record\n ZIP64VEM : 12, // zip64 version made by\n ZIP64VER : 14, // zip64 version needed to extract\n ZIP64DSK : 16, // zip64 number of this disk\n ZIP64DSKDIR : 20, // number of the disk with the start of the record directory\n ZIP64SUB : 24, // number of entries on this disk\n ZIP64TOT : 32, // total number of entries\n ZIP64SIZB : 40, // zip64 central directory size in bytes\n ZIP64OFF : 48, // offset of start of central directory with respect to the starting disk number\n ZIP64EXTRA : 56, // extensible data sector\n\n /* Compression methods */\n STORED : 0, // no compression\n SHRUNK : 1, // shrunk\n REDUCED1 : 2, // reduced with compression factor 1\n REDUCED2 : 3, // reduced with compression factor 2\n REDUCED3 : 4, // reduced with compression factor 3\n REDUCED4 : 5, // reduced with compression factor 4\n IMPLODED : 6, // imploded\n // 7 reserved for Tokenizing compression algorithm\n DEFLATED : 8, // deflated\n ENHANCED_DEFLATED: 9, // enhanced deflated\n PKWARE : 10,// PKWare DCL imploded\n // 11 reserved by PKWARE\n BZIP2 : 12, // compressed using BZIP2\n // 13 reserved by PKWARE\n LZMA : 14, // LZMA\n // 15-17 reserved by PKWARE\n IBM_TERSE : 18, // compressed using IBM TERSE\n IBM_LZ77 : 19, // IBM LZ77 z\n AES_ENCRYPT : 99, // WinZIP AES encryption method\n\n /* General purpose bit flag */\n // values can obtained with expression 2**bitnr\n FLG_ENC : 1, // Bit 0: encrypted file\n FLG_COMP1 : 2, // Bit 1, compression option\n FLG_COMP2 : 4, // Bit 2, compression option\n FLG_DESC : 8, // Bit 3, data descriptor\n FLG_ENH : 16, // Bit 4, enhanced deflating\n FLG_PATCH : 32, // Bit 5, indicates that the file is compressed patched data.\n FLG_STR : 64, // Bit 6, strong encryption (patented)\n // Bits 7-10: Currently unused.\n FLG_EFS : 2048, // Bit 11: Language encoding flag (EFS)\n // Bit 12: Reserved by PKWARE for enhanced compression.\n // Bit 13: encrypted the Central Directory (patented).\n // Bits 14-15: Reserved by PKWARE.\n FLG_MSK : 4096, // mask header values\n\n /* Load type */\n FILE : 2,\n BUFFER : 1,\n NONE : 0,\n\n /* 4.5 Extensible data fields */\n EF_ID : 0,\n EF_SIZE : 2,\n\n /* Header IDs */\n ID_ZIP64 : 0x0001,\n ID_AVINFO : 0x0007,\n ID_PFS : 0x0008,\n ID_OS2 : 0x0009,\n ID_NTFS : 0x000a,\n ID_OPENVMS : 0x000c,\n ID_UNIX : 0x000d,\n ID_FORK : 0x000e,\n ID_PATCH : 0x000f,\n ID_X509_PKCS7 : 0x0014,\n ID_X509_CERTID_F : 0x0015,\n ID_X509_CERTID_C : 0x0016,\n ID_STRONGENC : 0x0017,\n ID_RECORD_MGT : 0x0018,\n ID_X509_PKCS7_RL : 0x0019,\n ID_IBM1 : 0x0065,\n ID_IBM2 : 0x0066,\n ID_POSZIP : 0x4690,\n\n EF_ZIP64_OR_32 : 0xffffffff,\n EF_ZIP64_OR_16 : 0xffff,\n EF_ZIP64_SUNCOMP : 0,\n EF_ZIP64_SCOMP : 8,\n EF_ZIP64_RHO : 16,\n EF_ZIP64_DSN : 24\n};\n", "const errors = {\n /* Header error messages */\n INVALID_LOC: \"Invalid LOC header (bad signature)\",\n INVALID_CEN: \"Invalid CEN header (bad signature)\",\n INVALID_END: \"Invalid END header (bad signature)\",\n\n /* Descriptor */\n DESCRIPTOR_NOT_EXIST: \"No descriptor present\",\n DESCRIPTOR_UNKNOWN: \"Unknown descriptor format\",\n DESCRIPTOR_FAULTY: \"Descriptor data is malformed\",\n\n /* ZipEntry error messages*/\n NO_DATA: \"Nothing to decompress\",\n BAD_CRC: \"CRC32 checksum failed {0}\",\n MAX_OUTPUT_EXCEEDED: \"Decompressed data exceeds the declared uncompressed size\",\n FILE_IN_THE_WAY: \"There is a file in the way: {0}\",\n UNKNOWN_METHOD: \"Invalid/unsupported compression method\",\n\n /* Inflater error messages */\n AVAIL_DATA: \"inflate::Available inflate data did not terminate\",\n INVALID_DISTANCE: \"inflate::Invalid literal/length or distance code in fixed or dynamic block\",\n TO_MANY_CODES: \"inflate::Dynamic block code description: too many length or distance codes\",\n INVALID_REPEAT_LEN: \"inflate::Dynamic block code description: repeat more than specified lengths\",\n INVALID_REPEAT_FIRST: \"inflate::Dynamic block code description: repeat lengths with no first length\",\n INCOMPLETE_CODES: \"inflate::Dynamic block code description: code lengths codes incomplete\",\n INVALID_DYN_DISTANCE: \"inflate::Dynamic block code description: invalid distance code lengths\",\n INVALID_CODES_LEN: \"inflate::Dynamic block code description: invalid literal/length code lengths\",\n INVALID_STORE_BLOCK: \"inflate::Stored block length did not match one's complement\",\n INVALID_BLOCK_TYPE: \"inflate::Invalid block type (type == 3)\",\n\n /* ADM-ZIP error messages */\n CANT_EXTRACT_FILE: \"Could not extract the file\",\n CANT_OVERRIDE: \"Target file already exists\",\n DISK_ENTRY_TOO_LARGE: \"Number of disk entries is too large\",\n NO_ZIP: \"No zip file was loaded\",\n NO_ENTRY: \"Entry doesn't exist\",\n DUPLICATE_ENTRY: \"Duplicate entry name {0}\",\n DIRECTORY_CONTENT_ERROR: \"A directory cannot have content\",\n FILE_NOT_FOUND: 'File not found: \"{0}\"',\n NOT_IMPLEMENTED: \"Not implemented\",\n INVALID_FILENAME: \"Invalid filename\",\n INVALID_FORMAT: \"Invalid or unsupported zip format. No END header found\",\n ZIP64_VALUE_TOO_LARGE: \"Zip64 value exceeds the maximum safe integer\",\n INVALID_PASS_PARAM: \"Incompatible password parameter\",\n WRONG_PASSWORD: \"Wrong Password\",\n\n /* ADM-ZIP */\n COMMENT_TOO_LONG: \"Comment is too long\", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space)\n EXTRA_FIELD_PARSE_ERROR: \"Extra field parsing error\"\n};\n\n// template\nfunction E(message) {\n return function (...args) {\n if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number\n message = message.replace(/\\{(\\d)\\}/g, (_, n) => args[n] || '');\n }\n\n return new Error('ADM-ZIP: ' + message);\n };\n}\n\n// Init errors with template\nfor (const msg of Object.keys(errors)) {\n exports[msg] = E(errors[msg]);\n}\n", "const fsystem = require(\"fs\");\nconst pth = require(\"path\");\nconst Constants = require(\"./constants\");\nconst Errors = require(\"./errors\");\nconst isWin = typeof process === \"object\" && \"win32\" === process.platform;\n\nconst is_Obj = (obj) => typeof obj === \"object\" && obj !== null;\n\n// generate CRC32 lookup table\nconst crcTable = new Uint32Array(256).map((t, c) => {\n for (let k = 0; k < 8; k++) {\n if ((c & 1) !== 0) {\n c = 0xedb88320 ^ (c >>> 1);\n } else {\n c >>>= 1;\n }\n }\n return c >>> 0;\n});\n\n// UTILS functions\n\nfunction Utils(opts) {\n this.sep = pth.sep;\n this.fs = fsystem;\n\n if (is_Obj(opts)) {\n // custom filesystem\n if (is_Obj(opts.fs) && typeof opts.fs.statSync === \"function\") {\n this.fs = opts.fs;\n }\n }\n}\n\nmodule.exports = Utils;\n\n// INSTANTIABLE functions\n\nUtils.prototype.makeDir = function (/*String*/ folder) {\n const self = this;\n\n // Sync - make directories tree\n function mkdirSync(/*String*/ fpath) {\n let resolvedPath = fpath.split(self.sep)[0];\n fpath.split(self.sep).forEach(function (name) {\n if (!name || name.substr(-1, 1) === \":\") return;\n resolvedPath += self.sep + name;\n var stat;\n try {\n stat = self.fs.statSync(resolvedPath);\n } catch (e) {\n if (e.message && e.message.startsWith('ENOENT')) {\n self.fs.mkdirSync(resolvedPath);\n } else {\n throw e;\n }\n }\n if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`\"${resolvedPath}\"`);\n });\n }\n\n mkdirSync(folder);\n};\n\nUtils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr) {\n const self = this;\n if (self.fs.existsSync(path)) {\n if (!overwrite) return false; // cannot overwrite\n\n var stat = self.fs.statSync(path);\n if (stat.isDirectory()) {\n return false;\n }\n }\n var folder = pth.dirname(path);\n if (!self.fs.existsSync(folder)) {\n self.makeDir(folder);\n }\n\n var fd;\n try {\n fd = self.fs.openSync(path, \"w\", 0o666); // 0666\n } catch (e) {\n self.fs.chmodSync(path, 0o666);\n fd = self.fs.openSync(path, \"w\", 0o666);\n }\n if (fd) {\n try {\n self.fs.writeSync(fd, content, 0, content.length, 0);\n } finally {\n self.fs.closeSync(fd);\n }\n }\n self.fs.chmodSync(path, attr || 0o666);\n return true;\n};\n\nUtils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr, /*Function*/ callback) {\n if (typeof attr === \"function\") {\n callback = attr;\n attr = undefined;\n }\n\n const self = this;\n\n self.fs.exists(path, function (exist) {\n if (exist && !overwrite) return callback(false);\n\n self.fs.stat(path, function (err, stat) {\n if (exist && stat && stat.isDirectory()) {\n return callback(false);\n }\n\n var folder = pth.dirname(path);\n self.fs.exists(folder, function (exists) {\n if (!exists) {\n // makeDir is synchronous and can throw (e.g. EACCES); report failure\n // rather than letting it escape this callback as an uncaught exception\n try {\n self.makeDir(folder);\n } catch (e) {\n return callback(false);\n }\n }\n\n // write the content to an open descriptor, then apply the attributes\n const writeToFd = function (fd) {\n self.fs.write(fd, content, 0, content.length, 0, function (writeErr) {\n self.fs.close(fd, function () {\n // surface write failures instead of silently reporting success (issue #402)\n if (writeErr) return callback(false);\n self.fs.chmod(path, attr || 0o666, function () {\n callback(true);\n });\n });\n });\n };\n\n self.fs.open(path, \"w\", 0o666, function (err, fd) {\n if (err) {\n // the target may exist but be read-only: make it writable and retry once\n self.fs.chmod(path, 0o666, function () {\n self.fs.open(path, \"w\", 0o666, function (retryErr, fd) {\n // Previously the retry error was ignored and an undefined fd was\n // passed to fs.write, throwing an uncaught ERR_INVALID_ARG_TYPE that\n // crashed the process (issues #470, #459, #402). Report failure instead.\n if (retryErr || !fd) return callback(false);\n writeToFd(fd);\n });\n });\n } else if (fd) {\n writeToFd(fd);\n } else {\n callback(false);\n }\n });\n });\n });\n });\n};\n\n// Guard extraction against writing through a symlink that already exists inside\n// the target directory. sanitize() only proves the textual path stays under the\n// root; it cannot see that a component on disk is a symlink pointing elsewhere,\n// so open()/mkdir() would follow it and write outside the root. Walk every path\n// component strictly below root and reject any that is a symlink. Components at\n// or above root are the caller's own choice and are left untouched, so a root\n// that itself lives under a symlink (e.g. /tmp on macOS) still extracts.\nUtils.prototype.assertPathSafe = function (/*String*/ root, /*String*/ target) {\n const self = this;\n if (typeof self.fs.lstatSync !== \"function\") return;\n\n const resolvedRoot = pth.resolve(root);\n const resolvedTarget = pth.resolve(target);\n if (resolvedTarget === resolvedRoot) return;\n\n const rel = pth.relative(resolvedRoot, resolvedTarget);\n // Not under root: sanitize() is responsible for that case; nothing to walk.\n if (!rel || rel === \"..\" || rel.startsWith(\"..\" + pth.sep) || pth.isAbsolute(rel)) return;\n\n let cur = resolvedRoot;\n for (const part of rel.split(pth.sep)) {\n if (!part || part === \".\") continue;\n cur = pth.join(cur, part);\n let stat;\n try {\n stat = self.fs.lstatSync(cur);\n } catch (e) {\n break; // component does not exist yet: nothing below it can be a symlink\n }\n if (stat.isSymbolicLink()) throw Errors.FILE_IN_THE_WAY(`\"${cur}\"`);\n }\n};\n\nUtils.prototype.findFiles = function (/*String*/ path) {\n const self = this;\n const canLstat = typeof self.fs.lstatSync === \"function\";\n const rootReal = self.fs.realpathSync(path);\n\n // A symlink whose target lies outside the folder being archived must not be\n // followed: statSync would dereference it and copy the target's contents into\n // the archive, disclosing files outside the root (GHSA-wx42-xcp7-pgr4). Allow\n // symlinks that resolve to a location inside the root, reject any that escape.\n function escapesRoot(/*String*/ p) {\n if (!canLstat) return false;\n if (!self.fs.lstatSync(p).isSymbolicLink()) return false;\n let real;\n try {\n real = self.fs.realpathSync(p);\n } catch (e) {\n return true; // dangling or unresolvable symlink: do not follow\n }\n return !(real === rootReal || real.startsWith(rootReal + pth.sep));\n }\n\n function findSync(/*String*/ dir, /*RegExp*/ pattern, /*Boolean*/ recursive, /*Set*/ visited) {\n if (typeof pattern === \"boolean\") {\n recursive = pattern;\n pattern = undefined;\n }\n let files = [];\n self.fs.readdirSync(dir).forEach(function (file) {\n const path = pth.join(dir, file);\n\n if (escapesRoot(path)) return;\n\n const stat = self.fs.statSync(path);\n\n if (!pattern || pattern.test(path)) {\n files.push(pth.normalize(path) + (stat.isDirectory() ? self.sep : \"\"));\n }\n\n if (stat.isDirectory() && recursive) {\n // Descend by resolved real path and skip directories we have already\n // visited. This stops a symlink that points back to an ancestor from\n // recursing forever until the path fails with ELOOP / ENAMETOOLONG\n // (issue #541).\n const realDir = self.fs.realpathSync(path);\n if (!visited.has(realDir)) {\n visited.add(realDir);\n files = files.concat(findSync(path, pattern, recursive, visited));\n }\n }\n });\n return files;\n }\n\n return findSync(path, undefined, true, new Set([rootReal]));\n};\n\n/**\n * Callback for showing if everything was done.\n *\n * @callback filelistCallback\n * @param {Error} err - Error object\n * @param {string[]} list - was request fully completed\n */\n\n/**\n *\n * @param {string} dir\n * @param {filelistCallback} cb\n */\nUtils.prototype.findFilesAsync = function (dir, cb) {\n const self = this;\n const results = [];\n let finished = false;\n const finish = function (err) {\n if (finished) return;\n finished = true;\n cb(err, err ? undefined : results);\n };\n\n const canLstat = typeof self.fs.lstat === \"function\";\n let rootReal = null;\n\n // Reject a symlink whose target escapes the root being archived, so its\n // contents are not dereferenced and copied into the archive\n // (GHSA-wx42-xcp7-pgr4). A symlink resolving to a location inside the root is\n // allowed; a dangling or escaping one is skipped. Calls back (err, escapes).\n const escapesRoot = function (file, cb) {\n if (!canLstat) return cb(null, false);\n self.fs.lstat(file, function (err, lst) {\n if (err) return cb(err);\n if (!lst || !lst.isSymbolicLink()) return cb(null, false);\n self.fs.realpath(file, function (err, real) {\n if (err) return cb(null, true); // dangling: do not follow\n cb(null, !(real === rootReal || real.startsWith(rootReal + pth.sep)));\n });\n });\n };\n\n // Descend by resolved real path and skip directories already visited, so a\n // symlink pointing back to an ancestor cannot recurse forever (issue #541).\n const walk = function (dir, visited, done) {\n self.fs.readdir(dir, function (err, list) {\n if (err) return done(err);\n let pending = list.length;\n if (!pending) return done();\n list.forEach(function (name) {\n const file = pth.join(dir, name);\n escapesRoot(file, function (err, escapes) {\n if (err) return done(err);\n if (escapes) {\n if (!--pending) done();\n return;\n }\n self.fs.stat(file, function (err, stat) {\n if (err) return done(err);\n if (!stat) {\n if (!--pending) done();\n return;\n }\n results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : \"\"));\n if (!stat.isDirectory()) {\n if (!--pending) done();\n return;\n }\n self.fs.realpath(file, function (err, realDir) {\n if (err) return done(err);\n if (visited.has(realDir)) {\n if (!--pending) done();\n return;\n }\n visited.add(realDir);\n walk(file, visited, function (err) {\n if (err) return done(err);\n if (!--pending) done();\n });\n });\n });\n });\n });\n });\n };\n\n self.fs.realpath(dir, function (err, realDir) {\n if (err) return finish(err);\n rootReal = realDir;\n walk(dir, new Set([realDir]), finish);\n });\n};\n\nUtils.prototype.getAttributes = function () {};\n\nUtils.prototype.setAttributes = function () {};\n\n// STATIC functions\n\n// crc32 single update (it is part of crc32)\nUtils.crc32update = function (crc, byte) {\n return crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n};\n\nUtils.crc32 = function (buf) {\n if (typeof buf === \"string\") {\n buf = Buffer.from(buf, \"utf8\");\n }\n\n let len = buf.length;\n let crc = ~0;\n for (let off = 0; off < len; ) crc = Utils.crc32update(crc, buf[off++]);\n // xor and cast as uint32 number\n return ~crc >>> 0;\n};\n\nUtils.methodToString = function (/*Number*/ method) {\n switch (method) {\n case Constants.STORED:\n return \"STORED (\" + method + \")\";\n case Constants.DEFLATED:\n return \"DEFLATED (\" + method + \")\";\n default:\n return \"UNSUPPORTED (\" + method + \")\";\n }\n};\n\n/**\n * removes \"..\" style path elements\n * @param {string} path - fixable path\n * @returns string - fixed filepath\n */\nUtils.canonical = function (/*string*/ path) {\n if (!path) return \"\";\n // trick normalize think path is absolute\n const safeSuffix = pth.posix.normalize(\"/\" + path.split(\"\\\\\").join(\"/\"));\n return pth.join(\".\", safeSuffix);\n};\n\n/**\n * fix file names in achive\n * @param {string} path - fixable path\n * @returns string - fixed filepath\n */\n\nUtils.zipnamefix = function (path) {\n if (!path) return \"\";\n // trick normalize think path is absolute\n const safeSuffix = pth.posix.normalize(\"/\" + path.split(\"\\\\\").join(\"/\"));\n return pth.posix.join(\".\", safeSuffix);\n};\n\n/**\n *\n * @param {Array} arr\n * @param {function} callback\n * @returns\n */\nUtils.findLast = function (arr, callback) {\n if (!Array.isArray(arr)) throw new TypeError(\"arr is not array\");\n\n const len = arr.length >>> 0;\n for (let i = len - 1; i >= 0; i--) {\n if (callback(arr[i], i, arr)) {\n return arr[i];\n }\n }\n return void 0;\n};\n\n// make absolute paths taking prefix as root folder\nUtils.sanitize = function (/*string*/ prefix, /*string*/ name) {\n prefix = pth.resolve(pth.normalize(prefix));\n var parts = name.split(\"/\");\n for (var i = 0, l = parts.length; i < l; i++) {\n var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));\n if (path === prefix || path.startsWith(prefix + pth.sep)) {\n return path;\n }\n }\n return pth.normalize(pth.join(prefix, pth.basename(name)));\n};\n\n// converts buffer, Uint8Array, string types to buffer\nUtils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input, /* function */ encoder) {\n if (Buffer.isBuffer(input)) {\n return input;\n } else if (input instanceof Uint8Array) {\n return Buffer.from(input);\n } else {\n // expect string all other values are invalid and return empty buffer\n return typeof input === \"string\" ? encoder(input) : Buffer.alloc(0);\n }\n};\n\nUtils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) {\n const lo = buffer.readUInt32LE(index);\n const hi = buffer.readUInt32LE(index + 4);\n const value = hi * 0x100000000 + lo;\n // The result is a JS number, so values above 2^53 - 1 cannot be represented\n // exactly. These are zip64 sizes/offsets/counts used as buffer indices; a\n // silently rounded value would misparse the archive. Reject instead.\n if (value > Number.MAX_SAFE_INTEGER) {\n throw Errors.ZIP64_VALUE_TOO_LARGE();\n }\n return value;\n};\n\nUtils.writeBigUInt64LE = function (/*Buffer*/ buffer, /*Number*/ value, /*int*/ index) {\n const lo = value >>> 0;\n const hi = Math.floor(value / 0x100000000) >>> 0;\n buffer.writeUInt32LE(lo, index);\n buffer.writeUInt32LE(hi, index + 4);\n};\n\nUtils.fromDOS2Date = function (val) {\n return new Date(((val >> 25) & 0x7f) + 1980, Math.max(((val >> 21) & 0x0f) - 1, 0), Math.max((val >> 16) & 0x1f, 1), (val >> 11) & 0x1f, (val >> 5) & 0x3f, (val & 0x1f) << 1);\n};\n\nUtils.fromDate2DOS = function (val) {\n let date = 0;\n let time = 0;\n if (val.getFullYear() > 1979) {\n date = (((val.getFullYear() - 1980) & 0x7f) << 9) | ((val.getMonth() + 1) << 5) | val.getDate();\n time = (val.getHours() << 11) | (val.getMinutes() << 5) | (val.getSeconds() >> 1);\n }\n return (date << 16) | time;\n};\n\nUtils.isWin = isWin; // Do we have windows system\nUtils.crcTable = crcTable;\n", "const pth = require(\"path\");\n\nmodule.exports = function (/*String*/ path, /*Utils object*/ { fs }) {\n var _path = path || \"\",\n _obj = newAttr(),\n _stat = null;\n\n function newAttr() {\n return {\n directory: false,\n readonly: false,\n hidden: false,\n executable: false,\n mtime: 0,\n atime: 0\n };\n }\n\n if (_path && fs.existsSync(_path)) {\n _stat = fs.statSync(_path);\n _obj.directory = _stat.isDirectory();\n _obj.mtime = _stat.mtime;\n _obj.atime = _stat.atime;\n _obj.executable = (0o111 & _stat.mode) !== 0; // file is executable who ever har right not just owner\n _obj.readonly = (0o200 & _stat.mode) === 0; // readonly if owner has no write right\n _obj.hidden = pth.basename(_path)[0] === \".\";\n } else {\n console.warn(\"Invalid path: \" + _path);\n }\n\n return {\n get directory() {\n return _obj.directory;\n },\n\n get readOnly() {\n return _obj.readonly;\n },\n\n get hidden() {\n return _obj.hidden;\n },\n\n get mtime() {\n return _obj.mtime;\n },\n\n get atime() {\n return _obj.atime;\n },\n\n get executable() {\n return _obj.executable;\n },\n\n decodeAttributes: function () {},\n\n encodeAttributes: function () {},\n\n toJSON: function () {\n return {\n path: _path,\n isDirectory: _obj.directory,\n isReadOnly: _obj.readonly,\n isHidden: _obj.hidden,\n isExecutable: _obj.executable,\n mTime: _obj.mtime,\n aTime: _obj.atime\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n", "module.exports = {\n efs: true,\n encode: (data) => Buffer.from(data, \"utf8\"),\n decode: (data) => data.toString(\"utf8\")\n};\n", "module.exports = require(\"./utils\");\nmodule.exports.Constants = require(\"./constants\");\nmodule.exports.Errors = require(\"./errors\");\nmodule.exports.FileAttr = require(\"./fattr\");\nmodule.exports.decoder = require(\"./decoder\");\n", "var Utils = require(\"../util\"),\n Constants = Utils.Constants;\n\n/* The central directory file header */\nmodule.exports = function () {\n var _verMade = 20, // v2.0\n _version = 10, // v1.0\n _flags = 0,\n _method = 0,\n _time = 0,\n _crc = 0,\n _compressedSize = 0,\n _size = 0,\n _fnameLen = 0,\n _extraLen = 0,\n _comLen = 0,\n _diskStart = 0,\n _inattr = 0,\n _attr = 0,\n _offset = 0;\n\n _verMade |= Utils.isWin ? 0x0a00 : 0x0300;\n\n // Set EFS flag since filename and comment fields are all by default encoded using UTF-8.\n // Without it file names may be corrupted for other apps when file names use unicode chars\n _flags |= Constants.FLG_EFS;\n\n const _localHeader = {\n extraLen: 0\n };\n\n // casting\n const uint32 = (val) => Math.max(0, val) >>> 0;\n const uint16 = (val) => Math.max(0, val) & 0xffff;\n const uint8 = (val) => Math.max(0, val) & 0xff;\n\n _time = Utils.fromDate2DOS(new Date());\n\n return {\n get made() {\n return _verMade;\n },\n set made(val) {\n _verMade = val;\n },\n\n get version() {\n return _version;\n },\n set version(val) {\n _version = val;\n },\n\n get flags() {\n return _flags;\n },\n set flags(val) {\n _flags = val;\n },\n\n get flags_efs() {\n return (_flags & Constants.FLG_EFS) > 0;\n },\n set flags_efs(val) {\n if (val) {\n _flags |= Constants.FLG_EFS;\n } else {\n _flags &= ~Constants.FLG_EFS;\n }\n },\n\n get flags_desc() {\n return (_flags & Constants.FLG_DESC) > 0;\n },\n set flags_desc(val) {\n if (val) {\n _flags |= Constants.FLG_DESC;\n } else {\n _flags &= ~Constants.FLG_DESC;\n }\n },\n\n get method() {\n return _method;\n },\n set method(val) {\n switch (val) {\n case Constants.STORED:\n this.version = 10;\n break;\n case Constants.DEFLATED:\n default:\n this.version = 20;\n }\n _method = val;\n },\n\n get time() {\n return Utils.fromDOS2Date(this.timeval);\n },\n set time(val) {\n val = new Date(val);\n this.timeval = Utils.fromDate2DOS(val);\n },\n\n get timeval() {\n return _time;\n },\n set timeval(val) {\n _time = uint32(val);\n },\n\n get timeHighByte() {\n return uint8(_time >>> 8);\n },\n get crc() {\n return _crc;\n },\n set crc(val) {\n _crc = uint32(val);\n },\n\n get compressedSize() {\n return _compressedSize;\n },\n set compressedSize(val) {\n _compressedSize = uint32(val);\n },\n\n get size() {\n return _size;\n },\n set size(val) {\n _size = uint32(val);\n },\n\n get fileNameLength() {\n return _fnameLen;\n },\n set fileNameLength(val) {\n _fnameLen = val;\n },\n\n get extraLength() {\n return _extraLen;\n },\n set extraLength(val) {\n _extraLen = val;\n },\n\n get extraLocalLength() {\n return _localHeader.extraLen;\n },\n set extraLocalLength(val) {\n _localHeader.extraLen = val;\n },\n\n get commentLength() {\n return _comLen;\n },\n set commentLength(val) {\n _comLen = val;\n },\n\n get diskNumStart() {\n return _diskStart;\n },\n set diskNumStart(val) {\n _diskStart = uint32(val);\n },\n\n get inAttr() {\n return _inattr;\n },\n set inAttr(val) {\n _inattr = uint32(val);\n },\n\n get attr() {\n return _attr;\n },\n set attr(val) {\n _attr = uint32(val);\n },\n\n // get Unix file permissions\n get fileAttr() {\n // Mask to the 9 rwxrwxrwx bits only. The setuid (0o4000), setgid\n // (0o2000) and sticky (0o1000) bits are attacker-controlled archive\n // metadata; preserving them on extraction (keepOriginalPermission)\n // lets a crafted zip plant a setuid-root binary when extracting as\n // root, a local privilege escalation (GHSA-679w-jf3m-wh39).\n return ((_attr || 0) >> 16) & 0o777;\n },\n\n get offset() {\n return _offset;\n },\n set offset(val) {\n _offset = uint32(val);\n },\n\n get encrypted() {\n return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC;\n },\n\n get centralHeaderSize() {\n return Constants.CENHDR + _fnameLen + _extraLen + _comLen;\n },\n\n get realDataOffset() {\n return _offset + Constants.LOCHDR + _localHeader.fnameLen + _localHeader.extraLen;\n },\n\n get localHeader() {\n return _localHeader;\n },\n\n loadLocalHeaderFromBinary: function (/*Buffer*/ input) {\n // The LOC offset comes from the central directory and is attacker\n // controlled. Reject one that would read past the end of the buffer,\n // otherwise readUInt32LE below throws a raw RangeError instead of a\n // clean INVALID_LOC (and escapes the async error path).\n if (_offset < 0 || _offset + Constants.LOCHDR > input.length) {\n throw Utils.Errors.INVALID_LOC();\n }\n var data = input.slice(_offset, _offset + Constants.LOCHDR);\n // 30 bytes and should start with \"PK\\003\\004\"\n if (data.readUInt32LE(0) !== Constants.LOCSIG) {\n throw Utils.Errors.INVALID_LOC();\n }\n\n // version needed to extract\n _localHeader.version = data.readUInt16LE(Constants.LOCVER);\n // general purpose bit flag\n _localHeader.flags = data.readUInt16LE(Constants.LOCFLG);\n // desc flag\n _localHeader.flags_desc = (_localHeader.flags & Constants.FLG_DESC) > 0;\n // compression method\n _localHeader.method = data.readUInt16LE(Constants.LOCHOW);\n // modification time (2 bytes time, 2 bytes date)\n _localHeader.time = data.readUInt32LE(Constants.LOCTIM);\n // uncompressed file crc-32 valu\n _localHeader.crc = data.readUInt32LE(Constants.LOCCRC);\n // compressed size\n _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ);\n // uncompressed size\n _localHeader.size = data.readUInt32LE(Constants.LOCLEN);\n // filename length\n _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM);\n // extra field length\n _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT);\n\n // read extra data\n const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen;\n const extraEnd = extraStart + _localHeader.extraLen;\n return input.slice(extraStart, extraEnd);\n },\n\n loadFromBinary: function (/*Buffer*/ data) {\n // data should be 46 bytes and start with \"PK 01 02\"\n if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {\n throw Utils.Errors.INVALID_CEN();\n }\n // version made by\n _verMade = data.readUInt16LE(Constants.CENVEM);\n // version needed to extract\n _version = data.readUInt16LE(Constants.CENVER);\n // encrypt, decrypt flags\n _flags = data.readUInt16LE(Constants.CENFLG);\n // compression method\n _method = data.readUInt16LE(Constants.CENHOW);\n // modification time (2 bytes time, 2 bytes date)\n _time = data.readUInt32LE(Constants.CENTIM);\n // uncompressed file crc-32 value\n _crc = data.readUInt32LE(Constants.CENCRC);\n // compressed size\n _compressedSize = data.readUInt32LE(Constants.CENSIZ);\n // uncompressed size\n _size = data.readUInt32LE(Constants.CENLEN);\n // filename length\n _fnameLen = data.readUInt16LE(Constants.CENNAM);\n // extra field length\n _extraLen = data.readUInt16LE(Constants.CENEXT);\n // file comment length\n _comLen = data.readUInt16LE(Constants.CENCOM);\n // volume number start\n _diskStart = data.readUInt16LE(Constants.CENDSK);\n // internal file attributes\n _inattr = data.readUInt16LE(Constants.CENATT);\n // external file attributes\n _attr = data.readUInt32LE(Constants.CENATX);\n // LOC header offset\n _offset = data.readUInt32LE(Constants.CENOFF);\n },\n\n localHeaderToBinary: function () {\n // LOC header size (30 bytes)\n var data = Buffer.alloc(Constants.LOCHDR);\n // \"PK\\003\\004\"\n data.writeUInt32LE(Constants.LOCSIG, 0);\n // version needed to extract\n data.writeUInt16LE(_version, Constants.LOCVER);\n // general purpose bit flag\n // clear bit 3 (data descriptor): we always write the real crc-32\n // and sizes into this local header, so no trailing descriptor is\n // emitted. Leaving the flag set would make the output unreadable\n // (see issue #555).\n data.writeUInt16LE(_flags & ~Constants.FLG_DESC, Constants.LOCFLG);\n // compression method\n data.writeUInt16LE(_method, Constants.LOCHOW);\n // modification time (2 bytes time, 2 bytes date)\n data.writeUInt32LE(_time, Constants.LOCTIM);\n // uncompressed file crc-32 value\n data.writeUInt32LE(_crc, Constants.LOCCRC);\n // compressed size\n data.writeUInt32LE(_compressedSize, Constants.LOCSIZ);\n // uncompressed size\n data.writeUInt32LE(_size, Constants.LOCLEN);\n // filename length\n data.writeUInt16LE(_fnameLen, Constants.LOCNAM);\n // extra field length\n data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT);\n return data;\n },\n\n centralHeaderToBinary: function () {\n // CEN header size (46 bytes)\n var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen);\n // \"PK\\001\\002\"\n data.writeUInt32LE(Constants.CENSIG, 0);\n // version made by\n data.writeUInt16LE(_verMade, Constants.CENVEM);\n // version needed to extract\n data.writeUInt16LE(_version, Constants.CENVER);\n // encrypt, decrypt flags\n // clear bit 3 (data descriptor) to match the local header we emit\n // (real crc/sizes are written, no descriptor follows the data) \u2014 issue #555\n data.writeUInt16LE(_flags & ~Constants.FLG_DESC, Constants.CENFLG);\n // compression method\n data.writeUInt16LE(_method, Constants.CENHOW);\n // modification time (2 bytes time, 2 bytes date)\n data.writeUInt32LE(_time, Constants.CENTIM);\n // uncompressed file crc-32 value\n data.writeUInt32LE(_crc, Constants.CENCRC);\n // compressed size\n data.writeUInt32LE(_compressedSize, Constants.CENSIZ);\n // uncompressed size\n data.writeUInt32LE(_size, Constants.CENLEN);\n // filename length\n data.writeUInt16LE(_fnameLen, Constants.CENNAM);\n // extra field length\n data.writeUInt16LE(_extraLen, Constants.CENEXT);\n // file comment length\n data.writeUInt16LE(_comLen, Constants.CENCOM);\n // volume number start\n data.writeUInt16LE(_diskStart, Constants.CENDSK);\n // internal file attributes\n data.writeUInt16LE(_inattr, Constants.CENATT);\n // external file attributes\n data.writeUInt32LE(_attr, Constants.CENATX);\n // LOC header offset\n data.writeUInt32LE(_offset, Constants.CENOFF);\n return data;\n },\n\n toJSON: function () {\n const bytes = function (nr) {\n return nr + \" bytes\";\n };\n\n return {\n made: _verMade,\n version: _version,\n flags: _flags,\n method: Utils.methodToString(_method),\n time: this.time,\n crc: \"0x\" + _crc.toString(16).toUpperCase(),\n compressedSize: bytes(_compressedSize),\n size: bytes(_size),\n fileNameLength: bytes(_fnameLen),\n extraLength: bytes(_extraLen),\n commentLength: bytes(_comLen),\n diskNumStart: _diskStart,\n inAttr: _inattr,\n attr: _attr,\n offset: _offset,\n centralHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen)\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n", "var Utils = require(\"../util\"),\n Constants = Utils.Constants;\n\n/* The entries in the end of central directory */\nmodule.exports = function () {\n var _volumeEntries = 0,\n _totalEntries = 0,\n _size = 0,\n _offset = 0,\n _commentLength = 0;\n\n const needsZip64 = () => _volumeEntries > Constants.EF_ZIP64_OR_16 || _totalEntries > Constants.EF_ZIP64_OR_16 || _size > Constants.EF_ZIP64_OR_32 || _offset > Constants.EF_ZIP64_OR_32;\n\n return {\n get diskEntries() {\n return _volumeEntries;\n },\n set diskEntries(/*Number*/ val) {\n _volumeEntries = _totalEntries = val;\n },\n\n get totalEntries() {\n return _totalEntries;\n },\n set totalEntries(/*Number*/ val) {\n _totalEntries = _volumeEntries = val;\n },\n\n get size() {\n return _size;\n },\n set size(/*Number*/ val) {\n _size = val;\n },\n\n get offset() {\n return _offset;\n },\n set offset(/*Number*/ val) {\n _offset = val;\n },\n\n get commentLength() {\n return _commentLength;\n },\n set commentLength(/*Number*/ val) {\n _commentLength = val;\n },\n\n get mainHeaderSize() {\n return (needsZip64() ? Constants.ZIP64HDR + Constants.END64HDR : 0) + Constants.ENDHDR + _commentLength;\n },\n\n loadFromBinary: function (/*Buffer*/ data) {\n // data should be 22 bytes and start with \"PK 05 06\"\n // or be 56+ bytes and start with \"PK 06 06\" for Zip64\n if (\n (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) &&\n (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)\n ) {\n throw Utils.Errors.INVALID_END();\n }\n\n if (data.readUInt32LE(0) === Constants.ENDSIG) {\n // number of entries on this volume\n _volumeEntries = data.readUInt16LE(Constants.ENDSUB);\n // total number of entries\n _totalEntries = data.readUInt16LE(Constants.ENDTOT);\n // central directory size in bytes\n _size = data.readUInt32LE(Constants.ENDSIZ);\n // offset of first CEN header\n _offset = data.readUInt32LE(Constants.ENDOFF);\n // zip file comment length\n _commentLength = data.readUInt16LE(Constants.ENDCOM);\n } else {\n // number of entries on this volume\n _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB);\n // total number of entries\n _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT);\n // central directory size in bytes\n _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZB);\n // offset of first CEN header\n _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF);\n\n _commentLength = 0;\n }\n },\n\n toBinary: function () {\n if (!needsZip64()) {\n var b = Buffer.alloc(Constants.ENDHDR + _commentLength);\n // \"PK 05 06\" signature\n b.writeUInt32LE(Constants.ENDSIG, 0);\n b.writeUInt32LE(0, 4);\n // number of entries on this volume\n b.writeUInt16LE(_volumeEntries, Constants.ENDSUB);\n // total number of entries\n b.writeUInt16LE(_totalEntries, Constants.ENDTOT);\n // central directory size in bytes\n b.writeUInt32LE(_size, Constants.ENDSIZ);\n // offset of first CEN header\n b.writeUInt32LE(_offset, Constants.ENDOFF);\n // zip file comment length\n b.writeUInt16LE(_commentLength, Constants.ENDCOM);\n // fill comment memory with spaces so no garbage is left there\n b.fill(\" \", Constants.ENDHDR);\n\n return b;\n }\n\n var b = Buffer.alloc(this.mainHeaderSize);\n let offset = 0;\n\n // Zip64 end of central directory record.\n b.writeUInt32LE(Constants.ZIP64SIG, offset);\n Utils.writeBigUInt64LE(b, Constants.ZIP64HDR - Constants.ZIP64LEAD, offset + Constants.ZIP64SIZE);\n b.writeUInt16LE(45, offset + Constants.ZIP64VEM);\n b.writeUInt16LE(45, offset + Constants.ZIP64VER);\n b.writeUInt32LE(0, offset + Constants.ZIP64DSK);\n b.writeUInt32LE(0, offset + Constants.ZIP64DSKDIR);\n Utils.writeBigUInt64LE(b, _volumeEntries, offset + Constants.ZIP64SUB);\n Utils.writeBigUInt64LE(b, _totalEntries, offset + Constants.ZIP64TOT);\n Utils.writeBigUInt64LE(b, _size, offset + Constants.ZIP64SIZB);\n Utils.writeBigUInt64LE(b, _offset, offset + Constants.ZIP64OFF);\n\n const zip64EndOffset = _offset + _size;\n offset += Constants.ZIP64HDR;\n\n // Zip64 end of central directory locator.\n b.writeUInt32LE(Constants.END64SIG, offset);\n b.writeUInt32LE(0, offset + Constants.END64START);\n Utils.writeBigUInt64LE(b, zip64EndOffset, offset + Constants.END64OFF);\n b.writeUInt32LE(1, offset + Constants.END64NUMDISKS);\n offset += Constants.END64HDR;\n\n // \"PK 05 06\" signature\n b.writeUInt32LE(Constants.ENDSIG, offset);\n b.writeUInt32LE(0, offset + 4);\n // number of entries on this volume\n b.writeUInt16LE(Math.min(_volumeEntries, Constants.EF_ZIP64_OR_16), offset + Constants.ENDSUB);\n // total number of entries\n b.writeUInt16LE(Math.min(_totalEntries, Constants.EF_ZIP64_OR_16), offset + Constants.ENDTOT);\n // central directory size in bytes\n b.writeUInt32LE(Math.min(_size, Constants.EF_ZIP64_OR_32), offset + Constants.ENDSIZ);\n // offset of first CEN header\n b.writeUInt32LE(Math.min(_offset, Constants.EF_ZIP64_OR_32), offset + Constants.ENDOFF);\n // zip file comment length\n b.writeUInt16LE(_commentLength, offset + Constants.ENDCOM);\n // fill comment memory with spaces so no garbage is left there\n b.fill(\" \", offset + Constants.ENDHDR);\n\n return b;\n },\n\n toJSON: function () {\n // creates 0x0000 style output\n const offset = function (nr, len) {\n let offs = nr.toString(16).toUpperCase();\n while (offs.length < len) offs = \"0\" + offs;\n return \"0x\" + offs;\n };\n\n return {\n diskEntries: _volumeEntries,\n totalEntries: _totalEntries,\n size: _size + \" bytes\",\n offset: offset(_offset, 4),\n commentLength: _commentLength\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n// Misspelled\n", "exports.EntryHeader = require(\"./entryHeader\");\nexports.MainHeader = require(\"./mainHeader\");\n", "module.exports = function (/*Buffer*/ inbuf) {\n var zlib = require(\"zlib\");\n\n var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 };\n\n return {\n deflate: function () {\n return zlib.deflateRawSync(inbuf, opts);\n },\n\n deflateAsync: function (/*Function*/ callback) {\n var tmp = zlib.createDeflateRaw(opts),\n parts = [],\n total = 0;\n tmp.on(\"data\", function (data) {\n parts.push(data);\n total += data.length;\n });\n tmp.on(\"end\", function () {\n var buf = Buffer.alloc(total),\n written = 0;\n buf.fill(0);\n for (var i = 0; i < parts.length; i++) {\n var part = parts[i];\n part.copy(buf, written);\n written += part.length;\n }\n callback && callback(buf);\n });\n tmp.end(inbuf);\n }\n };\n};\n", "const version = +(process?.versions?.node ?? \"\").split(\".\")[0] || 0;\nconst Errors = require(\"../util/errors\");\n\nmodule.exports = function (/*Buffer*/ inbuf, /*number*/ expectedLength) {\n var zlib = require(\"zlib\");\n // Cap decompression output at the entry's declared uncompressed size to bound\n // decompression bombs (CVE-2026-39244). A declared size of 0 must not disable\n // the cap: a genuinely empty entry inflates to 0 bytes, so a 1-byte floor\n // still lets it through while stopping a bomb that lies about its size\n // (GHSA-rcw4-f5rp-g42v). zlib requires maxOutputLength >= 1.\n const maxOutputLength = expectedLength > 0 ? expectedLength : 1;\n const option = version >= 15 ? { maxOutputLength } : {};\n\n return {\n inflate: function () {\n return zlib.inflateRawSync(inbuf, option);\n },\n\n inflateAsync: function (/*Function*/ callback) {\n var tmp = zlib.createInflateRaw(option),\n parts = [],\n total = 0,\n done = false;\n const fail = function (err) {\n if (done) return;\n done = true;\n tmp.destroy();\n callback && callback(Buffer.alloc(0), err);\n };\n // Route stream errors (e.g. Z_DATA_ERROR on malformed input) through the\n // callback. Without an \"error\" listener zlib re-throws the event as an\n // uncaught exception on a later tick, crashing the host process instead\n // of failing the call (GHSA-8238-w5pm-2374).\n tmp.on(\"error\", function (err) {\n fail(err);\n });\n tmp.on(\"data\", function (data) {\n if (done) return;\n total += data.length;\n // The streaming API ignores maxOutputLength, so enforce the cap by\n // hand; otherwise the async path decompresses without limit while the\n // sync path is capped (GHSA-v429-h5qx-84wm, GHSA-c6fg-446q-cg94).\n if (total > maxOutputLength) {\n return fail(Errors.MAX_OUTPUT_EXCEEDED());\n }\n parts.push(data);\n });\n tmp.on(\"end\", function () {\n if (done) return;\n done = true;\n var buf = Buffer.alloc(total),\n written = 0;\n buf.fill(0);\n for (var i = 0; i < parts.length; i++) {\n var part = parts[i];\n part.copy(buf, written);\n written += part.length;\n }\n callback && callback(buf);\n });\n tmp.end(inbuf);\n }\n };\n};\n", "\"use strict\";\n\n// node crypt, we use it for generate salt\n// eslint-disable-next-line node/no-unsupported-features/node-builtins\nconst { randomFillSync } = require(\"crypto\");\nconst Errors = require(\"../util/errors\");\n\n// generate CRC32 lookup table\nconst crctable = new Uint32Array(256).map((t, crc) => {\n for (let j = 0; j < 8; j++) {\n if (0 !== (crc & 1)) {\n crc = (crc >>> 1) ^ 0xedb88320;\n } else {\n crc >>>= 1;\n }\n }\n return crc >>> 0;\n});\n\n// C-style uInt32 Multiply (discards higher bits, when JS multiply discards lower bits)\nconst uMul = (a, b) => Math.imul(a, b) >>> 0;\n\n// crc32 byte single update (actually same function is part of utils.crc32 function :) )\nconst crc32update = (pCrc32, bval) => {\n return crctable[(pCrc32 ^ bval) & 0xff] ^ (pCrc32 >>> 8);\n};\n\n// function for generating salt for encrytion header\nconst genSalt = () => {\n if (\"function\" === typeof randomFillSync) {\n return randomFillSync(Buffer.alloc(12));\n } else {\n // fallback if function is not defined\n return genSalt.node();\n }\n};\n\n// salt generation with node random function (mainly as fallback)\ngenSalt.node = () => {\n const salt = Buffer.alloc(12);\n const len = salt.length;\n for (let i = 0; i < len; i++) salt[i] = (Math.random() * 256) & 0xff;\n return salt;\n};\n\n// general config\nconst config = {\n genSalt\n};\n\n// Class Initkeys handles same basic ops with keys\nfunction Initkeys(pw) {\n const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw);\n this.keys = new Uint32Array([0x12345678, 0x23456789, 0x34567890]);\n for (let i = 0; i < pass.length; i++) {\n this.updateKeys(pass[i]);\n }\n}\n\nInitkeys.prototype.updateKeys = function (byteValue) {\n const keys = this.keys;\n keys[0] = crc32update(keys[0], byteValue);\n keys[1] += keys[0] & 0xff;\n keys[1] = uMul(keys[1], 134775813) + 1;\n keys[2] = crc32update(keys[2], keys[1] >>> 24);\n return byteValue;\n};\n\nInitkeys.prototype.next = function () {\n const k = (this.keys[2] | 2) >>> 0; // key\n return (uMul(k, k ^ 1) >> 8) & 0xff; // decode\n};\n\nfunction make_decrypter(/*Buffer*/ pwd) {\n // 1. Stage initialize key\n const keys = new Initkeys(pwd);\n\n // return decrypter function\n return function (/*Buffer*/ data) {\n // result - we create new Buffer for results\n const result = Buffer.alloc(data.length);\n let pos = 0;\n // process input data\n for (let c of data) {\n //c ^= keys.next();\n //result[pos++] = c; // decode & Save Value\n result[pos++] = keys.updateKeys(c ^ keys.next()); // update keys with decoded byte\n }\n return result;\n };\n}\n\nfunction make_encrypter(/*Buffer*/ pwd) {\n // 1. Stage initialize key\n const keys = new Initkeys(pwd);\n\n // return encrypting function, result and pos is here so we dont have to merge buffers later\n return function (/*Buffer*/ data, /*Buffer*/ result, /* Number */ pos = 0) {\n // result - we create new Buffer for results\n if (!result) result = Buffer.alloc(data.length);\n // process input data\n for (let c of data) {\n const k = keys.next(); // save key byte\n result[pos++] = c ^ k; // save val\n keys.updateKeys(c); // update keys with decoded byte\n }\n return result;\n };\n}\n\nfunction decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) {\n if (!data || !Buffer.isBuffer(data) || data.length < 12) {\n return Buffer.alloc(0);\n }\n\n // 1. We Initialize and generate decrypting function\n const decrypter = make_decrypter(pwd);\n\n // 2. decrypt salt what is always 12 bytes and is a part of file content\n const salt = decrypter(data.slice(0, 12));\n\n // if bit 3 (0x08) of the general-purpose flags field is set, check salt[11] with the high byte of the header time\n // 2 byte data block (as per Info-Zip spec), otherwise check with the high byte of the header entry\n const verifyByte = (header.flags & 0x8) === 0x8 ? header.timeHighByte : header.crc >>> 24;\n\n //3. does password meet expectations\n if (salt[11] !== verifyByte) {\n throw Errors.WRONG_PASSWORD();\n }\n\n // 4. decode content\n return decrypter(data.slice(12));\n}\n\n// lets add way to populate salt, NOT RECOMMENDED for production but maybe useful for testing general functionality\nfunction _salter(data) {\n if (Buffer.isBuffer(data) && data.length >= 12) {\n // be aware - currently salting buffer data is modified\n config.genSalt = function () {\n return data.slice(0, 12);\n };\n } else if (data === \"node\") {\n // test salt generation with node random function\n config.genSalt = genSalt.node;\n } else {\n // if value is not acceptable config gets reset.\n config.genSalt = genSalt;\n }\n}\n\nfunction encrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd, /*Boolean*/ oldlike = false) {\n // 1. test data if data is not Buffer we make buffer from it\n if (data == null) data = Buffer.alloc(0);\n // if data is not buffer be make buffer from it\n if (!Buffer.isBuffer(data)) data = Buffer.from(data.toString());\n\n // 2. We Initialize and generate encrypting function\n const encrypter = make_encrypter(pwd);\n\n // 3. generate salt (12-bytes of random data)\n const salt = config.genSalt();\n salt[11] = (header.crc >>> 24) & 0xff;\n\n // old implementations (before PKZip 2.04g) used two byte check\n if (oldlike) salt[10] = (header.crc >>> 16) & 0xff;\n\n // 4. create output\n const result = Buffer.alloc(data.length + 12);\n encrypter(salt, result);\n\n // finally encode content\n return encrypter(data, result, 12);\n}\n\nmodule.exports = { decrypt, encrypt, _salter };\n", "exports.Deflater = require(\"./deflater\");\nexports.Inflater = require(\"./inflater\");\nexports.ZipCrypto = require(\"./zipcrypto\");\n", "var Utils = require(\"./util\"),\n Headers = require(\"./headers\"),\n Constants = Utils.Constants,\n Methods = require(\"./methods\");\n\nmodule.exports = function (/** object */ options, /*Buffer*/ input) {\n var _centralHeader = new Headers.EntryHeader(),\n _entryName = Buffer.alloc(0),\n _comment = Buffer.alloc(0),\n _isDirectory = false,\n uncompressedData = null,\n _extra = Buffer.alloc(0),\n _extralocal = Buffer.alloc(0),\n _efs = true;\n\n // assign options\n const opts = options;\n\n const decoder = typeof opts.decoder === \"object\" ? opts.decoder : Utils.decoder;\n _efs = decoder.hasOwnProperty(\"efs\") ? decoder.efs : false;\n\n function getCompressedDataFromZip() {\n //if (!input || !Buffer.isBuffer(input)) {\n if (!input || !(input instanceof Uint8Array)) {\n return Buffer.alloc(0);\n }\n _extralocal = _centralHeader.loadLocalHeaderFromBinary(input);\n const dataOffset = _centralHeader.realDataOffset;\n const dataEnd = dataOffset + _centralHeader.compressedSize;\n // The offsets and sizes come from attacker-controlled headers. Require the\n // declared compressed extent to be fully present rather than letting slice()\n // silently clamp to a short buffer (which only surfaces later as a CRC\n // failure). Fail loudly with a header error instead (GHSA-wwrv-q5gf-5843).\n if (dataOffset < 0 || dataEnd < dataOffset || dataEnd > input.length) {\n throw Utils.Errors.INVALID_LOC();\n }\n return input.slice(dataOffset, dataEnd);\n }\n\n function crc32OK(data) {\n // When bit 3 (0x08) of the general-purpose flags is set, the crc-32 and\n // sizes were unknown when the local file header was written, so that\n // header carries placeholder zeros and the real values are repeated in a\n // data descriptor after the compressed data. adm-zip always parses the\n // central directory, whose header holds the authoritative crc-32 and\n // sizes, so we validate the payload against that value.\n //\n // Earlier versions instead located and parsed the trailing descriptor and\n // threw when it was absent or in an unexpected shape. Many valid archives\n // set the descriptor flag but write the real crc/sizes into the local and\n // central headers without emitting a descriptor (or write one we did not\n // recognise), so that strict handling rejected readable zips\n // (issues #533, #548, #554). Trusting the central-directory crc keeps the\n // integrity check while accepting those archives.\n const expectedCrc = _centralHeader.flags_desc || _centralHeader.localHeader.flags_desc ? _centralHeader.crc : _centralHeader.localHeader.crc;\n\n return Utils.crc32(data) === expectedCrc;\n }\n\n function decompress(/*Boolean*/ async, /*Function*/ callback, /*String, Buffer*/ pass) {\n if (typeof callback === \"undefined\" && typeof async === \"string\") {\n pass = async;\n async = void 0;\n }\n if (_isDirectory) {\n if (async && callback) {\n callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error.\n }\n return Buffer.alloc(0);\n }\n\n var compressedData;\n try {\n compressedData = getCompressedDataFromZip();\n\n if (compressedData.length === 0) {\n // File is empty, nothing to decompress.\n if (async && callback) callback(compressedData);\n return compressedData;\n }\n\n if (_centralHeader.encrypted) {\n if (\"string\" !== typeof pass && !Buffer.isBuffer(pass)) {\n throw Utils.Errors.INVALID_PASS_PARAM();\n }\n compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass);\n }\n } catch (err) {\n // These synchronous parse/setup steps run before any callback fires.\n // In async mode a malformed local header (e.g. a bad LOC offset) would\n // otherwise throw out of getDataAsync and bypass the callback error\n // channel, crashing the caller. Route it through the callback instead.\n if (async && callback) {\n callback(Buffer.alloc(0), err);\n return Buffer.alloc(0);\n }\n throw err;\n }\n\n var data;\n\n switch (_centralHeader.method) {\n case Utils.Constants.STORED:\n // STORED entries are not compressed, so the uncompressed output is\n // exactly the bytes present in the archive. Allocate from the real\n // data length rather than the attacker-declared central-directory\n // size, otherwise a tiny archive can declare a huge size and force a\n // multi-gigabyte allocation before any validation (CVE-2026-39244).\n data = Buffer.alloc(compressedData.length);\n compressedData.copy(data);\n if (!crc32OK(data)) {\n if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error\n throw Utils.Errors.BAD_CRC();\n } else {\n //si added otherwise did not seem to return data.\n if (async && callback) callback(data);\n return data;\n }\n case Utils.Constants.DEFLATED:\n // Do not pre-allocate the declared uncompressed size. The inflater\n // grows its output buffer as zlib emits data and caps the total at\n // the declared size (maxOutputLength), so a bogus size can no longer\n // trigger an eager allocation before the data is read (CVE-2026-39244).\n var inflater = new Methods.Inflater(compressedData, _centralHeader.size);\n if (!async) {\n data = inflater.inflate();\n if (!crc32OK(data)) {\n throw Utils.Errors.BAD_CRC(`\"${decoder.decode(_entryName)}\"`);\n }\n return data;\n } else {\n inflater.inflateAsync(function (result, err) {\n if (!callback) return;\n if (err) {\n // surface inflater/stream failures instead of validating\n // the empty placeholder buffer against the CRC\n callback(Buffer.alloc(0), err);\n } else if (!crc32OK(result)) {\n callback(result, Utils.Errors.BAD_CRC()); //si added error\n } else {\n callback(result);\n }\n });\n }\n break;\n default:\n if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD());\n throw Utils.Errors.UNKNOWN_METHOD();\n }\n }\n\n function compress(/*Boolean*/ async, /*Function*/ callback) {\n if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) {\n // no data set or the data wasn't changed to require recompression\n if (async && callback) callback(getCompressedDataFromZip());\n return getCompressedDataFromZip();\n }\n\n if (uncompressedData.length && !_isDirectory) {\n var compressedData;\n // Local file header\n switch (_centralHeader.method) {\n case Utils.Constants.STORED:\n _centralHeader.compressedSize = _centralHeader.size;\n\n compressedData = Buffer.alloc(uncompressedData.length);\n uncompressedData.copy(compressedData);\n\n if (async && callback) callback(compressedData);\n return compressedData;\n default:\n case Utils.Constants.DEFLATED:\n var deflater = new Methods.Deflater(uncompressedData);\n if (!async) {\n var deflated = deflater.deflate();\n _centralHeader.compressedSize = deflated.length;\n return deflated;\n } else {\n deflater.deflateAsync(function (data) {\n compressedData = Buffer.alloc(data.length);\n _centralHeader.compressedSize = data.length;\n data.copy(compressedData);\n callback && callback(compressedData);\n });\n }\n deflater = null;\n break;\n }\n } else if (async && callback) {\n callback(Buffer.alloc(0));\n } else {\n return Buffer.alloc(0);\n }\n }\n\n function readUInt64LE(buffer, offset) {\n return Utils.readBigUInt64LE(buffer, offset);\n }\n\n function parseExtra(data) {\n try {\n var offset = 0;\n var signature, size, part;\n while (offset + 4 < data.length) {\n signature = data.readUInt16LE(offset);\n offset += 2;\n size = data.readUInt16LE(offset);\n offset += 2;\n part = data.slice(offset, offset + size);\n offset += size;\n if (Constants.ID_ZIP64 === signature) {\n parseZip64ExtendedInformation(part);\n }\n }\n } catch (error) {\n throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR();\n }\n }\n\n //Override header field values with values from the ZIP64 extra field\n function parseZip64ExtendedInformation(data) {\n var size, compressedSize, offset, diskNumStart;\n\n if (data.length >= Constants.EF_ZIP64_SCOMP) {\n size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);\n if (_centralHeader.size === Constants.EF_ZIP64_OR_32) {\n _centralHeader.size = size;\n }\n }\n if (data.length >= Constants.EF_ZIP64_RHO) {\n compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP);\n if (_centralHeader.compressedSize === Constants.EF_ZIP64_OR_32) {\n _centralHeader.compressedSize = compressedSize;\n }\n }\n if (data.length >= Constants.EF_ZIP64_DSN) {\n offset = readUInt64LE(data, Constants.EF_ZIP64_RHO);\n if (_centralHeader.offset === Constants.EF_ZIP64_OR_32) {\n _centralHeader.offset = offset;\n }\n }\n if (data.length >= Constants.EF_ZIP64_DSN + 4) {\n diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN);\n if (_centralHeader.diskNumStart === Constants.EF_ZIP64_OR_16) {\n _centralHeader.diskNumStart = diskNumStart;\n }\n }\n }\n\n return {\n get entryName() {\n return decoder.decode(_entryName);\n },\n get rawEntryName() {\n return _entryName;\n },\n set entryName(val) {\n _entryName = Utils.toBuffer(val, decoder.encode);\n var lastChar = _entryName[_entryName.length - 1];\n _isDirectory = lastChar === 47 || lastChar === 92;\n _centralHeader.fileNameLength = _entryName.length;\n },\n\n get efs() {\n if (typeof _efs === \"function\") {\n return _efs(this.entryName);\n } else {\n return _efs;\n }\n },\n\n get extra() {\n return _extra;\n },\n set extra(val) {\n _extra = val;\n _centralHeader.extraLength = val.length;\n parseExtra(val);\n },\n\n get comment() {\n return decoder.decode(_comment);\n },\n set comment(val) {\n _comment = Utils.toBuffer(val, decoder.encode);\n _centralHeader.commentLength = _comment.length;\n if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG();\n },\n\n get name() {\n const n = decoder.decode(_entryName);\n // For directories the name is the last path segment; drop the trailing\n // separator first so \"a/b/c/\" yields \"c\" and not \"\" (issue #466).\n return _isDirectory\n ? n\n .replace(/[/\\\\]$/, \"\")\n .split(\"/\")\n .pop()\n : n.split(\"/\").pop();\n },\n get isDirectory() {\n return _isDirectory;\n },\n\n getCompressedData: function () {\n return compress(false, null);\n },\n\n getCompressedDataAsync: function (/*Function*/ callback) {\n compress(true, callback);\n },\n\n setData: function (value) {\n uncompressedData = Utils.toBuffer(value, Utils.decoder.encode);\n if (!_isDirectory && uncompressedData.length) {\n _centralHeader.size = uncompressedData.length;\n _centralHeader.method = Utils.Constants.DEFLATED;\n _centralHeader.crc = Utils.crc32(value);\n _centralHeader.changed = true;\n } else {\n // folders and blank files should be stored\n _centralHeader.method = Utils.Constants.STORED;\n }\n },\n\n getData: function (pass) {\n if (_centralHeader.changed) {\n return uncompressedData;\n } else {\n return decompress(false, null, pass);\n }\n },\n\n getDataAsync: function (/*Function*/ callback, pass) {\n if (_centralHeader.changed) {\n callback(uncompressedData);\n } else {\n decompress(true, callback, pass);\n }\n },\n\n set attr(attr) {\n _centralHeader.attr = attr;\n },\n get attr() {\n return _centralHeader.attr;\n },\n\n set header(/*Buffer*/ data) {\n _centralHeader.loadFromBinary(data);\n },\n\n get header() {\n return _centralHeader;\n },\n\n packCentralHeader: function () {\n _centralHeader.flags_efs = this.efs;\n _centralHeader.extraLength = _extra.length;\n // 1. create header (buffer)\n var header = _centralHeader.centralHeaderToBinary();\n var addpos = Utils.Constants.CENHDR;\n // 2. add file name\n _entryName.copy(header, addpos);\n addpos += _entryName.length;\n // 3. add extra data\n _extra.copy(header, addpos);\n addpos += _centralHeader.extraLength;\n // 4. add file comment\n _comment.copy(header, addpos);\n return header;\n },\n\n packLocalHeader: function () {\n let addpos = 0;\n _centralHeader.flags_efs = this.efs;\n _centralHeader.extraLocalLength = _extralocal.length;\n // 1. construct local header Buffer\n const localHeaderBuf = _centralHeader.localHeaderToBinary();\n // 2. localHeader - crate header buffer\n const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength);\n // 2.1 add localheader\n localHeaderBuf.copy(localHeader, addpos);\n addpos += localHeaderBuf.length;\n // 2.2 add file name\n _entryName.copy(localHeader, addpos);\n addpos += _entryName.length;\n // 2.3 add extra field\n _extralocal.copy(localHeader, addpos);\n addpos += _extralocal.length;\n\n return localHeader;\n },\n\n toJSON: function () {\n const bytes = function (nr) {\n return \"<\" + ((nr && nr.length + \" bytes buffer\") || \"null\") + \">\";\n };\n\n return {\n entryName: this.entryName,\n name: this.name,\n comment: this.comment,\n isDirectory: this.isDirectory,\n header: _centralHeader.toJSON(),\n compressedData: bytes(input),\n data: bytes(uncompressedData)\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n", "const ZipEntry = require(\"./zipEntry\");\nconst Headers = require(\"./headers\");\nconst Utils = require(\"./util\");\n\nmodule.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) {\n var entryList = [],\n // prototype-less: entry names come from untrusted input, so keys like\n // \"__proto__\" or \"constructor\" must be plain data, not touch the prototype\n // chain (which otherwise crashes addFile and hides such entries)\n entryTable = Object.create(null),\n _comment = Buffer.alloc(0),\n mainHeader = new Headers.MainHeader(),\n loadedEntries = false;\n var password = null;\n const temporary = new Set();\n\n // assign options\n const opts = options;\n\n const { noSort, decoder } = opts;\n\n if (inBuffer) {\n // is a memory buffer\n readMainHeader(opts.readEntries);\n } else {\n // none. is a new file\n loadedEntries = true;\n }\n\n function makeTemporaryFolders() {\n const foldersList = new Set();\n\n // Make list of all folders in file\n for (const elem of Object.keys(entryTable)) {\n const elements = elem.split(\"/\");\n elements.pop(); // filename\n if (!elements.length) continue; // no folders\n for (let i = 0; i < elements.length; i++) {\n const sub = elements.slice(0, i + 1).join(\"/\") + \"/\";\n foldersList.add(sub);\n }\n }\n\n // create missing folders as temporary\n for (const elem of foldersList) {\n if (!(elem in entryTable)) {\n const tempfolder = new ZipEntry(opts);\n tempfolder.entryName = elem;\n tempfolder.attr = 0x10;\n tempfolder.temporary = true;\n entryList.push(tempfolder);\n entryTable[tempfolder.entryName] = tempfolder;\n temporary.add(tempfolder);\n }\n }\n }\n\n function readEntries() {\n loadedEntries = true;\n entryTable = Object.create(null);\n if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) {\n throw Utils.Errors.DISK_ENTRY_TOO_LARGE();\n }\n entryList = new Array(mainHeader.diskEntries); // total number of entries\n var index = mainHeader.offset; // offset of first CEN header\n for (var i = 0; i < entryList.length; i++) {\n var tmp = index,\n entry = new ZipEntry(opts, inBuffer);\n entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR));\n\n entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength));\n\n if (entry.header.extraLength) {\n entry.extra = inBuffer.slice(tmp, (tmp += entry.header.extraLength));\n }\n\n if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);\n\n index += entry.header.centralHeaderSize;\n\n // Reject archives that declare the same entry name twice. adm-zip keeps\n // every entry in entryList but only the last in entryTable, so getEntry()\n // (table) and extractAllTo() (list) could resolve one name to different\n // content: an app that validates entry bytes via getEntry() before\n // extracting could approve one file while a different one lands on disk\n // (GHSA-p634-w6r4-rjp2). Fail closed on the ambiguity.\n if (entry.entryName in entryTable) {\n throw Utils.Errors.DUPLICATE_ENTRY(`\"${entry.entryName}\"`);\n }\n\n entryList[i] = entry;\n entryTable[entry.entryName] = entry;\n }\n temporary.clear();\n makeTemporaryFolders();\n }\n\n function readMainHeader(/*Boolean*/ readNow) {\n var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size\n max = Math.max(0, i - 0xffff), // 0xFFFF is the max zip file comment length\n n = max,\n endStart = inBuffer.length,\n endOffset = -1, // Start offset of the END header\n commentEnd = 0;\n\n // option to search header form entire file\n const trailingSpace = typeof opts.trailingSpace === \"boolean\" ? opts.trailingSpace : false;\n if (trailingSpace) max = 0;\n\n for (i; i >= n; i--) {\n if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P'\n if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) {\n // \"PK\\005\\006\"\n endOffset = i;\n commentEnd = i;\n endStart = i + Utils.Constants.ENDHDR;\n // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature\n n = i - Utils.Constants.END64HDR;\n continue;\n }\n\n if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) {\n // Found a zip64 signature, let's continue reading the whole zip64 record\n n = max;\n continue;\n }\n\n if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) {\n // Found the zip64 record, let's determine it's size\n endOffset = i;\n endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD;\n break;\n }\n }\n\n if (endOffset == -1) throw Utils.Errors.INVALID_FORMAT();\n\n mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart));\n if (mainHeader.commentLength) {\n _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR);\n }\n if (readNow) readEntries();\n }\n\n function sortEntries() {\n if (entryList.length > 1 && !noSort) {\n // Decode + lowercase each name once rather than on every comparison:\n // the entryName getter re-decodes the underlying buffer on each access,\n // so the previous inline comparator did O(n log n) redundant decoding.\n // Ordering is unchanged (same localeCompare on the same keys).\n entryList = entryList\n .map((entry) => ({ entry, key: entry.entryName.toLowerCase() }))\n .sort((a, b) => a.key.localeCompare(b.key))\n .map((pair) => pair.entry);\n }\n }\n\n return {\n /**\n * Returns an array of ZipEntry objects existent in the current opened archive\n * @return Array\n */\n get entries() {\n if (!loadedEntries) {\n readEntries();\n }\n return entryList.filter((e) => !temporary.has(e));\n },\n\n /**\n * Archive comment\n * @return {String}\n */\n get comment() {\n return decoder.decode(_comment);\n },\n set comment(val) {\n _comment = Utils.toBuffer(val, decoder.encode);\n mainHeader.commentLength = _comment.length;\n },\n\n getEntryCount: function () {\n if (!loadedEntries) {\n return mainHeader.diskEntries;\n }\n\n return entryList.length;\n },\n\n forEach: function (callback) {\n this.entries.forEach(callback);\n },\n\n /**\n * Returns a reference to the entry with the given name or null if entry is inexistent\n *\n * @param entryName\n * @return ZipEntry\n */\n getEntry: function (/*String*/ entryName) {\n if (!loadedEntries) {\n readEntries();\n }\n return entryTable[entryName] || null;\n },\n\n /**\n * Adds the given entry to the entry list\n *\n * @param entry\n */\n setEntry: function (/*ZipEntry*/ entry) {\n if (!loadedEntries) {\n readEntries();\n }\n entryList.push(entry);\n entryTable[entry.entryName] = entry;\n mainHeader.totalEntries = entryList.length;\n },\n\n /**\n * Removes the file with the given name from the entry list.\n *\n * If the entry is a directory, then all nested files and directories will be removed\n * @param entryName\n * @returns {void}\n */\n deleteFile: function (/*String*/ entryName, withsubfolders = true) {\n if (!loadedEntries) {\n readEntries();\n }\n const entry = entryTable[entryName];\n const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName);\n\n list.forEach(this.deleteEntry);\n },\n\n /**\n * Removes the entry with the given name from the entry list.\n *\n * @param {string} entryName\n * @returns {void}\n */\n deleteEntry: function (/*String*/ entryName) {\n if (!loadedEntries) {\n readEntries();\n }\n const entry = entryTable[entryName];\n const index = entryList.indexOf(entry);\n if (index >= 0) {\n entryList.splice(index, 1);\n delete entryTable[entryName];\n mainHeader.totalEntries = entryList.length;\n }\n },\n\n /**\n * Iterates and returns all nested files and directories of the given entry\n *\n * @param entry\n * @return Array\n */\n getEntryChildren: function (/*ZipEntry*/ entry, subfolders = true) {\n if (!loadedEntries) {\n readEntries();\n }\n if (typeof entry === \"object\") {\n if (entry.isDirectory && subfolders) {\n const list = [];\n const name = entry.entryName;\n\n for (const zipEntry of entryList) {\n if (zipEntry.entryName.startsWith(name)) {\n list.push(zipEntry);\n }\n }\n return list;\n } else {\n return [entry];\n }\n }\n return [];\n },\n\n /**\n * How many child elements entry has\n *\n * @param {ZipEntry} entry\n * @return {integer}\n */\n getChildCount: function (entry) {\n if (entry && entry.isDirectory) {\n const list = this.getEntryChildren(entry);\n return list.includes(entry) ? list.length - 1 : list.length;\n }\n return 0;\n },\n\n /**\n * Returns the zip file\n *\n * @return Buffer\n */\n compressToBuffer: function () {\n if (!loadedEntries) {\n readEntries();\n }\n sortEntries();\n\n const dataBlock = [];\n const headerBlocks = [];\n let totalSize = 0;\n let dindex = 0;\n\n mainHeader.size = 0;\n mainHeader.offset = 0;\n let totalEntries = 0;\n\n for (const entry of this.entries) {\n // compress data and set local and entry header accordingly. Reason why is called first\n const compressedData = entry.getCompressedData();\n entry.header.offset = dindex;\n\n // 1. construct local header\n const localHeader = entry.packLocalHeader();\n\n // 2. offsets\n const dataLength = localHeader.length + compressedData.length;\n dindex += dataLength;\n\n // 3. store values in sequence\n dataBlock.push(localHeader);\n dataBlock.push(compressedData);\n\n // 4. construct central header\n const centralHeader = entry.packCentralHeader();\n headerBlocks.push(centralHeader);\n // 5. update main header\n mainHeader.size += centralHeader.length;\n totalSize += dataLength + centralHeader.length;\n totalEntries++;\n }\n\n totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length\n // point to end of data and beginning of central directory first record\n mainHeader.offset = dindex;\n mainHeader.totalEntries = totalEntries;\n\n dindex = 0;\n const outBuffer = Buffer.alloc(totalSize);\n // write data blocks\n for (const content of dataBlock) {\n content.copy(outBuffer, dindex);\n dindex += content.length;\n }\n\n // write central directory entries\n for (const content of headerBlocks) {\n content.copy(outBuffer, dindex);\n dindex += content.length;\n }\n\n // write main header\n const mh = mainHeader.toBinary();\n if (_comment) {\n _comment.copy(mh, mh.length - _comment.length); // add zip file comment\n }\n mh.copy(outBuffer, dindex);\n\n // Since we update entry and main header offsets,\n // they are no longer valid and we have to reset content\n // (Issue 64)\n\n inBuffer = outBuffer;\n loadedEntries = false;\n\n return outBuffer;\n },\n\n toAsyncBuffer: function (/*Function*/ onSuccess, /*Function*/ onFail, /*Function*/ onItemStart, /*Function*/ onItemEnd) {\n try {\n if (!loadedEntries) {\n readEntries();\n }\n sortEntries();\n\n const dataBlock = [];\n const centralHeaders = [];\n let totalSize = 0;\n let dindex = 0;\n let totalEntries = 0;\n\n mainHeader.size = 0;\n mainHeader.offset = 0;\n\n const compress2Buffer = function (entryLists) {\n if (entryLists.length > 0) {\n const entry = entryLists.shift();\n const name = entry.entryName + entry.extra.toString();\n if (onItemStart) onItemStart(name);\n entry.getCompressedDataAsync(function (compressedData) {\n if (onItemEnd) onItemEnd(name);\n entry.header.offset = dindex;\n\n // 1. construct local header\n const localHeader = entry.packLocalHeader();\n\n // 2. offsets\n const dataLength = localHeader.length + compressedData.length;\n dindex += dataLength;\n\n // 3. store values in sequence\n dataBlock.push(localHeader);\n dataBlock.push(compressedData);\n\n // central header\n const centalHeader = entry.packCentralHeader();\n centralHeaders.push(centalHeader);\n mainHeader.size += centalHeader.length;\n totalSize += dataLength + centalHeader.length;\n totalEntries++;\n\n compress2Buffer(entryLists);\n });\n } else {\n totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length\n // point to end of data and beginning of central directory first record\n mainHeader.offset = dindex;\n mainHeader.totalEntries = totalEntries;\n\n dindex = 0;\n const outBuffer = Buffer.alloc(totalSize);\n dataBlock.forEach(function (content) {\n content.copy(outBuffer, dindex); // write data blocks\n dindex += content.length;\n });\n centralHeaders.forEach(function (content) {\n content.copy(outBuffer, dindex); // write central directory entries\n dindex += content.length;\n });\n\n const mh = mainHeader.toBinary();\n if (_comment) {\n _comment.copy(mh, mh.length - _comment.length); // add zip file comment\n }\n\n mh.copy(outBuffer, dindex); // write main header\n\n // Since we update entry and main header offsets, they are no\n // longer valid and we have to reset content using our new buffer\n // (Issue 64)\n\n inBuffer = outBuffer;\n loadedEntries = false;\n\n onSuccess(outBuffer);\n }\n };\n\n compress2Buffer(Array.from(this.entries));\n } catch (e) {\n onFail(e);\n }\n }\n };\n};\n", "const Utils = require(\"./util\");\nconst pth = require(\"path\");\nconst ZipEntry = require(\"./zipEntry\");\nconst ZipFile = require(\"./zipFile\");\n\nconst get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === \"boolean\");\nconst get_Str = (...val) => Utils.findLast(val, (c) => typeof c === \"string\");\nconst get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === \"function\");\n\nconst defaultOptions = {\n // option \"noSort\" : if true it disables files sorting\n noSort: false,\n // read entries during load (initial loading may be slower)\n readEntries: false,\n // default method is none\n method: Utils.Constants.NONE,\n // file system\n fs: null\n};\n\nmodule.exports = function (/**String*/ input, /** object */ options) {\n let inBuffer = null;\n\n // create object based default options, allowing them to be overwritten\n const opts = Object.assign(Object.create(null), defaultOptions);\n\n // test input variable\n if (input && \"object\" === typeof input) {\n // if value is not buffer we accept it to be object with options\n if (!(input instanceof Uint8Array)) {\n Object.assign(opts, input);\n input = opts.input ? opts.input : undefined;\n if (opts.input) delete opts.input;\n }\n\n // if input is buffer\n if (Buffer.isBuffer(input)) {\n inBuffer = input;\n opts.method = Utils.Constants.BUFFER;\n input = undefined;\n }\n }\n\n // assign options\n Object.assign(opts, options);\n\n // instanciate utils filesystem\n const filetools = new Utils(opts);\n\n // Restore the archived permissions on extracted directories. This has to run\n // after a directory's contents are written: applying a restrictive mode\n // (e.g. 0o500) up front would stop us writing the files it contains. Applying\n // the deepest paths first keeps parent directories traversable while their\n // children are updated (issue #530).\n const applyDirAttributes = (dirEntries) => {\n dirEntries\n .filter((d) => d.attr)\n .sort((a, b) => b.path.length - a.path.length)\n .forEach((d) => filetools.fs.chmodSync(d.path, d.attr));\n };\n\n if (typeof opts.decoder !== \"object\" || typeof opts.decoder.encode !== \"function\" || typeof opts.decoder.decode !== \"function\") {\n opts.decoder = Utils.decoder;\n }\n\n // if input is file name we retrieve its content\n if (input && \"string\" === typeof input) {\n // load zip file\n if (filetools.fs.existsSync(input)) {\n opts.method = Utils.Constants.FILE;\n opts.filename = input;\n inBuffer = filetools.fs.readFileSync(input);\n } else {\n throw Utils.Errors.INVALID_FILENAME();\n }\n }\n\n // create variable\n const _zip = new ZipFile(inBuffer, opts);\n\n const { canonical, sanitize, zipnamefix } = Utils;\n\n function getEntry(/**Object*/ entry) {\n if (entry && _zip) {\n var item;\n // If entry was given as a file name\n if (typeof entry === \"string\") item = _zip.getEntry(pth.posix.normalize(entry));\n // if entry was given as a ZipEntry object\n if (typeof entry === \"object\" && typeof entry.entryName !== \"undefined\" && typeof entry.header !== \"undefined\") item = _zip.getEntry(entry.entryName);\n\n if (item) {\n return item;\n }\n }\n return null;\n }\n\n function fixPath(zipPath) {\n const { join, normalize, sep } = pth.posix;\n // convert windows file separators and normalize\n return join(pth.isAbsolute(zipPath) ? \"/\": '.', normalize(sep + zipPath.split(\"\\\\\").join(sep) + sep));\n }\n\n function filenameFilter(filterfn) {\n if (filterfn instanceof RegExp) {\n // if filter is RegExp wrap it\n return (function (rx) {\n return function (filename) {\n return rx.test(filename);\n };\n })(filterfn);\n } else if (\"function\" !== typeof filterfn) {\n // if filter is not function we will replace it\n return () => true;\n }\n return filterfn;\n }\n\n // keep last character on folders\n const relativePath = (local, entry) => {\n let lastChar = entry.slice(-1);\n lastChar = lastChar === filetools.sep ? filetools.sep : \"\";\n return pth.relative(local, entry) + lastChar;\n };\n\n return {\n /**\n * Extracts the given entry from the archive and returns the content as a Buffer object\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {Buffer|string} [pass] - password\n * @return Buffer or Null in case of error\n */\n readFile: function (entry, pass) {\n var item = getEntry(entry);\n return (item && item.getData(pass)) || null;\n },\n\n /**\n * Returns how many child elements has on entry (directories) on files it is always 0\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @returns {integer}\n */\n childCount: function (entry) {\n const item = getEntry(entry);\n if (item) {\n return _zip.getChildCount(item);\n }\n },\n\n /**\n * Asynchronous readFile\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {callback} callback\n *\n * @return Buffer or Null in case of error\n */\n readFileAsync: function (entry, callback) {\n var item = getEntry(entry);\n if (item) {\n item.getDataAsync(callback);\n } else {\n callback(null, \"getEntry failed for:\" + entry);\n }\n },\n\n /**\n * Extracts the given entry from the archive and returns the content as plain text in the given encoding\n * @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry\n * @param {string} encoding - Optional. If no encoding is specified utf8 is used\n *\n * @return String\n */\n readAsText: function (entry, encoding) {\n var item = getEntry(entry);\n if (item) {\n var data = item.getData();\n if (data && data.length) {\n return data.toString(encoding || \"utf8\");\n }\n }\n return \"\";\n },\n\n /**\n * Asynchronous readAsText\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {callback} callback\n * @param {string} [encoding] - Optional. If no encoding is specified utf8 is used\n *\n * @return String\n */\n readAsTextAsync: function (entry, callback, encoding) {\n var item = getEntry(entry);\n if (item) {\n item.getDataAsync(function (data, err) {\n if (err) {\n callback(data, err);\n return;\n }\n\n if (data && data.length) {\n callback(data.toString(encoding || \"utf8\"));\n } else {\n callback(\"\");\n }\n });\n } else {\n callback(\"\");\n }\n },\n\n /**\n * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory\n *\n * @param {ZipEntry|string} entry\n * @param {boolean} withsubfolders\n * @returns {void}\n */\n deleteFile: function (entry, withsubfolders = true) {\n // @TODO: test deleteFile\n var item = getEntry(entry);\n if (item) {\n _zip.deleteFile(item.entryName, withsubfolders);\n }\n },\n\n /**\n * Remove the entry from the file or directory without affecting any nested entries\n *\n * @param {ZipEntry|string} entry\n * @returns {void}\n */\n deleteEntry: function (entry) {\n // @TODO: test deleteEntry\n var item = getEntry(entry);\n if (item) {\n _zip.deleteEntry(item.entryName);\n }\n },\n\n /**\n * Adds a comment to the zip. The zip must be rewritten after adding the comment.\n *\n * @param {string} comment\n */\n addZipComment: function (comment) {\n // @TODO: test addZipComment\n _zip.comment = comment;\n },\n\n /**\n * Returns the zip comment\n *\n * @return String\n */\n getZipComment: function () {\n return _zip.comment || \"\";\n },\n\n /**\n * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment\n * The comment cannot exceed 65535 characters in length\n *\n * @param {ZipEntry} entry\n * @param {string} comment\n */\n addZipEntryComment: function (entry, comment) {\n var item = getEntry(entry);\n if (item) {\n item.comment = comment;\n }\n },\n\n /**\n * Returns the comment of the specified entry\n *\n * @param {ZipEntry} entry\n * @return String\n */\n getZipEntryComment: function (entry) {\n var item = getEntry(entry);\n if (item) {\n return item.comment || \"\";\n }\n return \"\";\n },\n\n /**\n * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content\n *\n * @param {ZipEntry} entry\n * @param {Buffer} content\n */\n updateFile: function (entry, content) {\n var item = getEntry(entry);\n if (item) {\n item.setData(content);\n }\n },\n\n /**\n * Adds a file from the disk to the archive\n *\n * @param {string} localPath File to add to zip\n * @param {string} [zipPath] Optional path inside the zip\n * @param {string} [zipName] Optional name for the file\n * @param {string} [comment] Optional file comment\n */\n addLocalFile: function (localPath, zipPath, zipName, comment) {\n if (filetools.fs.existsSync(localPath)) {\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // p - local file name\n const p = pth.win32.basename(pth.win32.normalize(localPath));\n\n // add file name into zippath\n zipPath += zipName ? zipName : p;\n\n // read file attributes\n const _attr = filetools.fs.statSync(localPath);\n\n // get file content\n const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0);\n\n // if folder\n if (_attr.isDirectory()) zipPath += filetools.sep;\n\n // add file into zip file\n this.addFile(zipPath, data, comment, _attr);\n } else {\n throw Utils.Errors.FILE_NOT_FOUND(localPath);\n }\n },\n\n /**\n * Callback for showing if everything was done.\n *\n * @callback doneCallback\n * @param {Error} err - Error object\n * @param {boolean} done - was request fully completed\n */\n\n /**\n * Adds a file from the disk to the archive\n *\n * @param {(object|string)} options - options object, if it is string it us used as localPath.\n * @param {string} options.localPath - Local path to the file.\n * @param {string} [options.comment] - Optional file comment.\n * @param {string} [options.zipPath] - Optional path inside the zip\n * @param {string} [options.zipName] - Optional name for the file\n * @param {doneCallback} callback - The callback that handles the response.\n */\n addLocalFileAsync: function (options, callback) {\n options = typeof options === \"object\" ? options : { localPath: options };\n const localPath = pth.resolve(options.localPath);\n const { comment } = options;\n let { zipPath, zipName } = options;\n const self = this;\n\n filetools.fs.stat(localPath, function (err, stats) {\n if (err) return callback(err, false);\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n // p - local file name\n const p = pth.win32.basename(pth.win32.normalize(localPath));\n // add file name into zippath\n zipPath += zipName ? zipName : p;\n\n if (stats.isFile()) {\n filetools.fs.readFile(localPath, function (err, data) {\n if (err) return callback(err, false);\n self.addFile(zipPath, data, comment, stats);\n return setImmediate(callback, undefined, true);\n });\n } else if (stats.isDirectory()) {\n zipPath += filetools.sep;\n self.addFile(zipPath, Buffer.alloc(0), comment, stats);\n return setImmediate(callback, undefined, true);\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {string} localPath - local path to the folder\n * @param {string} [zipPath] - optional path inside zip\n * @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included.\n */\n addLocalFolder: function (localPath, zipPath, filter) {\n // Prepare filter\n filter = filenameFilter(filter);\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // normalize the path first\n localPath = pth.normalize(localPath);\n\n if (filetools.fs.existsSync(localPath)) {\n const items = filetools.findFiles(localPath);\n const self = this;\n\n if (items.length) {\n for (const filepath of items) {\n const p = pth.join(zipPath, relativePath(localPath, filepath));\n if (filter(p)) {\n self.addLocalFile(filepath, pth.dirname(p));\n }\n }\n }\n } else {\n throw Utils.Errors.FILE_NOT_FOUND(localPath);\n }\n },\n\n /**\n * Asynchronous addLocalFolder\n * @param {string} localPath\n * @param {callback} callback\n * @param {string} [zipPath] optional path inside zip\n * @param {RegExp|function} [filter] optional RegExp or Function if files match will\n * be included.\n */\n addLocalFolderAsync: function (localPath, callback, zipPath, filter) {\n // Prepare filter\n filter = filenameFilter(filter);\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // normalize the path first\n localPath = pth.normalize(localPath);\n\n var self = this;\n filetools.fs.open(localPath, \"r\", function (err) {\n if (err && err.code === \"ENOENT\") {\n callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));\n } else if (err) {\n callback(undefined, err);\n } else {\n var items = filetools.findFiles(localPath);\n var i = -1;\n\n var next = function () {\n i += 1;\n if (i < items.length) {\n var filepath = items[i];\n var p = relativePath(localPath, filepath).split(\"\\\\\").join(\"/\"); //windows fix\n p = p\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/[^\\x20-\\x7E]/g, \"\"); // accent fix\n if (filter(p)) {\n filetools.fs.stat(filepath, function (er0, stats) {\n if (er0) callback(undefined, er0);\n if (stats.isFile()) {\n filetools.fs.readFile(filepath, function (er1, data) {\n if (er1) {\n callback(undefined, er1);\n } else {\n self.addFile(zipPath + p, data, \"\", stats);\n next();\n }\n });\n } else {\n self.addFile(zipPath + p + \"/\", Buffer.alloc(0), \"\", stats);\n next();\n }\n });\n } else {\n process.nextTick(() => {\n next();\n });\n }\n } else {\n callback(true, undefined);\n }\n };\n\n next();\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {object | string} options - options object, if it is string it us used as localPath.\n * @param {string} options.localPath - Local path to the folder.\n * @param {string} [options.zipPath] - optional path inside zip.\n * @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included.\n * @param {function|string} [options.namefix] - optional function to help fix filename\n * @param {doneCallback} callback - The callback that handles the response.\n *\n */\n addLocalFolderAsync2: function (options, callback) {\n const self = this;\n options = typeof options === \"object\" ? options : { localPath: options };\n // Resolve the local filesystem path with the platform resolver. Do NOT\n // run it through fixPath: that normalizes ZIP-internal paths to POSIX\n // and prepends \"/\", which turns a Windows path like C:\\dir into\n // \\C:\\dir, so readdir finds nothing and the archive comes out empty.\n const localPath = pth.resolve(options.localPath);\n let { zipPath, filter, namefix } = options;\n\n if (filter instanceof RegExp) {\n filter = (function (rx) {\n return function (filename) {\n return rx.test(filename);\n };\n })(filter);\n } else if (\"function\" !== typeof filter) {\n filter = function () {\n return true;\n };\n }\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // Check Namefix function\n if (namefix === \"latin1\") {\n namefix = (str) =>\n str\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/[^\\x20-\\x7E]/g, \"\"); // accent fix (latin1 characers only)\n }\n\n if (typeof namefix !== \"function\") namefix = (str) => str;\n\n // internal, create relative path + fix the name\n const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry)));\n const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry)));\n\n filetools.fs.open(localPath, \"r\", function (err) {\n if (err && err.code === \"ENOENT\") {\n // callback is (err, done); errors belong in the first argument,\n // otherwise addLocalFolderPromise treats the error as \"done\" and\n // resolves instead of rejecting.\n callback(Utils.Errors.FILE_NOT_FOUND(localPath), false);\n } else if (err) {\n callback(err, false);\n } else {\n filetools.findFilesAsync(localPath, function (err, fileEntries) {\n if (err) return callback(err, false);\n fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir)));\n // Nothing to add (empty folder or everything filtered out) is a\n // success, not an error. Report done and stop, otherwise the\n // reduce below runs and the callback fires a second time -- and\n // signalling done=false left addLocalFolderPromise hanging.\n if (!fileEntries.length) return callback(undefined, true);\n\n setImmediate(\n fileEntries.reverse().reduce(function (next, entry) {\n return function (err, done) {\n if (err || done === false) return setImmediate(next, err, false);\n\n self.addLocalFileAsync(\n {\n localPath: entry,\n zipPath: pth.dirname(relPathFix(entry)),\n zipName: fileNameFix(entry)\n },\n next\n );\n };\n }, callback)\n );\n });\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {string} localPath - path where files will be extracted\n * @param {object} props - optional properties\n * @param {string} [props.zipPath] - optional path inside zip\n * @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included.\n * @param {function|string} [props.namefix] - optional function to help fix filename\n */\n addLocalFolderPromise: function (localPath, props) {\n return new Promise((resolve, reject) => {\n this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => {\n if (err) return reject(err);\n if (done) resolve(this);\n });\n });\n },\n\n /**\n * Allows you to create a entry (file or directory) in the zip file.\n * If you want to create a directory the entryName must end in / and a null buffer should be provided.\n * Comment and attributes are optional\n *\n * @param {string} entryName\n * @param {Buffer | string} content - file content as buffer or utf8 coded string\n * @param {string} [comment] - file comment\n * @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object\n */\n addFile: function (entryName, content, comment, attr) {\n entryName = zipnamefix(entryName);\n let entry = getEntry(entryName);\n const update = entry != null;\n\n // prepare new entry\n if (!update) {\n entry = new ZipEntry(opts);\n entry.entryName = entryName;\n }\n entry.comment = comment || \"\";\n\n const isStat = \"object\" === typeof attr && attr instanceof filetools.fs.Stats;\n\n // last modification time from file stats\n if (isStat) {\n entry.header.time = attr.mtime;\n }\n\n // Set file attribute\n var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag)\n\n // extended attributes field for Unix\n // set file type either S_IFDIR / S_IFREG\n let unix = entry.isDirectory ? 0x4000 : 0x8000;\n\n if (isStat) {\n // File attributes from file stats\n unix |= 0xfff & attr.mode;\n } else if (\"number\" === typeof attr) {\n // attr from given attr values\n unix |= 0xfff & attr;\n } else {\n // Default values:\n unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--)\n }\n\n fileattr = (fileattr | (unix << 16)) >>> 0; // add attributes\n\n entry.attr = fileattr;\n\n entry.setData(content);\n if (!update) _zip.setEntry(entry);\n\n return entry;\n },\n\n /**\n * Returns an array of ZipEntry objects representing the files and folders inside the archive\n *\n * @param {string} [password]\n * @returns Array\n */\n getEntries: function (password) {\n _zip.password = password;\n return _zip ? _zip.entries : [];\n },\n\n /**\n * Returns a ZipEntry object representing the file or folder specified by ``name``.\n *\n * @param {string} name\n * @return ZipEntry\n */\n getEntry: function (/**String*/ name) {\n return getEntry(name);\n },\n\n getEntryCount: function () {\n return _zip.getEntryCount();\n },\n\n forEach: function (callback) {\n return _zip.forEach(callback);\n },\n\n /**\n * Extracts the given entry to the given targetPath\n * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted\n *\n * @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry\n * @param {string} targetPath - Target folder where to write the file\n * @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE\n * @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true.\n * @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true.\n * @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file)\n *\n * @return Boolean\n */\n extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) {\n overwrite = get_Bool(false, overwrite);\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n maintainEntryPath = get_Bool(true, maintainEntryPath);\n outFileName = get_Str(keepOriginalPermission, outFileName);\n\n var item = getEntry(entry);\n if (!item) {\n throw Utils.Errors.NO_ENTRY();\n }\n\n var entryName = canonical(item.entryName);\n\n var target = sanitize(targetPath, outFileName && !item.isDirectory ? canonical(outFileName) : maintainEntryPath ? entryName : pth.basename(entryName));\n\n if (item.isDirectory) {\n var children = _zip.getEntryChildren(item);\n children.forEach(function (child) {\n if (child.isDirectory) return;\n var content = child.getData();\n if (!content) {\n throw Utils.Errors.CANT_EXTRACT_FILE();\n }\n // When not maintaining the full entry path, keep each child's path\n // relative to the extracted directory (drop the directory's own\n // prefix) instead of flattening every file to its basename, which\n // collapsed subdirectories together (issue #306).\n var name = canonical(maintainEntryPath ? child.entryName : child.entryName.substring(item.entryName.length));\n var childName = sanitize(targetPath, name);\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, childName);\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined;\n filetools.writeFileTo(childName, content, overwrite, fileAttr);\n });\n return true;\n }\n\n var content = item.getData(_zip.password);\n if (!content) throw Utils.Errors.CANT_EXTRACT_FILE();\n\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, target);\n\n if (filetools.fs.existsSync(target) && !overwrite) {\n throw Utils.Errors.CANT_OVERRIDE();\n }\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileTo(target, content, overwrite, fileAttr);\n\n return true;\n },\n\n /**\n * Test the archive\n * @param {string} [pass]\n */\n test: function (pass) {\n if (!_zip) {\n return false;\n }\n\n for (var entry of _zip.entries) {\n try {\n if (entry.isDirectory) {\n continue;\n }\n // was `_zip.entries[entry]` (indexing the array with an entry\n // object -> undefined -> threw -> test() always returned false)\n var content = entry.getData(pass);\n if (!content) {\n return false;\n }\n } catch (err) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Extracts the entire archive to the given location\n *\n * @param {string} targetPath Target location\n * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.\n * Default is FALSE\n * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.\n * Default is FALSE\n * @param {string|Buffer} [pass] password\n */\n extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) {\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n pass = get_Str(keepOriginalPermission, pass);\n overwrite = get_Bool(false, overwrite);\n if (!_zip) throw Utils.Errors.NO_ZIP();\n\n const dirEntries = [];\n _zip.entries.forEach(function (entry) {\n var entryName = sanitize(targetPath, canonical(entry.entryName));\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, entryName);\n if (entry.isDirectory) {\n filetools.makeDir(entryName);\n // defer restoring the directory permission until its files are written\n if (keepOriginalPermission) dirEntries.push({ path: entryName, attr: entry.header.fileAttr });\n return;\n }\n var content = entry.getData(pass);\n if (!content) {\n throw Utils.Errors.CANT_EXTRACT_FILE();\n }\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileTo(entryName, content, overwrite, fileAttr);\n try {\n // best-effort: an invalid date in the archive or a filesystem that\n // rejects utimes must not fail extraction of already-written content (issue #379)\n filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);\n } catch (err) {\n /* ignore timestamp failures */\n }\n });\n\n applyDirAttributes(dirEntries);\n },\n\n /**\n * Asynchronous extractAllTo\n *\n * @param {string} targetPath Target location\n * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.\n * Default is FALSE\n * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.\n * Default is FALSE\n * @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown.\n */\n extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) {\n callback = get_Fun(overwrite, keepOriginalPermission, callback);\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n overwrite = get_Bool(false, overwrite);\n if (!callback) {\n return new Promise((resolve, reject) => {\n this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) {\n if (err) {\n reject(err);\n } else {\n resolve(this);\n }\n });\n });\n }\n if (!_zip) {\n callback(Utils.Errors.NO_ZIP());\n return;\n }\n\n targetPath = pth.resolve(targetPath);\n // convert entryName to\n const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName)));\n const getError = (msg, file) => new Error(msg + ': \"' + file + '\"');\n\n // separate directories from files\n const dirEntries = [];\n const fileEntries = [];\n _zip.entries.forEach((e) => {\n if (e.isDirectory) {\n dirEntries.push(e);\n } else {\n fileEntries.push(e);\n }\n });\n\n // Create directory entries first synchronously\n // this prevents race condition and assures folders are there before writing files\n const deferredDirAttr = [];\n for (const entry of dirEntries) {\n const dirPath = getPath(entry);\n // The reverse operation for attr depend on method addFile()\n const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n try {\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, dirPath);\n filetools.makeDir(dirPath);\n } catch (er) {\n callback(getError(\"Unable to create folder\", dirPath));\n continue;\n }\n // defer restoring the directory permission until its files are written:\n // a restrictive mode applied now would block writing them\n if (dirAttr) deferredDirAttr.push({ path: dirPath, attr: dirAttr });\n try {\n // in unix timestamp will change if files are later added to folder, but still.\n // best-effort: a utimes failure must not abort extraction (issue #379)\n filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time);\n } catch (er) {\n /* ignore timestamp failures */\n }\n }\n\n // restore directory permissions once every file has been extracted\n const done = (err) => {\n if (!err) {\n try {\n applyDirAttributes(deferredDirAttr);\n } catch (er) {\n return callback(getError(\"Unable to set folder permissions\", er.path || \"\"));\n }\n }\n callback(err);\n };\n\n fileEntries.reverse().reduce(function (next, entry) {\n return function (err) {\n if (err) {\n next(err);\n } else {\n const entryName = pth.normalize(canonical(entry.entryName));\n const filePath = sanitize(targetPath, entryName);\n try {\n // reject writing through a pre-existing symlink inside the target\n filetools.assertPathSafe(targetPath, filePath);\n } catch (er) {\n return next(er);\n }\n entry.getDataAsync(function (content, err_1) {\n if (err_1) {\n next(err_1);\n } else if (!content) {\n next(Utils.Errors.CANT_EXTRACT_FILE());\n } else {\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) {\n if (!succ) {\n return next(getError(\"Unable to write file\", filePath));\n }\n filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function () {\n // best-effort: a utimes failure must not abort extraction\n // of already-written content (issue #379)\n next();\n });\n });\n }\n });\n }\n };\n }, done)();\n },\n\n /**\n * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip\n *\n * @param {string} targetFileName\n * @param {function} callback\n */\n writeZip: function (targetFileName, callback) {\n if (arguments.length === 1) {\n if (typeof targetFileName === \"function\") {\n callback = targetFileName;\n targetFileName = \"\";\n }\n }\n\n if (!targetFileName && opts.filename) {\n targetFileName = opts.filename;\n }\n if (!targetFileName) return;\n\n var zipData = _zip.compressToBuffer();\n if (zipData) {\n var ok = filetools.writeFileTo(targetFileName, zipData, true);\n if (typeof callback === \"function\") callback(!ok ? new Error(\"failed\") : null, \"\");\n }\n },\n\n /**\n *\n * @param {string} targetFileName\n * @param {object} [props]\n * @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true.\n * @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true.\n\n * @returns {Promise<void>}\n */\n writeZipPromise: function (/**String*/ targetFileName, /* object */ props) {\n const { overwrite, perm } = Object.assign({ overwrite: true }, props);\n\n return new Promise((resolve, reject) => {\n // find file name\n if (!targetFileName && opts.filename) targetFileName = opts.filename;\n if (!targetFileName) reject(\"ADM-ZIP: ZIP File Name Missing\");\n\n this.toBufferPromise().then((zipData) => {\n const ret = (done) => (done ? resolve(done) : reject(\"ADM-ZIP: Wasn't able to write zip file\"));\n filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);\n }, reject);\n });\n },\n\n /**\n * @returns {Promise<Buffer>} A promise to the Buffer.\n */\n toBufferPromise: function () {\n return new Promise((resolve, reject) => {\n _zip.toAsyncBuffer(resolve, reject);\n });\n },\n\n /**\n * Returns the content of the entire zip file as a Buffer object\n *\n * @prop {function} [onSuccess]\n * @prop {function} [onFail]\n * @prop {function} [onItemStart]\n * @prop {function} [onItemEnd]\n * @returns {Buffer}\n */\n toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) {\n if (typeof onSuccess === \"function\") {\n _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);\n return null;\n }\n return _zip.compressToBuffer();\n }\n };\n};\n", "// The programmatic API \u2014 what `require('@flowrunner/cli')` gives you.\n//\n// Importing this must have no side effects: no argv parsing, no output, no process exit. The command-line\n// program lives in `cli/index.ts` and is reached through `bin/flowrunner.js`, never through here. Anything\n// exported below is callable from a Node program that wants to do what the CLI does without being a CLI.\n\n// \u2500\u2500\u2500 Failures \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Every operation reports problems by throwing one of these. Branch on `error.code`, or catch `CliError`\n// for the lot.\n\nexport type { ClusterName, ProviderLayout } from './constants'\nexport {\n AI_INSTRUCTIONS_DIRECTORY,\n CLAUDE_PROVIDER,\n CLUSTERS,\n DEFAULT_CLUSTER,\n DEFAULT_SERVER_URL,\n PROVIDERS,\n SANDBOX_DIRECTORY,\n TEST_DEV_DEPENDENCIES,\n TEST_SCRIPTS,\n TESTING_FILES,\n} from './constants'\nexport type { CliErrorCode, SkippedService } from './errors'\nexport {\n AiDocsMissingError,\n CliError,\n DeployFailedError,\n ERROR_CODES,\n HttpError,\n LoginFailedError,\n LoginTimeoutError,\n NoServicesDirectoryError,\n NoServicesError,\n NotAProjectError,\n NotLoggedInError,\n NoWorkspaceError,\n PromptAbortedError,\n PromptRequiredError,\n SelectionAbortedError,\n TemplateNotFoundError,\n TokenExpiredError,\n UnknownServerError,\n} from './errors'\n\n// \u2500\u2500\u2500 Operations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Each one takes `{ cwd, onEvent }`, returns what it did, and throws one of the errors above. None of them\n// print, prompt or exit \u2014 supply `onEvent` to watch progress.\n\nexport type {\n DeployedService,\n DeployEvent,\n DeployOptions,\n DeployResult,\n DiscoveredService,\n DiscoveryResult,\n PlannedService,\n PublicFile,\n Selection,\n ServiceStatus,\n Workspace,\n} from './operations/deploy'\nexport {\n collectPublicFiles,\n computeServiceHash,\n createServiceZip,\n deploy,\n discoverServices,\n selectServices,\n} from './operations/deploy'\nexport type {\n InitEvent,\n InitOptions,\n InitResult,\n TargetDescription,\n TestingFilesResult,\n} from './operations/init'\nexport { describeTarget, init, testingFilesDirectory, writeTestingFiles } from './operations/init'\nexport type { Ask, AskRequest, ResolveAnswersOptions } from './operations/init/answers'\nexport { resolveAnswers } from './operations/init/answers'\nexport type {\n CreateServiceEvent,\n CreateServiceOptions,\n ScaffoldedService,\n} from './operations/init/create-service'\nexport { createService, resolveTemplateId, scaffoldFromTemplate } from './operations/init/create-service'\nexport type {\n InitClaudeEvent,\n InitClaudeOptions,\n InitClaudeResult,\n MergeResult,\n SegmentOutcome,\n} from './operations/init-claude'\nexport {\n BEGIN_MARKER,\n END_MARKER,\n initClaude,\n mergeSegment,\n providerDirectory,\n} from './operations/init-claude'\nexport type { LoginEvent, LoginOptions, LoginResult } from './operations/login'\nexport { login } from './operations/login'\nexport type { LogoutEvent, LogoutOptions, LogoutResult } from './operations/logout'\nexport { logout } from './operations/logout'\nexport type {\n PulledService,\n PullEvent,\n PullOptions,\n PullResult,\n} from './operations/pull'\nexport { declaredDependencies, extractService, isSafeServiceId, localState, pull } from './operations/pull'\nexport { CLUSTER_NAMES, clusterFor, normalizeServerUrl, resolveServerTarget } from './operations/server-target'\nexport type { OperationOptions } from './operations/types'\nexport type { UseServerResult } from './operations/use-server'\nexport { useServer } from './operations/use-server'\n\n// \u2500\u2500\u2500 Project state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type { AuthGap, AuthToSave, StoredAuth } from './project/auth'\nexport { authGap, clearAuth, describeWorkspace, loadAuth, requireAuth } from './project/auth'\nexport { getServerUrl, getWorkspaceId } from './project/config'\n\n// \u2500\u2500\u2500 Service templates \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type { Answers, Prompt, Template, TemplateManifest } from './templates'\nexport { defaultTemplate, findTemplate, listTemplates } from './templates'\n", "// What goes into a deployed package.\n//\n// A service is self-contained: `services/<id>/` holds its own source, its own `package.json`, and its own\n// `node_modules`. That folder IS the package \u2014 nothing from the project root travels with it, which is what\n// makes a service the same thing wherever it is checked out.\n\n/**\n * Packed, but left out of the source hash.\n *\n * `node_modules` has to ship \u2014 the pod installs nothing \u2014 but hashing it would mean walking thousands of\n * generated files on every deploy to learn what the service's own `package-lock.json` already says.\n */\nexport const HASH_EXCLUDED_FOLDERS = [\n 'node_modules',\n]\n", "// What a Flowrunner extensions project looks like on disk. Shared by `init` (which creates these) and\n// `project/` (which reads and writes them).\n\nexport const CONFIG_FILE = 'flowrunner.json'\n\nexport const TOKEN_DIR = '.flowrunner'\nexport const TOKEN_FILE = `${ TOKEN_DIR }/token`\n\n// \u2500\u2500\u2500 AI docs, shipped inside the installed package \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Packed by `scripts/pack-ai-docs.mjs` from the console repo's feature docs, so they are readable from a\n// customer's project without it having the repo. Every path below is relative to the *installed package*.\n//\n// `init` writes none of these into the project: which file an agent reads, and where, is provider-specific\n// (see `providers.ts`), so wiring one up is its own `init-<provider>` command.\n\n/** Where the CLI ships instructions written for an AI agent, relative to the installed package. */\nexport const AI_DOCS_DIRECTORY = 'ai-docs'\n\n/** The one shared authoring reference \u2014 how to write a service. Provider-independent. */\nexport const AI_INSTRUCTIONS_DIRECTORY = `${ AI_DOCS_DIRECTORY }/instructions/service-code-format`\n\n/** Per-provider glue: agent definitions and the segment for that provider's instructions file. */\nexport const AI_PROVIDERS_DIRECTORY = `${ AI_DOCS_DIRECTORY }/providers`\n", "// Where each AI provider keeps its instructions, and what the CLI ships for it.\n//\n// Every provider has its own rules \u2014 which file it reads as project instructions, whether it has a notion of\n// subagents, and where those live. None of that is guessable from one provider's layout, so it is declared\n// per provider here rather than inferred. Adding a provider is adding an entry plus its own `init-<provider>`\n// command; nothing about one provider's layout leaks into another's.\n//\n// This is the *target project* side. The packed side \u2014 what the CLI ships under\n// `ai-docs/providers/<id>/` \u2014 is the same `id` plus the two names below it.\n\n/** The orchestrator segment, inside `ai-docs/providers/<id>/`. */\nexport const ORCHESTRATOR_SEGMENT_FILE = 'main-orchestrator-segment.md'\n\n/** The agent definitions, inside `ai-docs/providers/<id>/`. */\nexport const PROVIDER_AGENTS_DIRECTORY = 'agents'\n\nexport interface ProviderLayout {\n /** Directory name under `ai-docs/providers/`, and the CLI's name for the provider. */\n id: string\n /** How the provider is named in output written for a human. */\n label: string\n /**\n * The provider's own project-instructions file, relative to the project root.\n *\n * The CLI never owns this file \u2014 it owns only the region between its markers inside it.\n */\n instructionsFile: string\n /**\n * Where the provider looks for subagent definitions, relative to the project root.\n *\n * These files *are* CLI-owned and are overwritten on every run.\n */\n agentsDirectory: string\n}\n\n/**\n * Claude Code.\n *\n * It reads `CLAUDE.md` and specifically **not** `AGENTS.md` \u2014 the cross-vendor convention is invisible to it,\n * which is the whole reason provider wiring cannot be one shared file written by `init`.\n */\nexport const CLAUDE_PROVIDER = 'claude'\n\nexport const PROVIDERS: Record<string, ProviderLayout> = {\n [CLAUDE_PROVIDER]: {\n id : CLAUDE_PROVIDER,\n label : 'Claude Code',\n instructionsFile: 'CLAUDE.md',\n agentsDirectory : '.claude/agents',\n },\n}\n", "// Where the CLI points, and the clusters it knows by name.\n\n/**\n * The Flowrunner clusters, by short name.\n *\n * A named table rather than free-form URLs so that `flowrunner use dev` is a typo-proof way to move a\n * project between them: a name that is not in here is refused, where a mistyped URL would be accepted and\n * only fail later, against a server that does not exist.\n */\nexport const CLUSTERS = {\n prod : 'https://app.flowrunner.ai',\n dev : 'https://dev.flowrunner.ai',\n local: 'http://localhost:3000',\n} as const\n\nexport type ClusterName = keyof typeof CLUSTERS\n\n/**\n * The cluster a fresh project points at.\n *\n * One line, deliberately: moving the default from local to dev to prod as the product ships should not mean\n * hunting for a URL literal in half a dozen places.\n */\nexport const DEFAULT_CLUSTER: ClusterName = 'prod'\n\n/**\n * The console a project talks to when it has not been told otherwise.\n *\n * A fresh project must be able to run `login` before anything has written `flowrunner.json` \u2014 asking the\n * user for a URL they have no way of knowing is the one thing a first run cannot afford.\n */\nexport const DEFAULT_SERVER_URL: string = CLUSTERS[DEFAULT_CLUSTER]\n\n/** Overrides the default without editing the project file \u2014 how you point the CLI at a local console. */\nexport const SERVER_URL_ENV = 'FLOWRUNNER_SERVER_URL'\n", "// The unit-test harness `init` copies into a project.\n//\n// Two halves that have to agree: the files under `project-files/` in this package, and what a project\n// needs installed to run them. Both are declared here so a change to one is made next to the other.\n\n/** Files shipped inside this package for copying into a project, relative to the package root. */\nexport const PROJECT_FILES_DIRECTORY = 'project-files'\n\n/** Where the harness lands in the project. Test suites reach it as `require('../../../sandbox')`. */\nexport const SANDBOX_DIRECTORY = 'sandbox'\n\n/**\n * What `init` copies, as paths relative to both `project-files/` and the project root.\n *\n * An explicit list rather than a directory walk: a file that ships in this package but is not meant to\n * land in a customer's project should not do so by being added to a folder.\n */\nexport const TESTING_FILES = [\n 'jest.config.js',\n 'jest.setup.js',\n `${ SANDBOX_DIRECTORY }/index.js`,\n `${ SANDBOX_DIRECTORY }/service.js`,\n `${ SANDBOX_DIRECTORY }/nock-mock.js`,\n `${ SANDBOX_DIRECTORY }/files-mock.js`,\n]\n\n/**\n * What the harness needs installed, pinned to the majors it was written against.\n *\n * `query-string` is the sharp one, and the pin is load-bearing: v8 and up are ESM-only, which jest's\n * CommonJS runtime refuses to execute \u2014 `Must use import to load ES Module` \u2014 however the package is\n * declared here, since installing it is not what fails. Getting off v7 therefore means bundling the\n * library into something the sandbox requires, or putting babel into every project; a version bump\n * alone only breaks the harness. `nock-mock.js` also depends on its `parseNumbers` / `parseBooleans`\n * options to put JS types back on a query string that carries none.\n *\n * `nock` 14 is the first version that intercepts `fetch` as well as `http`, which is what makes the\n * mock work for a service using a bundled SDK.\n */\nexport const TEST_DEV_DEPENDENCIES: Record<string, string> = {\n jest : '^30.0.0',\n nock : '^14.0.0',\n 'query-string': '^7.1.3',\n}\n\n/** Added to `scripts`, and only where the project has no script of that name already. */\nexport const TEST_SCRIPTS: Record<string, string> = {\n test : 'jest',\n 'test:coverage': 'jest --coverage',\n}\n\n/**\n * Script values that count as absent \u2014 `npm init -y` writes this one, and it is not a decision anybody made.\n *\n * Without it the extremely common `npm init -y` \u2192 `flowrunner init` \u2192 `npm test` ends at\n * *Error: no test specified*, with a jest config and a sandbox sitting right there unused. Matched on the\n * exact string, so a project that has written its own `test` script keeps it whatever it says.\n */\nexport const PLACEHOLDER_SCRIPTS: Record<string, string> = {\n test: 'echo \"Error: no test specified\" && exit 1',\n}\n\n/** Both are produced by a test run: coverage reports, and the Files sandbox's blob storage. */\nexport const TEST_GITIGNORE_ENTRIES = ['coverage/', 'temp/']\n", "// Every way an operation can fail, as one hierarchy.\n//\n// An operation called from code cannot report a problem by printing it and ending the process, so each\n// failure is a class with a stable `code` a caller can branch on. The message here states the fact and\n// nothing more \u2014 the advice that goes with it (\"run `flowrunner login`\") belongs to whoever is talking to a\n// human, which is `cli/fail.ts`. A library consumer gets the fact and writes their own sentence.\n\nexport const ERROR_CODES = [\n 'FR_NOT_LOGGED_IN',\n 'FR_NO_WORKSPACE',\n 'FR_NO_SERVICES_DIR',\n 'FR_NO_SERVICES',\n 'FR_SELECTION_REQUIRED',\n 'FR_UNKNOWN_SERVICE',\n 'FR_TOKEN_EXPIRED',\n 'FR_DEPLOY_FAILED',\n 'FR_LOGIN_TIMEOUT',\n 'FR_LOGIN_FAILED',\n 'FR_PROMPT_REQUIRED',\n 'FR_PROMPT_ABORTED',\n 'FR_TEMPLATE_NOT_FOUND',\n 'FR_UNKNOWN_SERVER',\n 'FR_NOT_A_PROJECT',\n 'FR_AI_DOCS_MISSING',\n 'FR_HTTP',\n] as const\n\nexport type CliErrorCode = typeof ERROR_CODES[number]\n\n/**\n * The base every failure below extends, so a caller can catch the whole family at once.\n *\n * `name` is assigned from the constructor rather than left to the class, because the bundler is free to\n * rename classes and `error.name` is the one thing that tends to end up in someone's log.\n */\nexport class CliError extends Error {\n readonly code: CliErrorCode\n\n constructor(code: CliErrorCode, message: string, name = 'CliError') {\n super(message)\n\n this.code = code\n this.name = name\n }\n}\n\n// \u2500\u2500\u2500 Auth \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** No `flowrunner.json` naming a server, or no token in `.flowrunner/`. */\nexport class NotLoggedInError extends CliError {\n constructor(message = 'This project is not connected to a Flowrunner server.') {\n super('FR_NOT_LOGGED_IN', message, 'NotLoggedInError')\n }\n}\n\n/** Logged in, but `flowrunner.json` names no workspace \u2014 so there is nowhere to deploy to. */\nexport class NoWorkspaceError extends CliError {\n constructor(message = 'This project has a login but no workspace attached.') {\n super('FR_NO_WORKSPACE', message, 'NoWorkspaceError')\n }\n}\n\n/** The server rejected the deploy token. */\nexport class TokenExpiredError extends CliError {\n constructor(message = 'The stored deploy token is no longer valid.') {\n super('FR_TOKEN_EXPIRED', message, 'TokenExpiredError')\n }\n}\n\nexport class LoginTimeoutError extends CliError {\n constructor(message = 'Login timed out. Please try again.') {\n super('FR_LOGIN_TIMEOUT', message, 'LoginTimeoutError')\n }\n}\n\nexport class LoginFailedError extends CliError {\n constructor(message: string) {\n super('FR_LOGIN_FAILED', message, 'LoginFailedError')\n }\n}\n\n// \u2500\u2500\u2500 Deploy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The project has no `services/` directory at all. */\nexport class NoServicesDirectoryError extends CliError {\n constructor(message = 'This project has no services/ directory.') {\n super('FR_NO_SERVICES_DIR', message, 'NoServicesDirectoryError')\n }\n}\n\n/**\n * `services/` exists but nothing in it loaded as a service.\n *\n * Carries the folders that were skipped and why: with the whole deploy refusing to run, the reason a\n * particular folder was not counted is the only thing that tells anyone what to fix.\n */\nexport class NoServicesError extends CliError {\n readonly skipped: SkippedService[]\n\n constructor(skipped: SkippedService[] = [], message = 'No deployable services were found under services/.') {\n super('FR_NO_SERVICES', message, 'NoServicesError')\n\n this.skipped = skipped\n }\n}\n\nexport interface SkippedService {\n serviceId: string\n reason: string\n}\n\n/**\n * More than one service is deployable and none was chosen.\n *\n * A deploy now touches only the services it names, so \"all of them\" has to be asked for rather than assumed\n * \u2014 silently deploying every service would be the old behaviour wearing a new coat.\n */\nexport class SelectionRequiredError extends CliError {\n readonly available: string[]\n\n constructor(available: string[], message = 'This project has more than one service, so the deploy needs to know which.') {\n super('FR_SELECTION_REQUIRED', message, 'SelectionRequiredError')\n\n this.available = available\n }\n}\n\n/** A `-s` name that matches no deployable service in this project. */\nexport class UnknownServiceError extends CliError {\n readonly serviceId: string\n readonly available: string[]\n\n constructor(serviceId: string, available: string[]) {\n super(\n 'FR_UNKNOWN_SERVICE',\n `Unknown service \"${ serviceId }\". Available: ${ available.join(', ') }`,\n 'UnknownServiceError'\n )\n\n this.serviceId = serviceId\n this.available = available\n }\n}\n\n/** The server accepted the request and refused the package. */\nexport class DeployFailedError extends CliError {\n readonly status?: number\n readonly body?: string\n\n constructor(message: string, { status, body }: { status?: number; body?: string } = {}) {\n super('FR_DEPLOY_FAILED', message, 'DeployFailedError')\n\n this.status = status\n this.body = body\n }\n}\n\n// \u2500\u2500\u2500 Templates and answers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class TemplateNotFoundError extends CliError {\n readonly templateId: string\n readonly available: string[]\n\n constructor(templateId: string, available: string[]) {\n super(\n 'FR_TEMPLATE_NOT_FOUND',\n `Unknown template \"${ templateId }\". Available: ${ available.join(', ') }`,\n 'TemplateNotFoundError'\n )\n\n this.templateId = templateId\n this.available = available\n }\n}\n\n/**\n * An answer is needed and there is no way to ask for it.\n *\n * The programmatic path throws this instead of blocking on a terminal that may not exist; supply the answer\n * up front, or pass the hook that knows how to ask.\n */\nexport class PromptRequiredError extends CliError {\n readonly promptName: string\n\n constructor(promptName: string, message: string) {\n super('FR_PROMPT_REQUIRED', message, 'PromptRequiredError')\n\n this.promptName = promptName\n }\n}\n\n/** The user was asked and declined \u2014 Ctrl-C, Escape, or an answer that failed its own validator. */\nexport class PromptAbortedError extends CliError {\n constructor(message: string) {\n super('FR_PROMPT_ABORTED', message, 'PromptAbortedError')\n }\n}\n\n/** Ctrl-C or Escape out of an interactive list. Its own type so a caller can offer something else instead. */\nexport class SelectionAbortedError extends PromptAbortedError {\n constructor(message = 'Cancelled.') {\n super(message)\n\n this.name = 'SelectionAbortedError'\n }\n}\n\n// \u2500\u2500\u2500 Project \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** There is no `flowrunner.json` here, so there is no project to act on. */\nexport class NotAProjectError extends CliError {\n constructor(message = 'There is no flowrunner.json here, so this is not a Flowrunner project.') {\n super('FR_NOT_A_PROJECT', message, 'NotAProjectError')\n }\n}\n\n/** A server name that is not one of the known clusters, and not a URL either. */\nexport class UnknownServerError extends CliError {\n readonly target: string\n readonly available: string[]\n\n constructor(target: string, available: string[]) {\n super(\n 'FR_UNKNOWN_SERVER',\n `Unknown server \"${ target }\". Available: ${ available.join(', ') }`,\n 'UnknownServerError'\n )\n\n this.target = target\n this.available = available\n }\n}\n\n// \u2500\u2500\u2500 AI docs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * The installed CLI ships no AI docs for the requested provider.\n *\n * They are build output packed into the package, so this means an install that predates them \u2014 or a repo\n * checkout that has not been built. Carries the directory looked for, because \"which path did you expect\"\n * is the only question anyone asks next.\n */\nexport class AiDocsMissingError extends CliError {\n readonly directory: string\n\n constructor(directory: string, message = `The installed FlowRunner CLI ships no AI docs at ${ directory }.`) {\n super('FR_AI_DOCS_MISSING', message, 'AiDocsMissingError')\n\n this.directory = directory\n }\n}\n\n// \u2500\u2500\u2500 Transport \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * A non-2xx response, with the status kept as a number.\n *\n * The status is the whole point: deciding \"expired token\" by looking for \"401\" inside a message is a test\n * that passes for any server that happens to mention the number.\n *\n * `what` names the call for a human (\"Token exchange\", \"Deploy\"); without it the message names the URL.\n */\nexport class HttpError extends CliError {\n readonly status: number\n readonly body: string\n readonly url: string\n\n constructor(status: number, body: string, url: string, what?: string) {\n super('FR_HTTP', `${ what ?? `Request to ${ url }` } failed (${ status }): ${ body }`, 'HttpError')\n\n this.status = status\n this.body = body\n this.url = url\n }\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport { listRemoteServices, uploadService } from '../../api/console-client'\nimport type { SkippedService } from '../../errors'\nimport {\n DeployFailedError,\n HttpError,\n NoServicesDirectoryError,\n NoServicesError,\n NotLoggedInError,\n NoWorkspaceError,\n TokenExpiredError,\n} from '../../errors'\nimport type { AuthGap, StoredAuth } from '../../project/auth'\nimport { authGap, loadAuth } from '../../project/auth'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport type { DiscoveredService } from './discover-services'\nimport { discoverServices } from './discover-services'\nimport { computeServiceHash } from './hash'\nimport type { PublicFile } from './public-files'\nimport { collectPublicFiles } from './public-files'\nimport type { Selection } from './select'\nimport { selectServices } from './select'\nimport { createServiceZip } from './zip'\n\nexport type { DiscoveredService, DiscoveryResult } from './discover-services'\nexport { discoverServices } from './discover-services'\nexport { computeServiceHash } from './hash'\nexport type { PublicFile, PublicFilesResult } from './public-files'\nexport { collectPublicFiles } from './public-files'\nexport type { Selection } from './select'\nexport { selectServices } from './select'\nexport { createServiceZip } from './zip'\n\n// Deploying: read the project, work out what has actually changed, and upload each changed service on its\n// own.\n//\n// One service per upload is the whole point. The workspace keeps whatever was deployed before from anywhere\n// else, so services authored in separate projects accumulate rather than replace one another.\n//\n// Every service is compared against the workspace before anything is packaged, so the run can say which are\n// new and which merely moved \u2014 and can decline to re-upload one that is byte-for-byte already there. A\n// service's `sourceHash` covers its folder and nothing else, which is what makes that comparison meaningful\n// from any project.\n//\n// Nothing here prints and nothing here exits. A missing login is an error, not a prompt \u2014 the CLI passes\n// `onAuthRequired` and turns it back into an offer, and everyone else gets something they can catch.\n\n/** What deploying a service would do to the workspace. */\nexport type ServiceStatus = 'new' | 'modified' | 'same'\n\nexport interface PlannedService {\n service: DiscoveredService\n serviceId: string\n /** The hash this deploy would publish. */\n sourceHash: string\n status: ServiceStatus\n}\n\nexport type DeployEvent =\n | { type: 'connecting'; serverUrl: string; workspace: Workspace }\n | { type: 'discovered'; planned: PlannedService[] }\n | { type: 'skipped'; skipped: SkippedService }\n | { type: 'selected'; planned: PlannedService[] }\n | { type: 'icon-missing'; serviceId: string; relativePath: string }\n | { type: 'deployed'; entry: DeployedService }\n | { type: 'unchanged'; entry: PlannedService }\n\nexport interface DeployOptions extends OperationOptions<DeployEvent>, Selection {\n /**\n * Called when the project has no usable credentials, before giving up.\n *\n * The CLI passes an interactive login here, which is why `flowrunner deploy` can offer to connect a\n * project mid-run. A caller that passes nothing gets NotLoggedInError or NoWorkspaceError thrown instead \u2014\n * a library must not open a browser on someone's behalf.\n */\n onAuthRequired?: (gap: AuthGap) => Promise<void>\n\n /**\n * Called when the project has several services and the caller named none.\n *\n * Same bargain as `onAuthRequired`: the CLI turns it into a picker, and a caller that passes nothing gets\n * SelectionRequiredError to handle its own way. Receives the classified list, so a picker can say which\n * services would actually change.\n */\n onSelectionRequired?: (available: PlannedService[]) => Promise<Selection>\n\n /**\n * Upload a service even when the workspace already has exactly this code.\n *\n * The default is to skip it \u2014 the deploy would produce the version that is already active, at the cost of\n * shipping the whole package. Worth overriding when the stored package itself is in doubt.\n */\n force?: boolean\n}\n\nexport interface Workspace {\n workspaceId: string\n workspaceName: string\n}\n\nexport interface DeployedService {\n serviceId: string\n serviceName: string\n sourceHash: string\n packageBytes: number\n /** `new` the first time the workspace sees it, `modified` when it replaces a different version. */\n status: Exclude<ServiceStatus, 'same'>\n}\n\nexport interface DeployResult {\n workspace: Workspace\n serverUrl: string\n /** Services actually uploaded. */\n services: DeployedService[]\n /** Selected, but the workspace already had exactly this code. */\n unchanged: PlannedService[]\n /** Folders under `services/` that were not deployable, and why. Empty on a clean run. */\n skipped: SkippedService[]\n}\n\n/**\n * Resolve the credentials, giving `onAuthRequired` one chance to fill a gap.\n *\n * Re-reads from disk afterwards rather than trusting the hook's return value: the login writes\n * `flowrunner.json` and the token file, and reading them back is what proves it actually happened.\n */\nasync function resolveAuth(projectRoot: string, onAuthRequired?: DeployOptions['onAuthRequired']): Promise<StoredAuth> {\n const stored = loadAuth(projectRoot)\n const gap = authGap(stored)\n\n if (!gap) {\n return stored as StoredAuth\n }\n\n if (!onAuthRequired) {\n throw errorForGap(gap)\n }\n\n await onAuthRequired(gap)\n\n const refreshed = loadAuth(projectRoot)\n const remaining = authGap(refreshed)\n\n if (remaining) {\n throw errorForGap(remaining)\n }\n\n return refreshed as StoredAuth\n}\n\nfunction errorForGap(gap: AuthGap): Error {\n return gap === 'not-logged-in' ? new NotLoggedInError() : new NoWorkspaceError()\n}\n\nexport async function deploy(options: DeployOptions = {}): Promise<DeployResult> {\n const projectRoot = options.cwd ?? process.cwd()\n const emit = emitter(options)\n\n const { serverUrl, workspaceId, workspaceName, deployToken } = await resolveAuth(projectRoot, options.onAuthRequired)\n const credentials = { serverUrl, workspaceId, deployToken }\n const workspace = { workspaceId, workspaceName }\n\n if (!fs.existsSync(path.resolve(projectRoot, 'services'))) {\n throw new NoServicesDirectoryError()\n }\n\n emit({ type: 'connecting', serverUrl, workspace })\n\n const { services: discovered, skipped } = discoverServices(projectRoot)\n\n for (const entry of skipped) {\n emit({ type: 'skipped', skipped: entry })\n }\n\n if (discovered.length === 0) {\n throw new NoServicesError(skipped)\n }\n\n // Classified before anything is selected, so a picker can say which services would actually change.\n const planned = await plan(projectRoot, discovered, credentials)\n\n emit({ type: 'discovered', planned })\n\n const selected = await resolveSelection(planned, options)\n\n emit({ type: 'selected', planned: selected })\n\n const deployed: DeployedService[] = []\n const unchanged: PlannedService[] = []\n\n // Sequential, and each upload stands alone: if the third service fails, the first two are deployed and\n // stay deployed. There is no package-wide transaction to roll back any more.\n for (const entry of selected) {\n if (entry.status === 'same' && !options.force) {\n unchanged.push(entry)\n emit({ type: 'unchanged', entry })\n\n continue\n }\n\n const { service, sourceHash } = entry\n const { files: icons, missing } = collectPublicFiles([service], projectRoot)\n\n for (const icon of missing) {\n emit({ type: 'icon-missing', ...icon })\n }\n\n const definition = { sourceHash, service }\n const zipBuffer = await createServiceZip(definition, projectRoot, service.serviceId)\n const result = await upload(credentials, zipBuffer, definition, icons)\n\n // `same` only reaches here under --force, where re-publishing the active version is the point.\n const status = entry.status === 'new' ? 'new' : 'modified'\n const record: DeployedService = { ...result, packageBytes: zipBuffer.length, status }\n\n deployed.push(record)\n emit({ type: 'deployed', entry: record })\n }\n\n return { workspace, serverUrl, services: deployed, unchanged, skipped }\n}\n\n/**\n * What deploying each discovered service would do, judged against what the workspace has active.\n *\n * The comparison is on `sourceHash`, which covers the service folder alone \u2014 so \"same\" means the active\n * version is this exact code, whichever project put it there.\n */\nasync function plan(\n projectRoot: string,\n discovered: DiscoveredService[],\n credentials: { serverUrl: string; workspaceId: string; deployToken: string }\n): Promise<PlannedService[]> {\n const remote = await guarded(() => listRemoteServices(credentials))\n const active = new Map(remote.map(service => [service.serviceId, service.sourceHash]))\n\n return Promise.all(discovered.map(async service => {\n const sourceHash = await computeServiceHash(projectRoot, service.serviceId)\n const deployedHash = active.get(service.serviceId)\n\n const status: ServiceStatus = deployedHash === undefined\n ? 'new'\n : deployedHash === sourceHash ? 'same' : 'modified'\n\n return { service, serviceId: service.serviceId, sourceHash, status }\n }))\n}\n\nasync function resolveSelection(\n planned: PlannedService[],\n options: DeployOptions\n): Promise<PlannedService[]> {\n try {\n return selectServices(planned, options)\n } catch (error) {\n if (!options.onSelectionRequired || (error as { code?: string }).code !== 'FR_SELECTION_REQUIRED') {\n throw error\n }\n\n // The hook answers the question this operation cannot ask; its answer goes back through the same\n // resolver so an unknown id is rejected identically however it arrived.\n return selectServices(planned, await options.onSelectionRequired(planned))\n }\n}\n\n/** One upload, with the transport's failures translated into the CLI's vocabulary. */\nasync function upload(\n credentials: { serverUrl: string; workspaceId: string; deployToken: string },\n zipBuffer: Buffer,\n definition: { sourceHash: string; service: DiscoveredService },\n icons: PublicFile[]\n) {\n return guarded(() => uploadService(credentials, zipBuffer, definition, icons))\n}\n\n/** Translates a transport failure into the CLI's vocabulary. */\nasync function guarded<T>(call: () => Promise<T>): Promise<T> {\n try {\n return await call()\n } catch (error) {\n // The status is the tell, not the prose. A console that mentions \"401\" while rejecting a package for an\n // unrelated reason used to be read as an expired session.\n if (error instanceof HttpError) {\n if (error.status === 401 || error.body.includes('CLI_TOKEN_EXPIRED')) {\n throw new TokenExpiredError()\n }\n\n throw new DeployFailedError(error.message, { status: error.status, body: error.body })\n }\n\n throw error\n }\n}\n", "import FormData from 'form-data'\nimport fetch from 'node-fetch'\n\nimport { HttpError } from '../errors'\n\n// Everything the CLI sends to a Flowrunner console. The counterpart of `server/`, which only listens.\n//\n// A non-2xx response becomes an HttpError carrying the status as a number, so callers can tell an expired\n// token from a rejected package without reading the message.\n//\n// This is also the only module that still says `appId` / `appName`. The console calls a workspace an \"app\"\n// in its URLs, its query strings and its token-exchange response; everything on our side of this boundary\n// calls it a workspace \u2014 `workspaceId`, `workspaceName`, and those are the names `flowrunner.json` uses too.\n// The translation happens here so that vocabulary does not leak into the rest of the CLI.\n\n// \u2500\u2500\u2500 Authorization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** What the console sends back. `appId` is its name for the workspace id. */\ninterface ExchangeResponse {\n token: string\n appId: string\n appName?: string\n}\n\nexport interface ExchangeResult {\n token: string\n workspaceId: string\n /** Absent from an older console; the CLI falls back to showing the id alone. */\n workspaceName?: string\n}\n\n/**\n * Where to send the user to authorize the CLI and choose a workspace.\n *\n * Built here rather than at the call site because the query string is the console's contract \u2014 `appId`\n * included \u2014 and this module is where that vocabulary is allowed to live.\n */\nexport function authorizeUrl(\n { serverUrl, callbackUrl, workspaceId }: { serverUrl: string; callbackUrl: string; workspaceId?: string }\n): string {\n const url = `${ serverUrl }/developer/cli/authorize` +\n `?callback=${ encodeURIComponent(callbackUrl) }` +\n '&clientType=cloud-code-deploy'\n\n // A workspace the project is already attached to is pre-selected on the page \u2014 shown as a disabled\n // control, with a \"use another workspace\" link beside it. Pre-selected, not locked: moving a project\n // between workspaces has to be possible without hand-editing flowrunner.json.\n return workspaceId ? `${ url }&appId=${ encodeURIComponent(workspaceId) }` : url\n}\n\n/**\n * Where a workspace's custom extensions live in the console.\n *\n * The path segment is the workspace *name*: `/app/:appName/\u2026` is the console's own route shape, and this\n * module is where that vocabulary is allowed to live.\n *\n * Builds unconditionally. Whether there is a name worth linking to is the caller's question \u2014 a project with\n * none recorded has nothing to put in that slot, and an id there would not resolve.\n */\nexport function customExtensionsUrl(serverUrl: string, workspaceName: string): string {\n return `${ serverUrl }/app/${ encodeURIComponent(String(workspaceName)) }/custom-extensions`\n}\n\nexport async function exchangeCodeForToken(serverUrl: string, code: string): Promise<ExchangeResult> {\n const url = `${ serverUrl }/developer/cli/token/exchange`\n\n const response = await fetch(url, {\n method : 'POST',\n headers: { 'Content-Type': 'application/json' },\n body : JSON.stringify({ code }),\n })\n\n if (!response.ok) {\n throw new HttpError(response.status, await response.text(), url, 'Token exchange')\n }\n\n const body = await response.json() as ExchangeResponse\n\n return { token: body.token, workspaceId: body.appId, workspaceName: body.appName }\n}\n\nexport async function revokeToken(serverUrl: string, token: string): Promise<void> {\n try {\n await fetch(`${ serverUrl }/developer/cli/token/revoke`, {\n method : 'POST',\n headers: { 'Content-Type': 'application/json' },\n body : JSON.stringify({ token }),\n })\n } catch {\n // Best effort: the local token is being deleted either way, and a revoke that never reached the server\n // is not a reason to leave the user still looking logged in.\n }\n}\n\n// \u2500\u2500\u2500 Deploy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface DeployCredentials {\n serverUrl: string\n workspaceId: string\n deployToken: string\n}\n\n/**\n * A file uploaded alongside the package \u2014 today the icons a service declares.\n *\n * Declared here rather than imported from `operations/deploy`: this layer knows how to send bytes with a\n * name attached, and nothing about what makes a file worth sending.\n */\nexport interface UploadFile {\n serviceId: string\n relativePath: string\n buffer: Buffer\n}\n\nexport interface UploadResult {\n packageId: string\n serviceId: string\n serviceName: string\n sourceHash: string\n}\n\n/** One service in the workspace, as `flowrunner pull` sees it. */\nexport interface RemoteService {\n serviceId: string\n serviceName: string\n /** The version, and \u2014 because it covers the service folder and nothing else \u2014 comparable to a local copy. */\n sourceHash: string\n}\n\n/**\n * Upload one service: its zip, its definition, and any icons it declares.\n *\n * One service per request \u2014 the server activates exactly what it receives and leaves every other service in\n * the workspace alone, which is what lets several projects deploy into the same workspace.\n */\nexport async function uploadService(\n credentials: DeployCredentials,\n zipBuffer: Buffer,\n definition: object,\n publicFiles: UploadFile[] = []\n): Promise<UploadResult> {\n const form = new FormData()\n\n form.append('file', zipBuffer, {\n filename : 'service.zip',\n contentType: 'application/zip',\n })\n form.append('definition', JSON.stringify(definition))\n\n for (const file of publicFiles) {\n // Just the path: the request already carries exactly one service, so the name has nothing to qualify.\n form.append('publicFiles', file.buffer, {\n filename : file.relativePath,\n contentType: 'application/octet-stream',\n })\n }\n\n const url = `${ credentials.serverUrl }/api/manage/app/${ credentials.workspaceId }/custom-extensions/deploy`\n\n const response = await fetch(url, {\n method : 'POST',\n headers: {\n 'deploy-token': credentials.deployToken,\n ...form.getHeaders(),\n },\n body: form,\n })\n\n if (!response.ok) {\n throw new HttpError(response.status, await response.text(), url, 'Deploy')\n }\n\n return response.json() as Promise<UploadResult>\n}\n\n// \u2500\u2500\u2500 Pull \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The workspace's active services \u2014 one entry per service, whichever project deployed it. */\nexport async function listRemoteServices(credentials: DeployCredentials): Promise<RemoteService[]> {\n const url = `${ credentials.serverUrl }/api/manage/app/${ credentials.workspaceId }/custom-extensions/cli/services`\n\n const response = await fetch(url, {\n headers: { 'deploy-token': credentials.deployToken },\n })\n\n if (!response.ok) {\n throw new HttpError(response.status, await response.text(), url, 'List services')\n }\n\n return response.json() as Promise<RemoteService[]>\n}\n\n/** The zip of a service's active version. */\nexport async function downloadRemoteService(credentials: DeployCredentials, serviceId: string): Promise<Buffer> {\n const url = `${ credentials.serverUrl }/api/manage/app/${ credentials.workspaceId }` +\n `/custom-extensions/cli/services/${ encodeURIComponent(serviceId) }/download`\n\n const response = await fetch(url, {\n headers: { 'deploy-token': credentials.deployToken },\n })\n\n if (!response.ok) {\n throw new HttpError(response.status, await response.text(), url, 'Download service')\n }\n\n return Buffer.from(await response.arrayBuffer())\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport { CONFIG_FILE, DEFAULT_SERVER_URL, SERVER_URL_ENV } from '../constants'\n\n// `flowrunner.json` \u2014 the tracked half of a project's identity. It names the server and the workspace, and\n// it belongs in git; the token that goes with it does not (see `./token`).\n//\n// Every function here takes the project root explicitly. It defaults to the current directory because that\n// is what a CLI means, but a caller driving this from code is usually pointing at a project somewhere else.\n\nexport interface ProjectConfig {\n serverUrl?: string\n workspaceId?: string\n /** Cosmetic: which workspace the id refers to, so the CLI can name it instead of printing a GUID. */\n workspaceName?: string\n [key: string]: unknown\n}\n\nexport interface EnsuredServerUrl {\n serverUrl: string\n /** `flowrunner.json` did not exist and was created. */\n created: boolean\n /** It existed but did not name a server, or named a different one, and was rewritten. */\n updated: boolean\n}\n\nexport function configPath(projectRoot: string = process.cwd()): string {\n return path.resolve(projectRoot, CONFIG_FILE)\n}\n\nexport function readConfig(projectRoot: string = process.cwd()): ProjectConfig {\n const fullPath = configPath(projectRoot)\n\n if (!fs.existsSync(fullPath)) {\n return {}\n }\n\n return JSON.parse(fs.readFileSync(fullPath, 'utf-8'))\n}\n\nexport function writeConfig(config: ProjectConfig, projectRoot: string = process.cwd()): void {\n fs.writeFileSync(configPath(projectRoot), JSON.stringify(config, null, 2) + '\\n', 'utf-8')\n}\n\n/**\n * Which console this project talks to: the project file first, then the environment, then the shipped\n * default. Never empty \u2014 a project that has never logged in still has somewhere to log in to.\n */\nexport function getServerUrl(projectRoot: string = process.cwd()): string {\n return readConfig(projectRoot).serverUrl || process.env[SERVER_URL_ENV] || DEFAULT_SERVER_URL\n}\n\nexport function getWorkspaceId(projectRoot: string = process.cwd()): string {\n return readConfig(projectRoot).workspaceId || ''\n}\n\n/**\n * Make the project's server URL explicit in `flowrunner.json`, creating the file if it is missing.\n *\n * Leaving it implicit reads as working by accident: the project would behave differently depending on an\n * environment variable, or on which CLI version happens to be installed. `init` writes the choice down\n * once, and every command after that reads the project's own decision.\n */\nexport function ensureServerUrl(projectRoot: string = process.cwd(), serverUrl?: string): EnsuredServerUrl {\n const exists = fs.existsSync(configPath(projectRoot))\n const config = readConfig(projectRoot)\n const resolved = serverUrl || config.serverUrl || process.env[SERVER_URL_ENV] || DEFAULT_SERVER_URL\n\n if (exists && config.serverUrl === resolved) {\n return { serverUrl: resolved, created: false, updated: false }\n }\n\n writeConfig({ ...config, serverUrl: resolved }, projectRoot)\n\n return { serverUrl: resolved, created: !exists, updated: exists }\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport { TOKEN_DIR, TOKEN_FILE } from '../constants'\n\n// `.flowrunner/token` \u2014 the untracked half. Writing one always makes sure `.gitignore` covers it: a deploy\n// token committed to a repository is the kind of mistake that is discovered by someone else.\n\nexport function tokenPath(projectRoot: string = process.cwd()): string {\n return path.resolve(projectRoot, TOKEN_FILE)\n}\n\nexport function readToken(projectRoot: string = process.cwd()): string | null {\n const fullPath = tokenPath(projectRoot)\n\n if (!fs.existsSync(fullPath)) {\n return null\n }\n\n return fs.readFileSync(fullPath, 'utf-8').trim()\n}\n\nexport function writeToken(token: string, projectRoot: string = process.cwd()): void {\n const dir = path.resolve(projectRoot, TOKEN_DIR)\n\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true })\n }\n\n fs.writeFileSync(tokenPath(projectRoot), token, 'utf-8')\n}\n\nexport function deleteToken(projectRoot: string = process.cwd()): void {\n const fullPath = tokenPath(projectRoot)\n\n if (fs.existsSync(fullPath)) {\n fs.unlinkSync(fullPath)\n }\n}\n\nexport function ensureGitignore(projectRoot: string = process.cwd()): void {\n const gitignorePath = path.resolve(projectRoot, '.gitignore')\n\n if (!fs.existsSync(gitignorePath)) {\n fs.writeFileSync(gitignorePath, `${ TOKEN_DIR }/\\n`, 'utf-8')\n\n return\n }\n\n const content = fs.readFileSync(gitignorePath, 'utf-8')\n\n if (!content.includes(TOKEN_DIR)) {\n fs.appendFileSync(gitignorePath, `\\n${ TOKEN_DIR }/\\n`)\n }\n}\n", "import { NotLoggedInError, NoWorkspaceError } from '../errors'\nimport { readConfig, writeConfig } from './config'\nimport { deleteToken, ensureGitignore, readToken, writeToken } from './token'\n\n// The two files above, read as one thing: is this project connected, and to what.\n\nexport interface StoredAuth {\n serverUrl: string\n workspaceId: string\n workspaceName: string\n deployToken: string\n}\n\n/** What is missing, when something is. The two gaps have different causes and different fixes. */\nexport type AuthGap = 'not-logged-in' | 'no-workspace'\n\n/** What a completed login has to write down. `workspaceName` is cosmetic and an older console may not send it. */\nexport interface AuthToSave {\n serverUrl: string\n workspaceId: string\n deployToken: string\n workspaceName?: string\n}\n\nexport function saveAuth(\n { serverUrl, workspaceId, deployToken, workspaceName }: AuthToSave,\n projectRoot: string = process.cwd()\n): void {\n writeConfig({ ...readConfig(projectRoot), serverUrl, workspaceId, ...(workspaceName ? { workspaceName } : {}) }, projectRoot)\n writeToken(deployToken, projectRoot)\n ensureGitignore(projectRoot)\n}\n\nexport function loadAuth(projectRoot: string = process.cwd()): StoredAuth | null {\n const config = readConfig(projectRoot)\n const token = readToken(projectRoot)\n\n if (!token || !config.serverUrl) {\n return null\n }\n\n return {\n serverUrl : config.serverUrl,\n workspaceId : config.workspaceId || '',\n workspaceName: config.workspaceName || '',\n deployToken : token,\n }\n}\n\nexport function clearAuth(projectRoot: string = process.cwd()): void {\n deleteToken(projectRoot)\n}\n\n/** Which half of the connection is missing, or null when the project is fully connected. */\nexport function authGap(stored: StoredAuth | null): AuthGap | null {\n if (!stored || !stored.serverUrl || !stored.deployToken) {\n return 'not-logged-in'\n }\n\n if (!stored.workspaceId) {\n return 'no-workspace'\n }\n\n return null\n}\n\n/**\n * The credentials, or a thrown error naming what is absent.\n *\n * Deliberately does nothing about the gap. Offering a login is an interaction, and an operation that opens\n * a browser on its own cannot be called from a program, a test or a CI job \u2014 so the offer lives in `cli/`\n * and this stays a question with two possible answers.\n */\nexport function requireAuth(projectRoot: string = process.cwd()): StoredAuth {\n const stored = loadAuth(projectRoot)\n const gap = authGap(stored)\n\n if (gap === 'not-logged-in') {\n throw new NotLoggedInError()\n }\n\n if (gap === 'no-workspace') {\n throw new NoWorkspaceError()\n }\n\n return stored as StoredAuth\n}\n\n/**\n * How to refer to the connected workspace in output: its name when the console gave us one, else the id.\n *\n * The full form states the connection \u2014 name *and* id, since the id is what lives in `flowrunner.json`. The\n * short form is for every mention after that: repeating a GUID three times in one screen of output is noise\n * that makes the name harder to notice, not easier.\n */\nexport function describeWorkspace(\n { workspaceId, workspaceName }: { workspaceId: string; workspaceName?: string },\n { short = false }: { short?: boolean } = {}\n): string {\n if (!workspaceName) {\n return workspaceId\n }\n\n return short ? workspaceName : `\"${ workspaceName }\" (${ workspaceId })`\n}\n", "// What every operation accepts, and how it talks while it works.\n\n/**\n * Progress, as structured events rather than sentences.\n *\n * An operation that called `report('Packaged 1.2 MB')` would still be composing English for a human, which\n * is the thing being moved out of this layer \u2014 and a caller rendering progress into a web page or a log line\n * would have to parse it back apart. Each operation declares its own event union instead, and whoever is\n * watching decides what those events look like. `cli/reporter.ts` turns them into the terminal output the\n * CLI has always produced.\n */\nexport interface OperationOptions<TEvent = never> {\n /**\n * Which project to work on. Defaults to the current directory, because that is what a command means, but\n * a caller driving this from code usually has a project somewhere else in mind.\n */\n cwd?: string\n /** Called as the operation progresses. Omitted means the operation runs silently, which is the default. */\n onEvent?: (event: TEvent) => void\n}\n\n/** Narrows `options.onEvent` to something always callable, so operations need no null checks. */\nexport function emitter<TEvent>(options: OperationOptions<TEvent>): (event: TEvent) => void {\n return options.onEvent ?? (() => undefined)\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { SharedExtensionConfigItem, SharedExtensionDefinition } from '@shared/scheme'\nimport { buildServiceDefinition, getServiceConfigs } from '@flowrunner/flow-extension-runner'\nimport { parseJsDocToServiceJson } from '@flowrunner/jsdoc-parser'\n\nimport type { SkippedService } from '../../errors'\n\nexport interface DiscoveredService {\n /** Entry point relative to the service root \u2014 'src/index.js', not 'services/<id>/src/index.js'. */\n serviceFilePath: string\n serviceId: string\n serviceInfo: SharedExtensionDefinition['serviceInfo']\n methodsMap: SharedExtensionDefinition['methodsMap']\n configDescriptions: SharedExtensionConfigItem[]\n /** Which authoring format the entry point turned out to be \u2014 the deploy carries it so the console can branch. */\n runnerVersion: SharedExtensionDefinition['runnerVersion']\n /** v2 only: the declared config schema, encoded. `null` for a JSDoc-parsed service. */\n configSchema: SharedExtensionDefinition['configSchema']\n}\n\nexport interface DiscoveryResult {\n services: DiscoveredService[]\n /**\n * Folders under `services/` that did not become a service, and why.\n *\n * Returned rather than warned about: a folder silently missing from a deploy is the kind of thing someone\n * notices a week later, and a caller driving this from code has no console to have missed a warning on.\n */\n skipped: SkippedService[]\n}\n\n/** Scan `services/*` under the project root and build each service's definition, v2 declarative or v1 JSDoc. */\nexport function discoverServices(projectRoot: string = process.cwd()): DiscoveryResult {\n const servicesDir = path.resolve(projectRoot, 'services')\n\n if (!fs.existsSync(servicesDir)) {\n return { services: [], skipped: [] }\n }\n\n const serviceIds = fs\n .readdirSync(servicesDir, { withFileTypes: true })\n .filter(file => file.isDirectory())\n .map(file => file.name)\n\n const services: DiscoveredService[] = []\n const skipped: SkippedService[] = []\n\n for (const serviceId of serviceIds) {\n const serviceDir = path.resolve(servicesDir, serviceId)\n const serviceDISTEntryPoint = path.resolve(serviceDir, './dist/index.js')\n const serviceSRCEntryPoint = path.resolve(serviceDir, './src/index.js')\n\n let serviceFilePath = null\n\n try {\n if (fs.existsSync(serviceDISTEntryPoint)) {\n serviceFilePath = serviceDISTEntryPoint\n } else if (fs.existsSync(serviceSRCEntryPoint)) {\n serviceFilePath = serviceSRCEntryPoint\n }\n\n if (!serviceFilePath) {\n skipped.push({ serviceId, reason: 'it has neither a dist/index.js nor a src/index.js' })\n\n continue\n }\n\n // null for a v1 service, which the JSDoc parser models instead. The cast is load-bearing: the runner's\n // model mirror and @shared/scheme have drifted and are not assignable in either direction.\n const v2Definition = buildServiceDefinition(serviceId, serviceFilePath) as SharedExtensionDefinition | null\n\n const { methodsMap, serviceInfo } = v2Definition ?? parseJsDocToServiceJson(serviceFilePath)\n\n // Only files that define a service (v1: @integrationName; v2: createExtension id).\n if (!serviceInfo || !serviceInfo.serviceClassName) {\n skipped.push({ serviceId, reason: 'its entry point does not define a service' })\n\n continue\n }\n\n // A failure here shouldn't drop the whole service \u2014 record it and fall back to an empty config.\n let configDescriptions: SharedExtensionConfigItem[] = []\n\n try {\n configDescriptions = getServiceConfigs(serviceId, serviceFilePath)\n } catch (error) {\n skipped.push({\n serviceId,\n reason: `its config items could not be read (${ (error as Error).message }) \u2014 deployed without them`,\n })\n }\n\n services.push({\n // Relative to the service, because the deployed archive's root IS the service.\n serviceFilePath: path.relative(serviceDir, serviceFilePath),\n serviceId,\n serviceInfo,\n methodsMap,\n configDescriptions,\n // v2 only. The console renders a v2 config dialog from the schema itself rather than from the\n // `configDescriptions` projection, so both travel: the schema for the new path, the projection for\n // every consumer that predates it.\n runnerVersion: v2Definition ? 'v2' : 'v1',\n configSchema : v2Definition?.configSchema ?? null,\n })\n } catch (error) {\n // Anything that throws while loading the entry point: a syntax error, a missing require, a module that\n // runs something at import time. The reason is the only clue the author gets about why their service\n // is not in the deploy, so it travels rather than being swallowed.\n skipped.push({ serviceId, reason: (error as Error).message })\n }\n }\n\n return { services, skipped }\n}\n", "import BLRequest from 'backendless-request'\n\nimport type { FlowrunnerRuntime } from './global'\nimport { createExtension } from './v2/create-extension'\nimport { crypto } from './v2/crypto'\nimport { z } from './v2/params'\nimport { getExtension } from './v2/registry'\n\n// Installs the single global `Flowrunner` namespace shared by v1 and v2. Importing this module for its\n// side effect guarantees the global exists before any service module is required. The v1 registration\n// seam (`ServerCode`) starts null and is toggled per-require by v1/namespace.ts.\n\nconst flowrunnerRuntime: FlowrunnerRuntime = {\n Request: BLRequest,\n z,\n crypto,\n createExtension,\n getExtension,\n ServerCode: null,\n}\n\nglobal.Flowrunner = flowrunnerRuntime\n\nexport { flowrunnerRuntime }\n", "import type { FlowExtensionErrorCode } from './codes'\n\n// Base class for all flow-extension runtime errors. Mirrors the console's `ApiError` shape (statusCode +\n// type/code + message + details) so the server can map it straight onto an HTTP response, while staying\n// self-contained (the runner never imports the console workspace).\n\nexport interface FlowExtensionErrorJSON {\n name: string\n code: FlowExtensionErrorCode\n statusCode: number\n message: string\n details?: unknown\n}\n\nexport class FlowExtensionError<DetailsT = unknown> extends Error {\n // Discriminant that survives structured-clone / JSON across the worker boundary, where `instanceof` fails.\n readonly isFlowExtensionError = true\n\n constructor(\n public readonly code: FlowExtensionErrorCode,\n public readonly statusCode: number,\n message: string,\n public readonly details?: DetailsT\n ) {\n super(message)\n this.name = this.constructor.name\n\n // Maintains a proper stack trace for where the error was thrown (V8 only).\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n\n toJSON(): FlowExtensionErrorJSON {\n return {\n name: this.name,\n code: this.code,\n statusCode: this.statusCode,\n message: this.message,\n details: this.details,\n }\n }\n}\n\n// True for a FlowExtensionError instance, or a plain object carrying the discriminant (e.g. after the error\n// crossed the worker IPC boundary and lost its prototype).\nexport function isFlowExtensionError(value: unknown): value is FlowExtensionError {\n if (value instanceof FlowExtensionError) {\n return true\n }\n\n return typeof value === 'object' &&\n value !== null &&\n (value as { isFlowExtensionError?: unknown }).isFlowExtensionError === true\n}\n", "// Stable, machine-readable codes for flow-extension runtime errors. These survive the worker \u2192 server IPC\n// boundary (as the error `code`), so the console and client can resolve/branch on the error type rather\n// than string-matching messages. Do not renumber/rename existing codes \u2014 they are part of the contract.\nexport const FlowExtensionErrorCodes = {\n // A method name that isn't a registered action/dictionary/trigger/SYSTEM method.\n UNKNOWN_METHOD: 'FR_EXT_UNKNOWN_METHOD',\n // A required named param (invocation / callbackObject / refreshToken) was absent from the method input.\n MISSING_METHOD_PARAM: 'FR_EXT_MISSING_METHOD_PARAM',\n // The method input failed its schema (action params, helper payload, SYSTEM invocation).\n INVALID_METHOD_INPUT: 'FR_EXT_INVALID_METHOD_INPUT',\n // A dictionary/loader `criteria` failed the declared criteria schema \u2014 reported apart from the payload so\n // the UI can point at the dependent fields instead of the whole call.\n INVALID_CRITERIA: 'FR_EXT_INVALID_CRITERIA',\n // Two registered items (action/dictionary/trigger) share an id.\n DUPLICATE_ITEM_ID: 'FR_EXT_DUPLICATE_ITEM_ID',\n // No v2 extension registered for the given serviceId after requiring the module.\n EXTENSION_NOT_REGISTERED: 'FR_EXT_NOT_REGISTERED',\n // A declared config value is missing or the wrong shape (see v2/schema/normalize).\n INVALID_CONFIG: 'FR_EXT_INVALID_CONFIG',\n // A schema slot that must be a z.object was declared as something else (see v2/schema/assert-object-schema).\n INVALID_SCHEMA: 'FR_EXT_INVALID_SCHEMA',\n // A polling trigger declared zero or multiple mechanisms, or is missing its fetch.\n INVALID_TRIGGER_CONFIG: 'FR_EXT_INVALID_TRIGGER_CONFIG',\n // A trigger dispatch referenced an unregistered trigger id.\n UNKNOWN_TRIGGER: 'FR_EXT_UNKNOWN_TRIGGER',\n // setupRealtimeTriggers is misconfigured (missing subscribe/unsubscribe, or declared twice).\n REALTIME_SETUP: 'FR_EXT_REALTIME_SETUP',\n // Inbound webhook failed signature verification.\n // setupOauth2 is misconfigured (e.g. declared twice).\n OAUTH_SETUP: 'FR_EXT_OAUTH_SETUP',\n // A handler accessed an opt-in feature (oauth/files) that the extension didn't enable.\n FEATURE_NOT_ENABLED: 'FR_EXT_FEATURE_NOT_ENABLED',\n // ...\n INVALID_DICTIONARY_OUTPUT_SCHEME: 'INVALID_DICTIONARY_OUTPUT_SCHEME',\n} as const\n\nexport type FlowExtensionErrorCode = (typeof FlowExtensionErrorCodes)[keyof typeof FlowExtensionErrorCodes]\n", "import { FlowExtensionError } from './base'\nimport { FlowExtensionErrorCodes } from './codes'\n\n// Concrete flow-extension errors. Messages are kept stable (callers/tests rely on them); the `code` is the\n// machine-resolvable identity.\n\nexport class UnknownMethodError extends FlowExtensionError {\n constructor(serviceId: string, methodName: string) {\n super(\n FlowExtensionErrorCodes.UNKNOWN_METHOD,\n 404,\n `[flow-extension:${ serviceId }] unknown method \"${ methodName }\"`,\n { serviceId, methodName }\n )\n }\n}\n\nexport class MissingMethodParamError extends FlowExtensionError {\n constructor(serviceId: string, param: string) {\n super(\n FlowExtensionErrorCodes.MISSING_METHOD_PARAM,\n 400,\n `[flow-extension:${ serviceId }] missing required \"${ param }\" in method input`,\n { serviceId, param }\n )\n }\n}\n\n// A single schema violation, flattened out of zod so the details survive the worker IPC boundary.\nexport interface ValidationIssue {\n // Dot/bracket path inside the validated value ('' when the value itself is invalid).\n path: string\n message: string\n code?: string\n}\n\nfunction formatIssues(issues: ValidationIssue[]): string {\n return issues.map(issue => (issue.path ? `${ issue.path }: ${ issue.message }` : issue.message)).join('; ')\n}\n\n// A method was called with input that doesn't match its schema \u2014 action params, a helper `payload`, or a\n// SYSTEM method's invocation. `target` names the validated slot so the caller can point at it.\nexport class InvalidMethodInputError extends FlowExtensionError {\n constructor(serviceId: string, methodName: string, target: string, issues: ValidationIssue[]) {\n super(\n FlowExtensionErrorCodes.INVALID_METHOD_INPUT,\n 400,\n `[flow-extension:${ serviceId }] invalid ${ target } for method \"${ methodName }\" \u2014 ${ formatIssues(issues) }`,\n { serviceId, methodName, target, issues }\n )\n }\n}\n\n// The `criteria` of a dictionary/loader call failed its declared schema. Separate from the payload error so\n// the console can surface \"these dependent fields are wrong\" rather than \"the whole call is malformed\".\nexport class InvalidCriteriaError extends FlowExtensionError {\n constructor(serviceId: string, methodName: string, issues: ValidationIssue[]) {\n super(\n FlowExtensionErrorCodes.INVALID_CRITERIA,\n 400,\n `[flow-extension:${ serviceId }] invalid criteria for method \"${ methodName }\" \u2014 ${ formatIssues(issues) }`,\n { serviceId, methodName, target: 'criteria', issues }\n )\n }\n}\n\nexport class DuplicateItemIdError extends FlowExtensionError {\n constructor(serviceId: string, id: string, kind: string) {\n super(\n FlowExtensionErrorCodes.DUPLICATE_ITEM_ID,\n 400,\n `[flow-extension:${ serviceId }] duplicate id \"${ id }\" (${ kind }) \u2014 ids must be unique across all registered items`,\n { serviceId, id, kind }\n )\n }\n}\n\nexport class ExtensionNotRegisteredError extends FlowExtensionError {\n constructor(serviceId: string, entryPoint?: string) {\n super(\n FlowExtensionErrorCodes.EXTENSION_NOT_REGISTERED,\n 404,\n `[flow-extension] no v2 extension registered for serviceId=\"${ serviceId }\"${ entryPoint ? ` (${ entryPoint })` : '' }`,\n { serviceId, entryPoint }\n )\n }\n}\n\nexport class InvalidConfigError extends FlowExtensionError {\n // Raised when the resolved `configItems` do not satisfy what the service declared. Carries one issue per\n // offending field, so the console can point at the config form rather than reporting the whole call.\n constructor(serviceId: string, issues: ValidationIssue[]) {\n super(\n FlowExtensionErrorCodes.INVALID_CONFIG,\n 400,\n `[flow-extension:${ serviceId }] invalid config \u2014 ${ formatIssues(issues) }`,\n { serviceId, issues }\n )\n }\n}\n\nexport class InvalidSchemaError extends FlowExtensionError {\n // `message` is composed by the guard, which knows how to describe what was received and what to do\n // about it (see v2/schema/assert-object-schema.ts).\n constructor(message: string, details: Record<string, unknown>) {\n super(FlowExtensionErrorCodes.INVALID_SCHEMA, 400, message, details)\n }\n}\n\nexport class InvalidTriggerConfigError extends FlowExtensionError {\n // `message` carries the specifics (kept verbatim for existing tests).\n constructor(serviceId: string, message: string, details?: Record<string, unknown>) {\n super(FlowExtensionErrorCodes.INVALID_TRIGGER_CONFIG, 400, `[flow-extension:${ serviceId }] ${ message }`, { serviceId, ...details })\n }\n}\n\nexport class UnknownTriggerError extends FlowExtensionError {\n constructor(serviceId: string, triggerId: string, kind = 'polling') {\n super(\n FlowExtensionErrorCodes.UNKNOWN_TRIGGER,\n 404,\n `[flow-extension:${ serviceId }] no ${ kind } trigger \"${ triggerId }\"`,\n { serviceId, triggerId, kind }\n )\n }\n}\n\nexport class RealtimeSetupError extends FlowExtensionError {\n constructor(serviceId: string, message: string) {\n super(FlowExtensionErrorCodes.REALTIME_SETUP, 400, `[flow-extension:${ serviceId }] ${ message }`, { serviceId })\n }\n}\n\nexport class OAuthSetupError extends FlowExtensionError {\n constructor(serviceId: string, message: string) {\n super(FlowExtensionErrorCodes.OAUTH_SETUP, 400, `[flow-extension:${ serviceId }] ${ message }`, { serviceId })\n }\n}\n\nexport class FeatureNotEnabledError extends FlowExtensionError {\n constructor(feature: string, hint: string) {\n super(\n FlowExtensionErrorCodes.FEATURE_NOT_ENABLED,\n 400,\n `[flow-extension] \"${ feature }\" is not enabled for this extension \u2014 ${ hint }`,\n { feature }\n )\n }\n}\n\nexport class InvalidDictionaryOutputScheme extends FlowExtensionError {\n constructor(serviceId: string, dictionaryName: string) {\n super(\n FlowExtensionErrorCodes.INVALID_DICTIONARY_OUTPUT_SCHEME,\n 400,\n `[flow-extension:${ serviceId }] dictionary \"${ dictionaryName }\" execution returns wrong result, it must result list of object {value, label, hist} or object {cursor:'string', items:[...]}`,\n { serviceId, dictionaryName }\n )\n }\n}\n", "import type { MethodParams } from '../params'\nimport type { ResultSpec } from '../result'\nimport type { AnySchema, HandlerBag } from '../types'\n\n// What a generated loader needs from the item it belongs to. Actions, polling triggers and realtime\n// triggers can all declare a loader `result`, so this is the narrow contract between them and ../loaders \u2014\n// it keeps a loader from having to know which of the three registered it.\n//\n// All three method classes implement it directly \u2014 a loader is handed its owner, not a description of one.\n\n// The generated loader method names. Frozen \u2014 these are published method names, derived from the owner's id.\nexport const sampleResultLoaderName = (ownerId: string): string => `${ ownerId }_SampleResultLoader`\nexport const dynamicParamsLoaderName = (ownerId: string): string => `${ ownerId }_DynamicParams`\n\nexport interface LoaderOwner {\n readonly id: string\n // The owner's grouping label; its loaders inherit it so they sort alongside it.\n readonly category: string\n readonly params: MethodParams\n readonly result: ResultSpec\n}\n\n// Only actions declare `dynamicParams`.\nexport interface DynamicParamsOwner extends LoaderOwner {\n readonly dynamicParamsCriteria: MethodParams\n resolveDynamicParams(bag: HandlerBag & { criteria: Record<string, unknown> }): AnySchema | Promise<AnySchema>\n}\n", "import { InvalidSchemaError } from '../../../errors'\nimport type { SchemaSource } from '../types'\nimport type { AnyZod } from './introspect'\n\n// Every schema slot is OPTIONAL. Declare it and it must be a `z.object` \u2014 because that is the only thing the\n// runner can do anything with: a container of named fields to validate input against and publish as the\n// method's input model.\n//\n// Without this guard a wrong shape degrades SILENTLY. `params: z.string()` has no `.shape`, so the method\n// publishes no params, the console renders a node with no inputs, validation becomes a passthrough, and the\n// service deploys clean \u2014 the author finds out when the action cannot be called correctly in production.\n//\n// So the check runs at REGISTRATION time, while the service module is being `require`d. That means it fires\n// on the first call the CLI or console makes against the extension, including the `buildServiceDefinition`\n// that `flowrunner deploy` performs per service \u2014 so a bad schema stops the deploy instead of shipping.\n\n// Zod's single-child wrappers. An object inside one of these cannot serve as a container: the wrapper has no\n// `.shape` and no `.partial()`, so every field would be invisible.\nconst WRAPPERS = new Set(['optional', 'nullable', 'nullish', 'default', 'prefault'])\n\nconst typeOf = (value: unknown): string | undefined =>\n (value as AnyZod | undefined)?._zod?.def?.type as string | undefined\n\n// How to name what the author actually passed, in their own vocabulary.\nfunction describe(value: unknown): string {\n const type = typeOf(value)\n\n if (type) {\n if (WRAPPERS.has(type)) {\n const inner = typeOf((value as { _zod?: { def?: { innerType?: unknown } } })._zod?.def?.innerType)\n\n return `z.${ inner ?? 'unknown' }().${ type }()`\n }\n\n return `z.${ type }()`\n }\n\n if (value === null) {\n return 'null'\n }\n\n if (Array.isArray(value)) {\n return 'an array'\n }\n\n if (typeof value === 'object') {\n return 'a plain object'\n }\n\n return `a ${ typeof value }`\n}\n\n// The most useful next step for this particular mistake.\nfunction hint(value: unknown, slot: string, isReturn: boolean): string {\n const type = typeOf(value)\n\n if (type && WRAPPERS.has(type)) {\n return '; an object container cannot be optional \u2014 mark its fields optional instead'\n }\n\n if (!type && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n return ' \u2014 did you forget to wrap it in z.object({ \u2026 })?'\n }\n\n // Every slot may simply be left out, which is usually what an author reaching for a non-object wanted.\n return isReturn ? '' : `; omit \\`${ slot }\\` entirely if there is nothing to declare`\n}\n\n/**\n * Throws unless `scheme` is a `z.object` (including `z.looseObject` / `z.strictObject`). `undefined` passes \u2014\n * an undeclared slot is legal everywhere.\n */\nexport function assertObjectSchema(scheme: unknown, source: SchemaSource): void {\n if (scheme == null || typeOf(scheme) === 'object') {\n return\n }\n\n const slot = source.slot ?? 'schema'\n const kind = source.kind ?? 'extension'\n // A slot spelled with parentheses is a function whose RETURN is being checked.\n const isReturn = slot.endsWith('()')\n // The extension itself has no item id to name; everything else does.\n const subject = source.itemId ? `${ kind } \"${ source.itemId }\": ` : ''\n const received = describe(scheme)\n\n throw new InvalidSchemaError(\n `[flow-extension:${ source.serviceId }] ${ subject }\\`${ slot }\\` ${ isReturn ? 'must return' : 'must be' }` +\n ` a z.object({ \u2026 }) \u2014 received ${ received }${ hint(scheme, slot, isReturn) }`,\n { serviceId: source.serviceId, kind, itemId: source.itemId, slot, received }\n )\n}\n", "/**\n * Platform param GROUPS \u2014 a whole `z.object` the runtime ships (see ./files-options.ts), not a control.\n *\n * They travel in the same `uiComponent.type` slot as a control token, so they belong in the map below. They\n * are named apart from it because **nothing renders a single input for one**: a consumer reads the token to\n * decide how to draw the whole group, and a registry of one-input-per-token has no entry for it.\n *\n * An author's own `z.object` carries none of these.\n */\nexport const FlowExtensionParamGroupTypes = {\n FILE_UPLOAD_OPTIONS: 'FILE_UPLOAD_OPTIONS',\n FILE_LIST_OPTIONS : 'FILE_LIST_OPTIONS',\n FILE_GET_OPTIONS : 'FILE_GET_OPTIONS',\n FILE_DELETE_OPTIONS: 'FILE_DELETE_OPTIONS',\n}\n\nexport const FlowExtensionParamWidgetTypes = {\n // Derived from a zod declaration \u2014 see `deriveWidget`.\n SINGLE_LINE_TEXT: 'SINGLE_LINE_TEXT',\n MULTI_LINE_TEXT : 'MULTI_LINE_TEXT',\n NUMERIC_STEPPER : 'NUMERIC_STEPPER',\n DATE_PICKER : 'DATE_PICKER',\n TOGGLE : 'TOGGLE',\n DROPDOWN : 'DROPDOWN',\n\n ...FlowExtensionParamGroupTypes,\n\n // legacy \u2014 no zod declaration produces these. They reach the console only from a legacy JSDoc-format\n // service, which writes `uiComponent` by hand. Kept because the console still renders them for an\n // already-installed extension.\n NUMERIC : 'NUMERIC',\n CHECKBOX : 'CHECKBOX',\n DATE_TIME_PICKER: 'DATE_TIME_PICKER',\n TIME_PICKER : 'TIME_PICKER',\n}\n\n/**\n * The widget tokens a declaration carries EXPLICITLY, as author metadata (`meta.frWidget`) \u2014 everything else\n * in the map above is DERIVED from the zod type by `deriveWidget`.\n *\n * `MULTI_LINE_TEXT` is `z.text()` / `z.json()`; the `FILE_*_OPTIONS` tokens name a platform param group.\n */\nexport type FrWidgetToken =\n | 'MULTI_LINE_TEXT'\n | 'FILE_UPLOAD_OPTIONS'\n | 'FILE_LIST_OPTIONS'\n | 'FILE_GET_OPTIONS'\n | 'FILE_DELETE_OPTIONS'\n\n/** The subset that names a platform param GROUP rather than a single control. */\nexport type FrGroupToken = Exclude<FrWidgetToken, 'MULTI_LINE_TEXT'>\n", "// Introspection over the extended zod schemas: walk a declared object's fields, unwrap the modifiers that do\n// not change what a field IS, collect merged author meta (outer wins), and derive the param type +\n// `uiComponent` widget. Everything here reads a schema and returns plain data \u2014 it is the layer both the\n// runner's model builder and the console's renderer sit on top of.\n//\n// This module DESCRIBES a schema; it never decides whether the schema is allowed. A declaration the runtime\n// cannot render is refused at registration by ./assert-supported-schema.ts, which reads `resolvedType` from\n// here. Keeping the two apart is what lets the runtime's own SYSTEM schemes \u2014 which model a wire contract\n// rather than a rendered form \u2014 be described by the same code that refuses an author writing the same thing\n// in a parameter.\nimport { FlowExtensionParamWidgetTypes } from '../widget-types'\nimport type { FrMeta } from '../zod'\n\nexport interface Inspected {\n // The unwrapped core schema (past the modifiers below).\n core: AnyZod\n // Core zod def type: 'string' | 'number' | 'boolean' | 'enum' | 'date' | 'object' | 'array' | \u2026\n // Defaulted to 'string' when the schema reports none, so every consumer has something to switch on.\n coreType: string\n // The SAME answer, undefined rather than defaulted. What the registration guard has to read: in `coreType`\n // \"declared nothing\" and \"declared a string\" are the same value, and a policy decision cannot conflate them.\n resolvedType?: string\n /**\n * A `z.union()`'s declared branches, outermost union only \u2014 `undefined` for everything else.\n *\n * `core` and `coreType` above have already been resolved to the FIRST branch, which is what publishes and\n * what picks the widget. That answer is right for every consumer that only needs a type, and wrong for the\n * two that must consider all of them: the registration guard has to refuse a union with an unsupported\n * branch, and coercion has to try each branch in turn. They read this.\n */\n branches?: AnyZod[]\n required: boolean\n defaultValue: unknown\n meta: FrMeta\n}\n\n// Structural zod shape \u2014 we read internals (`_zod.def`) rather than depend on zod's public generics.\nexport type AnyZod = {\n _zod?: { def?: Record<string, unknown> }\n meta?: () => Record<string, unknown> | undefined\n shape?: Record<string, AnyZod>\n options?: unknown[]\n}\n\nconst OPTIONAL_WRAPPERS = new Set(['optional', 'nullable', 'nullish'])\nexport const DEFAULT_WRAPPERS = new Set(['default', 'prefault'])\n\n/**\n * Modifiers that constrain or re-shape a value without changing what the AUTHOR declared it to be. The\n * runtime looks straight through them: they decide nothing about the widget, the published type, or which\n * coercion runs.\n *\n * - `readonly` \u2014 freezes zod's output; the declared type is the inner one.\n * - `pipe` \u2014 `.pipe(b)` and `.transform(fn)` both produce this. We follow `def.in`, the INPUT side, because\n * the published model describes **what a caller supplies**: it is what the console renders a form for, what\n * the AI-tool schema advertises, and what the coercion layer must convert to before zod sees the value.\n * What `execute` ends up receiving is the pipe's own business and is not a published fact.\n * - `lazy` \u2014 a thunk, for a recursive declaration.\n *\n * `.catch()` is deliberately NOT here. It is refused at registration instead (see\n * ./assert-supported-schema.ts): unwrapping it would fix the published type while leaving the declaration\n * silently substituting a fallback for invalid input, which is the more serious half of that defect.\n */\nexport const TRANSPARENT_WRAPPERS = new Set(['readonly', 'pipe', 'lazy'])\n\n// Where the schema inside a wrapper lives \u2014 it is not always `innerType`.\nexport function innerOf(def: Record<string, unknown>, type: string): AnyZod | undefined {\n if (type === 'pipe') {\n return def.in as AnyZod | undefined\n }\n\n if (type === 'lazy') {\n return (def.getter as (() => AnyZod) | undefined)?.()\n }\n\n return def.innerType as AnyZod | undefined\n}\n\n// A self-referential `z.lazy()` would peel forever. Nothing legitimate nests modifiers anywhere near this deep.\n// Shared with ../json/encode.ts, whose own wrapper walk has to stop on the same declarations this one does.\nexport const MAX_UNWRAP_DEPTH = 64\n\nexport function inspect(schema: AnyZod): Inspected {\n let current: AnyZod | undefined = schema\n // An `.optional()` / `.default()` seen OUTSIDE any `.nonoptional()`. The chain is walked outer\u2192inner and\n // the outermost modifier is the author's final word, so `.optional().nonoptional()` is required while\n // `.nonoptional().optional()` is not \u2014 `sealed` is what stops an inner one from speaking for an outer one.\n // Mirrors `declaredAbsence` in ./field-plan.ts, which has to reach the same answer.\n let optional = false\n let sealed = false\n let defaultValue: unknown\n let branches: AnyZod[] | undefined\n let depth = 0\n const metas: Record<string, unknown>[] = []\n\n while (current?._zod && depth++ < MAX_UNWRAP_DEPTH) {\n const meta = typeof current.meta === 'function' ? current.meta() : undefined\n\n if (meta) {\n metas.push(meta)\n }\n\n const def = current._zod.def || {}\n const type = def.type as string\n\n if (OPTIONAL_WRAPPERS.has(type)) {\n optional ||= !sealed\n current = def.innerType as AnyZod\n continue\n }\n\n if (DEFAULT_WRAPPERS.has(type)) {\n optional ||= !sealed\n\n if (defaultValue === undefined) {\n defaultValue = def.defaultValue\n }\n\n current = def.innerType as AnyZod\n continue\n }\n\n if (type === 'nonoptional') {\n sealed = true\n current = def.innerType as AnyZod\n continue\n }\n\n /**\n * A union resolves to its FIRST branch, and the branch list is carried on the result.\n *\n * \u26A0\uFE0F Declaration order is therefore published contract: `z.union([A, B])` and `z.union([B, A])` validate\n * identically and publish differently, and nothing in the source says so. It is documented in\n * service-code-format/02-zod-types.md; do not reorder a union's branches for readability.\n *\n * Only the OUTERMOST union is recorded \u2014 a nested one is resolved again when its own branch is walked.\n */\n if (type === 'union') {\n const options = def.options as AnyZod[] | undefined\n\n // A union with nothing in it resolves to nothing; leave it as the core so the guard reports it.\n if (!options?.length) {\n break\n }\n\n branches ??= options\n current = options[0]\n continue\n }\n\n if (TRANSPARENT_WRAPPERS.has(type)) {\n const inner = innerOf(def, type)\n\n // A wrapper we cannot see inside is the core as far as anything here is concerned; the guard reports it.\n if (!inner) {\n break\n }\n\n current = inner\n continue\n }\n\n break\n }\n\n // metas are collected outer\u2192inner; reverse so outer is applied last (wins) in the merge.\n const meta = Object.assign({}, ...metas.reverse()) as FrMeta\n const core = current as AnyZod\n const resolvedType = core?._zod?.def?.type as string | undefined\n\n return {\n core,\n coreType: resolvedType || 'string',\n resolvedType,\n required: !optional,\n defaultValue,\n meta,\n ...(branches ? { branches } : {}),\n }\n}\n\nexport interface WidgetInfo {\n paramType: string\n uiComponent?: Record<string, unknown>\n items?: { type: string }\n}\n\n/**\n * The runtime type of a `z.literal(\u2026)`, when every declared value agrees on one \u2014 `undefined` for a mixed\n * literal, which has neither a single widget nor a single conversion.\n *\n * Read by BOTH ends: `deriveWidget` publishes the type, ../schema/coerce.ts converts to it. They have to be\n * the same answer \u2014 a toggle the console draws for a field the runtime will not accept `'true'` for is the\n * defect this module exists to prevent \u2014 which is why the two read one function rather than each deciding.\n * `undefined` is what keeps a mixed literal out of coercion: stringifying the `1` in `z.literal(['a', 1])`\n * would turn a value the declaration accepts into one it rejects.\n */\n// `typeof` answers 'object' for null and 'function' for a function \u2014 neither is a widget, and `z.literal(null)`\n// drew an empty nested form before this was excluded. Only the scalar kinds name a real type.\nconst LITERAL_KINDS = new Set(['string', 'number', 'boolean', 'bigint'])\n\nexport function literalType(core: AnyZod): string | undefined {\n const values = (core._zod?.def?.values as unknown[] | undefined) ?? []\n const kinds = new Set(values.map(value => typeof value))\n const [kind] = [...kinds]\n\n return kinds.size === 1 && LITERAL_KINDS.has(kind) ? kind : undefined\n}\n\n// Derive the v1 param `type` + `uiComponent` from a core zod type (widget is derived from the type \u2014 there\n// is no `.uiComponent()` in v2). Tokens match the v1 conventions (MULTI_LINE_TEXT/NUMERIC_STEPPER/TOGGLE/\u2026).\n//\n// TOTAL by design: this is a projection, not a policy. It has to answer for the runtime's own SYSTEM schemes\n// too (see ../../model/params-model.ts `toOpaqueBodyParams`), which carry `z.unknown()` and loose records no\n// author would be allowed to declare in a parameter. What an AUTHOR may write is decided once, at\n// registration, by ./assert-supported-schema.ts.\nexport function deriveWidget(ins: Inspected): WidgetInfo {\n const { coreType, core, meta } = ins\n\n // `z.json()` \u2014 arbitrary JSON, typed into a textarea. Checked BEFORE the type switch because the\n // declaration underneath is `z.unknown()`: it has to accept the PARSED value once ./coerce.ts has run, so\n // the type says nothing about what the caller supplies. The meta does, and what the caller supplies is text.\n if (meta.frJson) {\n return { paramType: 'STRING', uiComponent: { type: FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT } }\n }\n\n switch (coreType) {\n case 'string':\n if (meta.frWidget === FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT) {\n return { paramType: 'STRING', uiComponent: { type: FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT } }\n }\n\n return { paramType: 'STRING' }\n\n case 'number':\n case 'bigint':\n return { paramType: 'NUMBER', uiComponent: { type: FlowExtensionParamWidgetTypes.NUMERIC_STEPPER } }\n\n case 'boolean':\n return { paramType: 'BOOLEAN', uiComponent: { type: FlowExtensionParamWidgetTypes.TOGGLE } }\n\n case 'date':\n return { paramType: 'STRING', uiComponent: { type: FlowExtensionParamWidgetTypes.DATE_PICKER } }\n\n case 'enum': {\n // `.map({ Label: value })` shows labels; otherwise the enum options are the values.\n // The options are always the declared VALUES \u2014 that is what a flow element stores. `.labels()` adds a\n // display name per value, published as `{ value, label }` pairs the console renders directly.\n const declared = ((core.options ?? Object.values((core._zod?.def?.entries as Record<string, unknown>) ?? {})) as unknown[])\n .map(String)\n const labels = meta.frLabels\n const values: unknown[] = labels\n ? declared.map(value => ({ value, label: labels[value] ?? value }))\n : declared\n\n return { paramType: 'STRING', uiComponent: { type: 'DROPDOWN', options: { values } } }\n }\n\n // A literal is a one-value type, so it renders as whatever that value IS rather than always as text.\n // A mixed one has no such type and falls back to text.\n case 'literal':\n return deriveWidget({ ...ins, coreType: literalType(core) ?? 'string' })\n\n // A platform param GROUP names itself: the runtime's own file-options objects (../files-options.ts) carry\n // a token so a consumer can render the group as the thing it is instead of as an anonymous nested form.\n // An author's own `z.object` carries no marker and publishes exactly as it always has.\n case 'object':\n return meta.frWidget\n ? { paramType: 'OBJECT', uiComponent: { type: meta.frWidget } }\n : { paramType: 'OBJECT' }\n\n // A record is an OBJECT whose KEYS are open. The coercion layer has always walked it as one (see\n // ./coerce.ts); publishing it as one is the model catching up with the runtime.\n case 'record':\n return { paramType: 'OBJECT' }\n\n case 'array': {\n const element = core._zod?.def?.element as AnyZod | undefined\n const elementType = element ? deriveWidget(inspect(element)).paramType : 'STRING'\n\n return { paramType: 'LIST', items: { type: elementType } }\n }\n\n // `z.any()` / `z.unknown()` declare nothing to render or to convert \u2014 the pipeline passes them through\n // untouched, and the model has no better word for \"anything\" than the permissive one.\n case 'any':\n case 'unknown':\n return { paramType: 'STRING' }\n\n // Reached only by a runtime-owned scheme; an author's is refused at registration. Text is the permissive\n // answer for a SYSTEM param the console never draws.\n default:\n return { paramType: 'STRING' }\n }\n}\n\n// The declared fields of a z.object, in declaration order. Tolerates a missing/!object schema by returning\n// nothing \u2014 an undeclared slot is treated as \"no fields\" (see ../params.ts).\nexport function shapeEntries(schema: AnyZod | undefined): [name: string, schema: AnyZod][] {\n const shape = schema?.shape\n\n return shape && typeof shape === 'object' ? Object.entries(shape) : []\n}\n\n// The display labels a field declared with `.labels({ value: 'Label' })`, if any. Display only \u2014 nothing is\n// translated at runtime, because the value the element stored is already the value the handler wants.\nexport function fieldLabels(schema: AnyZod): Record<string, string> | undefined {\n return inspect(schema).meta.frLabels\n}\n", "import { InvalidSchemaError } from '../../../errors'\nimport type { SchemaSource } from '../types'\nimport { type AnyZod, inspect, shapeEntries } from './introspect'\n\n// The declared type surface, enforced. Sibling of ./assert-object-schema.ts \u2014 that one checks the CONTAINER\n// is a z.object, this one checks what is declared INSIDE it, at every depth.\n//\n// Why it exists: the runtime reads a zod declaration to decide the published type, the widget the console\n// draws, and which coercion runs before `execute`. Everything it cannot classify used to fall through to\n// `STRING`. That fallback is worse than it looks, because it fails in two places at once \u2014 the parameter is\n// published as text (a list stops being a list, a toggle becomes a text box) AND it drops out of the\n// coercion layer, so the string values a flow supplies are never converted. A `z.boolean().catch(false)`\n// bound to a template therefore hands `execute` `false` for an explicit `'true'`: exactly the legacy boolean\n// defect that v2's coercion layer exists to close.\n//\n// So an unrecognised declaration must be an ERROR, not a guess. The supported set below is closed and\n// documented (service-code-format/02-zod-types.md); a zod release that adds a modifier cannot silently\n// degrade a parameter, because the new name simply is not in it.\n//\n// Runs at REGISTRATION, while the service module is being required \u2014 the same moment, and for the same\n// reason, as the object-container check: it fires on the first call the CLI or console makes against the\n// extension, including the `buildServiceDefinition` behind `flowrunner deploy`, so a bad declaration stops\n// the deploy instead of shipping.\n\n/**\n * Slots held to the documented surface \u2014 everything an AUTHOR writes.\n *\n * The runtime's own SYSTEM schemes (`kind: 'system method'`) are deliberately exempt: they model the wire\n * contract of a platform call rather than a rendered form, and legitimately carry `z.unknown()` bodies and\n * loose records. So is the anonymous slot used for per-invocation payload parsing, which re-wraps a schema\n * that was already checked where it was declared.\n */\nconst GUARDED_KINDS = new Set(['action', 'dictionary', 'polling trigger', 'realtime trigger', 'extension'])\n\n/**\n * The core types the runtime can publish, render and coerce.\n *\n * `any` / `unknown` are in deliberately: they declare nothing, the pipeline passes them through untouched,\n * and that is a coherent thing for an author to want. Everything absent is absent on purpose \u2014 `tuple` and\n * `intersection` have no single widget, and a `catch` is refused with its own message below.\n *\n * `union` is not listed because it never reaches this check as itself: `inspect()` resolves it to its first\n * branch, so `resolvedType` is that branch's type. Its branches are each held to this same set \u2014 see\n * `assertField` \u2014 so a union containing a `z.tuple()` is still refused.\n */\nconst SUPPORTED_TYPES = new Set([\n 'string', 'number', 'bigint', 'boolean', 'date', 'enum', 'literal',\n 'object', 'array', 'record',\n // `z.union([T, z.null()])` is the union-shaped spelling of `.nullable()`, which is supported \u2014 refusing one\n // and not the other is a distinction without a difference. It is also a branch of zod's own `z.json()`.\n 'null',\n 'any', 'unknown',\n])\n\n// Named in the \"supported\" half of an error message, in the spelling an author writes. Kept in step with\n// `SUPPORTED_TYPES` above and with the table in service-code-format/02-zod-types.md \u2014 an author who hits this\n// error reads the message, then the doc, and a type missing from either reads as one they may not use.\nconst SUPPORTED_SPELLING = 'z.string(), z.number(), z.bigint(), z.boolean(), z.date(), z.enum([\u2026]), ' +\n 'z.literal(\u2026), z.object({ \u2026 }), z.array(\u2026), z.record(\u2026), z.union([\u2026]), z.null(), z.any(), z.unknown()'\n\nconst MODIFIER_SPELLING = '.optional(), .nullable(), .nullish(), .default(v), .prefault(v), .readonly(), ' +\n '.nonoptional(), .pipe(\u2026)/.transform(\u2026) and z.lazy(\u2026)'\n\n// `action \"sendMessage\": `params.tags[]`` \u2014 enough for an author to find the declaration without a stack trace.\nfunction subjectOf(source: SchemaSource, path: string): string {\n const kind = source.kind ?? 'extension'\n const subject = source.itemId ? `${ kind } \"${ source.itemId }\": ` : ''\n\n return `${ subject }\\`${ path }\\``\n}\n\nfunction refuse(message: string, source: SchemaSource, path: string, received: string): never {\n throw new InvalidSchemaError(\n `[flow-extension:${ source.serviceId }] ${ message }`,\n { serviceId: source.serviceId, kind: source.kind ?? 'extension', itemId: source.itemId, slot: source.slot, path, received }\n )\n}\n\n/**\n * `.catch(v)` gets its own refusal, because the fix is not \"use a supported type\" \u2014 the author's intent is\n * fine and the spelling is one character away.\n *\n * It is refused rather than unwrapped on purpose. Unwrapping would restore the published type and the\n * coercion, but the declaration would still SWALLOW invalid input: zod replaces anything that fails with the\n * fallback, so a value the user actually supplied is silently discarded instead of being reported back. No\n * parameter should do that. `.default(v)` expresses the same intent honestly \u2014 it supplies the fallback when\n * the value is ABSENT, and still rejects one that is present and wrong.\n */\nfunction refuseCatch(source: SchemaSource, path: string): never {\n refuse(\n `${ subjectOf(source, path) } uses \\`.catch(\u2026)\\`, which a parameter may not: it replaces an invalid value` +\n ' with the fallback instead of reporting it, and drops the field out of type coercion.' +\n ' Use `.default(v)` \u2014 same fallback when the value is absent, and a supplied-but-invalid one still fails.',\n source, path, 'catch'\n )\n}\n\nfunction refuseType(source: SchemaSource, path: string, type: string | undefined): never {\n const received = type ? `z.${ type }()` : 'a value that is not a zod schema'\n\n refuse(\n `${ subjectOf(source, path) } declares ${ received }, which the runtime cannot publish as a parameter` +\n ' \u2014 it has no widget, no published type and no coercion for it.' +\n ` Supported: ${ SUPPORTED_SPELLING }; each may carry ${ MODIFIER_SPELLING }.`,\n source, path, type ?? 'unknown'\n )\n}\n\n// One declared field, then whatever it contains. `seen` stops a recursive `z.lazy()` from walking forever.\nfunction assertField(schema: AnyZod | undefined, source: SchemaSource, path: string, seen: Set<unknown>): void {\n if (!schema || seen.has(schema)) {\n return\n }\n\n seen.add(schema)\n\n const ins = inspect(schema)\n\n if (ins.resolvedType === 'catch') {\n refuseCatch(source, path)\n }\n\n if (!ins.resolvedType || !SUPPORTED_TYPES.has(ins.resolvedType)) {\n refuseType(source, path, ins.resolvedType)\n }\n\n // Every branch of a union is a declaration in its own right. The union itself already passed the check\n // above AS ITS FIRST BRANCH, which says nothing about the others.\n if (ins.branches) {\n // Numbered, because the reported path is otherwise the field \u2014 and \"declares z.tuple()\" against a field\n // the author wrote as a union names a type they cannot find in their own declaration.\n ins.branches.forEach((branch, index) => assertField(branch, source, `${ path }|branch ${ index + 1 }`, seen))\n }\n\n const def = ins.core._zod?.def ?? {}\n\n // A container's contents are declarations in their own right and are held to the same rule \u2014 the defect\n // this guards against is no less silent one level down.\n if (ins.resolvedType === 'array') {\n assertField(def.element as AnyZod | undefined, source, `${ path }[]`, seen)\n }\n\n if (ins.resolvedType === 'record') {\n assertField(def.valueType as AnyZod | undefined, source, `${ path }{}`, seen)\n }\n\n if (ins.resolvedType === 'object') {\n for (const [name, property] of shapeEntries(ins.core)) {\n assertField(property, source, `${ path }.${ name }`, seen)\n }\n }\n}\n\n/**\n * Throws unless every field `scheme` declares, at every depth, is something the runtime can publish, render\n * and coerce. `undefined` passes \u2014 an undeclared slot is legal everywhere.\n *\n * Only author-declared slots are checked (see `GUARDED_KINDS`).\n */\nexport function assertSupportedSchema(scheme: unknown, source: SchemaSource): void {\n if (scheme == null || !source.kind || !GUARDED_KINDS.has(source.kind)) {\n return\n }\n\n const slot = source.slot ?? 'schema'\n const seen = new Set<unknown>()\n\n for (const [name, field] of shapeEntries(scheme as AnyZod)) {\n assertField(field, source, `${ slot }.${ name }`, seen)\n }\n}\n", "import type { AnyZod, Inspected } from './introspect'\n\n// Everything date-shaped, in one place: what counts as a valid date input, and what each date declaration\n// hands the handler.\n//\n// The input space is whatever JSON can carry, because every path into the runner is an HTTP body \u2014 a real\n// `Date` instance is not reachable. That is why `z.date()`, which demands one, could never be satisfied and\n// had to be exempted from validation entirely. It is no longer exempt; instead the value is converted for\n// CHECKING and the declaration decides what comes out:\n//\n// z.date() the input, unchanged \u2014 converting would invent a time of day and a timezone\n// z.coerce.date() a real Date \u2014 zod's own opt-in, and the only honest way to ask for one\n// z.iso.datetime() an ISO datetime string\n// z.iso.date() an ISO date string\n// z.iso.time() an ISO time string\n// z.iso.duration() strict: a duration is not a point in time, so there is nothing to narrow or widen\n\n// A date-only string, and a datetime whose date half we can take without parsing.\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/\nconst HAS_TIME = /^(\\d{4}-\\d{2}-\\d{2})[T ](.+)$/\n// The trailing zone on an extracted time \u2014 `z.iso.time()` rejects it.\nconst ZONE = /(Z|[+-]\\d{2}:?\\d{2})$/\n\nconst isNumeric = (value: string): boolean => value.trim() !== '' && Number.isFinite(Number(value.trim()))\n\n/**\n * Any date input \u2192 a `Date`, or `undefined` when it is not a date at all.\n *\n * A finite number is EPOCH MILLIS, which is what the console's date control stores; a numeric string is that\n * same number through a stringly-typed transport. Everything else that is a string is handed to `Date`.\n *\n * `new Date('nope')` returns a `Date` whose value is `NaN` \u2014 and `z.date()` accepts it \u2014 so an invalid date\n * has to be rejected here explicitly, or garbage would reach a handler looking like a date.\n */\nexport function toDate(value: unknown): Date | undefined {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? undefined : value\n }\n\n if (typeof value === 'number') {\n return Number.isFinite(value) ? new Date(value) : undefined\n }\n\n if (typeof value !== 'string') {\n return undefined\n }\n\n const parsed = isNumeric(value) ? new Date(Number(value.trim())) : new Date(value)\n\n return Number.isNaN(parsed.getTime()) ? undefined : parsed\n}\n\n/**\n * A date input \u2192 the ISO shape the field declared.\n *\n * NARROWING IS LEXICAL. `'2024-06-01T23:00:00Z'` \u2192 `'2024-06-01'` takes the characters before the `T`;\n * parsing and reformatting would impose UTC, and in UTC+2 that instant is the 2nd, not the 1st. So a string\n * is sliced, never converted.\n *\n * Two conversions do assume UTC, and both are unavoidable:\n * \u2022 widening a date to a datetime invents a time of day (`'2024-06-01'` \u2192 `'2024-06-01T00:00:00Z'`)\n * \u2022 naming a date or a time from EPOCH MILLIS has to pick a wall clock \u2014 the same instant is 2024-06-01\n * in London and 2024-06-02 in Kiritimati\n *\n * `z.iso.datetime()` from millis is not in that class: the instant is preserved and UTC is merely which of\n * several equivalent spellings we emit.\n */\nexport function toIso(value: unknown, format: string): string | undefined {\n const text = typeof value === 'string' ? value.trim() : undefined\n // A string keeps its own wording wherever the shape can be reached by slicing it.\n const lexical = text && !isNumeric(text) ? sliceIso(text, format) : undefined\n\n if (lexical) {\n return lexical\n }\n\n const parsed = toDate(value)\n\n if (!parsed) {\n return undefined\n }\n\n const iso = parsed.toISOString()\n\n if (format === 'datetime') {\n return iso\n }\n\n if (format === 'date') {\n return iso.slice(0, 10)\n }\n\n if (format === 'time') {\n return iso.slice(11, 19)\n }\n\n return undefined\n}\n\n// The shape reachable from `text` without any timezone maths. `undefined` when slicing cannot get there.\nfunction sliceIso(text: string, format: string): string | undefined {\n const timed = HAS_TIME.exec(text)\n\n if (format === 'datetime') {\n // Already a datetime: keep the author's own spelling, offset and precision included.\n return timed ? text : undefined\n }\n\n if (format === 'date') {\n return timed ? timed[1] : DATE_ONLY.test(text) ? text : undefined\n }\n\n if (format === 'time') {\n const time = timed ? timed[2] : DATE_ONLY.test(text) ? undefined : text\n\n return time ? time.replace(ZONE, '') : undefined\n }\n\n return undefined\n}\n\n/** The zod format token a schema declared, if any: 'datetime' | 'date' | 'time' | 'duration' | \u2026 */\nexport const formatOf = (ins: Inspected): string | undefined =>\n (ins.core as { _zod?: { def?: { format?: string } } } | undefined)?._zod?.def?.format\n\n/** The ISO formats this module converts INTO. `duration` is absent on purpose \u2014 it stays strict. */\nexport const isConvertibleIso = (format?: string): boolean =>\n format === 'datetime' || format === 'date' || format === 'time'\n\n/**\n * True for `z.date()` and false for `z.coerce.date()`.\n *\n * `.coerce` is zod's own flag, set by `z.coerce.date()` and readable through the optional/nullable/default\n * wrappers \u2014 so the author's intent is a flag to look up rather than a heuristic to guess.\n */\nexport const passesDateThrough = (ins: Inspected): boolean =>\n ins.coreType === 'date' && !(ins.core as { _zod?: { def?: { coerce?: boolean } } })?._zod?.def?.coerce\n\n/** Whether a schema, at any depth, has a `z.date()` whose value must survive validation unchanged. */\nexport function hasPassThroughDate(schema: AnyZod | undefined, inspectSchema: (s: AnyZod) => Inspected,\n entriesOf: (s: AnyZod | undefined) => [string, AnyZod][]): boolean {\n if (!schema) {\n return false\n }\n\n const ins = inspectSchema(schema)\n\n if (passesDateThrough(ins)) {\n return true\n }\n\n const element = ins.core?._zod?.def?.element as AnyZod | undefined\n const valueType = ins.core?._zod?.def?.valueType as AnyZod | undefined\n const children = [\n ...entriesOf(ins.core).map(([, child]) => child),\n ...(element ? [element] : []),\n ...(valueType ? [valueType] : []),\n // Every branch of a union, not just the one it resolved to. `z.union([z.number(), z.date()])` coerces\n // through the date branch at runtime, so the restore walk has to know a date is reachable here \u2014 or the\n // handler receives the converted `Date` instead of the string the host sent.\n ...(ins.branches ?? []),\n ]\n\n return children.some(child => hasPassThroughDate(child, inspectSchema, entriesOf))\n}\n", "import { type AnyZod, inspect } from './introspect'\n\n// A field's display NAME. Unlike its description (./defaults.ts), this is never derived from the\n// declaration: the field key already carries intent a type or format cannot \u2014 `contactEmail` reads as\n// \"Contact Email\", where a per-format label would flatten it to \"Email\" \u2014 so a generic fallback word would\n// only ever be a downgrade.\n\n// Words a title-cased label should shout rather than capitalise. Without these, `baseUrl` reads as\n// \"Base Url\" \u2014 derived-looking in exactly the way that makes an author go and write the label by hand.\nconst ACRONYMS = new Set(['id', 'url', 'urls', 'api', 'uri', 'ip', 'ipv4', 'ipv6', 'uuid', 'guid', 'jwt',\n 'sms', 'html', 'css', 'json', 'xml', 'csv', 'pdf', 'sql', 'ttl', 'sku', 'utm', 'cc', 'bcc', 'crm', 'db'])\n\n// A field key as a human label: `contactEmail` \u2192 \"Contact Email\", `base_url` \u2192 \"Base URL\".\nexport function humanizeKey(name: string): string {\n return name\n // split camelCase and consecutive-capital runs (`baseURL` \u2192 `base URL`)\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .trim()\n .split(/\\s+/)\n .filter(Boolean)\n .map(word => ACRONYMS.has(word.toLowerCase())\n ? word.toUpperCase()\n : word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ')\n}\n\n// The label as the console should show it: the author's, else the field key made human.\nexport const labelOf = (name: string, schema: AnyZod): string =>\n inspect(schema).meta.title || humanizeKey(name) || name\n", "import { hasPassThroughDate, passesDateThrough } from './dates'\nimport { type AnyZod, DEFAULT_WRAPPERS, innerOf, inspect, shapeEntries, TRANSPARENT_WRAPPERS } from './introspect'\nimport { labelOf } from './labels'\n\n// What one declared field needs, worked out ONCE and reused for every invocation.\n//\n// The interesting part is `absence`. An author writes `.optional()` or `.nullable()` \u2014 whichever reads\n// naturally \u2014 and should not have to predict which absent form a client will send. So instead of reading the\n// wrapper chain, we ASK THE SCHEMA what it accepts: two `safeParse` probes settle it, and they are immune to\n// wrapper order (`.optional().nullable()` vs `.nullable().optional()`), to `.refine()` wrapping the type, and\n// to any modifier zod adds later. Introspection would have to keep up with all three.\n\nexport type AbsencePolicy =\n // The schema tolerates both forms, so whichever arrived is passed through (`.nullish()`).\n | 'as-received'\n // Only `undefined` is accepted (`.optional()`, `.default(v)`), so any absence becomes that.\n | 'undefined'\n // Only `null` is accepted (`.nullable()`), so any absence becomes that.\n | 'null'\n // Neither \u2014 the field has nothing to fall back on.\n | 'required'\n\nexport interface FieldPlan {\n name: string\n schema: AnyZod\n // The author's display name, used in messages. Falls back to the key.\n label: string\n // Core zod type past the wrappers: 'string' | 'number' | 'boolean' | 'enum' | 'date' | \u2026\n // For a union this is the FIRST branch's type \u2014 see `isUnion`.\n coreType: string\n /**\n * True when the declaration is a `z.union()`.\n *\n * Carried because `coreType` alone stops describing the field: a union resolves to its first branch, so a\n * `z.union([z.email(), z.literal('')])` reports `'string'` and would then treat a blank as a VALUE. It is\n * not one \u2014 `''` has always been absence on a union, which is exactly what makes the documented\n * \"blank means not set\" spelling (`z.union([z.url(), z.literal('')]).optional()`) work.\n */\n isUnion: boolean\n absence: AbsencePolicy\n // True when a declared `.default(v)` will absorb an absent value \u2014 which is also what lets a blank string\n // fall back to the default rather than surviving as `''`.\n absorbsBlank: boolean\n /**\n * True for a `z.date()` whose value must reach the handler UNCHANGED \u2014 validated through a converted copy,\n * handed over as the host sent it. False for `z.coerce.date()`, which the author asked to convert.\n *\n * Set when the field ITSELF is such a date; `restoresDates` covers one nested anywhere inside it.\n */\n passThroughDate: boolean\n // Whether anything at any depth needs that treatment, so the restore walk can be skipped entirely.\n restoresDates: boolean\n}\n\n// Ask the schema which absent forms it accepts. A probe can only throw for an async refinement placed\n// outside the modifier, in which case treating the field as required is the safe reading.\n/**\n * The absent forms the author DECLARED, read off the wrapper chain.\n *\n * Used only where the probe below cannot be trusted \u2014 see `probeAbsence`. It has to agree with the probe on\n * every schema the probe handles, which is why it treats `.default()` as accepting `undefined`: zod applies\n * a default to `undefined`, so that is what the probe observes too.\n */\nfunction declaredAbsence(schema: AnyZod): { absence: AbsencePolicy; absorbsBlank: boolean } {\n let current: AnyZod | undefined = schema\n let acceptsUndefined = false\n let acceptsNull = false\n let absorbsBlank = false\n // `.nonoptional()` re-asserts a requirement over whatever it wraps \u2014 an `.optional()` further in does not\n // undo it, so nothing after it may set a flag. Mirrors the same rule in ./introspect.ts `inspect`.\n let sealed = false\n\n while (current?._zod) {\n const def = current._zod.def ?? {}\n const type = def.type as string\n\n if (type === 'nonoptional') {\n sealed = true\n } else if (TRANSPARENT_WRAPPERS.has(type)) {\n // Says nothing about absence \u2014 look straight through it, exactly as `inspect` does.\n current = innerOf(def, type)\n continue\n } else if (sealed) {\n break\n } else if (type === 'optional') {\n acceptsUndefined = true\n } else if (type === 'nullable') {\n acceptsNull = true\n } else if (type === 'nullish') {\n acceptsUndefined = true\n acceptsNull = true\n } else if (DEFAULT_WRAPPERS.has(type)) {\n acceptsUndefined = true\n absorbsBlank = true\n } else {\n break\n }\n\n current = def.innerType as AnyZod\n }\n\n const absence: AbsencePolicy = acceptsUndefined && acceptsNull ? 'as-received'\n : acceptsUndefined ? 'undefined'\n : acceptsNull ? 'null'\n : 'required'\n\n return { absence, absorbsBlank }\n}\n\n// `z.coerce.*` converts an ABSENT value into a junk one rather than rejecting it \u2014 `new Date(null)` is the\n// epoch, `Number('')` is 0, `String(undefined)` is the text `'undefined'`, `Boolean(null)` is false. So a\n// coercing schema answers \"yes\" to the probe below for a field the author declared REQUIRED, and a blank\n// silently becomes 1970-01-01 or 0 instead of being reported. Where coercion is what makes the answer yes,\n// the declaration is the authority instead.\nfunction coerces(schema: AnyZod): boolean {\n return inspect(schema).core?._zod?.def?.coerce === true\n}\n\n/**\n * `z.json()` \u2014 the same problem as `z.coerce.*` above, from the other direction.\n *\n * It declares `z.unknown()` underneath, because what reaches the handler is a parsed JSON value and `null`\n * is one of those. The probe then sees a schema that accepts `null` and reads it as \"null is how this field\n * spells absence\", so a bare `z.json()` published as OPTIONAL \u2014 a field the author never marked optional and\n * which the runtime does in fact reject when it is missing.\n *\n * The probe cannot tell a legal value from an absent form by asking, so the declaration is the authority\n * here too: `.nonoptional()` on the helper means required, and an author's own `.optional()` sits outside it\n * and still wins.\n */\nconst parsesJson = (schema: AnyZod): boolean => !!inspect(schema).meta.frJson\n\nfunction probeAbsence(schema: AnyZod): { absence: AbsencePolicy; absorbsBlank: boolean } {\n if (coerces(schema) || parsesJson(schema)) {\n return declaredAbsence(schema)\n }\n\n const parse = (value: unknown): { success: boolean; data?: unknown } => {\n try {\n return (schema as unknown as { safeParse: (v: unknown) => { success: boolean; data?: unknown } }).safeParse(value)\n } catch {\n return { success: false }\n }\n }\n\n const asUndefined = parse(undefined)\n const asNull = parse(null)\n\n // \"Accepts both\" must win over \"has a default\": for `z.string().nullable().default('x')` the author said\n // null is meaningful, and zod applies the default to `undefined` on its own.\n const absence: AbsencePolicy = asUndefined.success && asNull.success ? 'as-received'\n : asUndefined.success ? 'undefined'\n : asNull.success ? 'null'\n : 'required'\n\n // A default reveals itself by yielding something other than what was fed in. This is also why a falsy\n // default (`''`, `0`, `false`) is detected correctly, where a truthiness check would drop it.\n return { absence, absorbsBlank: asUndefined.success && asUndefined.data !== undefined }\n}\n\n// Probing costs two `safeParse` calls, and the deep walk asks the same element or property schema once per\n// item. Schemas are stable objects built at registration, so the answer is cached against the schema itself.\nconst probeCache = new WeakMap<object, { absence: AbsencePolicy; absorbsBlank: boolean }>()\n\n/** The absent forms a schema accepts, at any depth. Same question `planField` asks for a top-level field. */\nexport function absenceOf(schema: AnyZod | undefined): { absence: AbsencePolicy; absorbsBlank: boolean } {\n if (!schema || typeof schema !== 'object') {\n return { absence: 'as-received', absorbsBlank: false }\n }\n\n const cached = probeCache.get(schema as object)\n\n if (cached) {\n return cached\n }\n\n const probed = probeAbsence(schema)\n\n probeCache.set(schema as object, probed)\n\n return probed\n}\n\nexport function planField(name: string, schema: AnyZod): FieldPlan {\n const ins = inspect(schema)\n const { absence, absorbsBlank } = probeAbsence(schema)\n\n return {\n name,\n schema,\n label: labelOf(name, schema),\n coreType: ins.coreType,\n isUnion : !!ins.branches,\n absence,\n absorbsBlank,\n passThroughDate: passesDateThrough(ins),\n restoresDates : hasPassThroughDate(schema, inspect, shapeEntries),\n }\n}\n", "import { formatOf, isConvertibleIso, toDate, toIso } from './dates'\nimport { absenceOf } from './field-plan'\nimport { type AnyZod, inspect, type Inspected, literalType, shapeEntries } from './introspect'\n\n// Step 2 of the pipeline: turn a transport value into the declared type.\n//\n// Coercion exists because the transport is stringly-typed. `toConfigType` maps `z.number()` to a *string*\n// config item \u2014 the config form has no numeric widget \u2014 so a number is stored and sent as `'123'`.\n// Expression-bound params do the same. Without this, every numeric config item would fail its own schema.\n//\n// Coerce only where the intent is unambiguous; anything else is an error rather than a guess. Note that\n// `z.coerce.*` is unusable here: `z.coerce.number().parse('')` is `0` and `z.coerce.boolean().parse('false')`\n// is `true`. This runs AFTER absence normalization, so a blank never reaches it.\n\nexport interface Coerced {\n ok: boolean\n value?: unknown\n // The zod type token the value should have been; ../schema/messages turns it into wording.\n expected?: string\n}\n\nconst ok = (value: unknown): Coerced => ({ ok: true, value })\nconst fail = (expected: string): Coerced => ({ ok: false, expected })\n\n// Matched after trim + lowercase. The test for ADDING a token, so the set has a stopping rule rather than\n// growing by precedent: it must have an unambiguous opposite, and the pair must both be listed. A word with\n// no opposite is a STATUS, not a boolean, and belongs in a `z.enum([...])`.\n//\n// Widening is only safe BECAUSE an unrecognised value fails (see `toBooleanValue`). Making an unknown default\n// to `false` \u2014 the partial hand-rolled allow-list this replaces \u2014 silently turns an explicit off into an on.\n//\n// The list is published to authors, so a change here is a change in three more places: the exhaustive pass in\n// `__tests__/configs-service.test.ts`, the table in `service-code-format/02-zod-types.md` (shipped inside the\n// CLI package), and the prose in `docs/guides/flow-extensions-custom/parameters-and-types.md`.\nconst TRUE = new Set(['true', '1', 'yes', 'y', 't', 'on', 'checked', 'enabled', 'enable', 'active'])\nconst FALSE = new Set(['false', '0', 'no', 'n', 'f', 'off', 'unchecked', 'disabled', 'disable', 'inactive'])\n\nfunction toStringValue(value: unknown): Coerced {\n if (typeof value === 'string') {\n return ok(value)\n }\n\n // A number or a boolean in a text field has one obvious text form. A structure does not \u2014 `String({})` is\n // '[object Object]' and `String([1,2])` is '1,2', which are artefacts of JS rather than what was meant.\n if (typeof value === 'boolean') {\n return ok(String(value))\n }\n\n return typeof value === 'number' && Number.isFinite(value) ? ok(String(value)) : fail('string')\n}\n\nfunction toNumberValue(value: unknown): Coerced {\n if (typeof value === 'number') {\n return Number.isFinite(value) ? ok(value) : fail('number')\n }\n\n if (typeof value !== 'string') {\n return fail('number')\n }\n\n // `Number('')` is 0 and `Number(' ')` is 0, so require actual digits. A blank has already been treated as\n // absence by this point; anything else non-numeric is a caller error.\n const parsed = Number(value.trim())\n\n return value.trim() !== '' && Number.isFinite(parsed) ? ok(parsed) : fail('number')\n}\n\n// `z.bigint()` wants an actual BigInt, so `Number()` would never satisfy it \u2014 a whole number is the only\n// input that can be converted without losing information.\nfunction toBigIntValue(value: unknown): Coerced {\n if (typeof value === 'bigint') {\n return ok(value)\n }\n\n if (typeof value === 'number') {\n return Number.isInteger(value) ? ok(BigInt(value)) : fail('bigint')\n }\n\n if (typeof value !== 'string' || value.trim() === '') {\n return fail('bigint')\n }\n\n try {\n return ok(BigInt(value.trim()))\n } catch {\n return fail('bigint')\n }\n}\n\nfunction toBooleanValue(value: unknown): Coerced {\n if (typeof value === 'boolean') {\n return ok(value)\n }\n\n if (typeof value === 'number') {\n return value === 1 ? ok(true) : value === 0 ? ok(false) : fail('boolean')\n }\n\n if (typeof value !== 'string') {\n return fail('boolean')\n }\n\n const lowered = value.trim().toLowerCase()\n\n return TRUE.has(lowered) ? ok(true) : FALSE.has(lowered) ? ok(false) : fail('boolean')\n}\n\n/**\n * `z.json()` \u2014 the transport carries text, the handler gets the structure.\n *\n * Parsing belongs here rather than in a `.transform()` for the reason the whole module exists: a failure has\n * to arrive as the same `Coerced` miss every other wrong-typed value produces, so it is reported against the\n * field by its label (\u00ABPayload\u00BB must be valid JSON) instead of escaping as a raw `SyntaxError` that names\n * neither the extension, the method, nor the parameter.\n */\nfunction toJsonValue(value: unknown): Coerced {\n // Already a structure. A flow can bind the parameter to an expression that evaluates to one, so the value\n // does not always arrive as text \u2014 and `JSON.parse({})` would throw on exactly the payload this type\n // exists to carry. Nothing to convert means nothing to do.\n if (typeof value !== 'string') {\n return ok(value)\n }\n\n try {\n return ok(JSON.parse(value))\n } catch {\n return fail('json')\n }\n}\n\n/**\n * Coerce one SCALAR `value` for a field whose core zod type is `coreType`. Types with no meaningful coercion\n * \u2014 enum, and everything the runtime does not special-case \u2014 pass through for the author's schema to judge:\n * membership is zod's job, not ours.\n *\n * Dates need the SCHEMA rather than the type name, because `z.date()`, `z.coerce.date()` and `z.iso.date()`\n * convert differently \u2014 see `coerceLeaf`.\n */\nexport function coerceValue(value: unknown, coreType: string): Coerced {\n if (coreType === 'string') {\n return toStringValue(value)\n }\n\n if (coreType === 'number') {\n return toNumberValue(value)\n }\n\n if (coreType === 'bigint') {\n return toBigIntValue(value)\n }\n\n if (coreType === 'boolean') {\n return toBooleanValue(value)\n }\n\n if (coreType === 'date') {\n const parsed = toDate(value)\n\n return parsed ? ok(parsed) : fail('date')\n }\n\n // An enum's options may be numbers declared as strings, so stringify a number and let zod check membership.\n if (coreType === 'enum' && typeof value === 'number') {\n return ok(String(value))\n }\n\n return ok(value)\n}\n\n/** Whether a schema accepts a value outright. A probe, so a throwing refinement reads as \"no\". */\nexport function accepts(schema: AnyZod, value: unknown): boolean {\n try {\n return !!(schema as unknown as { safeParse?: (v: unknown) => { success: boolean } })\n .safeParse?.(value)?.success\n } catch {\n return false\n }\n}\n\n/**\n * A union, resolved by TRYING its branches in declaration order \u2014 the first that coerces to something its\n * own branch accepts wins.\n *\n * Trying rather than picking is what keeps D1/D7 closed inside a union: a flow template supplies every value\n * as a string, so `z.union([z.boolean(), z.string()])` given `'true'` has to convert through the boolean\n * branch and succeed there. Picking the first branch blindly would hand `execute` the string.\n *\n * \u26A0\uFE0F **A permissive branch shadows every branch after it.** `z.union([z.string(), z.boolean()])` given\n * `'true'` matches the string branch as-is, so the boolean branch is never reached and `execute` receives\n * `'true'`. That is the same positional rule as publishing (both read declaration order, left to right),\n * which is why it was chosen \u2014 one mental model covers both. It is documented, and pinned by a test.\n *\n * When NO branch accepts it, the value is handed back untouched so the author's own union error is what the\n * user sees. This step never invents an error.\n */\nfunction coerceUnion(value: unknown, branches: AnyZod[]): unknown {\n for (const branch of branches) {\n const coerced = coerceDeep(value, branch)\n\n if (accepts(branch, coerced)) {\n return coerced\n }\n }\n\n return value\n}\n\n// The container types that DECLARE something about their contents, and so can be walked. Everything else \u2014\n// `unknown`, a bare `any` \u2014 declares nothing and is passed through as it arrived.\nconst CONTAINERS = new Set(['object', 'array', 'record'])\n\n/**\n * The same coercion, applied at every DEPTH \u2014 inside a declared object's properties and inside a list's\n * elements, not only at the top of a field.\n *\n * Without this a declaration means different things depending on where it sits: `z.string()` takes `42` at\n * the top level but `z.array(z.string())` rejects `[42]`, and `z.object({ zip: z.string() })` rejects\n * `{ zip: 12345 }`. The transport is no more type-faithful inside a container than outside one.\n *\n * The rule is simply: **walk whatever declares its contents, convert whatever declares a type, and leave\n * everything else alone.** A `z.record(z.string(), z.unknown())` therefore coerces nothing \u2014 not because\n * records are exempt, but because `unknown` declares no type to coerce to \u2014 while\n * `z.record(z.string(), z.number())` converts its values like any other declaration.\n *\n * BEST-EFFORT below the top level: a value that cannot be converted is left exactly as it arrived, for the\n * author's own schema to reject. That keeps the failure reported against the property that actually failed\n * (`tags.1`, `address.zip`) rather than as a coercion error naming the whole field, and it keeps this step\n * incapable of making anything stricter \u2014 it only ever converts.\n *\n * Absence is resolved at every depth too, by the same rule the top level uses: ask the sub-schema which\n * absent forms it accepts, and hand it the one it wants. Without that, `.optional()` means one thing on a\n * field and another inside a list \u2014 `z.array(z.string().optional())` would reject `[null]` while a bare\n * `z.string().optional()` accepts it.\n *\n * A sub-schema that accepts NO absent form is left exactly as it arrived, so zod raises it and the message\n * is built against the property that failed (`\u00ABCity\u00BB is required`) \u2014 this step never invents an error.\n */\nexport function coerceDeep(value: unknown, schema: AnyZod | undefined): unknown {\n if (!schema) {\n return value\n }\n\n const ins = inspect(schema)\n\n if (isBlank(value, ins, schema)) {\n return absentAs(schema, value)\n }\n\n if (value == null) {\n return value\n }\n\n // Before any type branch below: a union has no single type to walk, it has a list to try.\n if (ins.branches) {\n return coerceUnion(value, ins.branches)\n }\n\n if (ins.coreType === 'array') {\n const element = ins.core?._zod?.def?.element as AnyZod | undefined\n\n return Array.isArray(value) ? value.map(item => coerceDeep(item, element)) : value\n }\n\n if (ins.coreType === 'record') {\n if (typeof value !== 'object' || Array.isArray(value)) {\n return value\n }\n\n const valueType = ins.core?._zod?.def?.valueType as AnyZod | undefined\n\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, coerceDeep(item, valueType)])\n )\n }\n\n if (ins.coreType === 'object') {\n if (typeof value !== 'object' || Array.isArray(value)) {\n return value\n }\n\n const source = value as Record<string, unknown>\n // Only DECLARED properties are walked. An undeclared key is either stripped by zod or carried through\n // untouched by `z.looseObject`; either way the runtime has no declaration to coerce it against.\n const coerced: Record<string, unknown> = { ...source }\n\n for (const [name, property] of shapeEntries(ins.core)) {\n if (name in source) {\n coerced[name] = coerceDeep(source[name], property)\n }\n }\n\n return coerced\n }\n\n const result = coerceLeaf(value, ins)\n\n return result.ok ? result.value : value\n}\n\n/** True when a field's own type is a container this module walks rather than converts. */\nexport const isContainer = (coreType: string): boolean => CONTAINERS.has(coreType)\n\n/**\n * One leaf, converted for VALIDATION.\n *\n * Everything reaches zod as the type it declared: a date arrives as a `Date` whatever form the host sent, and\n * an ISO field arrives as a string in its own declared shape. What the HANDLER receives is a separate\n * question \u2014 a `z.date()` value is restored to the original afterwards (see ../normalize.ts).\n */\nexport function coerceLeaf(value: unknown, ins: Inspected): Coerced {\n // A union reaches here when its first branch is a scalar (that is what `isContainer` was asked about).\n // Always `ok`: an unmatched value is passed on for the author's union to reject with its own message.\n if (ins.branches) {\n return ok(coerceUnion(value, ins.branches))\n }\n\n // Ahead of every type branch below: `z.json()` declares `unknown`, so there is no core type to switch on.\n if (ins.meta.frJson) {\n return toJsonValue(value)\n }\n\n const format = formatOf(ins)\n\n if (ins.coreType === 'string' && isConvertibleIso(format)) {\n const iso = toIso(value, format as string)\n\n if (iso !== undefined) {\n return ok(iso)\n }\n\n // Nothing to reshape. A STRING is handed on unchanged so the format check speaks for itself \u2014 \"expects\n // an ISO date, e.g. 2024-01-01\" tells the author more than \"must be a date\", and it is what a blank or\n // a typo deserves. A non-string could never satisfy a string field at all, so it fails here.\n return typeof value === 'string' ? ok(value) : fail('date')\n }\n\n // A literal publishes as the type of its value (see ./introspect.ts `deriveWidget`), so it has to CONVERT\n // to that type as well. The console draws a toggle for `z.literal(true)` and the flow supplies the string\n // `'true'` like any other boolean; publishing a typed widget without the matching conversion would leave\n // the field unfillable from a flow. A mixed literal declares no single type and is passed through.\n if (ins.coreType === 'literal') {\n const declared = literalType(ins.core)\n\n return declared ? coerceValue(value, declared) : ok(value)\n }\n\n return coerceValue(value, ins.coreType)\n}\n\n// The same \"is this blank?\" rule the top-level pipeline applies (see ../schema/normalize.ts): `''` is a value\n// on a string unless a declared default can absorb it, and absence for every other type.\nfunction isBlank(value: unknown, ins: Inspected, schema: AnyZod): boolean {\n if (value === undefined || value === null) {\n return true\n }\n\n if (value !== '') {\n return false\n }\n\n // A union treats a blank as absence whatever its first branch resolved to. `''` is a value only on a plain\n // string type, and a union is not one \u2014 which is what makes `z.union([z.url(), z.literal('')]).optional()`\n // mean \"blank is not set\", the spelling the docs give for an optional formatted field.\n if (ins.branches) {\n return true\n }\n\n return ins.coreType !== 'string' || absenceOf(schema).absorbsBlank\n}\n\n// Hand the schema whichever absent form it accepts. `required` returns the value untouched, leaving zod to\n// report it against its own path.\nfunction absentAs(schema: AnyZod, value: unknown): unknown {\n const { absence } = absenceOf(schema)\n\n if (absence === 'required') {\n return value\n }\n\n if (absence === 'as-received') {\n return value === '' ? undefined : value\n }\n\n return absence === 'null' ? null : undefined\n}\n", "import { FlowExtensionParamWidgetTypes } from '../widget-types'\nimport { type AnyZod, inspect } from './introspect'\n\n// What a declaration explains about itself when the author wrote no `.describe()` \u2014 so `z.email()` stays a\n// legal one-liner and still renders with usable help text.\n//\n// These are applied at RENDER time, not baked into the published definition: the console derives them from\n// the schema the definition carries, so rewording an entry here reaches every already-deployed service\n// without a redeploy. `field-mapper` therefore publishes the author's description or nothing at all.\n//\n// Also read by ./messages.ts, which restates a format failure using the same wording the field advertises.\n//\n// Labels are NOT derived this way at all \u2014 see ./labels.ts for why the field key always wins.\n\n// Three maps rather than one, because the three key spaces overlap: `date` is both a zod format\n// (`z.iso.date()`) and a core type (`z.date()`). Kept separate, each stays a flat literal table and a\n// collision is impossible.\n\n/** `z.text()` \u2014 FlowRunner's own marker, the most specific thing a field can declare. */\nexport const WIDGET_DESCRIPTIONS: Record<string, string> = {\n [FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT]: 'Expects text; line breaks are allowed',\n}\n\n/**\n * `z.json()`. More specific than the widget it carries: it renders as the same textarea `z.text()` does, so\n * the widget wording would say \"line breaks are allowed\" and leave out the only rule that actually rejects\n * anything \u2014 that what is typed has to parse.\n */\nexport const JSON_DESCRIPTION = 'Expects JSON, e.g. {\"key\": \"value\"}'\n\n/**\n * The plain core type, when nothing more specific is declared.\n *\n * Only worth filling in where the widget does NOT already convey the type. `z.number()` earns one because a\n * number renders as a plain text field \u2014 there is no numeric widget \u2014 so \"Expects a number\" is real\n * information. `z.string()` and `z.boolean()` do not: the field is visibly a text box or a toggle, and\n * filling them would put generic prose under every field of every service, overwriting the meaningful empty\n * state that says \"the service author documented this\".\n */\nexport const TYPE_DESCRIPTIONS: Record<string, string> = {\n number : 'Expects a number',\n bigint : 'Expects a whole number',\n literal: 'Expects one fixed value',\n enum : 'Expects one of the listed options',\n // `z.date()` is deferred until the DATE type gets a widget; `z.iso.date()` is the working alternative.\n date : 'Expects a date',\n // string / boolean / array / object are deliberately absent \u2014 see above.\n}\n\n/**\n * A zod `format` token. Spelled out rather than composed \u2014 the wording is what a customer reads, so it\n * should be editable here without reasoning about how it is assembled. Every example is a value that\n * actually satisfies its helper.\n */\nexport const FORMAT_DESCRIPTIONS: Record<string, string> = {\n // \u2500\u2500 web \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n url : 'Expects a URL, e.g. https://example.com',\n email : 'Expects an email address, e.g. foo@bar.com',\n hostname : 'Expects a hostname, e.g. api.example.com',\n e164 : 'Expects a phone number in E.164 form, e.g. +14155552671',\n emoji : 'Expects an emoji, e.g. \uD83C\uDF89',\n // \u2500\u2500 identifiers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n uuid : 'Expects a UUID, e.g. 3f2504e0-4f89-11d3-9a0c-0305e82c3301',\n guid : 'Expects a GUID, e.g. 3f2504e0-4f89-11d3-9a0c-0305e82c3301',\n nanoid : 'Expects a Nano ID, e.g. V1StGXR8_Z5jdHi6B-myT',\n cuid : 'Expects a CUID, e.g. cjld2cyuq0000t3rmniod1foy',\n cuid2 : 'Expects a CUID2, e.g. tz4a98xxat96iws9zmbrgj3a',\n ulid : 'Expects a ULID, e.g. 01ARZ3NDEKTSV4RRFFQ69G5FAV',\n xid : 'Expects an XID, e.g. 9m4e2mr0ui3e8a215n4g',\n ksuid : 'Expects a KSUID, e.g. 0ujsswThIGTUYm2K8FjOOfXtY1K',\n // \u2500\u2500 ISO 8601 (z.iso.*) \u2014 a validated STRING, unlike the deferred z.date() \u2500\u2500\u2500\n datetime : 'Expects an ISO date and time, e.g. 2024-01-01T00:00:00Z',\n date : 'Expects an ISO date, e.g. 2024-01-01',\n time : 'Expects an ISO time, e.g. 12:30:00',\n duration : 'Expects an ISO duration, e.g. P3Y6M4D',\n // \u2500\u2500 encodings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n base64 : 'Expects a base64 string, e.g. aGVsbG8=',\n base64url: 'Expects a base64url string, e.g. aGVsbG8',\n hex : 'Expects a hex string, e.g. deadbeef',\n jwt : 'Expects a JWT, e.g. eyJhbGciOiJIUzI1NiJ9.eyJhIjoxfQ.c2ln',\n // \u2500\u2500 network \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n ipv4 : 'Expects an IPv4 address, e.g. 192.168.0.1',\n ipv6 : 'Expects an IPv6 address, e.g. 2001:db8::1',\n cidrv4 : 'Expects an IPv4 range, e.g. 192.168.0.0/24',\n cidrv6 : 'Expects an IPv6 range, e.g. 2001:db8::/32',\n}\n\n/**\n * What a field's declaration explains about itself, most specific wins:\n *\n * 1. `z.json()` \u2014 the content rule, which outranks the widget it shares with `z.text()`\n * 2. a FlowRunner widget marker \u2014 `z.text()`, a string the console renders specially\n * 3. a zod `format` token \u2014 `z.email()`, `z.ipv4()`, `z.iso.date()`, \u2026\n * 4. the plain core type \u2014 `number`, `bigint`, `literal`, `enum`, `date`\n *\n * All three are read past the optional/nullable/default wrappers, so a modifier never changes the answer.\n */\nexport function describeField(schema: AnyZod): string | undefined {\n const ins = inspect(schema)\n const format = (ins.core as { _zod?: { def?: { format?: string } } } | undefined)?._zod?.def?.format\n\n if (ins.meta.frJson) {\n return JSON_DESCRIPTION\n }\n\n return WIDGET_DESCRIPTIONS[ins.meta.frWidget ?? ''] ??\n FORMAT_DESCRIPTIONS[format ?? ''] ??\n TYPE_DESCRIPTIONS[ins.coreType]\n}\n", "import type { ValidationIssue } from '../../../errors'\nimport type { ZodIssue } from '../types'\nimport { FORMAT_DESCRIPTIONS } from './defaults'\nimport type { FieldPlan } from './field-plan'\nimport { type AnyZod, inspect, shapeEntries } from './introspect'\nimport { labelOf } from './labels'\n\n// Step 3's output, made readable. Zod's defaults describe the parser's disappointment rather than the\n// author's mistake \u2014 \"Invalid input: expected string, received undefined\" \u2014 so each issue code is restated\n// against the field's own `.label()`. An author-supplied message (`z.string().min(3, 'Too short')`) is left\n// exactly as written; only zod's own wording is replaced.\n//\n// A failure can be DEEPER than the field: `address.city` inside an object, `tags.1` inside a list. Those are\n// named by walking the declaration down the issue's own path, so the message names the property the user has\n// to fix rather than the container it sits in.\n\n// zod's `format` tokens, in the author's vocabulary. A format it does not name (a bare `.regex()`, say) has\n// nothing worth restating, so it falls back to the generic wording.\n// zod's `expected` tokens, as the phrase that completes \"\u00ABLabel\u00BB must be \u2026\". Spelled out so the wording is\n// editable without composing articles.\nconst EXPECTED: Record<string, string> = {\n string : 'a string',\n number : 'a number',\n int : 'an integer',\n bigint : 'a whole number',\n boolean: 'true or false',\n date : 'a date',\n object : 'an object',\n array : 'an array',\n // `z.json()`. Not a zod token \u2014 ./coerce.ts raises it when the submitted text will not parse.\n json : 'valid JSON',\n}\n\nexport const requiredMessage = (plan: FieldPlan): string => `\u00AB${ plan.label }\u00BB is required`\n\nexport const invalidTypeMessage = (plan: FieldPlan, expected: string): string =>\n `\u00AB${ plan.label }\u00BB must be ${ EXPECTED[expected] ?? expected }`\n\n// What one issue is ABOUT: the deepest declared thing on its path, and the value that sits there.\ninterface IssueTarget {\n // How to name it: a nested property uses its own label; a list item names the list plus its position.\n label: string\n // The submitted value at that path \u2014 how \"left empty\" is told apart from \"wrong type\" below the top level,\n // where the absence pipeline never ran (it only normalizes the field, not the field's insides).\n value: unknown\n found: boolean\n}\n\nconst isIndex = (segment: string): boolean => /^\\d+$/.test(segment)\n\n/**\n * Walk the field's declaration and the submitted value together, one path segment at a time.\n *\n * Stops early if the path leads somewhere the declaration does not describe (a passthrough object, say) and\n * reports the deepest thing it did resolve \u2014 a slightly less specific label beats a wrong one.\n */\nfunction resolveTarget(plan: FieldPlan, segments: string[], fieldValue: unknown): IssueTarget {\n let schema: AnyZod | undefined = plan.schema\n let value: unknown = fieldValue\n let label = plan.label\n let found = true\n\n for (const segment of segments) {\n const core = schema ? inspect(schema).core : undefined\n const coreType = core ? inspect(schema as AnyZod).coreType : undefined\n\n value = value == null ? undefined : (value as Record<string, unknown>)[segment]\n\n if (coreType === 'array' && isIndex(segment)) {\n // A list item has no name of its own, so it borrows the list's and states its position. 1-based: the\n // message is read by whoever filled the form in, not by whoever indexed the array.\n label = `${ label } item ${ Number(segment) + 1 }`\n schema = core?._zod?.def?.element as AnyZod | undefined\n continue\n }\n\n const nested = shapeEntries(core).find(([name]) => name === segment)\n\n if (!nested) {\n found = false\n break\n }\n\n schema = nested[1]\n label = labelOf(segment, schema)\n }\n\n return { label, value, found }\n}\n\n/**\n * A range bound, as the author would recognise it.\n *\n * zod compares dates as instants, so `z.date().min(new Date('2024-01-01'))` reports its bound as\n * `1704067200000` \u2014 a number nobody typed. On a date field it is rendered back as an ISO string.\n */\nfunction bound(value: unknown, plan: FieldPlan): string {\n if (plan.coreType !== 'date' || typeof value !== 'number') {\n return String(value)\n }\n\n const asDate = new Date(value)\n\n return Number.isNaN(asDate.getTime()) ? String(value) : asDate.toISOString()\n}\n\n// A zod issue carrying a custom message the author wrote \u2014 nothing to restate.\nfunction isAuthored(issue: ZodIssue & { message?: string }): boolean {\n const message = issue.message ?? ''\n\n // Every zod default starts by naming the input or the constraint; an authored one is arbitrary prose.\n return !!message && !/^(Invalid|Too big|Too small|Unrecognized|Not multiple)/.test(message)\n}\n\n/**\n * Restate one zod issue for a field. `path` is the field key \u2014 issues from a nested object keep the zod path\n * appended, so a caller can still point at the exact property.\n */\nexport function toFieldIssue(\n plan: FieldPlan,\n issue: ZodIssue & { message?: string; expected?: string; minimum?: unknown; maximum?: unknown; values?: unknown[] },\n fieldValue?: unknown\n): ValidationIssue {\n const segments = (issue.path ?? []).map(String).filter(Boolean)\n const path = segments.length ? `${ plan.name }.${ segments.join('.') }` : plan.name\n const code = issue.code ?? 'custom'\n const target = resolveTarget(plan, segments, fieldValue)\n // `plan` carries the top-level label; below the top level the resolved target carries the right one.\n const named = { ...plan, label: target.label }\n\n if (isAuthored(issue)) {\n return { path, code, message: issue.message as string }\n }\n\n if (code === 'invalid_type') {\n // Absence reaching validation means nothing was there to fall back on. At the top level the pipeline has\n // already normalized absence, so zod's `received` settles it; deeper down nothing normalized the value,\n // so the submitted value itself is what says whether the field was left empty or filled in wrongly.\n const received = (issue as { received?: string }).received\n const absent = segments.length\n ? target.found && target.value == null\n : received === 'undefined' || received === 'null' || issue.expected === undefined\n\n return absent\n ? { path, code, message: requiredMessage(named) }\n : { path, code, message: invalidTypeMessage(named, issue.expected ?? '') }\n }\n\n if (code === 'too_small') {\n return { path, code, message: `\u00AB${ target.label }\u00BB must be at least ${ bound(issue.minimum, plan) }` }\n }\n\n if (code === 'too_big') {\n return { path, code, message: `\u00AB${ target.label }\u00BB must be at most ${ bound(issue.maximum, plan) }` }\n }\n\n if (code === 'invalid_value') {\n // zod reports the accepted set as `values`.\n const values = (issue.values ?? []).map(String)\n\n return { path, code, message: `\u00AB${ target.label }\u00BB must be one of: ${ values.join(', ') }` }\n }\n\n if (code === 'invalid_format') {\n // The format's own description already says what shape is expected, so restate that rather than\n // inventing a second phrasing for the same fact.\n const described = FORMAT_DESCRIPTIONS[(issue as { format?: string }).format ?? '']\n\n return described\n ? { path, code, message: `\u00AB${ target.label }\u00BB is invalid \u2014 ${ described.replace(/^Expects /, 'expects ') }` }\n : { path, code, message: `\u00AB${ target.label }\u00BB has an invalid format` }\n }\n\n return { path, code, message: `\u00AB${ target.label }\u00BB is invalid` }\n}\n", "import type { ValidationIssue } from '../../../errors'\nimport type { ZodIssue } from '../types'\nimport { accepts, coerceDeep, coerceLeaf, isContainer } from './coerce'\nimport { passesDateThrough } from './dates'\nimport type { FieldPlan } from './field-plan'\nimport { type AnyZod, inspect, shapeEntries } from './introspect'\nimport { invalidTypeMessage, requiredMessage, toFieldIssue } from './messages'\n\n// The pipeline, per field:\n//\n// 1. normalize absence \u2192 2. coerce to the declared type \u2192 3. validate (the author's own schema)\n//\n// The order is load-bearing. Absence first, or a blank becomes garbage (`Number('')` is 0). Validation last,\n// and against the author's schema unchanged, so `.min()`, `.max()`, `.int()`, `.regex()`, enum membership and\n// refinements all work natively \u2014 nothing here reimplements them.\n\nexport interface FieldResult {\n // Absent from the output entirely when the field resolved to \"not present\" and had nothing to stand in.\n value?: unknown\n present: boolean\n issues: ValidationIssue[]\n}\n\nconst resolved = (value: unknown): FieldResult => ({ value, present: true, issues: [] })\nconst rejected = (issues: ValidationIssue[]): FieldResult => ({ present: false, issues })\n\n// `undefined` and `null` are always absence. `''` is absence only where the type has no empty value, or\n// where a declared default can absorb it \u2014 on a string it is otherwise a real value.\nfunction isAbsent(value: unknown, plan: FieldPlan): boolean {\n if (value === undefined || value === null) {\n return true\n }\n\n if (value !== '') {\n return false\n }\n\n // Same rule the deep walk applies (see ./coerce.ts `isBlank`): `''` is a value only on a plain string\n // type. A union resolves to its first branch for publishing, but that must not turn a blank into a value.\n if (plan.isUnion) {\n return true\n }\n\n return plan.coreType !== 'string' || plan.absorbsBlank\n}\n\n// Absence becomes whichever form the schema accepts, so the author's choice of modifier decides what the\n// handler sees rather than what the client happened to send.\nfunction normalizeAbsence(value: unknown, plan: FieldPlan): FieldResult {\n if (plan.absence === 'required') {\n return rejected([{ path: plan.name, code: 'invalid_type', message: requiredMessage(plan) }])\n }\n\n if (plan.absence === 'as-received') {\n // `.nullish()` accepts both, so a blank collapses to `undefined` and the rest arrive as sent.\n return validate(value === '' ? undefined : value, plan)\n }\n\n return validate(plan.absence === 'null' ? null : undefined, plan)\n}\n\n// Step 3. Zod short-circuits on the absent form it accepts, so a constraint never fires on an absent value.\nfunction validate(value: unknown, plan: FieldPlan): FieldResult {\n const schema = plan.schema as unknown as {\n safeParse: (v: unknown) => { success: boolean; data?: unknown; error?: { issues?: ZodIssue[] } }\n }\n\n let result\n\n try {\n result = schema.safeParse(value)\n } catch {\n // An async refinement cannot be evaluated here; surface it as a plain failure rather than crashing.\n return rejected([{ path: plan.name, code: 'custom', message: `\u00AB${ plan.label }\u00BB could not be validated` }])\n }\n\n return result.success\n ? resolved(result.data)\n : rejected((result.error?.issues ?? []).map(issue => toFieldIssue(plan, issue, value)))\n}\n\nexport function normalizeField(value: unknown, plan: FieldPlan): FieldResult {\n if (isAbsent(value, plan)) {\n return normalizeAbsence(value, plan)\n }\n\n // A container is WALKED \u2014 its declared properties and its elements are coerced in place \u2014 where a scalar\n // is converted outright. A container that cannot be walked (a string where a list was declared) is passed\n // through for zod to reject as the wrong type.\n if (isContainer(plan.coreType)) {\n return restore(validate(coerceDeep(value, plan.schema), plan), value, plan)\n }\n\n const coerced = coerceLeaf(value, inspect(plan.schema))\n\n if (!coerced.ok) {\n return rejected([{\n path : plan.name,\n code : 'invalid_type',\n message: invalidTypeMessage(plan, coerced.expected as string),\n }])\n }\n\n return restore(validate(coerced.value, plan), value, plan)\n}\n\n/**\n * Give a `z.date()` back the value the host actually sent.\n *\n * Validation needs a real `Date` \u2014 `z.date()` accepts nothing else, and `.min()` / `.max()` compare instants\n * \u2014 but converting is not what the handler should see: `'2024-06-01'` becomes `2024-06-01T00:00:00.000Z`,\n * inventing a time of day and a timezone nobody chose. So the check runs on a converted copy and the\n * original is restored afterwards, at every depth.\n *\n * `z.coerce.date()` is untouched: the author asked for a `Date`, so zod's output stands.\n */\nfunction restore(result: FieldResult, original: unknown, plan: FieldPlan): FieldResult {\n if (!plan.restoresDates || !result.present || result.issues.length) {\n return result\n }\n\n if (plan.passThroughDate) {\n return resolved(original)\n }\n\n return resolved(restoreDeep(result.value, original, plan.schema))\n}\n\n// Walk zod's output and the submitted value together, taking the ORIGINAL wherever the declaration is a\n// pass-through date. Only declared shapes are walked \u2014 the same rule the coercion walk follows.\nfunction restoreDeep(output: unknown, original: unknown, schema: AnyZod | undefined): unknown {\n if (!schema || output == null || original == null) {\n return output\n }\n\n const ins = inspect(schema)\n\n if (passesDateThrough(ins)) {\n return original\n }\n\n // A union was coerced through whichever branch accepted the value, so the restore walk has to follow that\n // same branch \u2014 the resolved first one says nothing about which date, if any, the value actually took.\n if (ins.branches) {\n const branch = ins.branches.find(option => accepts(option, output))\n\n return branch ? restoreDeep(output, original, branch) : output\n }\n\n const element = ins.core?._zod?.def?.element as AnyZod | undefined\n\n if (ins.coreType === 'array' && element && Array.isArray(output) && Array.isArray(original)) {\n return output.map((item, index) => restoreDeep(item, original[index], element))\n }\n\n const valueType = ins.core?._zod?.def?.valueType as AnyZod | undefined\n\n if (ins.coreType === 'record' && valueType && isPlain(output) && isPlain(original)) {\n return Object.fromEntries(\n Object.entries(output).map(([key, item]) => [key, restoreDeep(item, original[key], valueType)])\n )\n }\n\n if (ins.coreType === 'object' && isPlain(output) && isPlain(original)) {\n const restored: Record<string, unknown> = { ...output }\n\n for (const [name, property] of shapeEntries(ins.core)) {\n if (name in output) {\n restored[name] = restoreDeep(output[name], original[name], property)\n }\n }\n\n return restored\n }\n\n return output\n}\n\nconst isPlain = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n", "import type { ValidationIssue } from '../../../errors'\nimport type { ZodIssue, ZodSchema } from '../types'\n\n// The zod-facing half of validation: run a schema over a value and flatten its issues. Deciding WHICH\n// schema and WHICH error a failure becomes is the caller's job (see ../params.ts) \u2014 this module only knows\n// how to ask zod and how to translate what it answers.\n//\n// This is the WRAPPER path: the runtime-owned `payload` / `invocation` / `callbackObject` a helper route or\n// SYSTEM seam is called with, rather than a field a person filled in. A failure here means the CALLER is\n// malformed, so there is no author label to restate against \u2014 but zod's own wording (\"Invalid input:\n// expected object, received string\") describes the parser rather than the mistake, so the shape of the\n// wrapper itself is restated against the param's name. Everything deeper keeps zod's message: it is a\n// runtime contract detail, and inventing wording for it would only obscure what actually arrived.\n\n// A `fail` callback owns the error identity; it never returns.\nexport type FailFn = (issues: ValidationIssue[]) => never\n\n// Matches ./messages.ts, so the two paths word the same expectation the same way.\nconst EXPECTED: Record<string, string> = {\n string : 'a string',\n number : 'a number',\n boolean: 'true or false',\n object : 'an object',\n array : 'an array',\n}\n\nexport function toIssues(error: { issues?: ZodIssue[] } | undefined, param?: string): ValidationIssue[] {\n return (error?.issues ?? []).map(issue => {\n const path = (issue.path ?? []).map(String).join('.')\n const expected = (issue as { expected?: string }).expected\n\n // Only the wrapper's own type is restated \u2014 a deeper path is left as zod put it.\n const restated = param && !path && issue.code === 'invalid_type' && expected\n ? `\u00AB${ param }\u00BB must be ${ EXPECTED[expected] ?? expected }`\n : undefined\n\n return { path, message: restated ?? issue.message ?? 'invalid value', code: issue.code }\n })\n}\n\n// Parse `value`, handing the flattened issues to `fail` (which throws). Schema-less slots pass through \u2014\n// authors may declare no params/criteria at all.\nexport function parseSchema<T>(\n schema: ZodSchema | undefined,\n value: unknown,\n fail: FailFn,\n param?: string\n): T {\n if (typeof schema?.safeParse !== 'function') {\n return value as T\n }\n\n const result = schema.safeParse(value)\n\n if (!result.success) {\n fail(toIssues(result.error, param))\n }\n\n return result.data as T\n}\n", "import type { ValidationIssue } from '../../errors'\nimport { assertObjectSchema } from './schema/assert-object-schema'\nimport { assertSupportedSchema } from './schema/assert-supported-schema'\nimport { type FieldPlan, planField } from './schema/field-plan'\nimport { type AnyZod, shapeEntries } from './schema/introspect'\nimport { normalizeField } from './schema/normalize'\nimport { type FailFn, parseSchema } from './schema/parse'\nimport type { NormalizedInput, SchemaSource, ZodSchema } from './types'\n\n// A declared schema slot, as the runner works with it. Two things live here and nowhere else: the author's\n// zod schema, and the operations the runner performs on it. Anything zod can already do is DELEGATED \u2014 this\n// is a wrapper, never a re-implementation. `MethodParams` (inputs) and `ConfigParams` (config) extend it.\n//\n// Every slot is optional: an undeclared one produces an instance with no `scheme` that answers \"no fields\"\n// and passes values through unparsed, so call sites never need an `if (params)` guard. But a slot that IS\n// declared must be a z.object \u2014 the constructor enforces that, so an instance is never half-usable.\n\nexport abstract class Params {\n readonly scheme?: ZodSchema\n\n // Derived once per declared slot, at registration. The absence policy comes from probing the schema, which\n // is two `safeParse` calls we would rather not repeat on every invocation.\n #plans?: FieldPlan[]\n\n protected constructor(scheme?: unknown, readonly source: SchemaSource = {}) {\n // Declared \u21D2 must be a z.object. Checked here so EVERY slot is covered by construction, and at\n // registration time rather than on some later invocation (see ./schema/assert-object-schema.ts).\n assertObjectSchema(scheme, source)\n // \u2026and every field inside it must be something the runtime can publish, render and coerce. Same moment,\n // same reason: a declaration the runner cannot classify is a wrong contract, not a rendering nicety\n // (see ./schema/assert-supported-schema.ts).\n assertSupportedSchema(scheme, source)\n\n this.scheme = (scheme ?? undefined) as ZodSchema | undefined\n }\n\n // The declared field names. This is what a `dependsOn` is derived from.\n keys(): string[] {\n return this.fields().map(([name]) => name)\n }\n\n // The declared fields, in declaration order. Public: a renderer needs them as much as the pipeline does.\n fields(): [name: string, schema: AnyZod][] {\n return shapeEntries(this.scheme as AnyZod | undefined)\n }\n\n protected plans(): FieldPlan[] {\n this.#plans ??= this.fields().map(([name, schema]) => planField(name, schema))\n\n return this.#plans\n }\n\n /**\n * Normalize, coerce and validate a whole input object against the declared fields.\n *\n * Only declared fields appear in the output \u2014 an undeclared key is dropped, as it always was. Every\n * declared field appears, holding whatever it resolved to, which for an absent `.optional()` is\n * `undefined`: the key is there, so a handler asks `params.x === undefined` rather than `'x' in params`.\n * A field is omitted only when it FAILED, and then the caller is looking at `issues` instead.\n *\n * Every field is attempted even after one fails, so the caller can report the whole form at once instead\n * of making a user fix one field per attempt.\n */\n normalizeInput(input?: Record<string, unknown>): NormalizedInput {\n const source = input ?? {}\n const values: Record<string, unknown> = {}\n const issues: ValidationIssue[] = []\n\n for (const plan of this.plans()) {\n const result = normalizeField(source[plan.name], plan)\n\n if (result.issues.length) {\n issues.push(...result.issues)\n } else if (result.present) {\n values[plan.name] = result.value\n }\n }\n\n return { values, issues }\n }\n\n // Strict: required fields enforced, unknown stripped. For input the flow engine produces against the\n // published model, where a violation is a real contract break.\n parse<T>(value: unknown, fail: FailFn): T {\n return parseSchema<T>(this.scheme, value, fail)\n }\n\n}\n", "import type { ServiceConfigsValues } from '../../common/constants'\nimport { InvalidConfigError } from '../../errors'\nimport { Params } from './params'\nimport type { SchemaSource } from './types'\n\n// The extension's `configItems` slot: its description for the console, and the resolution of a concrete\n// invocation's values.\n//\n// Resolution runs the shared normalize \u2192 coerce \u2192 validate pipeline (see ./params.ts and ./schema/normalize),\n// so `configItems` obeys exactly the same policy as every other declared slot. It replaces the v1\n// `prepareServiceConfig` for this format: that resolver routed by the `shared` flag and applied defaults by\n// truthiness, which silently dropped a falsy default and never type-checked anything.\n\nexport class ConfigParams extends Params {\n static of(scheme?: unknown, source: SchemaSource = {}): ConfigParams {\n return new ConfigParams(scheme, source)\n }\n\n static empty(): ConfigParams {\n return new ConfigParams(undefined)\n }\n\n /**\n * The effective config for one invocation.\n *\n * Fails with every offending field at once rather than the first, so a half-configured service reports its\n * whole form. A field the schema resolved to \"not present\" is simply absent from the result.\n */\n resolve(configs?: ServiceConfigsValues): ServiceConfigsValues {\n const { values, issues } = this.normalizeInput(configs)\n\n if (issues.length) {\n throw new InvalidConfigError(this.source.serviceId ?? 'unknown', issues)\n }\n\n return values\n }\n}\n", "import { Params } from './params'\nimport type { FailFn } from './schema/parse'\nimport type { SchemaSource } from './types'\n\n// Every input container a method declares: an action's or trigger's `params`, a dictionary's `criteria`,\n// a `dynamicParams.criteria`, the object a `dynamicParams.resolve()` returns, and a SYSTEM method's\n// runtime-owned scheme. One class because they are the same thing \u2014 a z.object the runner validates input\n// against and publishes as the method's input model.\n\nexport class MethodParams extends Params {\n static of(scheme?: unknown, source: SchemaSource = {}): MethodParams {\n return new MethodParams(scheme, source)\n }\n\n // An undeclared slot. A real instance, so callers never branch on undefined.\n static empty(): MethodParams {\n return new MethodParams(undefined)\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Run the shared normalize \u2192 coerce \u2192 validate pipeline and hand the issues to `fail` (which throws).\n *\n * `carryUnknown` keeps the input's undeclared keys underneath the normalized ones. Two slots need it: an\n * action with `dynamicParams`, whose generated top-level fields are not in the static schema, and the\n * generated loaders, whose owner's `result` fn may read those same fields.\n */\n normalize<T extends Record<string, unknown>>(\n input: Record<string, unknown> | undefined,\n fail: FailFn,\n options: { carryUnknown?: boolean } = {}\n ): T {\n const { values, issues } = this.normalizeInput(input)\n\n if (issues.length) {\n fail(issues)\n }\n\n return (options.carryUnknown ? { ...input, ...values } : values) as T\n }\n}\n", "import { z as baseZod } from 'zod'\n\nimport {\n filesDeleteOptions,\n filesGetOptions,\n filesListOptions,\n filesUploadOptions,\n} from './files-options'\nimport { FlowExtensionParamWidgetTypes, type FrWidgetToken } from './widget-types'\n\n// The v2 authoring surface: real zod v4 extended with FlowRunner authoring plugins and custom types.\n// Exposed to services as `Flowrunner.z` (services do `const z = Flowrunner.z`) \u2014 see ../../namespace.ts.\n//\n// Author metadata is stored on the schema via zod's native `.meta()` (merges, immutable clone). Native\n// keys drive display (`title`, `description`, `examples`); FlowRunner-specific bits use `fr`-prefixed keys\n// so they never collide with zod/OpenAPI meta. The runner reads them back via ../schema/introspect.\n\n// A dictionary ref carried by `.dictionary(ref)` \u2014 returned from `ext.dictionary(...)` (see create-extension).\nexport interface DictionaryRef {\n id: string\n dependsOn?: string[]\n}\n\n// FlowRunner meta keys attached by the plugins below.\nexport interface FrMeta {\n title?: string\n description?: string\n examples?: unknown[]\n frShared?: boolean\n frDictionary?: { id: string; dependsOn: string[] }\n frLabels?: Record<string, string>\n /** A widget token the declaration carries explicitly \u2014 see `FrWidgetToken` in ./widget-types.ts. */\n frWidget?: FrWidgetToken\n frSecret?: boolean\n /** `z.json()` \u2014 the value arrives as TEXT and is parsed before the handler sees it. See `json()` below. */\n frJson?: boolean\n}\n\ndeclare module 'zod' {\n interface ZodType {\n /** Display label \u2192 native `meta.title`. */\n label(text: string): this\n /** Sample value \u2192 appended to native `meta.examples`. */\n example(value: unknown): this\n /** Mark a config field as shared (global) rather than per-app (OAuth client id/secret, secrets). */\n shared(): this\n /**\n * Mark a `z.string()` CONFIG field as sensitive: the console masks it and offers a reveal toggle.\n *\n * Display only. The value is stored, transmitted and validated exactly as it would be without it \u2014 this\n * hides a credential from a passer-by, it does not protect it.\n *\n * No effect anywhere else. Not on `z.text()`, which has no password mode; and not on an action or\n * trigger param, whose value lives in the flow definition and is readable through the API, so masking\n * its input would suggest a protection that is not there.\n */\n secret(): this\n /** Bind a param to a dictionary for dynamic options; auto-derives `dependsOn` from the dictionary criteria. */\n dictionary(ref: DictionaryRef): this\n /**\n * Show a human label per declared VALUE: `.labels({ asc: 'Ascending' })`.\n *\n * The flow element stores the VALUE, so renaming a label changes nothing that was saved \u2014 and the\n * handler receives the value it declared, with no translation step anywhere.\n */\n labels(byValue: Record<string, string>): this\n /** @deprecated Inverted and renamed \u2014 see `labels`. Throws, so the change cannot pass silently. */\n map(mapping: Record<string, unknown>): never\n }\n}\n\nlet extended = false\n\nfunction extendPrototype(): void {\n if (extended) {\n return\n }\n extended = true\n\n const proto = baseZod.ZodType.prototype as unknown as Record<string, unknown>\n\n proto.label = function label(this: baseZod.ZodType, text: string) {\n return this.meta({ title: text })\n }\n\n proto.example = function example(this: baseZod.ZodType, value: unknown) {\n const existing = (this.meta() as FrMeta | undefined)?.examples ?? []\n\n return this.meta({ examples: [...existing, value] })\n }\n\n proto.shared = function shared(this: baseZod.ZodType) {\n return this.meta({ frShared: true })\n }\n\n proto.secret = function secret(this: baseZod.ZodType) {\n return this.meta({ frSecret: true })\n }\n\n proto.dictionary = function dictionary(this: baseZod.ZodType, ref: DictionaryRef) {\n return this.meta({ frDictionary: { id: ref.id, dependsOn: ref.dependsOn ?? [] } })\n }\n\n proto.labels = function labels(this: baseZod.ZodType, byValue: Record<string, string>) {\n return this.meta({ frLabels: byValue })\n }\n\n /**\n * `.map({ Label: value })` declared the LABELS as the accepted values, so a flow element stored a display\n * string \u2014 renaming a label then broke every saved element that used it. `.labels()` inverts it: the enum\n * declares the values, the labels are display only.\n *\n * It throws rather than being quietly accepted because the two forms take the same shape of argument with\n * the opposite meaning. Silently reading an old `.map()` would store labels again; ignoring it would drop\n * the labels. A loud failure at registration is the only reading that cannot corrupt a flow.\n */\n proto.map = function map(this: baseZod.ZodType): never {\n throw new Error(\n '`.map({ Label: value })` has been replaced by `.labels({ value: \\'Label\\' })` \u2014 declare the VALUES in ' +\n 'the enum and the labels here, so a flow element stores the value and renaming a label is safe. ' +\n 'e.g. z.enum([\\'asc\\', \\'desc\\']).labels({ asc: \\'Ascending\\', desc: \\'Descending\\' })'\n )\n }\n}\n\nextendPrototype()\n\n// Custom type: multi-line text is a `z.string()` carrying a widget marker.\nfunction text() {\n\n return baseZod.string().meta({ frWidget: FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT })\n}\n\n/**\n * Custom type: a parameter that takes arbitrary JSON.\n *\n * Three facts have to hold at once, and each picks one piece of this declaration:\n *\n * - **The console renders a textarea.** `frWidget` says so, and ../schema/introspect.ts publishes the\n * parameter as `STRING` \u2014 the model describes what a caller SUPPLIES, and what a caller supplies is text.\n * - **`execute` receives the parsed structure.** `frJson` tells ../schema/coerce.ts to `JSON.parse` the text\n * on the way in, so no service writes its own parse and none has to invent wording for text that is not\n * JSON. Coercion already sits between the transport and zod for exactly this kind of conversion \u2014 this is\n * the same arrangement as `z.string().pipe(z.coerce.number())`, with a fixed conversion.\n * - **The author's TYPE is the parsed value, not the text.** Hence `unknown` underneath: `z.infer` gives the\n * handler `unknown`, which is what it actually receives. Declaring `z.string()` here would publish and\n * coerce correctly and then lie to every author about what lands in `params`.\n *\n * \u26A0\uFE0F This SHADOWS zod's own `z.json()` (the namespace is `Object.create(baseZod)`). Deliberate, and safe\n * only because zod's version cannot currently be declared at all \u2014 it recurses until the stack is gone, and\n * the extension never registers (FR-3600). An author reaching for `z.json()` gets this one.\n */\nfunction json() {\n\n // `.nonoptional()` because `z.unknown()` accepts `undefined` on its own, and the console asks the same\n // absence probe the runtime resolves with (see ../model/field-mapper.ts `isRequired`) \u2014 so without it a\n // bare `z.json()` would publish as an OPTIONAL field and the runner would accept a missing value, which is\n // not what an author who did not write `.optional()` asked for. An author's own `.optional()` still wins:\n // it lands outside this, and the outermost modifier is the final word.\n return baseZod.unknown().nonoptional().meta({\n frWidget: FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT,\n frJson : true,\n })\n}\n\n// NB: never mutate `baseZod` itself \u2014 zod's module exports are not extensible. The ESM build exposes\n// `z` as a frozen module namespace, and since zod 4.6.0 the CJS build freezes its exports too, so\n// `Object.assign(baseZod, ...)` throws \"Cannot add property text, object is not extensible\" at module\n// load \u2014 which takes down the whole extension worker thread before any service code runs. Layering the\n// additions onto a child object keeps every zod export reachable through the prototype chain while\n// leaving zod's own exports untouched.\n// The additions are DEFINED rather than assigned, for a second-order version of the same hazard: `json`\n// SHADOWS a zod export, `Object.assign` writes through plain assignment, and assignment respects the\n// PROTOTYPE's descriptor \u2014 zod's `json` is non-writable, so it throws \"Cannot assign to read only property\n// 'json'\" at module load and takes the worker down exactly as mutating `baseZod` would. `defineProperty`\n// creates an own property without consulting the prototype, which is what shadowing requires.\n//\n// `Omit` on the base is what makes `z.json()` unambiguous: intersecting the two signatures would leave zod's\n// recursive-JSON overload callable, and an author would get its type for our value.\nconst namespace = Object.create(baseZod) as typeof baseZod\n\n// The file-options groups are custom types in the same sense \u2014 see ./files-options.ts for why they are\n// shipped rather than hand-copied into each service.\nObject.defineProperties(namespace, {\n text: { value: text, enumerable: true },\n json: { value: json, enumerable: true },\n filesUploadOptions: { value: filesUploadOptions, enumerable: true },\n filesListOptions: { value: filesListOptions, enumerable: true },\n filesGetOptions: { value: filesGetOptions, enumerable: true },\n filesDeleteOptions: { value: filesDeleteOptions, enumerable: true },\n})\n\nexport const z = namespace as unknown as\n Omit<typeof baseZod, 'json'> & {\n text: typeof text\n json: typeof json\n filesUploadOptions: typeof filesUploadOptions\n filesListOptions: typeof filesListOptions\n filesGetOptions: typeof filesGetOptions\n filesDeleteOptions: typeof filesDeleteOptions\n }\n\nexport type ExtendedZod = typeof z\n", "import { z as baseZod } from 'zod'\n\nimport { FlowExtensionParamWidgetTypes, type FrGroupToken } from './widget-types'\n\n// The platform's own file-storage option groups, declared once and handed to services through\n// `Flowrunner.z` (see ./zod.ts) \u2014 the v2 counterpart of the built-in `FilesUploadOptions` /\n// `FilesListOptions` / `FilesGetOptions` / `FilesDeleteOptions` param types the v1 JSDoc parser registers\n// (`jsdoc-parser/src/custom-type-defs/files.ts`).\n//\n// **Why this is shipped rather than copied.** A v1 service names the type and gets the platform's values,\n// labels, descriptions and defaults; reword a label here and every v1 service picks it up on the next parse.\n// Without an equivalent, every v2 service that stores a file owns a private copy of the same ten lines \u2014\n// nothing propagates, and a copy that drifts publishes a field the runtime does not have. That is not\n// hypothetical: the v1 services that shadow the built-in with their own typedef publish a `directory` option\n// `uploadFile` silently drops.\n//\n// **The `include` argument.** v1 subsets a group at publish time with `@paramDef {\u2026 \"include\":[\"scope\"]}`,\n// and 706 of the catalog's 729 `@paramDef`s do. The factories below take that same list, so an existing\n// `@paramDef` translates by inspection and the published param comes out identical. No argument means every\n// field, matching v1's no-`include` behaviour.\n//\n// Two display differences from v1 are expected and harmless, because both are widgets the console resolves\n// to the same control: a plain string publishes no `uiComponent` at all (the v2 model omits display defaults\n// so they can be reworded without a redeploy \u2014 `SINGLE_LINE_TEXT` is the console's fallback), and a number\n// publishes `NUMERIC_STEPPER` where v1 hand-wrote the legacy `NUMERIC`. `scope`, the only field the catalog\n// actually exposes, is byte-identical \u2014 see `__tests__/files-options-schema.test.ts`.\n//\n// \u26A0\uFE0F Imports `zod` directly, never `./zod`, to keep the dependency one-way. The authoring plugins used below\n// (`.label()`) are installed on zod's prototype by ./zod.ts, which imports THIS module \u2014 safe because a\n// factory can only be reached through the namespace that module builds, so the plugins are always in place\n// by the time one runs.\n\n// Kept in step with `FileScope` in ../../common/context-files.ts, which cannot be imported here: it pulls in\n// the HTTP client, and the params framework is compiled into the console's browser bundle. A test asserts\n// the two agree.\nconst SCOPE_VALUES = ['WORKSPACE', 'FLOW', 'EXECUTION'] as const\n\n// `scope` is the one field shared by all four groups \u2014 and the only one the catalog exposes to flow authors.\nconst scope = () => baseZod.enum(SCOPE_VALUES)\n .label('Scope')\n .describe('Storage scope: WORKSPACE (shared across flows), FLOW (this flow only), EXECUTION (this run only)')\n .default('FLOW')\n\nconst ttl = () => baseZod.number()\n .label('URL TTL (seconds)')\n .describe('How long the download URL remains valid')\n .optional()\n\nconst generateUrl = () => baseZod.boolean()\n .label('Generate download URL')\n .describe('Include a pre-signed download URL in the response')\n .default(true)\n\n// A group is a table of FACTORIES, not of schemas: each call hands the service a fresh object, so one\n// service's `.optional()` or `.describe()` can never reach another's.\ntype FieldTable = Record<string, () => baseZod.ZodType>\n\nconst UPLOAD_FIELDS = {\n scope,\n filename: () => baseZod.string()\n .label('Filename')\n .describe('Custom filename (defaults to the original name if omitted)')\n .optional(),\n ttl,\n objectTtl: () => baseZod.number()\n .label('File TTL (seconds)')\n .describe('How long the file is kept in storage (omit for permanent storage)')\n .optional(),\n overwrite: () => baseZod.boolean()\n .label('Overwrite existing')\n .describe('Replace the file if one with the same name already exists')\n .optional(),\n generateUrl,\n} satisfies FieldTable\n\nconst LIST_FIELDS = {\n scope,\n limit: () => baseZod.number()\n .label('Limit')\n .describe('Maximum number of files to return')\n .optional(),\n ttl: () => baseZod.number()\n .label('URL TTL (seconds)')\n .describe('How long the download URLs remain valid')\n .optional(),\n generateUrl: () => baseZod.boolean()\n .label('Generate download URLs')\n .describe('Include pre-signed download URLs in the response')\n .default(true),\n cursor: () => baseZod.string()\n .label('Cursor')\n .describe('Pagination cursor from a previous response')\n .optional(),\n} satisfies FieldTable\n\nconst GET_FIELDS = {\n scope,\n ttl,\n generateUrl,\n} satisfies FieldTable\n\nconst DELETE_FIELDS = {\n scope,\n} satisfies FieldTable\n\n// The object a factory returns: the picked fields, each typed as its own factory declares it.\ntype Group<T extends FieldTable, K extends keyof T> = baseZod.ZodObject<{ [P in K]: ReturnType<T[P]> }>\n\n/**\n * Build one group, optionally subset to `include`.\n *\n * Two details reproduce v1 exactly (`jsdoc-parser/src/index.ts` `buildParam`): the result keeps the\n * CANONICAL field order rather than the order of `include` \u2014 so `['filename', 'scope']` still publishes\n * `scope` first \u2014 and an empty list is treated as no list, i.e. every field.\n *\n * An unknown name THROWS, where v1 silently published an empty object. A typo there is invisible until a\n * flow author opens the block and finds no settings at all; here it fails while the service registers, which\n * is the only moment anyone is looking.\n */\nfunction group<T extends FieldTable, K extends keyof T & string>(\n typeName: string,\n widget: FrGroupToken,\n table: T,\n include?: readonly K[]\n): Group<T, K> {\n const names = Object.keys(table)\n\n if (include?.length) {\n const unknown = include.filter(name => !names.includes(name))\n\n if (unknown.length) {\n throw new Error(\n `z.${ typeName }(): unknown field${ unknown.length > 1 ? 's' : '' } ${ unknown.map(n => `'${ n }'`).join(', ') }. ` +\n `Available fields: ${ names.join(', ') }.`\n )\n }\n }\n\n const selected = include?.length ? names.filter(name => include.includes(name as K)) : names\n\n const shape = Object.fromEntries(selected.map(name => [name, table[name]()]))\n\n // The group names itself in the published model (`uiComponent: { type: 'FILE_UPLOAD_OPTIONS' }`), so a\n // consumer can tell the platform's own options object from an anonymous one a service declared and render\n // it accordingly. See ../model/field-mapper.ts, which publishes it at every depth.\n return baseZod.object(shape).meta({ frWidget: widget }) as Group<T, K>\n}\n\nexport type FilesUploadOptionsField = keyof typeof UPLOAD_FIELDS & string\nexport type FilesListOptionsField = keyof typeof LIST_FIELDS & string\nexport type FilesGetOptionsField = keyof typeof GET_FIELDS & string\nexport type FilesDeleteOptionsField = keyof typeof DELETE_FIELDS & string\n\n/** Options for `ctx.files.uploadFile()`. `z.filesUploadOptions(['scope'])` is the form the catalog uses. */\nexport function filesUploadOptions<K extends FilesUploadOptionsField = FilesUploadOptionsField>(\n include?: readonly K[]\n): Group<typeof UPLOAD_FIELDS, K> {\n return group('filesUploadOptions', FlowExtensionParamWidgetTypes.FILE_UPLOAD_OPTIONS as FrGroupToken, UPLOAD_FIELDS, include)\n}\n\n/** Options for `ctx.files.list()`. */\nexport function filesListOptions<K extends FilesListOptionsField = FilesListOptionsField>(\n include?: readonly K[]\n): Group<typeof LIST_FIELDS, K> {\n return group('filesListOptions', FlowExtensionParamWidgetTypes.FILE_LIST_OPTIONS as FrGroupToken, LIST_FIELDS, include)\n}\n\n/** Options for `ctx.files.get()`. */\nexport function filesGetOptions<K extends FilesGetOptionsField = FilesGetOptionsField>(\n include?: readonly K[]\n): Group<typeof GET_FIELDS, K> {\n return group('filesGetOptions', FlowExtensionParamWidgetTypes.FILE_GET_OPTIONS as FrGroupToken, GET_FIELDS, include)\n}\n\n/** Options for `ctx.files.delete()`. */\nexport function filesDeleteOptions<K extends FilesDeleteOptionsField = FilesDeleteOptionsField>(\n include?: readonly K[]\n): Group<typeof DELETE_FIELDS, K> {\n return group('filesDeleteOptions', FlowExtensionParamWidgetTypes.FILE_DELETE_OPTIONS as FrGroupToken, DELETE_FIELDS, include)\n}\n\n// Exported for the test that keeps this table and `FileScope` in step.\nexport { SCOPE_VALUES }\n", "import type { JsonValue } from './types'\n\n// The two declarable primitives JSON has no room for. Boxed rather than stringified, so decoding can tell a\n// `BigInt('12')` from the string `'12'` \u2014 which matters, because `z.bigint()` rejects the string.\n\nconst isBox = (value: unknown, key: '$bigint' | '$date'): boolean =>\n !!value && typeof value === 'object' && key in (value as Record<string, unknown>)\n\n/** A declared value (a `.default()`, an enum member, a constraint bound) on its way out. */\nexport function toJsonValue(value: unknown): JsonValue {\n if (typeof value === 'bigint') {\n return { $bigint: value.toString() }\n }\n\n if (value instanceof Date) {\n return { $date: value.toISOString() }\n }\n\n if (Array.isArray(value)) {\n return value.map(toJsonValue)\n }\n\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, toJsonValue(inner)]))\n }\n\n return value as JsonValue\n}\n\n/** The same value on its way back in. */\nexport function fromJsonValue(value: JsonValue): unknown {\n if (isBox(value, '$bigint')) {\n return BigInt((value as { $bigint: string }).$bigint)\n }\n\n if (isBox(value, '$date')) {\n return new Date((value as { $date: string }).$date)\n }\n\n if (Array.isArray(value)) {\n return value.map(fromJsonValue)\n }\n\n if (value && typeof value === 'object') {\n return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, fromJsonValue(inner)]))\n }\n\n return value\n}\n", "import type { AnyZod } from '../schema/introspect'\nimport type { CheckJSON, FieldType, JsonValue, RegexJSON } from './types'\nimport { fromJsonValue, toJsonValue } from './values'\n\n// The constraint table, read in both directions from one place so encode and decode cannot drift.\n//\n// zod v4 keeps checks in `_zod.def.checks`, each with its own `_zod.def.check` discriminator. The names are\n// zod's internals rather than its API: `.min()` on a string is `min_length`, on a number `greater_than`, and\n// `.int()` is a `number_format`. Decoding goes back through the public API, where `.min()` covers both.\n\ninterface ZodCheckDef {\n check?: string\n format?: string\n minimum?: unknown\n maximum?: unknown\n length?: unknown\n value?: unknown\n inclusive?: boolean\n pattern?: RegExp\n prefix?: string\n suffix?: string\n includes?: string\n error?: unknown\n}\n\nconst defOf = (check: unknown): ZodCheckDef =>\n ((check as { _zod?: { def?: ZodCheckDef } } | undefined)?._zod?.def ?? {})\n\n/**\n * An author's own message, if they wrote one.\n *\n * zod normalizes a string message into a function, so the string is only reachable by CALLING it. A message\n * the author wrote as a function reads the issue and cannot be replayed here \u2014 the call is guarded and the\n * pipeline's own wording applies instead.\n */\nexport function messageOf(source: { error?: unknown }): string | undefined {\n const { error } = source\n\n if (typeof error === 'string') {\n return error\n }\n\n if (typeof error !== 'function') {\n return undefined\n }\n\n try {\n const produced = (error as (issue: unknown) => unknown)({ code: 'custom', input: undefined })\n\n return typeof produced === 'string' ? produced : undefined\n } catch {\n return undefined\n }\n}\n\nconst regexToJson = (pattern: RegExp): RegexJSON => ({ source: pattern.source, flags: pattern.flags })\n\n/** One zod check \u2192 its wire form, or `undefined` when it cannot cross (a function-backed check). */\nfunction encodeCheck(check: unknown): CheckJSON | undefined {\n const def = defOf(check)\n const message = messageOf(def)\n const at = (kind: CheckJSON['kind'], value?: JsonValue, exclusive?: true): CheckJSON => ({\n kind,\n ...(value === undefined ? {} : { value }),\n ...(exclusive ? { exclusive } : {}),\n ...(message ? { message } : {}),\n })\n\n switch (def.check) {\n // strings and arrays\n case 'min_length':\n return at('min', toJsonValue(def.minimum))\n case 'max_length':\n return at('max', toJsonValue(def.maximum))\n case 'length_equals':\n return at('length', toJsonValue(def.length))\n\n // numbers and bigints\n case 'greater_than':\n return at('min', toJsonValue(def.value), def.inclusive ? undefined : true)\n case 'less_than':\n return at('max', toJsonValue(def.value), def.inclusive ? undefined : true)\n case 'multiple_of':\n return at('multipleOf', toJsonValue(def.value))\n case 'number_format':\n // `.int()` \u2014 a format check rather than a range one.\n return def.format === 'safeint' || def.format === 'int32' ? at('int') : undefined\n\n // the string sub-formats that are checks rather than types\n case 'string_format':\n if (def.format === 'regex' && def.pattern) {\n return at('regex', regexToJson(def.pattern))\n }\n\n if (def.format === 'starts_with') {\n return at('startsWith', def.prefix ?? '')\n }\n\n if (def.format === 'ends_with') {\n return at('endsWith', def.suffix ?? '')\n }\n\n if (def.format === 'includes') {\n return at('includes', def.includes ?? '')\n }\n\n return undefined\n\n default:\n return undefined\n }\n}\n\nexport interface EncodedChecks {\n checks: CheckJSON[]\n unsupported: string[]\n}\n\n/** Every check a core schema carries. What cannot cross is NAMED rather than silently dropped. */\nexport function encodeChecks(core: AnyZod | undefined): EncodedChecks {\n const declared = (core?._zod?.def?.checks as unknown[] | undefined) ?? []\n const checks: CheckJSON[] = []\n const unsupported: string[] = []\n\n for (const check of declared) {\n const encoded = encodeCheck(check)\n\n if (encoded) {\n checks.push(encoded)\n continue\n }\n\n const def = defOf(check)\n\n unsupported.push(`check:${ def.check ?? 'unknown' }${ def.format ? `/${ def.format }` : '' }`)\n }\n\n return { checks, unsupported }\n}\n\n// A zod schema with the constraint methods the table above needs. Structural, so this file stays independent\n// of zod's generics \u2014 the methods exist on the string/number/array types that carry these checks.\ntype Constrainable = {\n min?: (value: never, message?: string) => Constrainable\n max?: (value: never, message?: string) => Constrainable\n gt?: (value: never, message?: string) => Constrainable\n lt?: (value: never, message?: string) => Constrainable\n length?: (value: number, message?: string) => Constrainable\n int?: (message?: string) => Constrainable\n multipleOf?: (value: never, message?: string) => Constrainable\n regex?: (pattern: RegExp, message?: string) => Constrainable\n startsWith?: (value: string, message?: string) => Constrainable\n endsWith?: (value: string, message?: string) => Constrainable\n includes?: (value: string, message?: string) => Constrainable\n}\n\n/**\n * Re-apply one wire check to a rebuilt schema.\n *\n * `type` decides nothing about WHICH method to call \u2014 `.min()` is `.min()` on a string, a number and an\n * array \u2014 it only guards the numeric-only ones. A check whose method is missing on this type is skipped\n * rather than thrown: a schema decoded slightly loose is the documented failure mode.\n */\nexport function applyCheck(schema: unknown, check: CheckJSON, type: FieldType): unknown {\n const target = schema as Constrainable\n const value = check.value === undefined ? undefined : fromJsonValue(check.value)\n const numeric = type === 'number' || type === 'bigint'\n const call = (\n method: keyof Constrainable,\n arg?: unknown\n ): unknown => {\n const fn = target[method]\n\n return typeof fn === 'function'\n ? (fn as (...args: unknown[]) => unknown).call(target, ...(arg === undefined ? [] : [arg]), check.message)\n : schema\n }\n\n switch (check.kind) {\n case 'min':\n return call(check.exclusive && numeric ? 'gt' : 'min', value)\n case 'max':\n return call(check.exclusive && numeric ? 'lt' : 'max', value)\n case 'length':\n return call('length', value)\n case 'int':\n return call('int')\n case 'multipleOf':\n return call('multipleOf', value)\n case 'regex': {\n const { source, flags } = (check.value ?? { source: '', flags: '' }) as unknown as RegexJSON\n\n return call('regex', new RegExp(source, flags))\n }\n case 'startsWith':\n return call('startsWith', value)\n case 'endsWith':\n return call('endsWith', value)\n case 'includes':\n return call('includes', value)\n default:\n return schema\n }\n}\n", "import type { FrWidgetToken } from '../widget-types'\n\n// The wire form of a declared schema.\n//\n// Written by the runner when a service is deployed or installed, stored on the definition, and read back by\n// the console \u2014 which rebuilds real zod from it (see ./decode.ts) and runs the SAME pipeline the runner runs.\n// That is the whole point: a form reports exactly the errors an execution would, because both sides validate\n// against the same schema rather than against two hand-kept descriptions of it.\n//\n// Hand-rolled rather than `z.toJSONSchema()`, because JSON Schema drops everything that makes a FlowRunner\n// field a FlowRunner field \u2014 `.label()`, `.shared()`, `.dictionary()`, `.map()`, an author's own check\n// message \u2014 and rebuilding zod from it would need a JSON-Schema interpreter anyway.\n\n// A value that survives JSON. The two primitives that do not are boxed (see ./encode.ts).\nexport type JsonValue =\n | string | number | boolean | null\n | { $bigint: string }\n | { $date: string }\n | JsonValue[]\n | { [key: string]: JsonValue }\n\n/** A constraint the author declared. `min`/`max` cover both length and magnitude \u2014 zod spells them alike. */\nexport interface CheckJSON {\n kind: 'min' | 'max' | 'length' | 'int' | 'multipleOf' | 'regex' | 'startsWith' | 'endsWith' | 'includes'\n value?: JsonValue\n // `.min(3)` is inclusive, `.gt(3)` is not. Absent means inclusive.\n exclusive?: true\n // An author's own message (`z.string().min(3, 'Too short')`), so the console words the failure the way the\n // runtime will. Absent \u21D2 the pipeline's own wording applies.\n message?: string\n}\n\n/** A serialized regex \u2014 `RegExp` itself is not JSON. Indexable so it satisfies `JsonValue`. */\nexport interface RegexJSON {\n [key: string]: JsonValue\n source: string\n flags: string\n}\n\n// The metadata an author attached. Native zod keys drive display; `fr`-prefixed keys are FlowRunner's.\nexport interface MetaJSON {\n title?: string\n description?: string\n examples?: JsonValue[]\n frShared?: boolean\n frWidget?: FrWidgetToken\n frSecret?: boolean\n frDictionary?: { id: string; dependsOn: string[] }\n frLabels?: Record<string, string>\n}\n\nexport type FieldType =\n | 'string' | 'number' | 'bigint' | 'boolean' | 'date'\n | 'enum' | 'literal' | 'object' | 'array' | 'record' | 'union'\n /**\n * Anything the encoder does not model \u2014 and also where a declared `z.any()` / `z.unknown()` legitimately\n * lands, since \"validates nothing\" is exactly what those two declare. The `unsupported` breadcrumb is what\n * separates the two cases: a modelling gap carries `['type:\u2026']`, a declared pass-through carries nothing.\n *\n * Decodes to `z.unknown()` either way, so it validates nothing.\n */\n | 'unknown'\n\nexport interface FieldJSON {\n name: string\n type: FieldType\n // A zod format token: 'email' | 'url' | 'ipv4' | 'datetime' | 'safeint' | \u2026\n format?: string\n // Accepts `undefined` / `null`. Recorded separately because they are separate modifiers, and the pipeline's\n // absence policy is derived by PROBING the rebuilt schema rather than by reading these back.\n optional?: true\n nullable?: true\n default?: JsonValue\n checks?: CheckJSON[]\n // enum members, or the literal's own value(s).\n values?: JsonValue[]\n meta?: MetaJSON\n // A schema-level message (`z.email('must be an email')`).\n message?: string\n // type === 'object'\n properties?: FieldJSON[]\n // type === 'array'\n element?: FieldJSON\n /**\n * type === 'union' \u2014 every declared branch, in declaration order.\n *\n * All of them are carried, not just the first. The first decides what the console DRAWS, but the rebuilt\n * schema has to accept everything the author's does: `json/types.ts`'s one-directional invariant is that a\n * decoded schema is never STRICTER than the author's, and encoding one branch would break it \u2014 the form\n * would reject a shape execution accepts.\n */\n options?: FieldJSON[]\n /**\n * type === 'record' \u2014 the schema its VALUES are held to. Keys are not modelled: the runtime only ever\n * walks a record's values (see ../schema/coerce.ts), and a decoded `z.record` therefore accepts any string\n * key, which keeps it no stricter than the author's.\n */\n value?: FieldJSON\n /**\n * What could not cross the wire \u2014 `['check:overwrite']`, `['wrapper:prefault']`, `['format:xyz']`.\n *\n * Functions cannot be serialized, so `.refine()`, `.transform()`, `.trim()` and friends are dropped. The\n * invariant that follows is deliberate and one-directional: **a decoded schema is never STRICTER than the\n * author's**. The console may therefore accept a value the runtime later rejects, but never reject one the\n * runtime would accept \u2014 and the runtime re-validates every invocation, so it stays the authority.\n */\n unsupported?: string[]\n}\n\nexport interface ParamsSchemaJSON {\n // Bumped only for a breaking change to the shapes above. Stored payloads outlive the code that wrote them:\n // a definition is encoded once at deploy time and decoded by whatever console version is live later.\n v: 1\n fields: FieldJSON[]\n}\n\nexport const SCHEMA_JSON_VERSION = 1 as const\n", "import { z } from '../zod'\nimport { applyCheck } from './checks'\nimport { type FieldJSON, type ParamsSchemaJSON, SCHEMA_JSON_VERSION } from './types'\nimport { fromJsonValue } from './values'\n\n// Wire \u2192 zod. Rebuilt through the PUBLIC zod API (and through the FlowRunner-extended `z`, so `.meta()`\n// carries `frWidget` / `frDictionary` / `frLabels` back), which is what makes the result indistinguishable from\n// the author's own schema as far as the pipeline is concerned.\n\ntype AnySchema = { meta?: (value: Record<string, unknown>) => AnySchema }\n\n// A zod factory that takes an optional message, as every one of these does.\ntype Factory = (message?: string) => unknown\n\n/**\n * `format` \u2192 the constructor that produces it.\n *\n * Rebuilt with the real helper rather than as `z.string().regex(...)`, because the pipeline reads the format\n * token back off the schema \u2014 it is what picks the widget and what words an `invalid_format` failure.\n *\n * Guarded with `typeof`, so a token this zod release does not know degrades to a plain string instead of\n * throwing at decode time. Stored payloads outlive the code that wrote them.\n */\nconst FORMAT_FACTORIES: Record<string, Factory | undefined> = {\n url : z.url,\n email : z.email,\n hostname : z.hostname,\n e164 : z.e164,\n emoji : z.emoji,\n uuid : z.uuid,\n guid : z.guid,\n nanoid : z.nanoid,\n cuid : z.cuid,\n cuid2 : z.cuid2,\n ulid : z.ulid,\n xid : z.xid,\n ksuid : z.ksuid,\n base64 : z.base64,\n base64url: z.base64url,\n hex : z.hex,\n jwt : z.jwt,\n ipv4 : z.ipv4,\n ipv6 : z.ipv6,\n cidrv4 : z.cidrv4,\n cidrv6 : z.cidrv6,\n // z.iso.* \u2014 validated STRINGS, unlike the `date` core type below.\n datetime : z.iso?.datetime,\n date : z.iso?.date,\n time : z.iso?.time,\n duration : z.iso?.duration,\n}\n\nfunction decodeString(field: FieldJSON): unknown {\n const factory = field.format ? FORMAT_FACTORIES[field.format] : undefined\n\n return typeof factory === 'function' ? factory(field.message) : z.string(field.message)\n}\n\nfunction decodeBase(field: FieldJSON): unknown {\n switch (field.type) {\n case 'string':\n return decodeString(field)\n\n case 'number':\n // `z.int()` is `z.number()` carrying the `safeint` format, and the pipeline reads that token back.\n return field.format === 'safeint' || field.format === 'int32' ? z.int(field.message) : z.number(field.message)\n\n case 'bigint':\n return z.bigint(field.message)\n\n case 'boolean':\n return z.boolean(field.message)\n\n case 'date':\n return z.date(field.message)\n\n case 'enum':\n return z.enum((field.values ?? []).map(fromJsonValue) as string[], field.message)\n\n case 'literal':\n return z.literal((field.values ?? []).map(fromJsonValue) as (string | number | boolean)[], field.message)\n\n case 'object':\n return z.object(Object.fromEntries((field.properties ?? []).map(inner => [inner.name, decodeField(inner)])))\n\n case 'array':\n return z.array((field.element ? decodeField(field.element) : z.unknown()) as never)\n\n // Every branch, so the rebuild accepts everything the author's union does. A single branch would make\n // the console's form stricter than execution, which ./types.ts forbids in that direction.\n case 'union': {\n const options = (field.options ?? []).map(decodeField)\n\n return options.length ? z.union(options as never) : z.unknown()\n }\n\n // Keys are open, as they are in the declaration: only the VALUES were modelled (see ./types.ts), so the\n // rebuild accepts any string key and stays no stricter than the author's.\n case 'record':\n return z.record(z.string(), (field.value ? decodeField(field.value) : z.unknown()) as never)\n\n default:\n // A field the encoder could not model validates nothing rather than rejecting everything \u2014 the\n // decoded schema is never stricter than the author's (see ./types.ts).\n return z.unknown()\n }\n}\n\n/**\n * One field, rebuilt.\n *\n * Order is load-bearing:\n * 1. the base type \u2014 a format helper, not a hand-rolled regex\n * 2. the author's checks \u2014 `.min()`, `.regex()`, \u2026\n * 3. `.meta()` LAST of the three, because a check clones the schema and metadata does not follow the clone\n * 4. the modifiers, canonically: nullable \u2192 optional \u2192 default\n *\n * Step 4's canonical order is why the wire form can record modifiers as flags \u2014 see ./encode.ts.\n */\nexport function decodeField(field: FieldJSON): unknown {\n let schema = decodeBase(field)\n\n for (const check of field.checks ?? []) {\n schema = applyCheck(schema, check, field.type)\n }\n\n if (field.meta) {\n schema = (schema as AnySchema).meta?.(fromJsonValue(field.meta as never) as Record<string, unknown>) ?? schema\n }\n\n const modifiers = schema as {\n nullable: () => typeof modifiers\n optional: () => typeof modifiers\n default: (value: unknown) => typeof modifiers\n }\n\n let wrapped = modifiers\n\n if (field.nullable) {\n wrapped = wrapped.nullable()\n }\n\n if (field.optional) {\n wrapped = wrapped.optional()\n }\n\n if (field.default !== undefined) {\n wrapped = wrapped.default(fromJsonValue(field.default))\n }\n\n return wrapped\n}\n\n/**\n * A whole stored schema, rebuilt as the `z.object` every slot must be. Nothing usable in \u21D2 `undefined` out,\n * which callers already treat as \"this slot declares nothing\".\n *\n * An envelope whose `v` this build does not know is refused rather than read as if it were the current\n * shape. Stored payloads outlive the code that wrote them \u2014 a definition is encoded once at deploy time and\n * decoded by whatever is deployed later \u2014 so a future `v: 2` would otherwise be silently misread field by\n * field. Refusing degrades to \"no schema\" and the caller falls back to the legacy projection, which is the\n * same direction every other loss in this codec takes (see ./types.ts).\n */\nexport function decodeParams(json: ParamsSchemaJSON | null | undefined): unknown {\n if (!json?.fields || json.v !== SCHEMA_JSON_VERSION) {\n return undefined\n }\n\n return z.object(Object.fromEntries(json.fields.map(field => [field.name, decodeField(field)])))\n}\n", "import { type AnyZod, innerOf, inspect, MAX_UNWRAP_DEPTH, shapeEntries, TRANSPARENT_WRAPPERS } from '../schema/introspect'\nimport { encodeChecks, messageOf } from './checks'\nimport { type FieldJSON, type FieldType, type MetaJSON, type ParamsSchemaJSON, SCHEMA_JSON_VERSION } from './types'\nimport { toJsonValue } from './values'\n\n// zod \u2192 wire. Reads the same `_zod.def` internals the rest of the framework reads (see ../schema/introspect).\n\n/**\n * The core types with a wire form of their own.\n *\n * Kept in step with `SUPPORTED_TYPES` (../schema/assert-supported-schema.ts) \u2014 the set registration holds an\n * author to. `any` and `unknown` are supported declarations that deliberately have no form here: they model\n * \"anything\", which is what the `unknown` wire type already means, so they encode to it WITHOUT an\n * `unsupported` breadcrumb (see `problemsFor`).\n */\nconst FIELD_TYPES = new Set<string>([\n 'string', 'number', 'bigint', 'boolean', 'date', 'enum', 'literal', 'object', 'array', 'record',\n])\n\n// `union` is not in FIELD_TYPES: `inspect()` resolves a union to its first branch, so it never arrives as a\n// declared type. It is detected by the branch list instead (see `encodeField`).\nconst UNION_TYPE = 'union' as FieldType\n\n// Declarations whose whole content is \"no constraint\". They encode as `unknown` legitimately, not as a gap.\nconst PASS_THROUGH_TYPES = new Set(['any', 'unknown'])\n\n// Wrappers whose effect the wire form records as a flag, and the one that cannot be recorded at all.\nconst WRAPPERS = new Set(['optional', 'nullable', 'default'])\n\ninterface Unwrapped {\n optional: boolean\n nullable: boolean\n defaultValue: unknown\n hasDefault: boolean\n unsupported: string[]\n}\n\n/**\n * Peel the modifier chain, recording WHICH modifiers were present rather than their order.\n *\n * This walk answers only \"which absence modifiers were declared\". **It does not decide the core type** \u2014\n * `inspect()` does, and `encodeField` reads it from there. Keeping a second opinion on the core here is what\n * let this module fall behind the rest of the framework once already: it kept its own narrower wrapper set,\n * so every declaration the type surface legitimized (`.readonly()`, `.pipe()`, `z.lazy()`, `.nonoptional()`,\n * `z.record()`) still crossed the wire as `unknown` while the published model had it right.\n *\n * Order is safe to lose because the pipeline derives its absence policy by probing the schema for the forms\n * it accepts (see ../schema/field-plan.ts), and the canonical order ./decode.ts rebuilds in preserves that\n * set for every combination \u2014 `.optional().nullable()` and `.nullable().optional()` accept the same things.\n */\nfunction unwrap(schema: AnyZod): Unwrapped {\n const result: Unwrapped = {\n optional: false,\n nullable: false,\n defaultValue: undefined,\n hasDefault: false,\n unsupported: [],\n }\n\n let current: AnyZod | undefined = schema\n // `.nonoptional()` re-asserts a requirement over whatever it wraps \u2014 mirrors ../schema/field-plan.ts.\n let sealed = false\n // The same bound `inspect()` puts on its own peel, for the same reason: a `z.lazy()` whose getter returns\n // another wrapper would unwrap forever, and nothing legitimate nests modifiers anywhere near this deep.\n let depth = 0\n\n while (current?._zod && depth++ < MAX_UNWRAP_DEPTH) {\n const def = current._zod.def ?? {}\n const type = def.type as string\n\n if (type === 'nonoptional') {\n sealed = true\n current = def.innerType as AnyZod\n continue\n }\n\n /**\n * Look STRAIGHT THROUGH the modifiers that say nothing about absence \u2014 the same set `inspect()` and\n * `declaredAbsence` look through.\n *\n * Without this the walk stopped at the first one and lost every flag beneath it:\n * `z.string().optional().readonly()` encoded as a plain required string, so the console rebuilt a schema\n * that DEMANDED a value the runner accepts as absent \u2014 a form that can never be saved, and a violation\n * of the one-directional invariant in ./types.ts. The core type was moved to `inspect()` and this walk\n * was left behind; it is the same drift, one function along.\n */\n if (TRANSPARENT_WRAPPERS.has(type)) {\n current = innerOf(def, type)\n continue\n }\n\n if (sealed) {\n break\n }\n\n if (!WRAPPERS.has(type)) {\n // `.prefault()` runs before parsing rather than in place of an absent value \u2014 a different contract, so\n // it is named as unsupported instead of being flattened into `default`.\n if (type === 'prefault' || type === 'nullish') {\n result.unsupported.push(`wrapper:${ type }`)\n current = def.innerType as AnyZod\n continue\n }\n\n break\n }\n\n if (type === 'optional') {\n result.optional = true\n }\n\n if (type === 'nullable') {\n result.nullable = true\n }\n\n if (type === 'default' && !result.hasDefault) {\n result.hasDefault = true\n result.defaultValue = def.defaultValue\n }\n\n current = def.innerType as AnyZod\n }\n\n return result\n}\n\n// Author metadata, dropping the keys that carry no meaning on the wire. `frLabels` values are declared by the\n// author and may be any JSON; `frDictionary` is a plain ref.\nfunction encodeMeta(meta: Record<string, unknown>): MetaJSON | undefined {\n const encoded = toJsonValue(meta) as MetaJSON\n\n return Object.keys(encoded).length ? encoded : undefined\n}\n\n// enum members live in a `{ key: value }` map; a literal keeps its own `values` array.\nfunction encodeValues(core: AnyZod | undefined, type: FieldType): FieldJSON['values'] {\n if (type === 'enum') {\n const entries = (core?._zod?.def?.entries as Record<string, unknown> | undefined) ?? {}\n\n return Object.values(entries).map(toJsonValue)\n }\n\n if (type === 'literal') {\n const values = (core?._zod?.def?.values as unknown[] | undefined) ?? []\n\n return values.map(toJsonValue)\n }\n\n return undefined\n}\n\n/**\n * One declared field \u2192 its wire form.\n *\n * `seen` holds the declarations this field is currently INSIDE \u2014 the ancestors on the walk, not everything\n * already encoded \u2014 so a schema that legitimately appears twice side by side is still encoded twice. It is\n * added before descending and removed after, which makes the check below a cycle test rather than a\n * deduplication.\n */\nexport function encodeField(name: string, schema: AnyZod, seen: Set<unknown> = new Set()): FieldJSON {\n /**\n * A self-referential declaration contains itself, so the structural walk below has no bottom.\n *\n * `const Tree = z.lazy(() => z.union([z.string(), z.array(Tree)]))` encodes its union, whose array branch\n * has `Tree` as its element, whose union has an array branch\u2026 \u2014 and since a `z.lazy()` getter REBUILDS its\n * schema on every call, each level allocates a fresh one and the stack is gone in milliseconds. That was\n * FR-3600: a `RangeError` naming no extension, method or parameter, with the extension never registering.\n * The recursion is structural rather than data-driven, so remembering the ancestors is enough to stop it.\n *\n * The wire form has no way to SAY \"and here it is again\" \u2014 ./decode.ts rebuilds a finite schema \u2014 so the\n * repeat is encoded as the pass-through it has to become, with a breadcrumb saying why. Everything above\n * the cycle still crosses intact: `Tree` publishes as the string its first branch declares, and the parts\n * of the declaration that are not recursive keep their own types.\n */\n if (seen.has(schema)) {\n return { name, type: 'unknown', unsupported: ['recursion'] }\n }\n\n seen.add(schema)\n\n const { optional, nullable, defaultValue, hasDefault, unsupported } = unwrap(schema)\n // The core, and the type of it, from the one place that decides that for the whole framework.\n const ins = inspect(schema)\n const core = ins.core\n const declaredType = ins.branches ? UNION_TYPE : ins.resolvedType ?? 'unknown'\n const type = (ins.branches || FIELD_TYPES.has(declaredType) ? declaredType : 'unknown') as FieldType\n // `core` is a union's FIRST BRANCH, so its format/checks/message describe that branch and not the union.\n // Encoding them onto the union node would hand `decodeField` constraints to apply to a `ZodUnion`: today\n // they no-op because a union has no `.min()`, which is luck rather than design \u2014 the first one that did\n // map to a real method would make the rebuild reject what a later branch accepts. The branches carry their\n // own constraints in `options`, which is where they belong.\n const isUnion = !!ins.branches\n const format = isUnion ? undefined : core?._zod?.def?.format as string | undefined\n const { checks, unsupported: checkIssues } = isUnion ? { checks: [], unsupported: [] } : encodeChecks(core)\n const meta = encodeMeta(ins.meta as Record<string, unknown>)\n const message = isUnion ? undefined : messageOf((core?._zod?.def ?? {}) as { error?: unknown })\n const values = encodeValues(core, type)\n const problems = [...unsupported, ...checkIssues]\n\n // `unknown` reached by a declaration that MEANS \"anything\" is the wire form working, not failing.\n if (type === 'unknown' && !PASS_THROUGH_TYPES.has(declaredType)) {\n problems.push(`type:${ declaredType }`)\n }\n\n const encoded: FieldJSON = {\n name,\n type,\n ...(format ? { format } : {}),\n ...(optional ? { optional: true as const } : {}),\n ...(nullable ? { nullable: true as const } : {}),\n ...(hasDefault ? { default: toJsonValue(defaultValue) } : {}),\n ...(checks.length ? { checks } : {}),\n ...(values?.length ? { values } : {}),\n ...(meta ? { meta } : {}),\n ...(message ? { message } : {}),\n ...(type === 'object' ? { properties: shapeEntries(core).map(([key, inner]) => encodeField(key, inner, seen)) } : {}),\n ...(type === 'array' ? { element: encodeField('', core?._zod?.def?.element as AnyZod, seen) } : {}),\n ...(type === 'record' ? { value: encodeField('', core?._zod?.def?.valueType as AnyZod, seen) } : {}),\n ...(ins.branches ? { options: ins.branches.map(branch => encodeField('', branch, seen)) } : {}),\n ...(problems.length ? { unsupported: problems } : {}),\n }\n\n // Off the walk again: the field is fully encoded, so this declaration is no longer an ancestor of anything.\n seen.delete(schema)\n\n return encoded\n}\n\n/**\n * A whole declared slot \u2192 its wire form. `null` for an undeclared slot, which is legal everywhere: a method\n * with no params publishes no schema rather than an empty one.\n *\n * Takes `unknown` because this is a boundary: callers hold a schema through whichever view they happen to\n * have (`Params.scheme`, an author's `z.object`, a decoded rebuild), and none of those structural views are\n * assignable to each other. Narrowing once here beats a cast at every call site.\n */\nexport function encodeParams(scheme: unknown): ParamsSchemaJSON | null {\n const schema = scheme as AnyZod | undefined\n\n if (!schema?._zod) {\n return null\n }\n\n return {\n v: SCHEMA_JSON_VERSION,\n fields: shapeEntries(schema).map(([name, field]) => encodeField(name, field)),\n }\n}\n", "import { InvalidCriteriaError, InvalidMethodInputError, MissingMethodParamError } from '../../errors'\nimport { type FailFn, MethodParams, parseSchema } from '../params'\nimport type { ZodSchema } from '../types'\n\n// One invocation's `methodData`, and the two ways the runner reads it.\n//\n// A method's input is keyed by its declared param names (see the console's execution controller). SYSTEM\n// methods carry a single well-known param, helper methods a `payload`. Pulling one out and validating it are\n// separate failures on purpose:\n// \u2022 the param is absent \u2192 MissingMethodParamError \u2014 the CALL is malformed\n// \u2022 the param's value is invalid \u2192 InvalidMethodInputError \u2014 the VALUE is malformed, with issue paths\n// relative to that param\n// Criteria always fail as InvalidCriteriaError so the console can point at the dependent fields instead of\n// reporting the whole call as broken; the two `invalid*` factories below are how a caller picks which.\n\nexport class MethodInput {\n constructor(\n readonly serviceId: string,\n readonly methodName: string,\n private readonly data: Record<string, unknown> = {}\n ) {}\n\n // Extract a declared param. Absent is loud rather than silently defaulted \u2014 a missing param means a\n // malformed call, and failing here surfaces it at the source.\n require<T>(param: string): T {\n const value = (this.data ?? {})[param]\n\n if (value == null) {\n throw new MissingMethodParamError(this.serviceId, param)\n }\n\n return value as T\n }\n\n /**\n * Extract a declared param and validate its value against the schema that owns it.\n *\n * An OBJECT schema \u2014 every runtime-owned wrapper (`callbackObject`, `invocation`, `payload`) \u2014 goes\n * through the same per-field pipeline every author-declared slot uses, so `.optional()` means one thing\n * everywhere: a blank arrives as absence whether the host sent `null`, `''` or nothing at all.\n *\n * That consistency is the point. While these wrappers were parsed by a bare `safeParse`, `.optional()`\n * rejected `null` here while accepting it everywhere else, and each field had to be remembered as\n * `.nullish()` the first time a host sent a null \u2014 which is how `state` on the OAuth callback stayed\n * broken for a non-PKCE provider, where the console legitimately has no verifier to hand back.\n *\n * `carryUnknown` preserves the passthrough these schemas declare with `z.looseObject`: a host may send\n * fields a given milestone does not model yet, and dropping them silently would be worse.\n */\n parseField<T>(param: string, schema?: ZodSchema): T {\n const value = this.require<unknown>(param)\n const fail = this.invalidInput(param)\n\n // A wrapper that is not an object at all fails as the WRAPPER, not field by field: iterating declared\n // fields over a string would report \"\u00ABSearch\u00BB must be a string\" for a payload that was never an object.\n const isObject = !!value && typeof value === 'object' && !Array.isArray(value)\n\n if (!schema?.shape || !isObject) {\n return parseSchema<T>(schema, value, fail, param)\n }\n\n return MethodParams.of(schema).normalize<Record<string, unknown>>(\n value as Record<string, unknown>,\n fail,\n { carryUnknown: true }\n ) as T\n }\n\n // \u2500\u2500 failure identities, for the slots a caller parses itself \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // `target` names the slot that failed \u2014 a param name, or 'params' / 'triggerData' for the whole input.\n invalidInput(target: string): FailFn {\n return issues => {\n throw new InvalidMethodInputError(this.serviceId, this.methodName, target, issues)\n }\n }\n\n invalidCriteria(): FailFn {\n return issues => {\n throw new InvalidCriteriaError(this.serviceId, this.methodName, issues)\n }\n }\n}\n", "import type { ExecutionContext } from './context/execution-context'\nimport { MethodInput } from './context/method-input'\nimport type { Extension } from './extension'\nimport type { SharedExtensionMethod } from './model/model-types'\n\n// One callable method of an extension. Every kind \u2014 action, dictionary, generated loader, SYSTEM seam \u2014\n// answers the same three questions, which is the whole dispatch and model-build contract:\n//\n// toModel() what the console/flow-engine sees in `methodsMap`\n// validate(input) what this kind accepts, and how a bad call fails\n// execute(params) what running it does\n//\n// So dispatch is a map lookup plus `execute(validate(input))`, and building the definition is one pass over\n// `extension.methods()`. Adding a kind means adding a subclass, not editing a chain of `if`s.\n\nexport abstract class ExtensionMethod {\n constructor(protected readonly extension: Extension) {}\n\n // The published method name \u2014 the key in `methodsMap`, and what the flow engine invokes.\n abstract get name(): string\n\n // The v1 kind token: ACTION | DICTIONARY | POLLING_TRIGGER | REALTIME_TRIGGER | SYSTEM |\n // SAMPLE_RESULT_LOADER | PARAM_SCHEMA_DEFINITION.\n abstract get registerAs(): string\n\n abstract toModel(): SharedExtensionMethod\n\n // Extra OAuth scopes this method needs. Only the author-declared kinds can carry any; the generated\n // loaders and the SYSTEM seams never do.\n get oauth2Scopes(): string[] {\n return []\n }\n\n /**\n * Whether this method appears in the published `methodsMap`. Almost always yes \u2014 but the realtime refresh\n * seam is callable whether or not the author declared a `refresh` handler (the runtime answers `{}` when\n * they did not), while only being ADVERTISED when they did. Callable and advertised are therefore two\n * different questions, and this is the second one.\n */\n get published(): boolean {\n return true\n }\n\n // Turn raw `methodData` into whatever `execute` takes. The default accepts anything \u2014 a kind with no\n // declared input has nothing to check.\n validate(methodData: Record<string, unknown>): unknown {\n return methodData\n }\n\n // May return a promise or a plain value; the caller awaits either way, so a synchronous handler is not\n // forced through an async wrapper.\n abstract execute(params: unknown, ctx: ExecutionContext): unknown\n\n protected input(methodData: Record<string, unknown>): MethodInput {\n return new MethodInput(this.extension.id, this.name, methodData)\n }\n}\n", "// Version-agnostic config constants shared by v1 and v2.\n\nexport type ServiceConfigsValues = Record<string, unknown>\n\nexport const ServiceConfigItemTypes = {\n STRING: 'string',\n BOOL: 'bool',\n DATE: 'date',\n CHOICE: 'choice',\n TEXT: 'text',\n} as const\n\nexport type ServiceConfigItemType = (typeof ServiceConfigItemTypes)[keyof typeof ServiceConfigItemTypes]\n", "import { ServiceConfigItemTypes } from '../../common/constants'\nimport type { ConfigItem } from '../../common/types'\nimport { absenceOf } from '../params/schema/field-plan'\nimport { type AnyZod, deriveWidget, inspect, type Inspected, shapeEntries } from '../params/schema/introspect'\nimport { labelOf } from '../params/schema/labels'\nimport { FlowExtensionParamWidgetTypes } from '../params/widget-types'\nimport type { SharedExtensionMetaInfoArg, SharedExtensionParam } from './model-types'\n\n// One declared field \u2194 one entry of the v1 output model. Every mapping the runner performs on a single zod\n// field lives here; ./params-model.ts iterates a `Params`' declared shape and collects what these return.\n//\n// Where a field's DISPLAY metadata (label / uiComponent / dictionary / dependsOn) ends up depends on its\n// depth, matching the v1 jsdoc-parser layout: a top-level param carries structure only and publishes its\n// display side through `metaInfo.args` (\u2192 fieldToArg), while a nested property inlines both. That is the\n// single `nested` flag below \u2014 the two used to be near-duplicate functions.\n//\n// Display metadata is published EXACTLY as the author wrote it. What a bare `z.email()` should show when the\n// author wrote no label and no description is decided when the field is RENDERED, from the schema the\n// definition now carries (see ../params/schema/defaults.ts) \u2014 so those defaults can be reworded without\n// every service having to be redeployed to pick the change up.\n\n// The description as the console should show it: the author's, or nothing. An empty string is meaningful \u2014\n// it says \"the author documented nothing here\", which is what lets the renderer supply its own default.\nconst descriptionOf = (schema: AnyZod): string =>\n inspect(schema).meta.description || ''\n\n/**\n * Whether the console should mark the field mandatory \u2014 asked of the SAME probe the runtime resolves absence\n * with (see ../params/schema/field-plan.ts), not of the wrapper chain.\n *\n * They are two ways of asking one question, and only one of them is authoritative: the runtime decides what\n * it accepts by parsing, so publishing anything else lets the form demand a value the runner would have let\n * through, or leave optional one it will reject. Reading the same answer is what keeps the two from drifting.\n */\nconst isRequired = (schema: AnyZod): boolean =>\n absenceOf(schema).absence === 'required'\n\n// Whether the field is one of the platform's own param groups \u2014 an object that arrived with a widget token\n// on it, which only ../params/files-options.ts produces.\nconst isParamGroup = (ins: Inspected): boolean =>\n ins.coreType === 'object' && !!ins.meta.frWidget\n\nexport interface FieldToParamOptions {\n nested?: boolean\n}\n\nexport function fieldToParam(name: string, schema: AnyZod, options: FieldToParamOptions = {}): SharedExtensionParam {\n const ins = inspect(schema)\n const widget = deriveWidget(ins)\n\n const param: SharedExtensionParam = {\n name,\n required: isRequired(schema),\n description: descriptionOf(schema),\n type: widget.paramType,\n }\n\n /**\n * A platform param GROUP names itself on the param, at every depth.\n *\n * It is the one piece of `uiComponent` that is not display metadata derived from the field's type \u2014 the\n * rule below, which sends a top-level param's display side to `metaInfo.args`, is about how ONE CONTROL\n * should look. This says what the param IS: the runtime's own file-options object rather than an anonymous\n * `z.object` a service happened to declare (see ../params/files-options.ts). A consumer that walks\n * `bodyParams` alone can act on it, and it survives being nested inside another object.\n *\n * It is published through `metaInfo.args` as well, by `fieldToArg` below, because that is where the flow\n * designer reads a top-level param's `uiComponent` from.\n */\n if (isParamGroup(ins) && widget.uiComponent) {\n param.uiComponent = widget.uiComponent\n }\n\n if (options.nested) {\n param.label = labelOf(name, schema)\n\n if (widget.uiComponent) {\n param.uiComponent = widget.uiComponent\n }\n\n if (ins.meta.frDictionary) {\n param.dictionary = ins.meta.frDictionary.id\n\n if (ins.meta.frDictionary.dependsOn.length) {\n param.dependsOn = ins.meta.frDictionary.dependsOn\n }\n }\n }\n\n if (ins.defaultValue !== undefined) {\n param.defaultValue = ins.defaultValue\n }\n\n if (widget.items) {\n param.items = widget.items\n }\n\n // Only a z.object HAS declared properties. A record publishes as OBJECT too, but its keys are open \u2014 there\n // is no field list to publish, and an empty one would read as \"this object has no fields\".\n if (ins.coreType === 'object') {\n param.properties = propertiesOf(ins.core)\n }\n\n /**\n * A LIST of objects publishes the ELEMENT's fields as the param's own `properties`, next to `items`.\n *\n * That looks redundant next to `items.type` until you see what reads it: the console decides a list is a\n * repeatable row editor rather than a single expression box by testing `paramDefinition.properties` (see\n * flow-builder's `getAvailableStructureTypes`), and then renders one input per entry in it. With only\n * `items: { type: 'OBJECT' }` to go on it has no fields to draw and falls back to one text box \u2014 the\n * author's declared structure is simply invisible.\n *\n * The legacy JSDoc format has always published it this way, so this is the v2 model matching a contract\n * the console already implements rather than a new one.\n */\n if (widget.paramType === 'LIST' && widget.items?.type === 'OBJECT') {\n param.properties = propertiesOf(elementOf(ins.core))\n }\n\n return param\n}\n\n// The element schema of a declared array, past its own modifiers.\nfunction elementOf(arrayCore: AnyZod | undefined): AnyZod | undefined {\n const element = arrayCore?._zod?.def?.element as AnyZod | undefined\n\n return element ? inspect(element).core : undefined\n}\n\n// The nested properties of an OBJECT field \u2014 its core schema's own shape, each mapped in nested form.\nexport function propertiesOf(objectCore: AnyZod | undefined): SharedExtensionParam[] {\n return shapeEntries(objectCore).map(([name, schema]) => fieldToParam(name, schema, { nested: true }))\n}\n\n// The display half of a top-level param: what `metaInfo.args[name]` carries.\nexport function fieldToArg(name: string, schema: AnyZod): SharedExtensionMetaInfoArg {\n const ins = inspect(schema)\n const arg: SharedExtensionMetaInfoArg = { label: labelOf(name, schema) }\n // A LIST's display metadata describes ONE ITEM, not the list: the console renders a repeatable editor and\n // draws each entry with this control. So `z.array(z.enum([\u2026]))` advertises the element's dropdown, and\n // `z.array(z.string().dictionary(ref))` advertises the element's dictionary \u2014 which is what the console\n // has always expected here, and what makes a list of choices a list of choices rather than a text box.\n const display = ins.coreType === 'array' ? elementDisplay(ins) : ins\n const widget = deriveWidget(display)\n\n if (display.meta.frDictionary) {\n arg.dictionary = display.meta.frDictionary.id\n\n if (display.meta.frDictionary.dependsOn.length) {\n arg.dependsOn = display.meta.frDictionary.dependsOn\n }\n }\n\n if (widget.uiComponent) {\n arg.uiComponent = widget.uiComponent\n }\n\n return arg\n}\n\n/**\n * What a list should ADVERTISE: its element's declaration, falling back to the list's own.\n *\n * The fallback matters for `z.array(z.string()).dictionary(ref)` \u2014 binding the list rather than the element\n * reads just as naturally to an author, and both forms mean the same thing.\n */\nfunction elementDisplay(list: Inspected): Inspected {\n const element = list.core?._zod?.def?.element as AnyZod | undefined\n const inspected = element ? inspect(element) : undefined\n\n if (!inspected) {\n return list\n }\n\n return inspected.meta.frDictionary || deriveWidget(inspected).uiComponent\n ? inspected\n : { ...inspected, meta: { ...inspected.meta, ...list.meta } }\n}\n\n// \u2500\u2500 config items \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction toConfigType(coreType: string, frWidget?: string): ConfigItem['type'] {\n if (coreType === 'boolean') {\n return ServiceConfigItemTypes.BOOL\n }\n\n if (coreType === 'date') {\n return ServiceConfigItemTypes.DATE\n }\n\n if (coreType === 'enum') {\n return ServiceConfigItemTypes.CHOICE\n }\n\n if (frWidget === FlowExtensionParamWidgetTypes.MULTI_LINE_TEXT) {\n return ServiceConfigItemTypes.TEXT\n }\n\n return ServiceConfigItemTypes.STRING\n}\n\n// A config field \u2192 the v1 `ConfigItem` the console renders. `.shared()` marks it global rather than per-app.\nexport function fieldToConfigItem(name: string, schema: AnyZod): ConfigItem {\n const ins = inspect(schema)\n\n return {\n name,\n type: toConfigType(ins.coreType, ins.meta.frWidget),\n shared: !!ins.meta.frShared,\n required: isRequired(schema),\n description: descriptionOf(schema),\n label: labelOf(name, schema),\n defaultValue: ins.defaultValue,\n options: ins.coreType === 'enum' ? ((ins.core.options as string[]) ?? []) : [],\n }\n}\n\n", "import type { SharedExtensionMetaInfoArg, SharedExtensionParam } from './model-types'\n\n// Shared pieces of the v1 method model \u2014 the shapes several kinds emit identically.\n\n// Every helper-route method (dictionaries, the generated loaders, and the OAuth/trigger SYSTEM methods) is\n// invoked with a single wrapper param \u2014 `payload` or `invocation` \u2014 via the console's helper-method route.\n// The method itself carries no per-field model params, so its input scheme is just that wrapper.\nexport function opaqueParam(name: string, type = 'OBJECT'): SharedExtensionParam {\n return { name, required: false, description: '', type }\n}\n\n// Describe a method's params in `metaInfo.args` (mirroring how actions describe theirs) so the method\n// advertises a labelled input instead of an empty `args` \u2014 consumers (AI tools, the console UI) rely on it.\nexport function argsFromParams(params: SharedExtensionParam[]): Record<string, SharedExtensionMetaInfoArg> {\n const args: Record<string, SharedExtensionMetaInfoArg> = {}\n\n for (const param of params) {\n const arg: SharedExtensionMetaInfoArg = { label: param.label ?? param.name }\n\n if (param.uiComponent) {\n arg.uiComponent = param.uiComponent\n }\n\n if (param.dictionary) {\n arg.dictionary = param.dictionary\n }\n\n if (param.dependsOn) {\n arg.dependsOn = param.dependsOn\n }\n\n args[param.name] = arg\n }\n\n return args\n}\n", "import type { ConfigItem } from '../../common/types'\nimport type { ConfigParams, MethodParams, Params } from '../params'\nimport { fieldToArg, fieldToConfigItem, fieldToParam, propertiesOf } from './field-mapper'\nimport { opaqueParam } from './method-model'\nimport type { SharedExtensionMetaInfoArg, SharedExtensionParam } from './model-types'\n\n// The v1 output model of a declared schema \u2014 `bodyParams`, `metaInfo.args`, `ConfigItem[]`.\n//\n// These are free functions rather than methods on `Params` on purpose: the params framework is consumed by\n// the console as well as the runner (it renders and validates the same schemas in the browser), and the v1\n// console model is meaningless there. So the framework describes a schema, and this module \u2014 which belongs\n// to the runner's output model \u2014 projects that description into the shapes v1 consumers expect.\n\n// Top-level params: structure only. Display metadata is published through `toArgs()`.\nexport function toBodyParams(params: MethodParams): SharedExtensionParam[] {\n return params.fields().map(([name, schema]) => fieldToParam(name, schema))\n}\n\n// `metaInfo.args` \u2014 the display half of the same fields.\nexport function toArgs(params: MethodParams): Record<string, SharedExtensionMetaInfoArg> {\n return Object.fromEntries(params.fields().map(([name, schema]) => [name, fieldToArg(name, schema)]))\n}\n\n/**\n * Top-level params rendered OPAQUELY: one entry per declared key, typed from its schema, with no recursion\n * into nested properties and nothing ever marked required.\n *\n * This is the SYSTEM seam's model shape. Those methods are invoked by the runtime with a whole invocation\n * object, never through a rendered form, so publishing their internals would be noise \u2014 and the v1 seam they\n * must stay compatible with declares them exactly this way.\n */\nexport function toOpaqueBodyParams(params: MethodParams): SharedExtensionParam[] {\n return params.fields().map(([name, schema]) => opaqueParam(name, fieldToParam(name, schema).type))\n}\n\n// The same fields as NESTED properties: display metadata inlined on each one. Used where the schema\n// describes the inside of a wrapper param rather than a method's top level (e.g. a dictionary's `criteria`\n// inside its `payload`).\nexport function toProperties(params: Params): SharedExtensionParam[] {\n return propertiesOf(params.scheme as Parameters<typeof propertiesOf>[0])\n}\n\n// The config descriptions the console renders. `.shared()` fields are marked shared (\u2192\n// sharedConfigDescriptions downstream); the rest are per-app.\nexport function toConfigItems(config: ConfigParams): ConfigItem[] {\n return config.fields().map(([name, schema]) => fieldToConfigItem(name, schema))\n}\n", "import { sampleResultLoaderName } from './loaders/loader-owner'\nimport type { SharedExtensionMetaInfo } from './model/model-types'\nimport type { MethodParams } from './params'\n\n// A declared `result`. Not a schema slot \u2014 it is a UNION zod cannot represent (a literal sample value, a zod\n// schema carrying `.example()`, or a loader fn that derives the sample from the current params), so it gets\n// its own wrapper rather than living in ../params.ts.\n//\n// It answers two questions for every owner (actions, both trigger kinds, dictionaries): what `returnType`\n// the method publishes, and where its sample comes from \u2014 an inline `sampleResult`, or a generated\n// SAMPLE_RESULT_LOADER method the console calls with the params filled in so far.\n\n// The loader is called with the owner's handler bag plus the current params.\ntype LoaderFn = (bag: object) => unknown\n\nfunction inferReturnType(value: unknown): string {\n if (Array.isArray(value)) {\n return 'LIST'\n }\n\n if (value && typeof value === 'object') {\n return 'OBJECT'\n }\n\n if (typeof value === 'string') {\n return 'STRING'\n }\n\n return 'VOID'\n}\n\nfunction isZodSchema(value: unknown): boolean {\n return !!value && typeof value === 'object' && '_zod' in (value as Record<string, unknown>)\n}\n\n// A zod `result` carries its sample in `.example(...)` \u2192 native `meta.examples`; the last one wins.\nfunction schemaExample(schema: { meta?: () => { examples?: unknown[] } | undefined }): unknown {\n const examples = typeof schema.meta === 'function' ? schema.meta()?.examples : undefined\n\n return examples && examples.length ? examples[examples.length - 1] : null\n}\n\nexport class ResultSpec {\n static from(result: unknown): ResultSpec {\n return new ResultSpec(result)\n }\n\n private constructor(private readonly declared: unknown) {}\n\n // The sample is not knowable statically \u2014 it comes from a generated loader method instead.\n get isLoader(): boolean {\n return typeof this.declared === 'function'\n }\n\n get returnType(): string {\n if (this.isLoader || isZodSchema(this.declared)) {\n return 'OBJECT'\n }\n\n return inferReturnType(this.declared)\n }\n\n // Whether anything was declared at all \u2014 a dictionary with no `result` still publishes OBJECT.\n get isDeclared(): boolean {\n return this.declared !== undefined\n }\n\n // The inline sample, or null when there is none (loader form, or an undeclared result).\n #sampleResult(): unknown {\n if (this.isLoader) {\n return null\n }\n\n if (isZodSchema(this.declared)) {\n return schemaExample(this.declared as { meta?: () => { examples?: unknown[] } | undefined })\n }\n\n return this.declared ?? null\n }\n\n // The `metaInfo` halves that describe the output. In loader form the sample is replaced by a reference to\n // the generated method, which depends on every param of its owner (any of them can change the shape).\n toMetaInfo(ownerId: string, params: MethodParams): Pick<SharedExtensionMetaInfo, 'sampleResult' | 'sampleResultLoader'> {\n if (this.isLoader) {\n return {\n sampleResult: null,\n sampleResultLoader: { methodName: sampleResultLoaderName(ownerId), dependsOn: params.keys() },\n }\n }\n\n return { sampleResult: this.#sampleResult(), sampleResultLoader: null }\n }\n\n // Run the loader form against a handler bag carrying the current params.\n async runLoader(bag: object): Promise<unknown> {\n return (this.declared as LoaderFn)(bag)\n }\n}\n", "import type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { dynamicParamsLoaderName, type LoaderOwner } from '../loaders/loader-owner'\nimport { ExtensionMethod } from '../method'\nimport type { SharedExtensionMetaInfo, SharedExtensionMethod } from '../model/model-types'\nimport { toArgs, toBodyParams } from '../model/params-model'\nimport { encodeParams, MethodParams } from '../params'\nimport { ResultSpec } from '../result'\nimport type { ActionProps, AnySchema, HandlerBag } from '../types'\n\n// An action \u2014 the primary operation a service exposes (07-actions.md). Its `params` are the method input\n// itself, keyed by param name, and its handler receives them already parsed.\n\nexport class ActionMethod extends ExtensionMethod implements LoaderOwner {\n readonly params: MethodParams\n readonly result: ResultSpec\n readonly dynamicParamsCriteria: MethodParams\n\n constructor(extension: Extension, private readonly props: ActionProps) {\n super(extension)\n\n this.params = MethodParams.of(props.params, { serviceId: extension.id, kind: 'action', itemId: props.id, slot: 'params' })\n this.result = ResultSpec.from(props.result)\n this.dynamicParamsCriteria = MethodParams.of(props.dynamicParams?.criteria, {\n serviceId: extension.id,\n kind: 'action',\n itemId: props.id,\n slot: 'dynamicParams.criteria',\n })\n }\n\n get id(): string {\n return this.props.id\n }\n\n get name(): string {\n return this.props.id\n }\n\n get registerAs(): string {\n return 'ACTION'\n }\n\n get category(): string {\n return this.props.category\n }\n\n get oauth2Scopes(): string[] {\n return this.props.oauth2Scopes ?? []\n }\n\n hasDynamicParams(): boolean {\n return !!this.props.dynamicParams\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Normalize, coerce and validate against the declared `params` \u2014 the same pipeline every other declared\n * slot uses, so an author expresses optionality in the schema and nowhere else.\n *\n * An action with `dynamicParams` carries the input's undeclared keys through, since its runtime-generated\n * top-level fields are not in the static schema.\n */\n validate(methodData: Record<string, unknown>): Record<string, unknown> {\n return this.params.normalize<Record<string, unknown>>(\n methodData,\n this.input(methodData).invalidInput('params'),\n { carryUnknown: this.hasDynamicParams() }\n )\n }\n\n execute(params: Record<string, unknown>, ctx: ExecutionContext): unknown {\n return this.props.execute(ctx.bagWith({ params }))\n }\n\n // Resolve the extra top-level param fields this action generates at runtime (see 03-parameters.md).\n resolveDynamicParams(bag: HandlerBag & { criteria: Record<string, unknown> }): AnySchema | Promise<AnySchema> {\n return this.props.dynamicParams!.resolve(bag)\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toModel(): SharedExtensionMethod {\n const [ownStart, ownEnd] = this.props.appearanceColors ?? []\n const [colorStart, colorEnd] = this.extension.appearanceColors\n const metaInfo: SharedExtensionMetaInfo = {\n args: toArgs(this.params),\n ...this.result.toMetaInfo(this.id, this.params),\n }\n\n if (this.hasDynamicParams()) {\n metaInfo.dynamicParams = {\n methodName: dynamicParamsLoaderName(this.id),\n dependsOn: this.dynamicParamsCriteria.keys(),\n }\n }\n\n return {\n name: this.id,\n operationName: this.props.label,\n description: this.props.description || '',\n registerAs: this.registerAs,\n category: this.category,\n colorStart: ownStart ?? colorStart,\n colorEnd: ownEnd ?? colorEnd,\n customIcon: this.props.logo ?? '',\n returnType: this.result.returnType,\n queryParams: [],\n bodyParams: toBodyParams(this.params),\n paramsSchema: encodeParams(this.params.scheme),\n metaInfo,\n }\n }\n}\n", "import BLRequest from 'backendless-request'\n\nexport const FileScope = {\n WORKSPACE: 'WORKSPACE',\n FLOW: 'FLOW',\n EXECUTION: 'EXECUTION',\n} as const\n\nexport type FileScope = (typeof FileScope)[keyof typeof FileScope]\n\n// The scope namespace as handlers receive it (`filesScope` in the bag), so author code names a layer instead\n// of spelling the string: `files.list({ scope: filesScope.WORKSPACE })`.\nexport type FileScopes = typeof FileScope\n\ntype FileScopePath = 'workspace' | 'flow' | 'execution'\n\nfunction toScopePath(scope: FileScope): FileScopePath {\n return scope.toLowerCase() as FileScopePath\n}\n\ntype CollectionFn = (flowId: string | null, executionId: string | null) => string\ntype FileFn = (filename: string, flowId: string | null, executionId: string | null) => string\n\nconst collectionPathByScope: Record<FileScopePath, CollectionFn> = {\n workspace: () => '/workspace',\n flow: flowId => {\n if (!flowId) {\n throw new Error('Flow scope requires flowId')\n }\n\n return `/flow/${ flowId }`\n },\n execution: (flowId, executionId) => {\n if (!flowId || !executionId) {\n throw new Error('Execution scope requires flowId and executionId')\n }\n\n return `/flow/${ flowId }/execution/${ executionId }`\n },\n}\n\nconst filePathByScope: Record<FileScopePath, FileFn> = {\n workspace: filename => `/workspace/${ filename }`,\n flow: (filename, flowId) => {\n if (!flowId) {\n throw new Error('Flow scope requires flowId')\n }\n\n return `/flow/${ flowId }/${ filename }`\n },\n execution: (filename, flowId, executionId) => {\n if (!flowId || !executionId) {\n throw new Error('Execution scope requires flowId and executionId')\n }\n\n return `/flow/${ flowId }/execution/${ executionId }/${ filename }`\n },\n}\n\nexport interface FlowrunnerContextFilesOptions {\n serverURL: string\n appId: string\n apiKey: string\n //\n runtimeKey: string\n //\n flowId?: string | null\n executionId?: string | null\n //\n retrieveNewS3Token: (runtimeKey: string) => Promise<{\n filesS3Token: string\n }>\n}\n\nexport interface UploadFileOptions {\n scope?: FileScope\n filename?: string\n ttl?: number\n generateUrl?: boolean\n objectTtl?: number\n overwrite?: boolean\n}\n\nexport interface ListOptions {\n scope?: FileScope\n ttl?: number\n generateUrl?: boolean\n limit?: number\n cursor?: string\n}\n\nexport interface GetOptions {\n scope?: FileScope\n ttl?: number\n generateUrl?: boolean\n}\n\nexport interface DeleteOptions {\n scope?: FileScope\n}\n\nexport interface UploadResult {\n key: string\n filename: string\n url: string\n size: number\n urlExpiresAt: string\n objectExpiresAt: string | null\n overwritten: boolean\n}\n\nexport interface FileInfo {\n key: string\n filename: string\n url: string\n size: number\n createdAt: string\n urlExpiresAt: string\n objectExpiresAt: string | null\n}\n\nexport interface ListResult {\n files: FileInfo[]\n cursor: string | null\n hasMore: boolean\n}\n\nexport interface DeleteResult {\n key: string\n freedBytes: number\n deleted: boolean\n}\n\nexport interface UsageResult {\n workspaceId: string\n usedBytes: number\n quotaBytes: number\n usedFormatted: string\n quotaFormatted: string\n utilizationPercent: number\n fileCount: number\n}\n\n// The file-service contract as HANDLERS see it (`ctx.files`) \u2014 the five methods, nothing about transport.\n// `FlowrunnerContextFiles` below is the implementation that talks to the console; a host may supply its\n// own via `runServiceMethod({ createFiles })`, which is how an e2e harness points file storage at a local\n// S3 without the runner knowing. Keep this in step with the class.\nexport interface FilesApi {\n uploadFile(file: Buffer | Uint8Array, options?: UploadFileOptions): Promise<UploadResult>\n list(options?: ListOptions): Promise<ListResult>\n get(filename: string, options?: GetOptions): Promise<FileInfo>\n delete(filename: string, options?: DeleteOptions): Promise<DeleteResult>\n usage(): Promise<UsageResult>\n}\n\nfunction cleanParams(params: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(params).filter(([, v]) => v !== undefined && v !== null)\n )\n}\n\n// Minimal shape of the node `form-data` instance BLRequest.FormData produces at\n// runtime \u2014 its append(name, value, options) signature differs from the DOM type.\ntype MultipartForm = {\n append: (name: string, value: unknown, options?: { filename?: string }) => void\n}\n\nfunction appendFormParams(form: MultipartForm, params: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n form.append(key, String(value))\n }\n }\n}\n\nexport class FlowrunnerContextFiles implements FilesApi {\n appId: string\n apiKey: string\n runtimeKey: string\n serverURL: string\n flowId: string | null\n executionId: string | null\n retrieveNewS3Token: (runtimeKey: string) => Promise<{\n filesS3Token: string\n }>\n\n constructor({\n appId,\n apiKey,\n runtimeKey,\n serverURL,\n flowId,\n executionId,\n retrieveNewS3Token,\n }: FlowrunnerContextFilesOptions) {\n this.appId = appId\n this.apiKey = apiKey\n this.runtimeKey = runtimeKey\n this.serverURL = serverURL\n this.flowId = flowId ?? null\n this.executionId = executionId ?? null\n\n this.retrieveNewS3Token = retrieveNewS3Token\n }\n\n get base(): string {\n return `${ this.serverURL }/${ this.appId }/${ this.apiKey }/v1/files`\n }\n\n private collectionPath(scope: FileScopePath): string {\n return this.base + collectionPathByScope[scope](this.flowId, this.executionId)\n }\n\n private filePath(filename: string, scope: FileScopePath): string {\n return this.base + filePathByScope[scope](encodeURIComponent(filename), this.flowId, this.executionId)\n }\n\n private async resolveFilesS3Token(): Promise<string> {\n const { filesS3Token } = await this.retrieveNewS3Token(this.runtimeKey)\n\n return filesS3Token\n }\n\n private async request<T>(method: string, url: string, body?: unknown, params?: Record<string, unknown>): Promise<T> {\n const token = await this.resolveFilesS3Token()\n\n const httpMethod = method.toLowerCase() as 'get' | 'post' | 'put' | 'patch' | 'delete'\n\n let req = BLRequest[httpMethod](url)\n .set('Authorization', `Bearer ${ token }`)\n\n if (params) {\n req = req.query(cleanParams(params))\n }\n\n // `.form()` returns a chainable request; `.send()` returns a promise directly.\n // The request instance is itself thenable, so returning it awaits the response.\n if (BLRequest.FormData && body instanceof BLRequest.FormData) {\n return req.form(body as unknown as Record<string, unknown>) as unknown as Promise<T>\n }\n\n if (body) {\n return req.send(body) as Promise<T>\n }\n\n return req as unknown as Promise<T>\n }\n\n async uploadFile(file: Buffer | Uint8Array, options: UploadFileOptions = {}): Promise<UploadResult> {\n const { scope = FileScope.FLOW, filename, ttl, generateUrl = true, objectTtl, overwrite } = options\n const scopePath = toScopePath(scope)\n\n // BLRequest.FormData is the node `form-data` instance at runtime (see MultipartForm) \u2014\n // cast to that shape to append a Buffer + filename.\n const form = new BLRequest.FormData!() as unknown as MultipartForm\n\n form.append('file', Buffer.from(file), { filename: filename ?? 'file' })\n appendFormParams(form, { filename, ttl, generateUrl, objectTtl, overwrite })\n\n return this.request<UploadResult>('POST', this.collectionPath(scopePath), form)\n }\n\n async list(options: ListOptions = {}): Promise<ListResult> {\n const { scope = FileScope.FLOW, ttl, generateUrl, limit, cursor } = options\n const scopePath = toScopePath(scope)\n\n return this.request<ListResult>('GET', this.collectionPath(scopePath), undefined, cleanParams({\n ttl,\n generateUrl,\n limit,\n cursor,\n }))\n }\n\n async get(filename: string, options: GetOptions = {}): Promise<FileInfo> {\n const { scope = FileScope.FLOW, ttl, generateUrl } = options\n const scopePath = toScopePath(scope)\n\n return this.request<FileInfo>('GET', this.filePath(filename, scopePath), undefined, cleanParams({\n ttl,\n generateUrl,\n }))\n }\n\n async delete(filename: string, options: DeleteOptions = {}): Promise<DeleteResult> {\n const { scope = FileScope.FLOW } = options\n\n return this.request<DeleteResult>('DELETE', this.filePath(filename, toScopePath(scope)))\n }\n\n async usage(): Promise<UsageResult> {\n return this.request<UsageResult>('GET', `${ this.collectionPath('workspace') }/usage`)\n }\n}\n", "import type { Logger } from '../types'\n\n// Default runtime logger handed to service handlers as `logger`. Service code uses `logger.debug/info`\n// for redacted tracing; only warn/error surface to the console by default (matching the no-bare-console\n// policy). A host can supply its own Logger to route these elsewhere.\n \nexport const defaultLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n}\n \n", "import { FeatureNotEnabledError } from '../../errors'\n\n// Throwing proxies for opt-in features (oauth / files). When a feature isn't enabled, its slot in the\n// handler bag is a proxy that throws on ANY access \u2014 so accidental use fails loudly at the call site\n// instead of silently no-op'ing or reading `undefined`. See 10-files-api.md and 06-oauth2.md.\n\nexport function createThrowingProxy(feature: string, hint: string): Record<string, never> {\n const fail = (): never => {\n throw new FeatureNotEnabledError(feature, hint)\n }\n\n return new Proxy(\n {},\n {\n get(_target, prop) {\n // Let promise-unwrapping / stringification probe the proxy without throwing.\n if (prop === 'then' || prop === Symbol.toPrimitive || prop === Symbol.toStringTag) {\n return undefined\n }\n\n return fail()\n },\n apply: fail,\n has: fail,\n }\n ) as Record<string, never>\n}\n", "import type { ServiceConfigsValues } from '../../common/constants'\nimport { type FilesApi,FileScope, type FileScopes } from '../../common/context-files'\nimport type { Extension } from '../extension'\nimport type { OAuthBag } from '../oauth/types'\nimport type { HandlerBag, Logger } from '../types'\nimport { defaultLogger } from './logger'\nimport { createThrowingProxy } from './proxies'\n\n// One invocation's resolved surroundings, and the `bag` handlers see (07-actions.md): the resolved `config`,\n// the `initContext` return as `context`, `oauth`, the bound `apiRequest`, `files`, `filesScope`, `logger`,\n// and `helpers`.\n//\n// Everything is derived LAZILY and memoized per instance. That matters because the OAuth callback needs a\n// second context bound to the freshly-obtained token (`withAccessToken`), and used to rebuild the whole bag\n// from scratch each time it asked \u2014 resolving config, running `initContext` and re-running the `helpers`\n// factory up to three times per callback. Now each context resolves each of those once, and a differently\n// tokened context is an explicit second instance rather than an implicit rebuild.\n//\n// `toBag()` returns a PLAIN OBJECT. Author code never receives a class instance \u2014 that is the frozen\n// handler contract.\n\nexport interface ExecutionContextOptions {\n configs?: ServiceConfigsValues\n accessToken?: string\n logger?: Logger\n // Provisioned by the caller only when the extension declares `usesFileStorage`; otherwise the bag's\n // `files` slot is a proxy that throws on any access.\n files?: unknown\n}\n\nexport class ExecutionContext {\n readonly #extension: Extension\n readonly #options: ExecutionContextOptions\n\n #config?: Record<string, unknown>\n #context?: unknown\n #oauth?: OAuthBag\n #apiRequest?: HandlerBag['apiRequest']\n #bag?: HandlerBag\n\n constructor(extension: Extension, options: ExecutionContextOptions = {}) {\n this.#extension = extension\n this.#options = options\n }\n\n get logger(): Logger {\n return this.#options.logger ?? defaultLogger\n }\n\n get config(): Record<string, unknown> {\n this.#config ??= this.#extension.config.resolve(this.#options.configs)\n\n return this.#config\n }\n\n // The header access token plus its deserialized composite payload \u2014 or a throwing proxy when the\n // extension never declared oauth, so accidental use fails loudly at the call site.\n get oauth(): OAuthBag {\n this.#oauth ??= this.#extension.oauth\n ? this.#extension.oauth.buildBag(this.#options.accessToken)\n : (createThrowingProxy('oauth', 'declare ext.setupOauth2(...) first') as OAuthBag)\n\n return this.#oauth\n }\n\n // The scope names, so a handler writes `filesScope.WORKSPACE` instead of the bare string. Deliberately NOT\n // gated on `usesFileStorage`: it is a set of constants, not a capability, and it is useful for building a\n // scope value to pass around even where no file call happens. Reaching for `files` without the opt-in still\n // fails loudly on its own.\n get filesScope(): FileScopes {\n return FileScope\n }\n\n // The proxy stands in for the real client and throws on ANY access, so handlers see one type either way.\n get files(): FilesApi {\n return (this.#props.usesFileStorage && this.#options.files\n ? this.#options.files\n : createThrowingProxy('files', 'set usesFileStorage:true in createExtension first')) as FilesApi\n }\n\n get context(): unknown {\n this.#context ??= this.#props.initContext\n ? this.#props.initContext({ config: this.config, oauth: this.oauth })\n : {}\n\n return this.#context\n }\n\n // The author's own `apiRequest`, with `context` + `logger` injected so handlers don't pass them. Both are\n // read at CALL time, off this context.\n get apiRequest(): HandlerBag['apiRequest'] {\n if (!this.#props.apiRequest) {\n return undefined as unknown as HandlerBag['apiRequest']\n }\n\n this.#apiRequest ??= ((arg: Record<string, unknown>) =>\n (this.#props.apiRequest as (a: unknown) => unknown)({\n ...arg,\n context: this.context,\n logger: this.logger,\n })) as HandlerBag['apiRequest']\n\n return this.#apiRequest\n }\n\n // The bag every handler receives. Memoized: one bag per context, so the `helpers` factory runs once.\n toBag(): HandlerBag {\n if (this.#bag) {\n return this.#bag\n }\n\n const bag = {\n config: this.config,\n context: this.context,\n oauth: this.oauth,\n apiRequest: this.apiRequest,\n files: this.files,\n filesScope: this.filesScope,\n logger: this.logger,\n } as HandlerBag\n\n // Published before `helpers` is attached: the factory receives the bag it is about to complete, and\n // anything it captures sees the finished object.\n this.#bag = bag\n bag.helpers = this.#props.helpers ? this.#props.helpers(bag) : undefined\n\n return bag\n }\n\n // A handler's bag plus whatever its kind adds \u2014 `params`, `criteria`, `providerEventData`, \u2026 Always a\n // fresh object, so a handler cannot mutate the shared bag.\n bagWith<T extends object>(extra: T): HandlerBag & T {\n return { ...this.toBag(), ...extra }\n }\n\n // A sibling context bound to a different access token \u2014 the OAuth callback runs its identity lookup\n // against the token it just obtained. Everything else (config source, files client, logger) is shared.\n withAccessToken(accessToken?: string): ExecutionContext {\n return new ExecutionContext(this.#extension, { ...this.#options, accessToken })\n }\n\n get #props() {\n return this.#extension.props\n }\n}\n", "import { z } from '../params'\n\n// The console's helper-method route invokes a dictionary with `methodData = { payload }`, where the payload\n// is `{ search, cursor, criteria }`: `search` and `cursor` are universal (the runtime always provides them),\n// `criteria` carries the current values of the params this dictionary depends on. LOOSE, like every wrapper\n// the runtime owns \u2014 unmodelled fields ride through rather than being silently dropped.\nexport const DictionaryPayloadSchema = z.looseObject({\n search: z.string().optional(),\n cursor: z.union([z.string(), z.number()]).nullish(),\n criteria: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport interface DictionaryPayload {\n search?: string\n cursor?: unknown\n criteria: Record<string, unknown>\n}\n", "import { InvalidDictionaryOutputScheme } from '../../errors'\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { ExtensionMethod } from '../method'\nimport type { SharedExtensionMethod, SharedExtensionParam } from '../model/model-types'\nimport { toProperties } from '../model/params-model'\nimport { MethodParams } from '../params'\nimport { ResultSpec } from '../result'\nimport type { DictionaryProps, DictionaryResult } from '../types'\nimport { type DictionaryPayload, DictionaryPayloadSchema } from './payload-schema'\n\n// A dictionary \u2014 the dynamic option source behind a param (05-dictionaries.md). Invoked through the\n// console's helper-method route while a user fills a form, and answers `{ items, cursor }`.\n\nexport class DictionaryMethod extends ExtensionMethod {\n readonly criteria: MethodParams\n readonly result: ResultSpec\n\n constructor(extension: Extension, private readonly props: DictionaryProps) {\n super(extension)\n\n this.criteria = MethodParams.of(props.criteria, {\n serviceId: extension.id,\n kind: 'dictionary',\n itemId: props.id,\n slot: 'criteria',\n })\n this.result = ResultSpec.from(props.result)\n }\n\n get id(): string {\n return this.props.id\n }\n\n get name(): string {\n return this.props.id\n }\n\n get registerAs(): string {\n return 'DICTIONARY'\n }\n\n // Optional on a dictionary (unlike an action), so `''` when undeclared. Also satisfies `LoaderOwner`, so a\n // generated loader inherits it the same way an action's does.\n get category(): string {\n return this.props.category ?? ''\n }\n\n get oauth2Scopes(): string[] {\n return this.props.oauth2Scopes ?? []\n }\n\n // The params a dictionary-bound field depends on \u2014 derived from the criteria, never hand-written.\n get dependsOn(): string[] {\n return this.criteria.keys()\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // Two-stage: the `{ search, cursor, criteria }` envelope the runtime owns, then the author-declared\n // criteria through the shared pipeline \u2014 reported as a criteria failure so the console can point at the\n // dependent fields rather than the whole call.\n validate(methodData: Record<string, unknown>): DictionaryPayload {\n const input = this.input(methodData)\n const payload = input.parseField<DictionaryPayload>('payload', DictionaryPayloadSchema)\n const criteria = this.criteria.normalize<Record<string, unknown>>(payload.criteria, input.invalidCriteria())\n\n return {\n search: payload.search,\n cursor: payload.cursor,\n criteria,\n }\n }\n\n // Authors may answer with the bare item list; the runtime contract is `{ cursor, items }`.\n async execute(payload: DictionaryPayload, ctx: ExecutionContext): Promise<DictionaryResult> {\n const result = await this.props.execute(ctx.bagWith(payload))\n\n if (Array.isArray(result)) {\n return { cursor: null, items: result } as unknown as DictionaryResult\n }\n\n if (result && typeof result === 'object' && Array.isArray(result.items)) {\n return { cursor: result.cursor, items: result.items }\n }\n\n throw new InvalidDictionaryOutputScheme(this.extension.id, this.name)\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toModel(): SharedExtensionMethod {\n const [colorStart, colorEnd] = this.extension.appearanceColors\n\n return {\n name: this.id,\n // Dictionaries are surfaced to the UI and to AI tools, so they need a human label. Fall back to the id.\n operationName: this.props.label ?? this.id,\n description: this.props.description || '',\n registerAs: this.registerAs,\n category: this.category,\n colorStart,\n colorEnd,\n customIcon: '',\n // A dictionary returns a `{ items, cursor }` OBJECT; default to OBJECT when no explicit sample is given.\n returnType: this.result.isDeclared ? this.result.returnType : 'OBJECT',\n queryParams: [],\n bodyParams: [this.#payloadParam()],\n // The `payload` wrapper's display label lives here (the bodyParam itself stays label-free, matching v1).\n metaInfo: {\n args: { payload: { label: 'Payload' } },\n ...this.result.toMetaInfo(this.id, this.criteria),\n },\n }\n }\n\n // Describe the full payload shape so the method advertises a complete, labelled input scheme (nested\n // props inline their own labels \u2014 mirroring the v1 jsdoc-parser layout).\n #payloadParam(): SharedExtensionParam {\n const properties: SharedExtensionParam[] = [\n { name: 'search', required: false, description: 'Optional search string to filter results.', type: 'STRING', label: 'Search' },\n { name: 'cursor', required: false, description: 'Pagination offset for retrieving the next page of results.', type: 'STRING', label: 'Cursor' },\n ]\n\n const criteriaProps = toProperties(this.criteria)\n\n if (criteriaProps.length) {\n properties.push({\n name: 'criteria',\n required: false,\n description: 'Current values of the params this dictionary depends on.',\n type: 'OBJECT',\n properties: criteriaProps,\n })\n }\n\n return {\n name: 'payload',\n required: false,\n description: 'Contains optional search string and pagination cursor.',\n type: 'OBJECT',\n properties,\n }\n }\n}\n", "import { z } from '../params'\n\n// The console's helper-method route invokes a loader with `methodData = { payload }`, and a loader's\n// payload is `{ criteria }` \u2014 the current values of the params it depends on. LOOSE, like every wrapper the\n// runtime owns: the console may send fields a given milestone doesn't model yet, and dropping them silently\n// would be worse than carrying them through.\nexport const LoaderPayloadSchema = z.looseObject({\n criteria: z.record(z.string(), z.unknown()).optional(),\n})\n", "import type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { ExtensionMethod } from '../method'\nimport { argsFromParams, opaqueParam } from '../model/method-model'\nimport type { SharedExtensionMethod, SharedExtensionParam } from '../model/model-types'\nimport { toBodyParams } from '../model/params-model'\nimport { MethodParams } from '../params'\nimport {\n dynamicParamsLoaderName,\n type DynamicParamsOwner,\n type LoaderOwner,\n sampleResultLoaderName,\n} from './loader-owner'\nimport { LoaderPayloadSchema } from './payload-schema'\n\n// The methods the RUNTIME generates from what an author declared \u2014 never written by hand:\n//\n// result: fn \u2192 a SAMPLE_RESULT_LOADER the console calls to preview the output shape\n// dynamicParams \u2192 a PARAM_SCHEMA_DEFINITION that resolves extra top-level param fields\n//\n// Both are invoked with `{ payload: { criteria } }` \u2014 the values of the params they depend on. They obey the\n// same policy as every other declared slot, so a sample-result loader (whose criteria ARE its owner's params)\n// only resolves once the owner's required params are filled.\n\nabstract class LoaderMethod extends ExtensionMethod {\n constructor(extension: Extension, protected readonly owner: LoaderOwner) {\n super(extension)\n }\n\n // The params this loader's criteria are checked against.\n protected abstract get criteria(): MethodParams\n\n validate(methodData: Record<string, unknown>): Record<string, unknown> {\n const input = this.input(methodData)\n const payload = input.parseField<{ criteria?: Record<string, unknown> }>('payload', LoaderPayloadSchema)\n\n // Undeclared keys ride through: the node's other params come along, and the owner's `result` fn may read\n // fields its `dynamicParams` generated.\n return this.criteria.normalize(payload.criteria, input.invalidCriteria(), { carryUnknown: true })\n }\n\n // Internal (SYSTEM-like): no icon, no colours, no sample. Its params are left opaque in the model \u2014 it is\n // invoked with `{ criteria }` at runtime, not through a rendered form.\n toModel(): SharedExtensionMethod {\n const bodyParams: SharedExtensionParam[] = [opaqueParam('payload')]\n\n return {\n name: this.name,\n operationName: this.name,\n description: '',\n registerAs: this.registerAs,\n category: this.owner.category,\n colorStart: '',\n colorEnd: '',\n customIcon: undefined,\n returnType: this.returnType,\n queryParams: [],\n bodyParams,\n metaInfo: { args: argsFromParams(bodyParams), sampleResult: null, sampleResultLoader: null },\n }\n }\n\n protected abstract get returnType(): string\n}\n\n// Derives the sample output from the params filled in so far \u2014 for shapes that aren't known statically\n// (user-defined fields, a record whose columns depend on which table was picked).\nexport class SampleResultLoaderMethod extends LoaderMethod {\n get name(): string {\n return sampleResultLoaderName(this.owner.id)\n }\n\n get registerAs(): string {\n return 'SAMPLE_RESULT_LOADER'\n }\n\n protected get returnType(): string {\n return 'OBJECT'\n }\n\n // The sample varies with ANY param of the owner, so all of them are its criteria.\n protected get criteria(): MethodParams {\n return this.owner.params\n }\n\n execute(criteria: Record<string, unknown>, ctx: ExecutionContext): unknown {\n return this.owner.result.runLoader(ctx.bagWith({ params: criteria }))\n }\n}\n\n// Resolves additional top-level param fields at runtime, returned as the v1 param model the console renders.\nexport class DynamicParamsLoaderMethod extends LoaderMethod {\n constructor(extension: Extension, protected readonly owner: DynamicParamsOwner) {\n super(extension, owner)\n }\n\n get name(): string {\n return dynamicParamsLoaderName(this.owner.id)\n }\n\n get registerAs(): string {\n return 'PARAM_SCHEMA_DEFINITION'\n }\n\n protected get returnType(): string {\n return 'LIST'\n }\n\n protected get criteria(): MethodParams {\n return this.owner.dynamicParamsCriteria\n }\n\n async execute(criteria: Record<string, unknown>, ctx: ExecutionContext): Promise<SharedExtensionParam[]> {\n const schema = await this.owner.resolveDynamicParams(ctx.bagWith({ criteria }))\n\n return toBodyParams(MethodParams.of(schema, {\n serviceId: this.extension.id,\n kind: 'action',\n itemId: this.owner.id,\n slot: 'dynamicParams.resolve()',\n }))\n }\n}\n", "import crypto from 'crypto'\n\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { z } from '../params'\nimport type { SystemMethodSpec } from '../system-method'\nimport { OAUTH_SYSTEM_METHODS } from './method-names'\nimport { OAuthCallbackObjectSchema, RefreshTokenSchema } from './system-params'\nimport type {\n OAuth2Props,\n OAuthBag,\n OAuthCallbackObject,\n OAuthCallbackResult,\n OAuthRefreshResult,\n} from './types'\n\n// `ext.setupOauth2(...)` \u2014 the OAuth2 subsystem (06-oauth2.md). Declarative for the common case, with an\n// escape hatch per step for providers that deviate. It owns the three v1 SYSTEM methods, the frozen runtime\n// seam the platform drives:\n//\n// getOAuth2ConnectionURL (GET) \u2192 where to send the user\n// executeCallback (POST) \u2192 trade the code for a token, and name the connection\n// refreshToken (PUT) \u2192 trade a refresh token for the next access token\n\nexport class OAuth2 {\n constructor(private readonly extension: Extension, private readonly props: OAuth2Props) {\n this.#registerSystemMethods()\n }\n\n // The handler bag's `oauth`: the header access token, plus its deserialized composite payload when the\n // author declared a deserializer (the pattern for providers whose \"token\" carries a realm or instance id).\n buildBag(accessToken?: string): OAuthBag {\n const token = this.props.deserializeToken && accessToken != null\n ? this.props.deserializeToken(accessToken)\n : undefined\n\n return { accessToken, token }\n }\n\n // \u2500\u2500 SYSTEM seam: name \u00B7 input \u00B7 return \u00B7 handler, in one table \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #registerSystemMethods(): void {\n const { CONNECTION_URL, EXECUTE_CALLBACK, REFRESH_TOKEN } = OAUTH_SYSTEM_METHODS\n\n // Every step runs where no usable access token exists yet \u2014 connect precedes one entirely, and the\n // callback and refresh are what PRODUCE the next one \u2014 so each sees a TOKENLESS context. The single\n // exception is the callback's identity lookup, which must use the token it just obtained (#handleCallback).\n const anonymous = (ctx: ExecutionContext): ExecutionContext => ctx.withAccessToken(undefined)\n\n this.extension.registerSystemMethods([\n {\n name: CONNECTION_URL,\n // Takes no input at all \u2014 no scheme.\n returnType: 'STRING',\n run: (_params, ctx) => this.#connectionUrl(anonymous(ctx), this.#composeScopes()),\n },\n {\n name: EXECUTE_CALLBACK,\n scheme: z.object({ callbackObject: OAuthCallbackObjectSchema }),\n run: ({ callbackObject }, ctx) => this.#handleCallback(callbackObject as OAuthCallbackObject, anonymous(ctx)),\n },\n {\n name: REFRESH_TOKEN,\n scheme: z.object({ refreshToken: RefreshTokenSchema }),\n run: ({ refreshToken }, ctx) => this.#refresh(refreshToken as string, anonymous(ctx)),\n },\n ] satisfies SystemMethodSpec[])\n }\n\n /**\n * The scopes to ask the user for: the base set \u222A every registered item's `oauth2Scopes`.\n *\n * Composed ON DEMAND, when the connect step actually runs, and never stored. `setupOauth2(...)` may be\n * called BEFORE the actions and triggers that carry scopes are registered \u2014 a service file is free to\n * order those however it likes \u2014 so a set computed at setup time would silently omit whatever registered\n * afterwards, and the user would be sent to a consent screen missing permissions the service needs.\n */\n #composeScopes(): string[] {\n return [...new Set([...(this.props.scopes ?? []), ...this.extension.declaredOAuthScopes()])]\n }\n\n // \u2500\u2500 the three steps \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n async #connectionUrl(ctx: ExecutionContext, scopes: string[]): Promise<string> {\n if (this.props.getConnectionURL) {\n return this.props.getConnectionURL(ctx.bagWith({ scopes }))\n }\n\n const { id } = this.#clientCreds(ctx.config)\n const params = new URLSearchParams({ client_id: id, response_type: 'code', scope: scopes.join(' ') })\n\n if (this.props.pkce) {\n // The verifier round-trips through `state`, which the console hands back on the callback.\n const verifier = crypto.randomBytes(32).toString('base64url')\n\n params.set('code_challenge', crypto.createHash('sha256').update(verifier).digest('base64url'))\n params.set('code_challenge_method', 'S256')\n params.set('state', verifier)\n }\n\n return `${ this.props.authorizeUrl }?${ params.toString() }`\n }\n\n async #handleCallback(callbackObject: OAuthCallbackObject, ctx: ExecutionContext): Promise<OAuthCallbackResult> {\n if (this.props.executeCallback) {\n return this.props.executeCallback(ctx.bagWith({ callbackObject }))\n }\n\n const tokenResponse = await this.#exchangeToken(ctx.config, {\n grant_type: 'authorization_code',\n code: callbackObject.code ?? '',\n redirect_uri: callbackObject.redirectURI ?? '',\n ...(callbackObject.state ? { code_verifier: callbackObject.state } : {}),\n })\n\n const accessToken = tokenResponse.access_token as string\n const refreshToken = tokenResponse.refresh_token as string | undefined\n\n // Identity lookup runs against the freshly-obtained token \u2014 the one exception to the tokenless rule.\n let identity: { name?: string; imageUrl?: string | null; userData?: unknown } = {}\n\n if (this.props.identityRequest) {\n const raw = await this.props.identityRequest(ctx.withAccessToken(accessToken).toBag())\n\n identity = this.props.identity ? this.props.identity(raw) : {}\n }\n\n return {\n token: this.#serialize(accessToken, refreshToken, identity.userData),\n expirationInSeconds: tokenResponse.expires_in as number | undefined,\n refreshToken,\n connectionIdentityName: identity.name || 'Unknown Account',\n connectionIdentityImageURL: identity.imageUrl ?? null,\n overwrite: true,\n userData: identity.userData,\n }\n }\n\n async #refresh(currentRefreshToken: string, ctx: ExecutionContext): Promise<OAuthRefreshResult> {\n if (this.props.refreshToken) {\n return this.props.refreshToken(ctx.bagWith({ refreshToken: currentRefreshToken }))\n }\n\n const tokenResponse = await this.#exchangeToken(ctx.config, {\n grant_type: 'refresh_token',\n refresh_token: currentRefreshToken,\n })\n\n // Providers that rotate refresh tokens send a new one; those that don't leave the current one valid.\n const nextRefresh = (tokenResponse.refresh_token as string | undefined) ?? currentRefreshToken\n\n return {\n token: this.#serialize(tokenResponse.access_token as string, nextRefresh),\n expirationInSeconds: tokenResponse.expires_in as number | undefined,\n refreshToken: nextRefresh,\n }\n }\n\n // \u2500\u2500 token exchange \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #serialize(accessToken: string, refreshToken?: string, userData?: unknown): string {\n return this.props.serializeToken\n ? this.props.serializeToken({ accessToken, refreshToken, userData })\n : accessToken\n }\n\n #clientCreds(config: Record<string, unknown>): { id: string; secret: string } {\n return {\n id: String(config[this.props.clientIdConfig ?? 'clientId'] ?? ''),\n secret: String(config[this.props.clientSecretConfig ?? 'clientSecret'] ?? ''),\n }\n }\n\n // x-www-form-urlencoded token exchange against `tokenUrl`; client creds go in the Basic header\n // (`clientAuth: 'basic'`) or the body (default).\n async #exchangeToken(config: Record<string, unknown>, body: Record<string, string>): Promise<Record<string, unknown>> {\n const { id, secret } = this.#clientCreds(config)\n const params = new URLSearchParams(body)\n const headers: Record<string, string> = { 'Content-Type': 'application/x-www-form-urlencoded' }\n\n if (this.props.clientAuth === 'basic') {\n headers.Authorization = `Basic ${ Buffer.from(`${ id }:${ secret }`).toString('base64') }`\n } else {\n params.set('client_id', id)\n params.set('client_secret', secret)\n }\n\n return Flowrunner.Request\n .post(this.props.tokenUrl as string)\n .set(headers)\n .send(params.toString()) as Promise<Record<string, unknown>>\n }\n}\n", "// The three runtime-owned OAuth SYSTEM methods \u2014 the frozen v1 seam. Do not rename: these are published\n// method names the platform invokes by string.\nexport const OAUTH_SYSTEM_METHODS = {\n CONNECTION_URL: 'getOAuth2ConnectionURL',\n EXECUTE_CALLBACK: 'executeCallback',\n REFRESH_TOKEN: 'refreshToken',\n} as const\n", "import { z } from '../params'\n\n// The input each OAuth SYSTEM method carries. Runtime-owned, not author-declared. LOOSE where the producer\n// is the console's OAuth controller: it may send fields a given milestone doesn't model yet, and dropping\n// them silently would be worse than carrying them through.\n\nexport const OAuthCallbackObjectSchema = z.looseObject({\n code: z.string().optional(),\n redirectURI: z.string().optional(),\n // The PKCE verifier round-trips through `state`.\n state: z.string().optional(),\n})\n\nexport const RefreshTokenSchema = z.string().min(1)\n", "// The single runtime-owned SYSTEM method shared by every polling trigger of a service; the runtime invokes\n// it on each tick and it routes by `invocation.eventName`. Frozen \u2014 a published method name.\nexport const POLLING_SYSTEM_METHOD = 'handleTriggerPollingForEvent'\n", "import { z } from '../params'\n\n// The invocation the runtime hands to the polling SYSTEM method on each tick. Runtime-owned, not\n// author-declared. LOOSE: the flow engine may send fields a given milestone doesn't model yet.\nexport const PollingInvocationSchema = z.looseObject({\n eventName: z.string().min(1),\n // The trigger instance's configured params \u2014 validated against the trigger's own schema separately.\n triggerData: z.record(z.string(), z.unknown()).optional(),\n state: z.record(z.string(), z.unknown()).nullish(),\n learningMode: z.boolean().optional(),\n connectionId: z.string().nullish(),\n})\n", "import { UnknownTriggerError } from '../../errors'\nimport type { Extension } from '../extension'\nimport { z } from '../params'\nimport type { SystemMethodSpec } from '../system-method'\nimport { POLLING_SYSTEM_METHOD } from './method-names'\nimport { PollingInvocationSchema } from './system-params'\nimport type { PollingTriggerMethod } from './trigger-method'\nimport type { PollingInvocation } from './types'\n\n// The polling triggers a service declares, as a set.\n//\n// The SYSTEM seam that drives them belongs HERE rather than to any one trigger: the runtime ticks a single\n// `handleTriggerPollingForEvent` and this routes it by `eventName`. Registering it on the first trigger\n// added is what makes it exist exactly when at least one trigger does \u2014 the model no longer needs a\n// separate \"are there any?\" check, because the method is simply there or not.\n\nexport class PollingTriggers {\n readonly #triggers = new Map<string, PollingTriggerMethod>()\n\n constructor(private readonly extension: Extension) {}\n\n get size(): number {\n return this.#triggers.size\n }\n\n get(id: string): PollingTriggerMethod | undefined {\n return this.#triggers.get(id)\n }\n\n all(): PollingTriggerMethod[] {\n return [...this.#triggers.values()]\n }\n\n add(trigger: PollingTriggerMethod): void {\n const first = this.size === 0\n\n this.#triggers.set(trigger.id, trigger)\n\n if (first) {\n this.#registerSystemMethods()\n }\n }\n\n // \u2500\u2500 SYSTEM seam: name \u00B7 input \u00B7 handler, in one place \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #registerSystemMethods(): void {\n this.extension.registerSystemMethods([{\n name: POLLING_SYSTEM_METHOD,\n scheme: z.object({ invocation: PollingInvocationSchema }),\n run: ({ invocation }, ctx) => {\n const value = invocation as PollingInvocation\n const trigger = this.get(value.eventName)\n\n if (!trigger) {\n throw new UnknownTriggerError(this.extension.id, value.eventName, 'polling')\n }\n\n return trigger.poll(value, ctx)\n },\n } satisfies SystemMethodSpec])\n }\n}\n", "// Read a dot-notation path (`a.b.c`) from a nested object; returns undefined if any segment is missing.\n// Shared by dictionaries/triggers for field-path config (dedupe/watermark `by`, match paths, extract*).\nexport function getPath(source: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>(\n (acc, key) => (acc == null ? acc : (acc as Record<string, unknown>)[key]),\n source\n )\n}\n", "import { InvalidTriggerConfigError } from '../../errors'\nimport { getPath } from '../path'\nimport type { HandlerBag } from '../types'\nimport type {\n DedupeConfig,\n PollingInvocation,\n PollingPollBag,\n PollingResult,\n PollingTriggerProps,\n WatermarkConfig,\n} from './types'\n\n// How a polling trigger decides what is NEW (08-polling-triggers.md). Three strategies, of which an author\n// declares exactly one:\n//\n// dedupe \u2014 remember the ids already seen, emit the rest (unordered feeds, no reliable timestamp)\n// watermark \u2014 remember the newest marker, emit anything past it (ordered feeds with a cursor field)\n// poll \u2014 the author owns the whole { events, state } contract (escape hatch)\n//\n// The first two share a lifecycle the base class owns, so a strategy only implements its own delta:\n// \u2022 first poll (no state) \u2192 SEED the state, emit nothing (wiring up must not fire a run)\n// \u2022 learningMode \u2192 emit the fetched head, state null (a sample for setup; nothing persisted)\n// \u2022 thereafter \u2192 emit the delta, advance the state\n//\n// The runtime drives the interval and the persistence; this file only computes `{ events, state }`.\n\n// What one invocation gives a strategy to work with.\ninterface PollCycle {\n bag: HandlerBag\n params: Record<string, unknown>\n isLearningMode: boolean\n state: Record<string, unknown> | null\n}\n\ntype FetchFn = (bag: HandlerBag & { params: Record<string, unknown>; isLearningMode: boolean }) =>\n unknown[] | Promise<unknown[]>\n\nexport abstract class PollingMechanism {\n /**\n * Pick the strategy an author declared, rejecting the combinations that cannot work. Runs at REGISTRATION\n * time, so a misconfigured trigger fails while the service module is being required rather than on some\n * later tick in production.\n */\n static from(props: PollingTriggerProps, serviceId: string): PollingMechanism {\n const declared = (['dedupe', 'watermark', 'poll'] as const)\n .filter(key => props[key] != null)\n\n if (declared.length !== 1) {\n throw new InvalidTriggerConfigError(\n serviceId,\n `polling trigger \"${ props.id }\" must declare exactly one of dedupe|watermark|poll (got: ${ declared.join(', ') || 'none' })`,\n { triggerId: props.id }\n )\n }\n\n if (props.poll) {\n return new CustomPollMechanism(props.poll)\n }\n\n // dedupe and watermark both filter a fetched list \u2014 without `fetch` there is nothing to filter.\n if (typeof props.fetch !== 'function') {\n throw new InvalidTriggerConfigError(\n serviceId,\n `polling trigger \"${ props.id }\" with dedupe/watermark requires a fetch(...) function`,\n { triggerId: props.id }\n )\n }\n\n return props.dedupe\n ? new DedupeMechanism(props.fetch as FetchFn, props.dedupe)\n : new WatermarkMechanism(props.fetch as FetchFn, props.watermark!)\n }\n\n run(invocation: PollingInvocation, bag: HandlerBag): Promise<PollingResult> {\n return this.poll({\n bag,\n params: invocation.triggerData ?? {},\n isLearningMode: !!invocation.learningMode,\n state: invocation.state ?? null,\n })\n }\n\n protected abstract poll(cycle: PollCycle): Promise<PollingResult>\n}\n\n// The escape hatch: the author owns fetching, comparison and state.\nclass CustomPollMechanism extends PollingMechanism {\n constructor(private readonly fn: NonNullable<PollingTriggerProps['poll']>) {\n super()\n }\n\n protected async poll({ bag, params, state, isLearningMode }: PollCycle): Promise<PollingResult> {\n return this.fn({ ...bag, params, state, isLearningMode } as PollingPollBag)\n }\n}\n\n// The shared lifecycle of the two strategies that filter a fetched list.\nabstract class FetchingMechanism extends PollingMechanism {\n constructor(private readonly fetch: FetchFn) {\n super()\n }\n\n protected async poll({ bag, params, state, isLearningMode }: PollCycle): Promise<PollingResult> {\n const items = await this.fetch({ ...bag, params, isLearningMode })\n\n // Learning mode: emit the fetched head as the sample; do not persist state.\n if (isLearningMode) {\n return { events: items, state: null }\n }\n\n return this.delta(items, state, params)\n }\n\n // What is new since `state`, and the state to remember next time.\n protected abstract delta(\n items: unknown[],\n state: Record<string, unknown> | null,\n params: Record<string, unknown>\n ): PollingResult\n}\n\n// \u2500\u2500 dedupe (seen-set) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass DedupeMechanism extends FetchingMechanism {\n readonly #by: (item: unknown) => unknown\n readonly #stateKey: string\n readonly #max: number\n\n constructor(fetch: FetchFn, config: DedupeConfig) {\n super(fetch)\n\n if (typeof config === 'function') {\n this.#by = config\n this.#stateKey = 'seen'\n this.#max = 500\n } else if (typeof config === 'string') {\n this.#by = item => getPath(item, config)\n this.#stateKey = 'seen'\n this.#max = 500\n } else {\n this.#by = typeof config.by === 'function' ? config.by : (item: unknown) => getPath(item, config.by as string)\n this.#stateKey = config.stateKey ?? 'seen'\n this.#max = config.max ?? 500\n }\n }\n\n protected delta(items: unknown[], state: Record<string, unknown> | null): PollingResult {\n const currentIds = items.map(this.#by).map(id => `${ id }`)\n\n // Seed on first poll: remember ids, emit nothing.\n if (!state?.[this.#stateKey]) {\n return { events: [], state: { [this.#stateKey]: this.#buildSeen([], currentIds) } }\n }\n\n const seen = toSeenList(state[this.#stateKey])\n const seenSet = new Set(seen)\n const events = items.filter((_item, index) => !seenSet.has(currentIds[index]))\n\n return { events, state: { [this.#stateKey]: this.#buildSeen(seen, currentIds) } }\n }\n\n // Bounded id list, oldest first, keeping the most-recent `max` ids. An id fetched again moves to the end,\n // so an item that is still in the feed is never the one evicted. It is a list, not an `{ id: 1 }` map: a\n // map orders integer-like keys numerically, which evicted the SMALLEST id instead of the oldest one.\n #buildSeen(seen: string[], currentIds: string[]): string[] {\n const fetched = new Set(currentIds)\n\n return [...seen.filter(id => !fetched.has(id)), ...fetched].slice(-this.#max)\n }\n}\n\n// State persisted before the list format is an `{ id: 1 }` map. It is still read so a live trigger keeps\n// its seen ids across the upgrade; its order is lost, which only matters until the next `max` ids roll in.\nconst toSeenList = (value: unknown): string[] => {\n return Array.isArray(value)\n ? value.map(id => `${ id }`)\n : Object.keys(value as Record<string, unknown>)\n}\n\n// \u2500\u2500 watermark (marker) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n// Markers are compared with JS relational ordering, which is exactly what lets one `by` field work whether\n// the provider hands out ISO timestamps, sortable ids or plain numbers \u2014 the author never declares which.\nconst isNewer = (value: unknown, marker: unknown): boolean => (value as string) > (marker as string)\n\nclass WatermarkMechanism extends FetchingMechanism {\n readonly #stateKey: string\n\n constructor(fetch: FetchFn, private readonly config: WatermarkConfig) {\n super(fetch)\n\n this.#stateKey = config.stateKey ?? 'watermark'\n }\n\n protected delta(\n items: unknown[],\n state: Record<string, unknown> | null,\n params: Record<string, unknown>\n ): PollingResult {\n const valueOf = (item: unknown): unknown =>\n typeof this.config.by === 'function' ? this.config.by(item, { params }) : getPath(item, this.config.by)\n\n const advance = (start: unknown): unknown =>\n items.reduce((max, item) => {\n const value = valueOf(item)\n\n if (value == null) {\n return max\n }\n\n return max == null || isNewer(value, max) ? value : max\n }, start)\n\n // Seed on first poll: store the newest marker, emit nothing.\n if (state?.[this.#stateKey] === undefined || state?.[this.#stateKey] === null) {\n return { events: [], state: { [this.#stateKey]: advance(undefined) } }\n }\n\n const marker = state[this.#stateKey]\n const events: unknown[] = []\n\n for (const item of items) {\n const value = valueOf(item)\n\n if (value != null && isNewer(value, marker)) {\n events.push(item)\n } else if (this.config.sortedDesc) {\n // newest-first list \u2192 the first non-newer item means the rest are older too.\n break\n }\n }\n\n return { events, state: { [this.#stateKey]: advance(marker) } }\n }\n}\n", "import { UnknownMethodError } from '../../errors'\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport type { LoaderOwner } from '../loaders/loader-owner'\nimport { ExtensionMethod } from '../method'\nimport type { SharedExtensionMethod } from '../model/model-types'\nimport { toArgs, toBodyParams } from '../model/params-model'\nimport { encodeParams, MethodParams } from '../params'\nimport { ResultSpec } from '../result'\nimport { PollingMechanism } from './mechanisms'\nimport type { PollingInvocation, PollingResult, PollingTriggerProps } from './types'\n\n// A polling trigger (08-polling-triggers.md). It is a published method \u2014 the console renders it as a start\n// node with its own params and sample result \u2014 but it is NOT invocable by name: the runtime reaches it\n// through the shared polling SYSTEM method, which routes by `eventName` (see ./polling-triggers.ts).\n\nexport class PollingTriggerMethod extends ExtensionMethod implements LoaderOwner {\n readonly params: MethodParams\n readonly result: ResultSpec\n readonly mechanism: PollingMechanism\n\n constructor(extension: Extension, private readonly props: PollingTriggerProps) {\n super(extension)\n\n this.params = MethodParams.of(props.params, {\n serviceId: extension.id,\n kind: 'polling trigger',\n itemId: props.id,\n slot: 'params',\n })\n this.result = ResultSpec.from(props.result)\n // Validates the declared combination \u2014 see PollingMechanism.from.\n this.mechanism = PollingMechanism.from(props, extension.id)\n }\n\n get id(): string {\n return this.props.id\n }\n\n get name(): string {\n return this.props.id\n }\n\n get registerAs(): string {\n return 'POLLING_TRIGGER'\n }\n\n get category(): string {\n return this.props.category\n }\n\n get oauth2Scopes(): string[] {\n return this.props.oauth2Scopes ?? []\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // Not dispatchable by name \u2014 the platform ticks `handleTriggerPollingForEvent` instead, so a call that\n // lands here is a caller using the trigger id as if it were an action.\n execute(): never {\n throw new UnknownMethodError(this.extension.id, this.name)\n }\n\n // One tick for this trigger, with its instance params already validated.\n poll(invocation: PollingInvocation, ctx: ExecutionContext): Promise<PollingResult> {\n return this.mechanism.run(\n { ...invocation, triggerData: this.#triggerData(invocation.triggerData) },\n ctx.toBag()\n )\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toModel(): SharedExtensionMethod {\n const [ownStart, ownEnd] = this.props.appearanceColors ?? []\n const [colorStart, colorEnd] = this.extension.appearanceColors\n\n return {\n name: this.id,\n operationName: this.props.label,\n description: this.props.description || '',\n registerAs: this.registerAs,\n category: this.category,\n colorStart: ownStart ?? colorStart,\n colorEnd: ownEnd ?? colorEnd,\n customIcon: this.props.logo ?? '',\n returnType: this.result.returnType,\n queryParams: [],\n bodyParams: toBodyParams(this.params),\n paramsSchema: encodeParams(this.params.scheme),\n metaInfo: { args: toArgs(this.params), ...this.result.toMetaInfo(this.id, this.params) },\n }\n }\n\n // A trigger instance's configured params, through the same pipeline as everything else. A saved instance\n // missing a required param therefore fails the poll rather than polling with `undefined` \u2014 the trigger\n // genuinely cannot work without it. Unknown fields ride through to the handler.\n #triggerData(data: Record<string, unknown> = {}): Record<string, unknown> {\n return this.params.normalize(data, this.input(data).invalidInput('triggerData'), { carryUnknown: true })\n }\n}\n", "// The five runtime-owned realtime SYSTEM methods \u2014 the frozen v1 webhook lifecycle seam. Do not rename:\n// these are published method names the platform invokes by string.\nexport const REALTIME_SYSTEM_METHODS = {\n UPSERT: 'handleTriggerUpsertWebhook',\n RESOLVE: 'handleTriggerResolveEvents',\n SELECT: 'handleTriggerSelectMatched',\n DELETE: 'handleTriggerDeleteWebhook',\n REFRESH: 'handleTriggerRefreshWebhook',\n} as const\n", "import { z } from '../params'\n\n// The invocation shapes the runtime hands to the realtime SYSTEM methods (v1-compatible). Runtime-owned,\n// not author-declared, and all LOOSE: the flow engine may send fields a given milestone doesn't model yet,\n// and dropping them silently would be worse than carrying them through.\n\nconst anyRecord = () => z.record(z.string(), z.unknown())\n\nconst SubscriptionEventSchema = z.looseObject({\n name: z.string().min(1),\n triggerData: anyRecord().optional(),\n})\n\n// upsert + refresh \u2014 both subscribe the callback URL for a set of trigger instances.\nexport const RealtimeSubscriptionInvocationSchema = z.looseObject({\n callbackUrl: z.string().min(1),\n events: z.array(SubscriptionEventSchema).default([]),\n webhookData: anyRecord().nullish(),\n connectionId: z.string().nullish(),\n})\n\n// delete \u2014 the webhook is torn down from its stored data; the callback URL is informational.\nexport const RealtimeDeleteInvocationSchema = z.looseObject({\n callbackUrl: z.string().optional(),\n webhookData: anyRecord().nullish(),\n connectionId: z.string().nullish(),\n})\n\n// resolve \u2014 the raw inbound HTTP delivery, plus the webhook document persisted at subscription time.\n// `webhookData` is NULLISH on purpose: the platform looks the document up per workspace, so a delivery\n// arriving on the general callback of a service that is not app-hosted carries none, and neither does one\n// for which no document exists (yet).\nexport const RealtimeInboundInvocationSchema = z.looseObject({\n headers: anyRecord().optional(),\n queryParams: anyRecord().optional(),\n body: z.unknown(),\n rawBody: z.string().optional(),\n webhookData: anyRecord().nullish(),\n connectionId: z.string().nullish(),\n})\n\n// select \u2014 one resolved event fanned out over the registered trigger instances. `webhookData` rides along\n// for the same reason it does on resolve, and is READ-ONLY here too: this seam answers with matched ids and\n// enriched data, never with a new document.\nexport const RealtimeSelectInvocationSchema = z.looseObject({\n eventName: z.string().min(1),\n eventData: z.unknown(),\n webhookData: anyRecord().nullish(),\n triggers: z.array(z.looseObject({\n id: z.string().min(1),\n // A partially-configured instance is legal \u2014 `match` treats an empty param as \"matches all\".\n data: anyRecord().optional(),\n })).default([]),\n})\n", "import type { RealtimeVerify } from './types'\n\n// The declarative inbound-signature check (09-realtime-triggers.md): HMAC the raw body with a secret drawn\n// from config, compare it in constant time to the header the provider sent, and \u2014 when the provider stamps\n// its deliveries \u2014 reject anything too old to be a live event rather than a replay.\n//\n// Services cannot `require` node modules, so the primitives come from `Flowrunner.crypto` (see ../crypto).\n// An author who needs something this shape cannot express writes `verifyRequest` instead.\n\nexport function verifyDeclarative(\n verify: RealtimeVerify,\n rawBody: string | undefined,\n headers: Record<string, unknown>,\n config: Record<string, unknown>,\n // The stored webhook document of this delivery \u2014 `null` when none. A provider that mints the signing\n // secret at registration time keeps it here, so `secret` has to be able to read it.\n webhookData: unknown\n): boolean {\n const provided = (headers[verify.header] ?? headers[verify.header.toLowerCase()]) as string | undefined\n\n if (!provided) {\n return false\n }\n\n const secret = verify.secret(config, { webhookData })\n const computed = Flowrunner.crypto.hmac(verify.algo, secret, rawBody ?? '', verify.encoding)\n\n if (!Flowrunner.crypto.timingSafeEqual(provided, computed)) {\n return false\n }\n\n if (verify.freshness && verify.timestampHeader) {\n const timestamp = headers[verify.timestampHeader] as string | undefined\n\n if (timestamp && Flowrunner.crypto.ageSeconds(timestamp) > verify.freshness) {\n return false\n }\n }\n\n return true\n}\n", "import { RealtimeSetupError, UnknownTriggerError } from '../../errors'\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport { z } from '../params'\nimport { getPath } from '../path'\nimport type { SystemMethodSpec } from '../system-method'\nimport type { AnySchema, ProviderPayload } from '../types'\nimport { REALTIME_SYSTEM_METHODS } from './method-names'\nimport {\n RealtimeDeleteInvocationSchema,\n RealtimeInboundInvocationSchema,\n RealtimeSelectInvocationSchema,\n RealtimeSubscriptionInvocationSchema,\n} from './system-params'\nimport type { RealtimeInvocation, RealtimeSetupProps, RealtimeSubTrigger } from './types'\nimport { verifyDeclarative } from './verify'\n\n// `ext.setupRealtimeTriggers(...)` \u2014 the webhook plumbing shared by every realtime trigger of a service\n// (09-realtime-triggers.md). The author writes declarative config plus lifecycle functions; this owns the\n// five v1 SYSTEM methods and drives them:\n//\n// handleTriggerUpsertWebhook \u2192 subscribe register the callback URL with the provider\n// handleTriggerDeleteWebhook \u2192 unsubscribe tear it down\n// handleTriggerRefreshWebhook \u2192 refresh (optional) renew a subscription that expires\n// handleTriggerResolveEvents \u2192 handshake \u2192 verify \u2192 route shape one inbound delivery into events\n// handleTriggerSelectMatched \u2192 per-instance match pick which configured instances fire\n//\n// Splitting resolve from select is what keeps the expensive work rare: resolve runs once per delivery and\n// touches no API, select runs per event and may enrich once, only if something actually matched.\n\n// Read a `string | fn` extractor against the request body.\nfunction readExtract(\n extract: string | ((bag: { requestBody: ProviderPayload }) => unknown) | undefined,\n body: unknown\n): unknown {\n if (typeof extract === 'function') {\n return extract({ requestBody: body })\n }\n\n if (typeof extract === 'string') {\n return getPath(body, extract)\n }\n\n return undefined\n}\n\nfunction isEmptyBody(body: unknown): boolean {\n return body == null || (typeof body === 'object' && Object.keys(body as object).length === 0)\n}\n\nexport class RealtimeSetup {\n constructor(private readonly extension: Extension, private readonly props: RealtimeSetupProps) {\n if (typeof props.subscribe !== 'function' || typeof props.unsubscribe !== 'function') {\n throw new RealtimeSetupError(extension.id, 'setupRealtimeTriggers requires subscribe and unsubscribe functions')\n }\n\n this.#registerSystemMethods()\n }\n\n get scope(): RealtimeSetupProps['scope'] {\n return this.props.scope\n }\n\n get hasRefresh(): boolean {\n return typeof this.props.refresh === 'function'\n }\n\n // \u2500\u2500 SYSTEM seam: name \u00B7 input \u00B7 handler, in one table \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n #registerSystemMethods(): void {\n const M = REALTIME_SYSTEM_METHODS\n\n // Every realtime SYSTEM method takes the same single `invocation` param; only its shape differs.\n const spec = (\n name: string,\n schema: AnySchema,\n run: (invocation: RealtimeInvocation, ctx: ExecutionContext) => unknown,\n published = true\n ): SystemMethodSpec => ({\n name,\n scheme: z.object({ invocation: schema }),\n published,\n run: ({ invocation }, ctx) => run(invocation as RealtimeInvocation, ctx),\n })\n\n this.extension.registerSystemMethods([\n spec(M.UPSERT, RealtimeSubscriptionInvocationSchema, (i, ctx) => this.#subscribe(i, ctx)),\n spec(M.DELETE, RealtimeDeleteInvocationSchema, (i, ctx) => this.#unsubscribe(i, ctx)),\n spec(M.RESOLVE, RealtimeInboundInvocationSchema, (i, ctx) => this.#resolve(i, ctx)),\n spec(M.SELECT, RealtimeSelectInvocationSchema, (i, ctx) => this.#selectMatched(i, ctx)),\n // Refresh stays CALLABLE either way \u2014 it answers `{}` when no handler was declared \u2014 but is only\n // advertised in the model when the author actually declared one.\n spec(M.REFRESH, RealtimeSubscriptionInvocationSchema, (i, ctx) => this.#refresh(i, ctx), this.hasRefresh),\n ])\n }\n\n // \u2500\u2500 subscription lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n async #subscribe(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n const result = await this.props.subscribe(ctx.bagWith({\n callbackUrl: invocation.callbackUrl as string,\n triggers: this.#toSubTriggers(invocation.events),\n webhookData: invocation.webhookData ?? null,\n connectionId: invocation.connectionId,\n }))\n\n return {\n webhookData: result?.webhookData,\n eventScopeId: result?.eventScopeId,\n refreshIntervalInSeconds: result?.refreshIntervalInSeconds,\n }\n }\n\n async #unsubscribe(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n const result = await this.props.unsubscribe(ctx.bagWith({\n callbackUrl: invocation.callbackUrl,\n webhookData: invocation.webhookData,\n connectionId: invocation.connectionId,\n }))\n\n return { webhookData: result?.webhookData ?? {} }\n }\n\n async #refresh(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n if (!this.props.refresh) {\n return {}\n }\n\n const result = await this.props.refresh(ctx.bagWith({\n callbackUrl: invocation.callbackUrl as string,\n triggers: this.#toSubTriggers(invocation.events),\n webhookData: invocation.webhookData,\n }))\n\n return { webhookData: result?.webhookData, refreshIntervalInSeconds: result?.refreshIntervalInSeconds }\n }\n\n // v1 upsert/refresh hand over events [{ name, triggerData }]. A trigger that declares provider event\n // names expands to one entry EACH, which is what a provider's subscribe API actually wants.\n //\n // A trigger that declares NONE still gets an entry. `providerEventName` is a ROUTING declaration and this\n // is a LIFECYCLE seam: an extension that resolves its own events (`resolveEvents`) legitimately has nothing to\n // route by, yet its triggers still run and `subscribe`/`refresh` still have to reconcile them. Gating the\n // bag on the routing declaration handed such a service an empty bag on every subscribe \u2014 silently, since\n // an empty subscription is a perfectly well-formed result.\n //\n // NOTHING is dropped here. A `name` resolving to no trigger THROWS, because this is the CONTROL PLANE:\n // upsert/refresh are initiated by FlowRunner itself, something is waiting on the result, and no third\n // party is affected \u2014 so an error reaches a place where it can be acted on. `subscribe` is the seam that\n // registers with the PROVIDER, so a dropped entry meant a flow that reported LIVE while its trigger was\n // never subscribed \u2014 silent, and indistinguishable from a working flow that simply never fired. One throw\n // does block the rest of the batch from subscribing, and that is the intent: a flow refusing to start\n // beats a live flow with half its triggers registered. (The data plane is ruled the other way \u2014 see\n // `#selectMatched`, which declines rather than throws because nothing is waiting on it.)\n #toSubTriggers(events: RealtimeInvocation['events'] = []): RealtimeSubTrigger[] {\n const subTriggers: RealtimeSubTrigger[] = []\n\n for (const event of events) {\n const trigger = this.extension.findRealtimeTrigger(event.name)\n\n if (!trigger) {\n throw new UnknownTriggerError(this.extension.id, event.name, 'realtime')\n }\n\n const params = event.triggerData ?? {}\n const providerEventNames = trigger.providerEventNames(params)\n\n // No placeholder: a `providerEventName` the provider has never heard of would reach `subscribe`, the\n // seam that calls the provider's own subscription API. A missing field an author can test for is safer.\n if (!providerEventNames.length) {\n subTriggers.push({ id: event.name, params })\n continue\n }\n\n for (const providerEventName of providerEventNames) {\n subTriggers.push({ id: event.name, params, providerEventName })\n }\n }\n\n return subTriggers\n }\n\n // \u2500\u2500 inbound delivery \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n async #resolve(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n const headers = invocation.headers ?? {}\n const body = invocation.body\n const rawBody = invocation.rawBody\n // The document `subscribe` returned, as the platform stored it \u2014 the only way state registered with the\n // provider (a signing secret, an external webhook id) reaches the delivery it describes. Normalized to\n // `null` so every inbound seam reports \"nothing stored\" the one way, rather than `undefined` here and\n // `null` there depending on whether the platform sent the field or sent it empty.\n const webhookData = invocation.webhookData ?? null\n\n // 1. Endpoint-verification handshake (challenge/echo). Anything returned \u2192 ack without processing.\n if (this.props.handshake) {\n const result = await this.props.handshake(ctx.bagWith({ requestBody: body, headers, rawBody, webhookData }))\n\n if (result && (\n result.responseToExternalService !== undefined || result.responseHeaders || result.responseToWebhook\n )) {\n // Both shapes travel, exactly as the author wrote them. `responseToWebhook` is the newer, fuller\n // one, but the platform does not understand it yet \u2014 so translating the older pair into it would\n // drop the response of every service already using it. The platform picks whichever it supports.\n return {\n handshake: true,\n responseToExternalService: result.responseToExternalService,\n responseHeaders: result.responseHeaders,\n responseToWebhook: result.responseToWebhook,\n }\n }\n }\n\n // Empty-body deliveries are auto-acked.\n if (isEmptyBody(body)) {\n return { handshake: true, events: [] }\n }\n\n // 2. Signature verification (escape hatch or declarative). Reject on failure \u2014 by RETURNING a 401,\n // never by throwing.\n //\n // A forged delivery is a normal, expected outcome of a public callback URL, not a runtime failure. A\n // throw leaves the pod with a 4xx, which the platform reads as \"the invocation failed\" rather than \"the\n // extension answered 401\" \u2014 so the provider receives a 500. That fails exactly the validation this is\n // for: Xero's Intent to Receive sends a deliberately mis-signed delivery and requires a 401 back.\n //\n // Empty `rawBody` rather than `body`: a rejection carries no content, and `body` is always JSON, so an\n // empty string there would arrive quoted.\n if (!await this.#verify(rawBody, headers, webhookData, ctx)) {\n ctx.logger.warn(`[flow-extension:${ this.extension.id }] webhook signature verification failed \u2014 answering 401`)\n\n return { events: [], responseToWebhook: { httpStatus: 401, rawBody: '' } }\n }\n\n // 3. Escape hatch for irregular/multi-shape payloads \u2014 emits v1 events directly.\n if (this.props.resolveEvents) {\n const result = await this.props.resolveEvents(ctx.bagWith({\n rawBody,\n headers,\n query: invocation.queryParams ?? {},\n body,\n webhookData,\n connectionId: invocation.connectionId,\n }))\n\n return {\n handshake: result.handshake,\n responseToExternalService: result.responseToExternalService,\n responseHeaders: result.responseHeaders,\n responseToWebhook: result.responseToWebhook,\n eventScopeId: result.eventScopeId,\n events: (result.events ?? []).map(event => ({ name: event.id, data: event.providerEventData })),\n }\n }\n\n // 4. Declarative routing: discriminator \u2192 every trigger claiming it; build providerEventData.\n const eventName = readExtract(this.props.extractProviderEventName, body)\n\n if (eventName == null) {\n return { events: [] }\n }\n\n const baseData = this.props.extractProviderEventData\n ? readExtract(this.props.extractProviderEventData, body)\n : body\n const events: { name: string; data: unknown }[] = []\n\n for (const trigger of this.extension.realtimeTriggers()) {\n if (!trigger.claims(eventName as string)) {\n continue\n }\n\n const extra = trigger.extendEventData(body, baseData as Record<string, unknown>)\n\n events.push({ name: trigger.id, data: extra ? { ...(baseData as object), ...extra } : baseData })\n }\n\n const eventScopeId = this.props.scopeAt ? getPath(body, this.props.scopeAt) : undefined\n\n return { events, eventScopeId, connectionId: invocation.connectionId }\n }\n\n // The author's own check wins; otherwise the declarative one; otherwise nothing was asked for.\n async #verify(\n rawBody: string | undefined,\n headers: Record<string, unknown>,\n webhookData: unknown,\n ctx: ExecutionContext\n ): Promise<boolean> {\n if (this.props.verifyRequest) {\n return !!await this.props.verifyRequest(ctx.bagWith({ rawBody, headers, webhookData, config: ctx.config }))\n }\n\n if (this.props.verify) {\n return verifyDeclarative(this.props.verify, rawBody, headers, ctx.config, webhookData)\n }\n\n return true\n }\n\n // Fan one resolved event out over the configured instances of its trigger. An `eventName` this service\n // does not declare is DECLINED outright \u2014 `{ ids: [], enrichedEventData: null }`, no instance offered up\n // and no per-event seam run. That is deliberately not the same case as a trigger which declares no\n // `match`: `matches()` already answers \"fires always\" for that one, so resolve the name FIRST and never\n // let the two share a branch.\n //\n // Declining is the GUARANTEE here, not an accident of a past fix, and it is why this seam is ruled the\n // opposite way to `#toSubTriggers`. This is the DATA PLANE: the platform has already answered the\n // provider and detached this work, so a throw reaches nobody \u2014 and worse, it aborts every remaining event\n // of the same delivery, dropping the good ones beside the stale name.\n async #selectMatched(invocation: RealtimeInvocation, ctx: ExecutionContext): Promise<object> {\n // `eventName` is in practice always present \u2014 RealtimeSelectInvocationSchema declares it\n // `z.string().min(1)`, so SystemMethod.validate rejects a missing one before this runs. The shared\n // invocation bag cannot say so (the other four SYSTEM methods carry no event name), and an absent name\n // is not a trigger id either way, so it folds into the same decline rather than earning a branch.\n const trigger = invocation.eventName ? this.extension.findRealtimeTrigger(invocation.eventName) : undefined\n\n if (!trigger) {\n return { ids: [], enrichedEventData: null }\n }\n\n const eventData = invocation.eventData\n // Read-only here, exactly as on resolve: `match` and `extendResult` may consult what the subscription\n // registered, and neither can write it back \u2014 this seam's answer is ids and enriched data, nothing else.\n const webhookData = invocation.webhookData ?? null\n const ids = (invocation.triggers ?? [])\n .filter(instance => trigger.matches(instance.data ?? {}, eventData, webhookData))\n .map(instance => instance.id)\n\n // extendResult runs ONCE if any instance matched \u2014 the only per-event place that may call the API.\n const enrichedEventData = ids.length && trigger.hasExtendResult()\n ? await trigger.extendResult(eventData, ctx, webhookData)\n : null\n\n return { ids, enrichedEventData }\n }\n}\n", "import { UnknownMethodError } from '../../errors'\nimport type { ExecutionContext } from '../context/execution-context'\nimport type { Extension } from '../extension'\nimport type { LoaderOwner } from '../loaders/loader-owner'\nimport { ExtensionMethod } from '../method'\nimport type { SharedExtensionMethod } from '../model/model-types'\nimport { toArgs, toBodyParams } from '../model/params-model'\nimport { encodeParams, MethodParams } from '../params'\nimport { getPath } from '../path'\nimport { ResultSpec } from '../result'\nimport type { ProviderPayload } from '../types'\nimport type { RealtimeTriggerProps } from './types'\n\n// A realtime (webhook) trigger (09-realtime-triggers.md). Like a polling trigger it is a published method\n// the console renders as a start node, but is NOT invocable by name \u2014 the runtime reaches it through the\n// realtime SYSTEM seam (see ./realtime-setup.ts), which routes inbound deliveries to it.\n//\n// Its three author hooks answer three different questions, at three different moments:\n// providerEventNames which provider events is this trigger about? (routing, per delivery)\n// matches does THIS configured instance care about it? (fan-out, per instance)\n// extendResult what extra data should the event carry? (once, if anything matched)\n\nexport class RealtimeTriggerMethod extends ExtensionMethod implements LoaderOwner {\n readonly params: MethodParams\n readonly result: ResultSpec\n\n constructor(extension: Extension, private readonly props: RealtimeTriggerProps) {\n super(extension)\n\n this.params = MethodParams.of(props.params, {\n serviceId: extension.id,\n kind: 'realtime trigger',\n itemId: props.id,\n slot: 'params',\n })\n this.result = ResultSpec.from(props.result)\n }\n\n get id(): string {\n return this.props.id\n }\n\n get name(): string {\n return this.props.id\n }\n\n get registerAs(): string {\n return 'REALTIME_TRIGGER'\n }\n\n get category(): string {\n return this.props.category\n }\n\n get oauth2Scopes(): string[] {\n return this.props.oauth2Scopes ?? []\n }\n\n // Not dispatchable by name \u2014 inbound deliveries arrive through the realtime SYSTEM methods.\n execute(): never {\n throw new UnknownMethodError(this.extension.id, this.name)\n }\n\n // \u2500\u2500 routing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // The provider event(s) this trigger claims. The fn form depends on instance params (unusual for routing)\n // \u2014 best-effort with the params given.\n providerEventNames(params: Record<string, unknown> = {}): string[] {\n const declared = this.props.providerEventName\n\n if (typeof declared === 'function') {\n return declared({ params }) ?? []\n }\n\n if (Array.isArray(declared)) {\n return declared\n }\n\n return declared ? [declared] : []\n }\n\n claims(providerEventName: string): boolean {\n return this.providerEventNames().includes(providerEventName)\n }\n\n // Per-trigger enrichment of the shaped event data, before instances are matched against it.\n extendEventData(requestBody: ProviderPayload, providerEventData: ProviderPayload): Record<string, unknown> | undefined {\n return this.props.extendEventData?.({ requestBody, providerEventData })\n }\n\n /**\n * Whether one CONFIGURED INSTANCE of this trigger cares about an event. Declarative form: type-coerced\n * equality per filled param, where an empty param means \"any\" \u2014 that is what lets a user leave a filter\n * blank and receive everything. Predicate form: the author decides. No `match` at all: always fires.\n *\n * `webhookData` is handed to the predicate form to be READ \u2014 an instance filter that depends on what the\n * subscription registered (a tenant id, a resource the webhook was scoped to) has nowhere else to get it.\n * Returning a new document is not a thing this seam can do; only subscribe/refresh/unsubscribe persist.\n */\n matches(\n params: Record<string, unknown>,\n providerEventData: ProviderPayload,\n webhookData: ProviderPayload = null\n ): boolean {\n const match = this.props.match\n\n if (!match) {\n return true\n }\n\n if (typeof match === 'function') {\n return !!match({ params, providerEventData, webhookData })\n }\n\n for (const [paramKey, path] of Object.entries(match)) {\n const paramValue = params[paramKey]\n\n if (paramValue == null || paramValue === '') {\n continue\n }\n\n if (`${ paramValue }` !== `${ getPath(providerEventData, path) }`) {\n return false\n }\n }\n\n return true\n }\n\n // Runs ONCE per event if any instance matched \u2014 the only per-event place that may call the provider API.\n // It reads `webhookData` (an access token or external id the subscription stored) but cannot change it.\n extendResult(\n providerEventData: ProviderPayload,\n ctx: ExecutionContext,\n webhookData: ProviderPayload = null\n ): Promise<unknown> | unknown {\n return this.props.extendResult?.(ctx.bagWith({ providerEventData, webhookData }))\n }\n\n hasExtendResult(): boolean {\n return typeof this.props.extendResult === 'function'\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toModel(): SharedExtensionMethod {\n const [ownStart, ownEnd] = this.props.appearanceColors ?? []\n const [colorStart, colorEnd] = this.extension.appearanceColors\n\n return {\n name: this.id,\n operationName: this.props.label,\n description: this.props.description || '',\n registerAs: this.registerAs,\n category: this.category,\n colorStart: ownStart ?? colorStart,\n colorEnd: ownEnd ?? colorEnd,\n customIcon: this.props.logo ?? '',\n returnType: this.result.returnType,\n queryParams: [],\n bodyParams: toBodyParams(this.params),\n paramsSchema: encodeParams(this.params.scheme),\n metaInfo: { args: toArgs(this.params), ...this.result.toMetaInfo(this.id, this.params) },\n }\n }\n}\n", "import type { ExecutionContext } from './context/execution-context'\nimport type { Extension } from './extension'\nimport { ExtensionMethod } from './method'\nimport { argsFromParams } from './model/method-model'\nimport type { SharedExtensionMethod } from './model/model-types'\nimport { toOpaqueBodyParams } from './model/params-model'\nimport type { ZodSchema } from './params'\nimport { MethodParams } from './params'\nimport type { AnySchema } from './types'\n\n// The runtime-owned methods \u2014 the frozen v1 seam the platform calls rather than a flow: the OAuth connect /\n// callback / refresh steps, the polling tick, and the five realtime webhook lifecycle hooks. An author\n// never writes one; they exist because a feature was set up.\n//\n// Mechanically they are all the same: a runtime-owned params scheme, a SYSTEM model entry, and a handler.\n// Only the handler differs \u2014 so there is ONE class, driven by a spec, and each feature declares its own\n// specs in one place (see each owner's `#registerSystemMethods`). That single row now holds every fact\n// about a SYSTEM method: its name, its input contract, its model shape, and what it does.\n\nexport interface SystemMethodSpec {\n name: string\n /**\n * The params this method takes, as a normal z.object. Today every SYSTEM method happens to declare\n * exactly ONE property (`invocation` / `callbackObject` / `refreshToken`) \u2014 but that is a fact about the\n * current seam, not a constraint of the machinery: a second property needs no change here. Omit entirely\n * for a method that takes no input (getOAuth2ConnectionURL).\n */\n scheme?: AnySchema\n // The v1 `returnType` token. OBJECT for everything but the connect step, which answers a URL.\n returnType?: string\n // Set false for a seam that must stay callable without being advertised (see ExtensionMethod.published).\n published?: boolean\n // Receives the validated params, exactly as an action's handler receives its own.\n run: (params: Record<string, unknown>, ctx: ExecutionContext) => unknown\n}\n\nexport class SystemMethod extends ExtensionMethod {\n readonly params: MethodParams\n\n constructor(extension: Extension, private readonly spec: SystemMethodSpec) {\n super(extension)\n\n this.params = MethodParams.of(spec.scheme, { serviceId: extension.id, kind: 'system method', itemId: spec.name, slot: 'scheme' })\n }\n\n get name(): string {\n return this.spec.name\n }\n\n get registerAs(): string {\n return 'SYSTEM'\n }\n\n get published(): boolean {\n return this.spec.published ?? true\n }\n\n /**\n * FIELD-BY-FIELD validation: every declared param is required, then checked against its OWN schema. The\n * input here is a wrapper carrying named params rather than the params themselves \u2014 `{ invocation }` /\n * `{ callbackObject }` / `{ refreshToken }` are separate method params.\n *\n * Deliberately not one `parse(methodData)` over the whole object, because two failures must stay\n * distinguishable: an ABSENT param is a malformed call (MissingMethodParamError naming the param), while a\n * bad VALUE is a malformed value (InvalidMethodInputError whose issue paths are relative to that param,\n * not to `methodData`). A whole-object parse would flatten both into the second, with `invocation.` in\n * front of every path.\n */\n validate(methodData: Record<string, unknown>): Record<string, unknown> {\n const input = this.input(methodData)\n const parsed: Record<string, unknown> = {}\n\n for (const [name, schema] of this.params.fields()) {\n parsed[name] = input.parseField(name, schema as ZodSchema)\n }\n\n return parsed\n }\n\n execute(params: Record<string, unknown>, ctx: ExecutionContext): unknown {\n return this.spec.run(params, ctx)\n }\n\n toModel(): SharedExtensionMethod {\n const bodyParams = toOpaqueBodyParams(this.params)\n\n return {\n name: this.name,\n operationName: this.name,\n description: '',\n registerAs: this.registerAs,\n category: '',\n colorStart: '',\n colorEnd: '',\n customIcon: undefined,\n returnType: this.spec.returnType ?? 'OBJECT',\n queryParams: [],\n bodyParams,\n metaInfo: { args: argsFromParams(bodyParams), sampleResult: null, sampleResultLoader: null },\n }\n }\n}\n", "import type { ConfigItem } from '../common/types'\nimport { DuplicateItemIdError, OAuthSetupError, RealtimeSetupError, UnknownMethodError } from '../errors'\nimport { ActionMethod } from './actions/action-method'\nimport { ExecutionContext, type ExecutionContextOptions } from './context/execution-context'\nimport { DictionaryMethod } from './dictionaries/dictionary-method'\nimport { DynamicParamsLoaderMethod, SampleResultLoaderMethod } from './loaders/loader-method'\nimport type { LoaderOwner } from './loaders/loader-owner'\nimport type { ExtensionMethod } from './method'\nimport type { SharedExtensionDefinition, SharedExtensionMethod, SharedExtensionServiceInfo } from './model/model-types'\nimport { toConfigItems } from './model/params-model'\nimport { OAuth2 } from './oauth/oauth2'\nimport type { OAuth2Props } from './oauth/types'\nimport type { DictionaryRef } from './params'\nimport { ConfigParams, encodeParams } from './params'\nimport { PollingTriggers } from './polling-triggers/polling-triggers'\nimport { PollingTriggerMethod } from './polling-triggers/trigger-method'\nimport type { PollingTriggerProps } from './polling-triggers/types'\nimport { RealtimeSetup } from './realtime-triggers/realtime-setup'\nimport { RealtimeTriggerMethod } from './realtime-triggers/trigger-method'\nimport type { RealtimeSetupProps, RealtimeTriggerProps } from './realtime-triggers/types'\nimport { SystemMethod, type SystemMethodSpec } from './system-method'\nimport type { ActionProps, DictionaryProps, ExtensionProps } from './types'\n\n// One registered extension: everything a service declared, and everything the runner does with it. The\n// composition root \u2014 `Flowrunner.createExtension(props)` builds one, the registry stores it, and every\n// caller (definition build, config resolution, method dispatch) goes through it rather than reaching into a\n// bag of Maps.\n//\n// Registration happens once, while the service module is being `require`d, and is validated as it goes: ids\n// must be unique across ALL item kinds, a polling trigger must declare exactly one mechanism, and the\n// opt-in features can only be set up once. An authoring mistake therefore surfaces from the first call the\n// console or CLI makes against the extension, naming what has to be fixed.\n\nexport class Extension {\n readonly #props: ExtensionProps\n readonly #config: ConfigParams\n readonly #methods = new Map<string, ExtensionMethod>()\n readonly #pollingTriggers = new PollingTriggers(this)\n readonly #realtimeTriggers = new Map<string, RealtimeTriggerMethod>()\n readonly #usedIds = new Set<string>()\n #oauth?: OAuth2\n #realtime?: RealtimeSetup\n\n constructor(props: ExtensionProps) {\n this.#props = props\n // Eager: `configItems` is validated as the extension registers, like every other declared slot. Leaving\n // it lazy would let a bad one hide behind handlers that never happen to read config.\n this.#config = ConfigParams.of(props.configItems, { serviceId: props.id, kind: 'extension', slot: 'configItems' })\n }\n\n get id(): string {\n return this.#props.id\n }\n\n get props(): ExtensionProps {\n return this.#props\n }\n\n // The declared `configItems`, mapped once per extension rather than per invocation.\n get config(): ConfigParams {\n return this.#config\n }\n\n get oauth(): OAuth2 | undefined {\n return this.#oauth\n }\n\n get realtime(): RealtimeSetup | undefined {\n return this.#realtime\n }\n\n realtimeTriggers(): RealtimeTriggerMethod[] {\n return [...this.#realtimeTriggers.values()]\n }\n\n findRealtimeTrigger(id: string): RealtimeTriggerMethod | undefined {\n return this.#realtimeTriggers.get(id)\n }\n\n get pollingTriggers(): PollingTriggers {\n return this.#pollingTriggers\n }\n\n // The extension-level colours every item falls back to.\n get appearanceColors(): [string, string] {\n const [start = '', end = ''] = this.props.appearanceColors ?? []\n\n return [start, end]\n }\n\n // \u2500\u2500 authoring-time registration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n registerDictionary(props: DictionaryProps): DictionaryRef {\n const dictionary = new DictionaryMethod(this, props)\n\n this.#addMethod(dictionary, 'dictionary')\n\n // The ref threaded into `.dictionary(ref)` on a param; carries the auto-derived dependsOn.\n return { id: props.id, dependsOn: dictionary.dependsOn }\n }\n\n registerAction(props: ActionProps): void {\n const action = new ActionMethod(this, props)\n\n this.#addMethod(action, 'action')\n\n this.#registerSampleResultLoader(action, 'sample-result loader')\n\n // `dynamicParams` \u2192 a PARAM_SCHEMA_DEFINITION method that resolves extra param fields from criteria.\n if (action.hasDynamicParams()) {\n this.#addMethod(new DynamicParamsLoaderMethod(this, action), 'dynamic params loader')\n }\n }\n\n registerPollingTrigger(props: PollingTriggerProps): void {\n // Claim the id before constructing, so a duplicate id is reported ahead of a bad mechanism.\n this.#claimId(props.id, 'polling trigger')\n\n const trigger = new PollingTriggerMethod(this, props)\n\n this.#putMethod(trigger)\n this.#pollingTriggers.add(trigger)\n this.#registerSampleResultLoader(trigger, 'sample-result loader')\n }\n\n registerRealtimeTrigger(props: RealtimeTriggerProps): void {\n this.#claimId(props.id, 'realtime trigger')\n\n const trigger = new RealtimeTriggerMethod(this, props)\n\n this.#putMethod(trigger)\n this.#realtimeTriggers.set(trigger.id, trigger)\n this.#registerSampleResultLoader(trigger, 'sample-result loader')\n }\n\n setupRealtime(props: RealtimeSetupProps): void {\n if (this.#realtime) {\n throw new RealtimeSetupError(this.id, 'setupRealtimeTriggers(...) called more than once')\n }\n\n // The setup validates itself and publishes its SYSTEM methods as it is constructed.\n this.#realtime = new RealtimeSetup(this, props)\n }\n\n setupOAuth2(props: OAuth2Props): void {\n if (this.#oauth) {\n throw new OAuthSetupError(this.id, 'setupOauth2(...) called more than once')\n }\n\n // Like RealtimeSetup, it publishes its SYSTEM methods as it is constructed.\n this.#oauth = new OAuth2(this, props)\n }\n\n // Publish a feature's runtime-owned methods. Called by each subsystem as it is set up, so a SYSTEM method\n // exists exactly when the feature behind it does \u2014 and an id that collides with an author's own item is\n // caught here, loudly, instead of one silently shadowing the other.\n registerSystemMethods(specs: SystemMethodSpec[]): void {\n for (const spec of specs) {\n this.#addMethod(new SystemMethod(this, spec), 'system method')\n }\n }\n\n // \u2500\u2500 runtime \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // Every method this extension publishes, in registration order.\n methods(): ExtensionMethod[] {\n return [...this.#methods.values()]\n }\n\n findMethod(name: string): ExtensionMethod | undefined {\n return this.#methods.get(name)\n }\n\n getMethod(name: string): ExtensionMethod {\n const method = this.findMethod(name)\n\n if (!method) {\n throw new UnknownMethodError(this.id, name)\n }\n\n return method\n }\n\n createContext(options: ExecutionContextOptions = {}): ExecutionContext {\n return new ExecutionContext(this, options)\n }\n\n // Dispatch: find the method, let it check its own input, run it. Every kind \u2014 action, dictionary,\n // generated loader, SYSTEM seam \u2014 arrives here through the same three steps.\n async run(methodName: string, methodData: Record<string, unknown>, ctx: ExecutionContext): Promise<unknown> {\n const method = this.getMethod(methodName)\n\n return method.execute(method.validate(methodData ?? {}), ctx)\n }\n\n // \u2500\u2500 output model \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n toConfigItems(): ConfigItem[] {\n return toConfigItems(this.config)\n }\n\n toServiceInfo(): SharedExtensionServiceInfo {\n return {\n serviceClassName: this.props.id,\n integrationName: this.props.name,\n integrationIcon: this.props.logo ?? null,\n integrationTriggersScope: this.#realtime?.scope ?? null,\n requireOAuth: this.#oauth ? true : undefined,\n }\n }\n\n /**\n * The published model \u2014 the v2 analogue of jsdoc-parser's `parseJsDocToServiceJson`, and the same\n * `{ serviceInfo, methodsMap }` shape the console consumes for a v1 service.\n *\n * Every method describes itself, so this is one pass with no per-kind branches: what a service publishes\n * is exactly what it registered.\n */\n toDefinition(): SharedExtensionDefinition {\n const methodsMap: Record<string, SharedExtensionMethod> = {}\n\n for (const method of this.methods()) {\n if (method.published) {\n methodsMap[method.name] = method.toModel()\n }\n }\n\n return {\n runnerVersion: 'v2', //TODO: temp\n serviceInfo: this.toServiceInfo(),\n methodsMap,\n configSchema: encodeParams(this.config.scheme),\n }\n }\n\n // \u2500\u2500 queries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // The `oauth2Scopes` every registered method declares, in registration order. The base set and the\n // dedupe live with the OAuth subsystem that consumes them (see OAuth2.#composeScopes).\n declaredOAuthScopes(): string[] {\n return this.methods().flatMap(method => method.oauth2Scopes)\n }\n\n // \u2500\u2500 private \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // Every registered item is keyed by `id` (= the v1 method name, frozen for back-compat), and the ids must\n // be unique across ALL kinds \u2014 including the loader methods the runtime generates from them.\n #claimId(id: string, kind: string): void {\n if (!id) {\n throw new Error(`[flow-extension:${ this.id }] a ${ kind } was registered without an id`)\n }\n\n if (this.#usedIds.has(id)) {\n throw new DuplicateItemIdError(this.id, id, kind)\n }\n\n this.#usedIds.add(id)\n }\n\n #addMethod(method: ExtensionMethod, kind: string): void {\n this.#claimId(method.name, kind)\n this.#putMethod(method)\n }\n\n #putMethod(method: ExtensionMethod): void {\n this.#methods.set(method.name, method)\n }\n\n // A loader `result` fn \u2192 a SAMPLE_RESULT_LOADER method. Actions and both trigger kinds can declare one,\n // and each satisfies LoaderOwner directly.\n #registerSampleResultLoader(owner: LoaderOwner, kind: string): void {\n if (owner.result.isLoader) {\n this.#addMethod(new SampleResultLoaderMethod(this, owner), kind)\n }\n }\n\n}\n", "import { ExtensionNotRegisteredError } from '../errors'\nimport type { Extension } from './extension'\n\n// The process-wide registry of v2 extensions, keyed by service id. Mirrors the v1 `services` map in\n// v1/namespace.ts: a service module registers once at require time (via Flowrunner.createExtension) and the\n// entry persists across the require cache, so re-requiring the same module is a cheap no-op. Version\n// detection (../index.ts) checks `registry.get(serviceId)` after a module is required \u2014 a hit means v2.\n\nexport class ExtensionRegistry {\n readonly #extensions = new Map<string, Extension>()\n\n register(extension: Extension): void {\n this.#extensions.set(extension.id, extension)\n }\n\n get(id: string): Extension | undefined {\n return this.#extensions.get(id)\n }\n\n all(): Extension[] {\n return [...this.#extensions.values()]\n }\n\n /**\n * The extension for `id`, requiring its module first if it hasn't registered yet. Registration is a\n * require-time side effect and the require cache is shared, so this is a no-op once loaded.\n *\n * The shared namespace must already be installed (../namespace) \u2014 callers reach here via ../index.ts,\n * which imports it.\n */\n load(id: string, entryPointPath: string): Extension {\n if (!this.get(id)) {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require(entryPointPath)\n }\n\n const extension = this.get(id)\n\n if (!extension) {\n throw new ExtensionNotRegisteredError(id, entryPointPath)\n }\n\n return extension\n }\n\n // Test-only: clear the registry between isolated cases.\n reset(): void {\n this.#extensions.clear()\n }\n}\n\nexport const registry = new ExtensionRegistry()\n\n// Function-shaped accessors, kept because they are the package's published surface.\nexport function getExtension(id: string): Extension | undefined {\n return registry.get(id)\n}\n\nexport function getAllExtensions(): Extension[] {\n return registry.all()\n}\n\nexport function resetRegistry(): void {\n registry.reset()\n}\n", "import { Extension } from './extension'\nimport type { OAuth2Props } from './oauth/types'\nimport type { DictionaryRef } from './params'\nimport type { PollingTriggerProps } from './polling-triggers/types'\nimport type { RealtimeSetupProps, RealtimeTriggerProps } from './realtime-triggers/types'\nimport { registry } from './registry'\nimport type {\n ActionProps,\n AnySchema,\n ApiRequestFn,\n DictionaryProps,\n ExtensionApi,\n ExtensionProps,\n ShapeOf,\n} from './types'\n\n// `Flowrunner.createExtension(props)` \u2014 the v2 factory. Builds the Extension, registers it, and returns the\n// `ext` handle: the authoring-facing fa\u00E7ade whose registrars delegate straight to the Extension, which owns\n// the validation and the runtime-generated loader methods (see ./extension.ts).\n\n// Generic so an author's own types reach their handlers: `configItems` / `initContext` / `helpers` /\n// `apiRequest` are inferred here once, and the returned `ext` threads them into every registrar (which\n// then infers its own params). The body works against the erased props, since none of that matters to the\n// runtime \u2014 the single cast on the way out is where the author's shape is re-attached.\nexport function createExtension<\n TConfigSchema extends AnySchema = AnySchema,\n TContext = Record<string, unknown>,\n THelpers = Record<string, unknown>,\n TApiRequest extends ApiRequestFn = ApiRequestFn,\n>(\n props: ExtensionProps<TConfigSchema, TContext, THelpers, TApiRequest>\n): ExtensionApi<ShapeOf<TConfigSchema, TContext, THelpers, TApiRequest>> {\n const extension = new Extension(props as unknown as ExtensionProps)\n\n const api = {\n dictionary(dictionaryProps: DictionaryProps): DictionaryRef {\n return extension.registerDictionary(dictionaryProps)\n },\n\n addAction(actionProps: ActionProps): void {\n extension.registerAction(actionProps)\n },\n\n addPollingTrigger(triggerProps: PollingTriggerProps): void {\n extension.registerPollingTrigger(triggerProps)\n },\n\n setupRealtimeTriggers(realtimeProps: RealtimeSetupProps): void {\n extension.setupRealtime(realtimeProps)\n },\n\n addRealtimeTrigger(triggerProps: RealtimeTriggerProps): void {\n extension.registerRealtimeTrigger(triggerProps)\n },\n\n setupOauth2(oauthProps: OAuth2Props): void {\n extension.setupOAuth2(oauthProps)\n },\n\n extension,\n }\n\n registry.register(extension)\n\n return api as unknown as ExtensionApi<ShapeOf<TConfigSchema, TContext, THelpers, TApiRequest>>\n}\n", "import nodeCrypto from 'crypto'\n\n// Runtime crypto helpers exposed to service code as `Flowrunner.crypto` \u2014 realtime `verify`/`verifyRequest`\n// signature checks (09-realtime-triggers.md). Services can't `require` node modules, so HMAC, constant-time\n// comparison, and timestamp freshness live here.\n\nexport interface FlowrunnerCrypto {\n hmac(algo: string, key: string, data: string, encoding?: 'hex' | 'base64'): string\n timingSafeEqual(a: unknown, b: unknown): boolean\n ageSeconds(timestamp: string | number): number\n}\n\nexport const crypto: FlowrunnerCrypto = {\n hmac(algo, key, data, encoding = 'hex') {\n return nodeCrypto.createHmac(algo, key).update(data ?? '').digest(encoding)\n },\n\n // Constant-time string comparison; false (not throw) on nullish/length-mismatch so callers can `return`.\n timingSafeEqual(a, b) {\n if (typeof a !== 'string' || typeof b !== 'string') {\n return false\n }\n\n const bufferA = Buffer.from(a)\n const bufferB = Buffer.from(b)\n\n if (bufferA.length !== bufferB.length) {\n return false\n }\n\n try {\n return nodeCrypto.timingSafeEqual(bufferA, bufferB)\n } catch {\n return false\n }\n },\n\n // Seconds since `timestamp` (ISO string, or epoch seconds/ms \u2014 magnitude-detected).\n ageSeconds(timestamp) {\n const numeric = typeof timestamp === 'number' ? timestamp : Date.parse(timestamp) || Number(timestamp)\n const milliseconds = numeric < 1e12 ? numeric * 1000 : numeric\n\n return (Date.now() - milliseconds) / 1000\n },\n}\n", "import { type ServiceConfigItemType, ServiceConfigItemTypes, type ServiceConfigsValues } from './constants'\nimport type { ConfigItem } from './types'\n\ntype ConfigValueAdapter = {\n deserialize: (v: unknown) => unknown,\n isEmpty: (v: unknown) => boolean\n}\n\n// Keyed by item type with a mandatory `default` fallback; only types that need\n// special handling are listed, so a lookup by any ServiceConfigItemType may miss\n// and fall through to `default`.\nconst ConfigValueAdapters: Partial<Record<ServiceConfigItemType, ConfigValueAdapter>> & { default: ConfigValueAdapter } = {\n [ServiceConfigItemTypes.BOOL]: {\n deserialize: value => typeof value === 'string' ? value === 'true' : !!value,\n isEmpty: value => typeof value !== 'boolean',\n },\n\n default: {\n deserialize: value => value,\n isEmpty: value => !value,\n },\n}\n\n/**\n * Resolve the effective config values for a service instance: for each declared item take its value from the\n * single `configs` bag, deserialize it with the type adapter, and fall back to the item's default when empty.\n *\n * ONE bag on purpose. `shared` is a UI directive \u2014 it decides who fills a value in and in which dialog \u2014 so\n * it has no business steering resolution. A service installed as a custom extension has no shared tier at\n * all: the customer fills in every item in one dialog. Whoever runs a *shared* extension merges the two\n * tiers before calling in; everyone else passes the single bag they already have.\n */\nexport function prepareServiceConfig(configItems: ConfigItem[], configs: ServiceConfigsValues = {}): ServiceConfigsValues {\n const targetConfig: ServiceConfigsValues = {}\n\n for (const configItem of configItems) {\n const configName = configItem.name\n const configType = configItem.type\n\n const adapter = ConfigValueAdapters[configType] || ConfigValueAdapters.default\n\n targetConfig[configName] = adapter.deserialize(configs[configName])\n\n if (!adapter.isEmpty(targetConfig[configName])) {\n continue\n }\n\n const defaultConfig = adapter.deserialize(configItem.defaultValue)\n\n if (!adapter.isEmpty(defaultConfig)) {\n targetConfig[configName] = defaultConfig\n }\n }\n\n return targetConfig\n}\n", "import { ServiceConfigItemTypes } from '../common/constants'\nimport type { ConfigItem } from '../common/types'\nimport type { ConfigItemSource } from './types'\n\n// Normalize the raw descriptors a v1 service declares via `addService` into the canonical `ConfigItem`\n// shape returned to the console (resolving legacy `hint`/`displayName` aliases and filling defaults).\nexport function normalizeConfigItems(sourceConfigItems?: ConfigItemSource[]): ConfigItem[] {\n return sourceConfigItems?.map(item => ({\n name: item.name,\n type: item.type || ServiceConfigItemTypes.STRING,\n shared: !!item.shared,\n required: !!item.required,\n description: item.description || item.hint || '',\n label: item.label || item.displayName || item.name,\n defaultValue: item.defaultValue,\n options: item.options || [],\n })) || []\n}\n", "import '../namespace'\n\nimport { ServiceConfigItemTypes } from '../common/constants'\nimport type { ConfigItem } from '../common/types'\nimport { normalizeConfigItems } from './config'\nimport { type ServiceClassType } from './constants'\nimport type { ConfigItemSource } from './types'\n\n// The shared global `Flowrunner` is installed by ../namespace (imported above for its side effect). This\n// module owns only the v1 registration seam: `createFlowrunnerSandboxV1` toggles `Flowrunner.ServerCode` for\n// the duration of a v1 require so the required module's `addService(...)` call lands in the `services` map.\n\ninterface RegisteredService {\n ServiceClass: ServiceClassType\n configItems: ConfigItem[]\n}\n\nconst services = new Map<string, RegisteredService>()\n\nexport function createFlowrunnerSandboxV1(serviceId: string, cb: () => void): RegisteredService | undefined {\n global.Flowrunner.ServerCode = {\n addService(ServiceClass: ServiceClassType, sourceConfigItems?: ConfigItemSource[]) {\n services.set(serviceId, {\n ServiceClass,\n configItems: normalizeConfigItems(sourceConfigItems),\n })\n },\n\n ConfigItems: {\n TYPES: ServiceConfigItemTypes,\n },\n }\n\n try {\n cb()\n } finally {\n global.Flowrunner.ServerCode = null\n }\n\n return services.get(serviceId)\n}\n\n", "import { prepareServiceConfig } from '../common/config'\nimport { type ServiceConfigsValues } from '../common/constants'\nimport { FlowrunnerContext, type FlowrunnerContextOptions } from '../common/context'\nimport type { FilesApi } from '../common/context-files'\nimport type { ConfigItem } from '../common/types'\nimport {\n type MethodRequestArgumentsList,\n type MethodRequestArgumentsMap,\n OAUTH_ACCESS_TOKEN_HEADER,\n} from './constants'\nimport { createFlowrunnerSandboxV1 } from './namespace'\n\nfunction requireService(serviceId: string, serviceEntryPointPath: string) {\n const registered = createFlowrunnerSandboxV1(serviceId, () => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require(serviceEntryPointPath)\n })\n\n if (!registered?.ServiceClass) {\n throw new Error(`There is no registered ServiceClass serviceEntryPointPath=\"${ serviceEntryPointPath }\"`)\n }\n\n return registered\n}\n\ntype CreateRuntimeContextData = {\n serverURL: string,\n appId: string,\n apiKey: string,\n //\n runtimeKey: string,\n //\n flowId: string,\n executionId: string\n //\n accessToken?: string\n //\n retrieveNewS3Token: (runtimeKey: string) => Promise<{\n filesS3Token: string\n }>\n //\n createFiles?: (options: FlowrunnerContextOptions) => FilesApi\n\n}\n\n// `flowrunner` is typed by the surface a service actually touches \u2014 `this.flowrunner.Files` \u2014 rather than by\n// the concrete FlowrunnerContext, so a host-supplied client (see `createFiles`) is assignable here too.\ntype FlowrunnerRuntimeContext = {\n flowrunner: { Files: FilesApi }\n httpHeaders: {\n [OAUTH_ACCESS_TOKEN_HEADER]?: string\n }\n}\n\nfunction createRuntimeContext(data: CreateRuntimeContextData): FlowrunnerRuntimeContext {\n const { serverURL, appId, apiKey, runtimeKey, flowId, executionId, accessToken, retrieveNewS3Token } = data\n\n const filesOptions: FlowrunnerContextOptions = {\n serverURL,\n appId,\n apiKey,\n //\n runtimeKey,\n //\n flowId,\n executionId,\n //\n retrieveNewS3Token,\n }\n\n // A v1 service has no `usesFileStorage` opt-in \u2014 `this.flowrunner.Files` is always live \u2014 so a\n // host-supplied client replaces it unconditionally. (v2 consults `createFiles` only when the extension\n // declares `usesFileStorage`, because that is what decides between a real client and the throwing proxy.)\n const flowrunnerContext: FlowrunnerRuntimeContext['flowrunner'] = data.createFiles\n ? { Files: data.createFiles(filesOptions) }\n : new FlowrunnerContext(filesOptions)\n\n const httpHeaders: FlowrunnerRuntimeContext['httpHeaders'] = {}\n\n if (accessToken) {\n httpHeaders[OAUTH_ACCESS_TOKEN_HEADER] = accessToken\n }\n\n return {\n httpHeaders,\n flowrunner: flowrunnerContext,\n }\n}\n\nfunction initServiceInstance(\n serviceId: string,\n serviceEntryPointPath: string,\n configs: ServiceConfigsValues | undefined,\n context: FlowrunnerRuntimeContext\n) {\n const { ServiceClass, configItems } = requireService(serviceId, serviceEntryPointPath)\n\n const config = prepareServiceConfig(configItems, configs)\n\n const service = new ServiceClass(config, context)\n\n Object.assign(service, {\n config,\n flowrunner: context.flowrunner,\n request: {\n context,\n headers: context.httpHeaders,\n },\n })\n\n return service\n}\n\nexport function getServiceConfigs(serviceId: string, serviceEntryPointPath: string): ConfigItem[] {\n const { configItems } = requireService(serviceId, serviceEntryPointPath)\n\n return configItems\n}\n\ntype RunServiceMethodData = {\n serviceId: string,\n serviceEntryPointPath: string,\n configs?: ServiceConfigsValues\n methodName: string\n methodData?: MethodRequestArgumentsMap,\n methodArgs?: MethodRequestArgumentsList\n retrieveNewS3Token: (runtimeKey: string) => Promise<{\n filesS3Token: string\n }>\n // Replaces `this.flowrunner.Files` for this invocation. The default talks to the console over HTTP; a host\n // may build its own against different storage (a legacy-service test mocking the Files API, an e2e harness\n // pointing at a local S3) without the runner or the service knowing.\n createFiles?: (options: FlowrunnerContextOptions) => FilesApi\n executionContext: {\n runtimeKey: string\n accessToken: string\n appId: string\n apiKey: string\n serverURL: string\n flowId: string\n executionId: string\n }\n}\n\nexport async function runServiceMethod(data: RunServiceMethodData): Promise<unknown> {\n const {\n serviceId,\n serviceEntryPointPath,\n configs,\n methodName,\n methodArgs,\n retrieveNewS3Token,\n createFiles,\n } = data\n const { accessToken, runtimeKey, appId, apiKey, serverURL, flowId, executionId } = data.executionContext\n\n const context = createRuntimeContext({\n serverURL,\n appId,\n apiKey,\n //\n runtimeKey,\n //\n flowId,\n executionId,\n //\n accessToken,\n //\n retrieveNewS3Token,\n //\n createFiles,\n })\n\n const serviceInstance = initServiceInstance(serviceId, serviceEntryPointPath, configs, context)\n\n const invoke = (serviceInstance as Record<string, (...args: unknown[]) => unknown>)[methodName]\n\n return invoke.apply(serviceInstance, methodArgs || [])\n}\n\n", "// Public surface of the v2 (declarative, zod-based) extension runtime. Mirrors the v1 entry points\n// (getServiceConfigs / runServiceMethod) plus buildServiceDefinition \u2014 the v2 analogue of jsdoc-parser\n// that produces the same SharedExtensionDefinition model. Version-agnostic callers go through ../index.ts;\n// this module is only reached once a service has been detected as v2.\n\nimport { type ServiceConfigsValues } from '../common/constants'\nimport { FlowrunnerContext, type FlowrunnerContextOptions } from '../common/context'\nimport type { FilesApi } from '../common/context-files'\nimport type { ConfigItem } from '../common/types'\nimport type { SharedExtensionDefinition } from './model/model-types'\nimport { registry } from './registry'\nimport type { Logger } from './types'\n\nexport type { ConfigItem } from '../common/types'\nexport type { SharedExtensionDefinition } from './model/model-types'\n\n// The registry and what it holds. `getExtension` is how ../index.ts detects a v2 service; `resetRegistry`\n// lets a test harness isolate cases (@flowrunner/cli/runtime re-exports it).\nexport { ExecutionContext } from './context/execution-context'\nexport { Extension } from './extension'\nexport { getAllExtensions, getExtension, resetRegistry } from './registry'\n\n// The invocation/result shapes a host may need to type a call against the trigger seams.\nexport type { PollingInvocation, PollingResult } from './polling-triggers/types'\nexport type { RealtimeInvocation } from './realtime-triggers/types'\nexport type { HandlerBag, Logger } from './types'\n\nexport interface RunServiceMethodData {\n serviceId: string\n serviceEntryPointPath: string\n configs?: ServiceConfigsValues\n methodName: string\n methodData?: Record<string, unknown>\n methodArgs?: unknown[]\n logger?: Logger\n retrieveNewS3Token: (runtimeKey: string) => Promise<{ filesS3Token: string }>\n // Replaces the file-service client for this invocation. The default talks to the console over HTTP; a\n // host may build its own against different storage (an e2e harness pointing `ctx.files` at a local S3,\n // say) without the runner or the service knowing. Only consulted when the extension declares\n // `usesFileStorage` \u2014 the throwing proxy is unaffected.\n createFiles?: (options: FlowrunnerContextOptions) => FilesApi\n executionContext: {\n runtimeKey: string\n accessToken: string\n appId: string\n apiKey: string\n serverURL: string\n flowId: string\n executionId: string\n }\n}\n\nexport function getServiceConfigs(serviceId: string, serviceEntryPointPath: string): ConfigItem[] {\n return registry.load(serviceId, serviceEntryPointPath).toConfigItems()\n}\n\nexport function buildServiceDefinition(serviceId: string, serviceEntryPointPath: string): SharedExtensionDefinition {\n return registry.load(serviceId, serviceEntryPointPath).toDefinition()\n}\n\n// The stock file-service client: the console's REST API at `{serverURL}/{appId}/{apiKey}/v1/files`.\nconst defaultCreateFiles = (options: FlowrunnerContextOptions): FilesApi => new FlowrunnerContext(options).Files\n\nexport async function runServiceMethod(data: RunServiceMethodData): Promise<unknown> {\n const { serviceId, serviceEntryPointPath, executionContext, retrieveNewS3Token, methodName } = data\n\n const methodData = data.methodData || {}\n\n const { serverURL, appId, apiKey, runtimeKey, flowId, executionId, accessToken } = executionContext\n\n const extension = registry.load(serviceId, serviceEntryPointPath)\n\n const filesOptions: FlowrunnerContextOptions = {\n serverURL,\n appId,\n apiKey,\n runtimeKey,\n flowId,\n executionId,\n retrieveNewS3Token,\n }\n\n const files = extension.props.usesFileStorage\n ? (data.createFiles ?? defaultCreateFiles)(filesOptions)\n : undefined\n\n const ctx = extension.createContext({ configs: data.configs, accessToken, logger: data.logger, files })\n\n return extension.run(methodName, methodData, ctx)\n}\n", "// Version-agnostic entry point for the flow-extension runner.\n//\n// Consumers import { getServiceConfigs, runServiceMethod } from\n// '@flowrunner/flow-extension-runner' without knowing the extension format version. This module requires\n// the service module once (in the v1 ServerCode sandbox so v1 modules register), then branches on whether\n// the module registered a v2 extension: a hit in the v2 registry \u21D2 v2, otherwise v1.\n\nimport './namespace'\n\nimport * as v1 from './v1'\nimport { createFlowrunnerSandboxV1 } from './v1/namespace'\nimport * as v2 from './v2'\n\nexport * from './errors'\nexport type { RunServiceMethodData } from './v2'\n\n// The file-storage contract and its value shapes, so a host can build its own `ctx.files` for\n// `runServiceMethod({ createFiles })` \u2014 see FilesApi in ./common/context-files.\nexport type { FlowrunnerContextOptions } from './common/context'\nexport type {\n DeleteOptions,\n DeleteResult,\n FileInfo,\n FilesApi,\n GetOptions,\n ListOptions,\n ListResult,\n UploadFileOptions,\n UploadResult,\n UsageResult,\n} from './common/context-files'\nexport { FileScope } from './common/context-files'\n\nexport type ExtensionVersion = 'v1' | 'v2'\n\nexport {\n createFlowrunnerSandboxV1,\n}\n\n// Require the module through the v1 sandbox (harmless for v2 \u2014 it just runs createExtension), then detect.\n// The require is cached, so the subsequent v1/v2 call re-requires for free.\nexport function detectVersion(serviceId: string, serviceEntryPointPath: string): ExtensionVersion {\n createFlowrunnerSandboxV1(serviceId, () => {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n require(serviceEntryPointPath)\n })\n\n return v2.getExtension(serviceId) ? 'v2' : 'v1'\n}\n\nexport function getServiceConfigs(\n serviceId: string,\n serviceEntryPointPath: string\n): ReturnType<typeof v1.getServiceConfigs> {\n return detectVersion(serviceId, serviceEntryPointPath) === 'v2'\n ? v2.getServiceConfigs(serviceId, serviceEntryPointPath)\n : v1.getServiceConfigs(serviceId, serviceEntryPointPath)\n}\n\nexport async function runServiceMethod(data: v2.RunServiceMethodData): Promise<unknown> {\n const frameworkVersion = detectVersion(data.serviceId, data.serviceEntryPointPath)\n\n const result = frameworkVersion === 'v2'\n ? await v2.runServiceMethod(data)\n : await v1.runServiceMethod(data as Parameters<typeof v1.runServiceMethod>[0])\n\n // console.log('got result:', JSON.stringify({\n // frameworkVersion,\n // serviceId: data.serviceId,\n // methodName: data.methodName,\n // methodData: data.methodData,\n // methodArgs: data.methodArgs,\n // result,\n // }, null, 2))\n\n return result\n}\n\n// Build the SharedExtensionDefinition model (serviceInfo + methodsMap). v2 derives it from the declarative\n// definition; v1 services are modeled by the jsdoc-parser, so this only serves v2 (returns null for v1).\nexport function buildServiceDefinition(\n serviceId: string,\n serviceEntryPointPath: string\n): v2.SharedExtensionDefinition | null {\n return detectVersion(serviceId, serviceEntryPointPath) === 'v2'\n ? v2.buildServiceDefinition(serviceId, serviceEntryPointPath)\n : null\n}\n", "import { type SharedExtensionMethodParam } from '@shared/scheme'\n\nimport type { TypedefsMap } from '../types'\n\nconst SCOPE_FIELD: SharedExtensionMethodParam = {\n name : 'scope',\n type : 'String',\n required : false,\n label : 'Scope',\n description : 'Storage scope: WORKSPACE (shared across flows), FLOW (this flow only), EXECUTION (this run only)',\n uiComponent : { type: 'DROPDOWN', options: { values: ['WORKSPACE', 'FLOW', 'EXECUTION'] } },\n defaultValue: 'FLOW',\n}\n\nexport const filesTypeDefs: TypedefsMap = {\n FilesUploadOptions: [\n SCOPE_FIELD,\n {\n name : 'filename',\n type : 'String',\n required : false,\n label : 'Filename',\n description: 'Custom filename (defaults to the original name if omitted)',\n uiComponent: { type: 'SINGLE_LINE_TEXT' },\n },\n {\n name : 'ttl',\n type : 'Number',\n required : false,\n label : 'URL TTL (seconds)',\n description: 'How long the download URL remains valid',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'objectTtl',\n type : 'Number',\n required : false,\n label : 'File TTL (seconds)',\n description: 'How long the file is kept in storage (omit for permanent storage)',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'overwrite',\n type : 'Boolean',\n required : false,\n label : 'Overwrite existing',\n description: 'Replace the file if one with the same name already exists',\n uiComponent: { type: 'TOGGLE' },\n },\n {\n name : 'generateUrl',\n type : 'Boolean',\n required : false,\n label : 'Generate download URL',\n description : 'Include a pre-signed download URL in the response',\n uiComponent : { type: 'TOGGLE' },\n defaultValue: true,\n },\n ],\n\n FilesListOptions: [\n SCOPE_FIELD,\n {\n name : 'limit',\n type : 'Number',\n required : false,\n label : 'Limit',\n description: 'Maximum number of files to return',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'ttl',\n type : 'Number',\n required : false,\n label : 'URL TTL (seconds)',\n description: 'How long the download URLs remain valid',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'generateUrl',\n type : 'Boolean',\n required : false,\n label : 'Generate download URLs',\n description : 'Include pre-signed download URLs in the response',\n uiComponent : { type: 'TOGGLE' },\n defaultValue: true,\n },\n {\n name : 'cursor',\n type : 'String',\n required : false,\n label : 'Cursor',\n description: 'Pagination cursor from a previous response',\n uiComponent: { type: 'SINGLE_LINE_TEXT' },\n },\n ],\n\n FilesGetOptions: [\n SCOPE_FIELD,\n {\n name : 'ttl',\n type : 'Number',\n required : false,\n label : 'URL TTL (seconds)',\n description: 'How long the download URL remains valid',\n uiComponent: { type: 'NUMERIC' },\n },\n {\n name : 'generateUrl',\n type : 'Boolean',\n required : false,\n label : 'Generate download URL',\n description : 'Include a pre-signed download URL in the response',\n uiComponent : { type: 'TOGGLE' },\n defaultValue: true,\n },\n ],\n\n FilesDeleteOptions: [\n SCOPE_FIELD,\n ],\n}\n", "/* eslint-disable @typescript-eslint/no-require-imports */\nimport fs from 'fs'\nimport path from 'path'\n\n// ============================================================================\n// JSDoc programmatic parser (adapted from JS-Code-Runner)\n// ============================================================================\n\nexport interface DocletTag {\n originalTitle: string\n value?: string\n text?: string\n}\n\ninterface DocletParam {\n name: string\n type?: { names?: string[] }\n optional?: boolean\n description?: string\n}\n\ninterface DocletProperty {\n name: string\n type?: { names?: string[] }\n optional?: boolean\n description?: string\n}\n\nexport interface Doclet {\n kind: string\n name: string\n memberof?: string\n scope?: string\n description?: string\n tags?: DocletTag[]\n params?: DocletParam[]\n properties?: DocletProperty[]\n returns?: { type?: { names?: string[] } }[]\n access?: string\n}\n\nfunction resolveJSDocPath(): string {\n const jsDocHolders = require.resolve.paths('jsdoc/lib') || []\n const jsDocPaths = jsDocHolders.map((p: string) => path.join(p, 'jsdoc/lib'))\n\n for (let i = 0; i < jsDocPaths.length; i++) {\n if (fs.existsSync(jsDocPaths[i])) {\n return jsDocPaths[i]\n }\n }\n\n throw new Error('Can not resolve path to JSDoc module.')\n}\n\nconst jsdocPath = resolveJSDocPath()\nconst jsdocModulePath = (mod: string) => path.join(jsdocPath, ...mod.split('/'))\n\nlet _jsdocRequire: NodeRequire\n\nconst jsdocRequire = (modulePath: string) => {\n if (!_jsdocRequire) {\n _jsdocRequire = require('requizzle')({\n infect: true,\n requirePaths: { before: [jsdocPath] },\n })\n\n const Config = _jsdocRequire(jsdocModulePath('jsdoc/config'))\n const env = _jsdocRequire(jsdocModulePath('jsdoc/env'))\n env.conf = new Config().get()\n }\n\n return _jsdocRequire(jsdocModulePath(modulePath))\n}\n\n/**\n * Parse a JS file using jsdoc programmatically and return the doclets array.\n */\nexport function parseJSDoc(filePath: string): Doclet[] {\n const parser = jsdocRequire('jsdoc/src/parser').createParser()\n const handlers = jsdocRequire('jsdoc/src/handlers')\n\n handlers.attachTo(parser)\n\n return parser.parse([filePath])\n}\n", "import {\n type SharedExtensionDefinition,\n type SharedExtensionMetaInfo,\n type SharedExtensionMetaInfoArg,\n type SharedExtensionMethod,\n type SharedExtensionMethodParam,\n type SharedExtensionServiceInfo,\n} from '@shared/scheme'\n\nimport { filesTypeDefs } from './custom-type-defs/files'\nimport type { Doclet, DocletTag } from './lib'\nimport { parseJSDoc } from './lib'\nimport type { TypedefsMap } from './types'\n\n// ============================================================================\n// Internal types\n// ============================================================================\n\ninterface ParsedJSDocsResult {\n serviceInfo: SharedExtensionServiceInfo | null\n methods: MethodInfo[]\n typedefsMap: TypedefsMap\n}\n\ninterface MethodInfo extends Omit<SharedExtensionMethod, 'bodyParams' | 'queryParams' | 'metaInfo'> {\n // name: string\n // description: string\n // returnType: string\n // registerAs: string\n // colorStart: string\n // colorEnd: string\n private: boolean\n // operationName: string\n // customIcon: string\n // category: string\n sampleResult: SharedExtensionMethod['metaInfo']['sampleResult']\n sampleResultLoader: SharedExtensionMethod['metaInfo']['sampleResultLoader']\n route?: string\n routeStr: string\n paramDefs: SharedExtensionMethod['bodyParams']\n}\n\ntype TagCallback = (title: string, value: string, tag: DocletTag) => void\n\n// ============================================================================\n// customTypeDef \u2014 registry of built-in reusable param groups.\n// To add a new domain: create custom-type-defs/<domain>.ts and spread it here.\n// ============================================================================\n\nconst customTypeDef: TypedefsMap = {\n FilesUploadOptions: filesTypeDefs.FilesUploadOptions,\n FilesListOptions: filesTypeDefs.FilesListOptions,\n FilesGetOptions: filesTypeDefs.FilesGetOptions,\n FilesDeleteOptions: filesTypeDefs.FilesDeleteOptions,\n}\n\ntype TagProcessor<T> = (target: T, tagValue: string) => void\n\n// ============================================================================\n// Doclet extraction\n// ============================================================================\n\n/**\n * Find the main service class from doclets.\n * Looks for a class with @integrationName tag, or falls back to the last non-Error class.\n */\nfunction findServiceClassName(doclets: Doclet[]): string | null {\n const withIntegration = doclets\n .find(d => {\n if (d.kind === 'class' && d.tags) {\n return d.tags.find(t => t.originalTitle === 'integrationName')\n }\n })\n\n if (withIntegration) {\n return withIntegration.name\n }\n\n return null\n}\n\n/**\n * Parse a JS file, extract the service class, and return normalized doclets.\n */\nfunction parseJSDocs(filePath: string): ParsedJSDocsResult {\n const doclets = parseJSDoc(filePath)\n const className = findServiceClassName(doclets)\n\n let serviceInfo: SharedExtensionServiceInfo | null = null\n\n const methods: MethodInfo[] = []\n\n const typedefsMap: TypedefsMap = {}\n\n doclets.forEach(d => {\n if (d.kind === 'class' && d.name === className) {\n serviceInfo = composeServiceInfo(d)\n } else if (d.kind === 'function' && d.memberof === className && d.scope === 'instance') {\n methods.push(composeMethod(d))\n } else if (d.kind === 'typedef') {\n const typedefParams = collectTypedef(d)\n\n if (typedefParams) {\n typedefsMap[d.name] = typedefParams\n }\n }\n })\n\n return {\n serviceInfo,\n methods,\n // Extension-defined typedefs override built-ins so authors can customise if needed\n typedefsMap: { ...customTypeDef, ...typedefsMap },\n }\n}\n\nconst ServiceInfoTagsProcessors: Record<string, TagProcessor<SharedExtensionServiceInfo>> = {\n integrationName: (serviceInfo, tagValue) => {\n serviceInfo.integrationName = tagValue || undefined as unknown as string\n },\n\n integrationIcon: (serviceInfo, tagValue) => {\n serviceInfo.integrationIcon = tagValue || null\n },\n\n requireOAuth: serviceInfo => {\n serviceInfo.requireOAuth = true\n },\n\n integrationTriggersScope: (serviceInfo, tagValue) => {\n serviceInfo.integrationTriggersScope = tagValue || null\n },\n}\n\nfunction composeServiceInfo(d: Doclet): SharedExtensionServiceInfo {\n const serviceInfo: SharedExtensionServiceInfo = {\n serviceClassName: d.name,\n integrationName: d.name,\n integrationIcon: null,\n requireOAuth: undefined,\n integrationTriggersScope: null,\n }\n\n iterateTags(d.tags, (tagName, tagValue) => {\n if (ServiceInfoTagsProcessors[tagName]) {\n ServiceInfoTagsProcessors[tagName](serviceInfo, tagValue)\n }\n })\n\n return serviceInfo\n}\n\nfunction iterateTags(tags: DocletTag[] | undefined, cb: TagCallback): void {\n if (tags) {\n tags.forEach(tag => {\n const title = tag.originalTitle\n const value = tag.value || tag.text || ''\n\n cb(title, value, tag)\n })\n }\n}\n\nconst MethodTagsProcessors: Record<string, TagProcessor<MethodInfo>> = {\n paramDef: (methodInfo, tagValue) => {\n if (tagValue) {\n const parsedValue = parseJSON(tagValue)\n\n if (parsedValue) {\n methodInfo.paramDefs.push(parsedValue as SharedExtensionMethodParam)\n }\n }\n },\n\n route: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.route = tagValue\n }\n },\n\n registerAs: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.registerAs = tagValue\n }\n },\n\n operationName: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.operationName = tagValue\n }\n },\n\n customIcon: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.customIcon = tagValue\n }\n },\n\n category: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.category = tagValue\n }\n },\n\n description: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.description = tagValue\n }\n },\n\n appearanceColor: (methodInfo, tagValue) => {\n if (tagValue) {\n const colors = extractColors(tagValue)\n\n methodInfo.colorStart = colors.colorStart\n methodInfo.colorEnd = colors.colorEnd\n }\n },\n\n private: methodInfo => {\n methodInfo.private = true\n },\n\n sampleResult: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.sampleResult = parseJSON(tagValue)\n }\n },\n\n sampleResultLoader: (methodInfo, tagValue) => {\n if (tagValue) {\n methodInfo.sampleResultLoader = parseJSON(tagValue) as SharedExtensionMetaInfo['sampleResultLoader']\n }\n },\n}\n\nfunction composeMethod(m: Doclet): MethodInfo {\n const methodInfo: MethodInfo = {\n name: m.name,\n description: m.description || '',\n returnType: mapReturnType(m.returns?.[0].type?.names?.[0]),\n registerAs: '',\n colorStart: '',\n colorEnd: '',\n private: m.access === 'private',\n operationName: m.name,\n customIcon: '',\n category: '',\n sampleResult: null,\n sampleResultLoader: null,\n routeStr: '',\n paramDefs: [],\n }\n\n if (m.params) {\n m.params.forEach(p => {\n methodInfo.paramDefs.push({\n name: p.name,\n type: p.type?.names?.[0] || 'String',\n required: !p.optional,\n })\n })\n }\n\n iterateTags(m.tags, (tagName, tagValue) => {\n if (MethodTagsProcessors[tagName]) {\n MethodTagsProcessors[tagName](methodInfo, tagValue)\n }\n })\n\n return methodInfo\n}\n\n// ============================================================================\n// Type mapping\n// ============================================================================\n\nconst PRIMITIVES = ['String', 'Object', 'Boolean', 'Number']\n\nconst ParamTypesMap: Record<string, string> = {\n String: 'STRING',\n Object: 'OBJECT',\n Boolean: 'BOOLEAN',\n Number: 'NUMBER',\n}\n\nfunction mapParamType(type: string | undefined): string {\n if (!type) {\n return 'STRING'\n }\n\n if (type.startsWith('Array')) {\n return 'LIST'\n }\n\n return ParamTypesMap[type] || 'STRING'\n}\n\nfunction mapReturnType(type: string | undefined): string {\n if (type) {\n if (type === 'Array' || type.startsWith('Array.') || type.startsWith('Array<')) return 'LIST'\n if (type === 'Object') return 'OBJECT'\n if (type === 'String') return 'STRING'\n }\n\n return 'VOID'\n}\n\n// ============================================================================\n// Typedef map (from @paramDef tags on typedefs)\n// ============================================================================\n\nfunction collectTypedef(d: Doclet): SharedExtensionMethodParam[] | undefined {\n const defs: SharedExtensionMethodParam[] = []\n\n iterateTags(d.tags, (title, value) => {\n if (title === 'paramDef') {\n const parsedValue = parseJSON(value)\n\n if (parsedValue) {\n defs.push(parsedValue as SharedExtensionMethodParam)\n }\n }\n })\n\n if (d.properties) {\n d.properties.forEach(property => {\n // JSDoc may omit the type on a @property line \u2014 preserved as-is at runtime\n const type = property?.type?.names?.[0] as string\n\n defs.push({\n name: property.name,\n required: !property.optional,\n description: property.description,\n type,\n })\n })\n }\n\n if (defs.length > 0) {\n return defs\n }\n}\n\n// ============================================================================\n// Param building (resolves typedefs)\n// ============================================================================\n\nfunction buildParam(paramDef: SharedExtensionMethodParam, typedefsMap: TypedefsMap, nested = false): SharedExtensionMethodParam {\n const isCustomType = !nested &&\n paramDef.type &&\n !PRIMITIVES.includes(paramDef.type) &&\n !paramDef.type.startsWith('Array')\n\n let properties: SharedExtensionMethodParam[] | undefined\n\n if (isCustomType && typedefsMap[paramDef.type!]) {\n let subDefs = typedefsMap[paramDef.type!]\n\n if (paramDef.include?.length) {\n const includeSet = new Set(paramDef.include)\n\n subDefs = subDefs.filter(sd => includeSet.has(sd.name))\n }\n\n if (subDefs.length > 0) {\n properties = subDefs.map(sp => buildParam(sp, typedefsMap, true))\n }\n }\n\n const param: SharedExtensionMethodParam = {\n name: paramDef.name,\n required: paramDef.required || false,\n description: paramDef.description || '',\n type: isCustomType ? 'OBJECT' : mapParamType(paramDef.type),\n }\n\n if (nested) {\n if (paramDef.label !== undefined) {\n param.label = paramDef.label\n }\n\n if (paramDef.uiComponent !== undefined) {\n param.uiComponent = paramDef.uiComponent\n }\n\n if (paramDef.dependsOn !== undefined) {\n param.dependsOn = paramDef.dependsOn\n }\n\n if (paramDef.dictionary !== undefined) {\n param.dictionary = paramDef.dictionary\n }\n\n if (paramDef.defaultValue !== undefined) {\n param.defaultValue = paramDef.defaultValue\n }\n }\n\n if (properties && properties.length > 0) {\n param.properties = properties\n }\n\n if (param.type === 'LIST') {\n param.items = { type: 'OBJECT' }\n }\n\n return param\n}\n\n// ============================================================================\n// MetaInfo args\n// ============================================================================\n\nfunction buildMetaInfoArgs(paramDefs: SharedExtensionMethodParam[], typedefsMap: TypedefsMap): Record<string, SharedExtensionMetaInfoArg> {\n const args: Record<string, SharedExtensionMetaInfoArg> = {}\n\n for (const pd of paramDefs) {\n const isCustomType = pd.type &&\n !PRIMITIVES.includes(pd.type) &&\n !pd.type.startsWith('Array')\n\n if (isCustomType && typedefsMap[pd.type!]) {\n const entry: SharedExtensionMetaInfoArg = {}\n if (pd.label) entry.label = pd.label\n args[pd.name] = entry\n continue\n }\n\n const entry: SharedExtensionMetaInfoArg = {}\n\n if (pd.label) entry.label = pd.label\n if (pd.dictionary) entry.dictionary = pd.dictionary\n if (pd.dependsOn && pd.dependsOn.length > 0) entry.dependsOn = pd.dependsOn\n if (pd.uiComponent) entry.uiComponent = pd.uiComponent\n\n args[pd.name] = entry\n }\n\n return args\n}\n\n// ============================================================================\n// Colors\n// ============================================================================\n\nfunction extractColors(colorStr: string): { colorStart: string; colorEnd: string } {\n if (!colorStr) {\n return { colorStart: '', colorEnd: '' }\n }\n\n const colors = colorStr.split(/[,\\s]+/).map(c => c.trim()).filter(Boolean)\n\n return {\n colorStart: colors[0] || '',\n colorEnd: colors[1] || colors[0] || '',\n }\n}\n\n// ============================================================================\n// Service JSON builder \u2014 converts normalized parseJSDocs output to service JSON\n// ============================================================================\n\nfunction parseJSON(str: string): unknown {\n try {\n return JSON.parse(str)\n } catch {\n return null\n }\n}\n\nexport function parseJsDocToServiceJson(entryPoint: string): SharedExtensionDefinition {\n const { serviceInfo, methods, typedefsMap } = parseJSDocs(entryPoint)\n\n const methodsMap: SharedExtensionDefinition['methodsMap'] = {}\n\n for (const method of methods) {\n if (method.private) {\n continue\n }\n\n const {\n name,\n route,\n registerAs,\n colorStart,\n colorEnd,\n operationName,\n customIcon,\n category,\n description,\n sampleResult,\n sampleResultLoader,\n paramDefs,\n returnType,\n } = method\n\n const isSystem = registerAs === 'SYSTEM'\n\n // Determine HTTP method from @route for param placement\n const httpMethod = route\n ? route.split(/\\s+/)[0].toUpperCase()\n : name.startsWith('get') ? 'GET' : 'POST'\n\n const isQueryPlacement = httpMethod === 'GET'\n\n // Build params\n const params = paramDefs.map(pd => buildParam(pd, typedefsMap))\n\n const queryParams = isQueryPlacement ? params : []\n const bodyParams = isQueryPlacement ? [] : params\n\n // Build metaInfo \u2014 only from @paramDef, not from standard @param fallback\n const metaInfoArgs = paramDefs.length > 0\n ? buildMetaInfoArgs(paramDefs, typedefsMap)\n : {}\n\n methodsMap[name] = {\n colorStart,\n colorEnd,\n queryParams, // todo remove me\n bodyParams,\n customIcon: isSystem ? undefined : customIcon,\n registerAs,\n category,\n metaInfo: {\n args: metaInfoArgs,\n sampleResult: isSystem ? undefined : sampleResult,\n sampleResultLoader: (isSystem ? undefined : sampleResultLoader) as SharedExtensionMethod['metaInfo']['sampleResultLoader'],\n },\n returnType,\n description,\n operationName,\n name,\n }\n }\n\n return {\n runnerVersion: 'v1', //TODO: temp\n methodsMap,\n serviceInfo: serviceInfo!,\n }\n}\n", "import { createHash } from 'crypto'\nimport fs from 'fs'\nimport path from 'path'\n\nimport { HASH_EXCLUDED_FOLDERS } from '../../constants'\n\n// The version of a service is a hash of the service, and of nothing else.\n//\n// That is what makes it comparable as well as unique: two checkouts of the same service hash the same\n// wherever they live, so `pull` can tell \"already up to date\" from \"differs\" without downloading anything \u2014\n// and a change to a sibling service, or to the project around it, cannot move it.\n//\n// `node_modules` is packed but not hashed. The service's own `package-lock.json` is hashed and says\n// everything about the dependency tree that matters, so a bump still produces a new version \u2014 which it must,\n// since the pod caches by this hash and the tree ships inside the package.\n//\n// Paths stay relative to the service root: the same sources unpacked anywhere else must hash the same.\n\nexport async function computeServiceHash(projectRoot: string, serviceId: string): Promise<string> {\n const hash = createHash('sha256')\n const serviceDir = path.resolve(projectRoot, 'services', serviceId)\n\n const files: string[] = []\n\n collectFiles(serviceDir, '', files)\n files.sort()\n\n for (const file of files) {\n hash.update(file)\n hash.update(fs.readFileSync(path.resolve(serviceDir, file)))\n }\n\n return hash.digest('hex')\n}\n\n/** Walks `dir` and appends every file to `files`, relative to the service root. */\nfunction collectFiles(serviceDir: string, relativeDir: string, files: string[]): void {\n const entries = fs.readdirSync(path.resolve(serviceDir, relativeDir), { withFileTypes: true })\n\n for (const entry of entries) {\n if (HASH_EXCLUDED_FOLDERS.includes(entry.name)) {\n continue\n }\n\n const relativePath = relativeDir ? path.join(relativeDir, entry.name) : entry.name\n\n if (!entry.isSymbolicLink()) {\n if (entry.isDirectory()) {\n collectFiles(serviceDir, relativePath, files)\n } else {\n files.push(relativePath)\n }\n }\n }\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { DiscoveredService } from './discover-services'\n\nexport interface PublicFile {\n serviceId: string\n /** Path relative to public/, e.g. \"icon.webp\" */\n relativePath: string\n buffer: Buffer\n}\n\nexport interface PublicFilesResult {\n files: PublicFile[]\n /** Icons a service declares that are not on disk \u2014 the deploy goes ahead without them. */\n missing: { serviceId: string; relativePath: string }[]\n}\n\n/**\n * Collects all public files referenced by the given service definitions (e.g. integrationIcon).\n * Icon paths in JSDoc use a leading slash relative to public/ (e.g. \"/icon.webp\").\n */\nexport function collectPublicFiles(\n services: DiscoveredService[],\n projectRoot: string = process.cwd()\n): PublicFilesResult {\n const files: PublicFile[] = []\n const missing: { serviceId: string; relativePath: string }[] = []\n\n for (const service of services) {\n // Per service, not per project: icons live in `services/<id>/public/`. Guarding on a root `public/`\n // directory instead used to drop every icon in a project that has no such folder.\n const servicePublicDir = path.resolve(projectRoot, 'services', service.serviceId, 'public')\n\n if (!fs.existsSync(servicePublicDir)) {\n continue\n }\n\n const iconPath = service.serviceInfo.integrationIcon\n\n if (!iconPath) {\n continue\n }\n\n // Strip leading slash \u2014 \"/icon.webp\" \u2192 \"icon.webp\"\n const relativePath = iconPath.replace(/^\\//, '')\n const fullPath = path.resolve(servicePublicDir, relativePath)\n\n // Confine the resolved path to public/. The separator is what makes this a containment check rather than\n // a prefix match: without it, `services/<id>/public-anything/` also starts with the directory name.\n if (!fullPath.startsWith(servicePublicDir + path.sep)) {\n continue\n }\n\n if (!fs.existsSync(fullPath)) {\n missing.push({ serviceId: service.serviceId, relativePath })\n\n continue\n }\n\n files.push({\n relativePath,\n serviceId: service.serviceId,\n buffer : fs.readFileSync(fullPath),\n })\n }\n\n return { files, missing }\n}\n", "import { SelectionRequiredError, UnknownServiceError } from '../../errors'\n\n// Which of the project's services a command is about.\n//\n// A deploy touches only the services it names, so \"everything\" has to be asked for. The one exception is a\n// project with a single service, where there is nothing to disambiguate.\n//\n// Generic over anything with a `serviceId` so the same rules cover a discovered service, a planned one, and\n// a service listed by the workspace \u2014 the question is the same in all three cases.\n\nexport interface Selection {\n /** Explicit ids. Wins over `all`. */\n serviceIds?: string[]\n /** Take every candidate. */\n all?: boolean\n}\n\nexport function selectServices<T extends { serviceId: string }>(\n available: T[],\n selection: Selection = {}\n): T[] {\n const ids = available.map(entry => entry.serviceId)\n\n if (selection.serviceIds?.length) {\n return selection.serviceIds.map(serviceId => {\n const match = available.find(entry => entry.serviceId === serviceId)\n\n if (!match) {\n throw new UnknownServiceError(serviceId, ids)\n }\n\n return match\n })\n }\n\n if (selection.all || available.length === 1) {\n return available\n }\n\n throw new SelectionRequiredError(ids)\n}\n", "import archiver from 'archiver'\nimport path from 'path'\n\n// The archive the pod unpacks, and it IS the service folder:\n//\n// package/src/index.js \u2190 the service's source\n// package/public/icon.webp\n// package/package.json \u2190 the service's own manifest\n// package/package-lock.json\n// package/node_modules/** \u2190 the service's own dependencies\n//\n// So `serviceFilePath` is relative to the service ('src/index.js'), and `require` resolves by walking up\n// from `package/src/` to `package/node_modules`. Nothing from the project root is in here.\n\nexport async function createServiceZip(\n definition: object,\n projectRoot: string,\n serviceId: string\n): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const archive = archiver('zip', { zlib: { level: 9 } })\n const chunks: Buffer[] = []\n\n archive.on('data', (chunk: Buffer) => chunks.push(chunk))\n archive.on('end', () => resolve(Buffer.concat(chunks)))\n archive.on('error', reject)\n\n // Everything the service folder holds, `node_modules` included \u2014 the pod installs nothing.\n archive.directory(`${ path.resolve(projectRoot, 'services', serviceId) }/`, 'package')\n\n // Add definition.json next to package/ (for debugging/testing)\n archive.append(JSON.stringify(definition, null, 2), { name: 'definition.json' })\n\n archive.finalize()\n })\n}\n", "import { execFileSync } from 'child_process'\nimport fs from 'fs'\nimport path from 'path'\n\nimport {\n CONFIG_FILE,\n PLACEHOLDER_SCRIPTS,\n TEST_DEV_DEPENDENCIES,\n TEST_GITIGNORE_ENTRIES,\n TEST_SCRIPTS,\n TOKEN_DIR,\n} from '../../constants'\nimport { PromptAbortedError, PromptRequiredError } from '../../errors'\nimport { ensureServerUrl } from '../../project/config'\nimport { packageRoot } from '../../templates/package-root'\nimport { PORTABLE_CLI_COMMAND } from '../../utils/invocation'\nimport { resolveServerTarget } from '../server-target'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport type { CreateServiceOptions, ScaffoldedService } from './create-service'\nimport { resolveTemplateId, scaffoldFromTemplate } from './create-service'\nimport { writeTestingFiles } from './testing'\n\n// `init` bootstraps the project the other commands assume: an npm package with the CLI as a devDependency,\n// a `flowrunner.json` naming a server, a `.gitignore` that keeps the token out of git, and the unit-test\n// harness a service is written against (see `testing.ts`).\n//\n// Nothing here overwrites. The command is meant to be safe to run in a directory that already has files \u2014\n// adding FlowRunner to an existing repository is the same operation as starting from nothing, minus the\n// files that are already there.\n\nexport type InitEvent =\n | { type: 'target'; projectRoot: string; lines: string[] }\n | { type: 'files'; created: string[]; skipped: string[]; serverUrl: string }\n | { type: 'repository'; committed: boolean }\n | { type: 'cancelled' }\n | { type: 'warning'; message: string }\n\nexport interface InitOptions extends Omit<CreateServiceOptions, 'onEvent'>, OperationOptions<InitEvent> {\n /** A template to scaffold a first service from. Omitted creates just the project. */\n template?: string\n /**\n * Written into `flowrunner.json`; defaults to the CLI's own default cluster.\n *\n * A cluster name (`prod`/`dev`/`local`) or a full URL.\n */\n server?: string\n /** Set false to skip `npm install`. */\n install?: boolean\n /**\n * Set false to skip the unit-test harness \u2014 the sandbox, the jest config, and their dependencies.\n *\n * For a project that already has a test runner it does not want two of.\n */\n tests?: boolean\n /** Set false to skip initialising a git repository and making the first commit. */\n git?: boolean\n /**\n * Confirm writing into a directory that already holds something.\n *\n * `init` never overwrites, but landing a project on top of an unrelated one \u2014 a mistyped `--dir`, a\n * stray `..` \u2014 is worth a second look. Omitted means nothing can be asked, so a directory that needs\n * confirming throws instead.\n */\n onConfirmTarget?: (target: TargetDescription) => Promise<boolean>\n /** Progress from the service scaffold, when a template was given. */\n onServiceEvent?: CreateServiceOptions['onEvent']\n}\n\nexport interface TargetDescription {\n projectRoot: string\n lines: string[]\n defaultYes: boolean\n}\n\nexport interface InitResult {\n projectRoot: string\n /** The target was not confirmed, so nothing was written. */\n cancelled: boolean\n created: string[]\n skipped: string[]\n serverUrl: string\n /** The harness files that were written, relative to the project root. Empty under `tests: false`. */\n testingFiles: string[]\n service?: ScaffoldedService\n installed: boolean\n /** 'created' \u2014 a new repository; 'existing' \u2014 left alone; 'skipped' \u2014 `--no-git`; 'failed' \u2014 git refused. */\n repository: 'created' | 'existing' | 'skipped' | 'failed'\n committed: boolean\n}\n\nconst GITIGNORE_ENTRIES = ['node_modules/', `${ TOKEN_DIR }/`, ...TEST_GITIGNORE_ENTRIES]\n\n/** The package `init` writes into `devDependencies`, and the pre-rename name a project may already hold. */\nconst CLI_PACKAGE = '@flowrunner/cli'\nconst CLI_PACKAGE_NAMES = [CLI_PACKAGE, 'flowrunner-cli']\n\n/** Reports something that went wrong without stopping the init. */\ntype Warn = (message: string) => void\n\n/** The CLI's own version, so a generated project pins the version that generated it. */\nfunction cliVersion(): string {\n return JSON.parse(fs.readFileSync(path.join(packageRoot(), 'package.json'), 'utf-8')).version\n}\n\n/** A directory name turned into something npm will accept as a package name. */\nfunction packageNameFrom(directory: string): string {\n const name = path.basename(path.resolve(directory))\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^[._-]+|[-._]+$/g, '')\n\n return name || 'flowrunner-extensions'\n}\n\n/**\n * Add every entry of `additions` that the section does not already have, and report whether anything\n * changed.\n *\n * \"Already have\" is by key, never by value: a project pinning jest 29, or defining its own `test` script\n * that runs something else first, has made a decision \u2014 and `init` is not the command that revisits it.\n *\n * `placeholders` is the one exception, and it is not a value judgement: `npm init -y` writes a `test` script\n * that exits 1, which is a stand-in for the absence of one rather than anything the project chose.\n */\nfunction addMissing(\n section: Record<string, string>,\n additions: Record<string, string>,\n placeholders: Record<string, string> = {}\n): boolean {\n let changed = false\n\n for (const [name, value] of Object.entries(additions)) {\n if (section[name] === undefined || section[name] === placeholders[name]) {\n section[name] = value\n changed = true\n }\n }\n\n return changed\n}\n\nfunction writePackageJson(projectRoot: string, tests: boolean): 'created' | 'updated' | 'skipped' {\n const fullPath = path.join(projectRoot, 'package.json')\n const version = cliVersion()\n\n const devDependencies = { [CLI_PACKAGE]: version, ...(tests ? TEST_DEV_DEPENDENCIES : {}) }\n const scripts = { deploy: 'flowrunner deploy --all', ...(tests ? TEST_SCRIPTS : {}) }\n\n if (!fs.existsSync(fullPath)) {\n const manifest = {\n name : packageNameFrom(projectRoot),\n version : '0.0.1',\n private : true,\n description: 'FlowRunner custom extensions.',\n scripts,\n devDependencies,\n }\n\n fs.writeFileSync(fullPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8')\n\n return 'created'\n }\n\n // An existing project keeps its own manifest, including a version of the CLI or of jest it has\n // deliberately pinned. What is worth adding is what the project cannot work without: the CLI itself,\n // without which `npx flowrunner` resolves to whatever is globally installed \u2014 or to nothing \u2014 and the\n // packages the harness files just copied in would fail to require.\n const manifest = JSON.parse(fs.readFileSync(fullPath, 'utf-8'))\n\n // A CLI the project already declares is left exactly where it is. Which section it sits in is the\n // project's own decision, and listing it twice is how npm ends up resolving two copies \u2014 which is also\n // why the pre-rename name counts: adding `@flowrunner/cli` beside an existing `flowrunner-cli` would\n // install both and leave the launcher choosing between them.\n const alreadyDeclared = CLI_PACKAGE_NAMES.some(name =>\n manifest.dependencies?.[name] || manifest.devDependencies?.[name])\n\n const additions = alreadyDeclared\n ? Object.fromEntries(Object.entries(devDependencies).filter(([name]) => name !== CLI_PACKAGE))\n : devDependencies\n\n manifest.devDependencies ??= {}\n manifest.scripts ??= {}\n\n // Both run \u2014 `.some()` on an array, not `||` \u2014 so a manifest needing only the scripts still gets them.\n const changed = [\n addMissing(manifest.devDependencies, additions),\n addMissing(manifest.scripts, tests ? TEST_SCRIPTS : {}, PLACEHOLDER_SCRIPTS),\n ].some(Boolean)\n\n if (!changed) {\n return 'skipped'\n }\n\n fs.writeFileSync(fullPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8')\n\n return 'updated'\n}\n\nfunction writeGitignore(projectRoot: string): 'created' | 'updated' | 'skipped' {\n const fullPath = path.join(projectRoot, '.gitignore')\n\n if (!fs.existsSync(fullPath)) {\n fs.writeFileSync(fullPath, GITIGNORE_ENTRIES.join('\\n') + '\\n', 'utf-8')\n\n return 'created'\n }\n\n const content = fs.readFileSync(fullPath, 'utf-8')\n const lines = content.split('\\n').map(line => line.trim())\n // A bare `node_modules` covers `node_modules/`; compare on the stem so an existing entry is respected.\n const missing = GITIGNORE_ENTRIES.filter(entry => !lines.includes(entry) && !lines.includes(entry.replace(/\\/$/, '')))\n\n if (missing.length === 0) {\n return 'skipped'\n }\n\n fs.appendFileSync(fullPath, `${ content.endsWith('\\n') ? '' : '\\n' }${ missing.join('\\n') }\\n`)\n\n return 'updated'\n}\n\nconst README = (name: string) => `# ${ name }\n\nFlowRunner custom extensions for this workspace.\n\nEach folder under \\`services/\\` is one extension and one npm package: it has its own \\`package.json\\` and its\nown \\`node_modules\\`, so \\`npm install\\` for a service is run **inside that service's folder**. It is deployed\nand versioned on its own, and deploying one leaves every other service in the workspace untouched \u2014 which is\nwhat lets several projects deploy into the same workspace.\n\n\\`\\`\\`bash\n${ PORTABLE_CLI_COMMAND } cs # scaffold another service\n${ PORTABLE_CLI_COMMAND } login # authorize against the console (once)\n${ PORTABLE_CLI_COMMAND } deploy -s <id># build one service's definition and upload it (--all for every one)\n${ PORTABLE_CLI_COMMAND } pull # bring the workspace's services down into services/\n${ PORTABLE_CLI_COMMAND } init-claude # wire the FlowRunner agents into Claude Code\n\ncd services/<id> && npm install # add a dependency to one service\nnpm test # run the unit suites in services/*/tests/\n\\`\\`\\`\n\nWith \\`npm i -g @flowrunner/cli\\` you can drop the \\`npx\\` and just write \\`flowrunner cs\\`. The global copy only\nlaunches the one in this project's \\`node_modules\\`, so the version pinned in \\`package.json\\` is still the one\nthat runs.\n\nTo move this project to a newer CLI, upgrade the dependency and commit it \u2014 that is what decides which code\nruns, for you and for CI:\n\n\\`\\`\\`bash\nnpm i -D @flowrunner/cli@<version>\n\\`\\`\\`\n\nUpdating the global copy (\\`npm i -g @flowrunner/cli@latest\\`) is rarely needed and changes nothing here.\n\nTests run each service the way the platform does, with HTTP intercepted at the socket \u2014 see\n\\`sandbox/index.js\\`, which \\`${ PORTABLE_CLI_COMMAND } init\\` copied here for you to edit.\n\nThe authoring reference the CLI ships lives in\n\\`node_modules/@flowrunner/cli/ai-docs/instructions/service-code-format/\\`. Point your AI agent at it \u2014 or run\n\\`${ PORTABLE_CLI_COMMAND } init-claude\\` and Claude Code is wired up for you.\n\n\\`flowrunner.json\\` names the server and the workspace and belongs in git.\n\\`.flowrunner/token\\` is the deploy token and must not.\n`\n\nfunction writeReadme(projectRoot: string): 'created' | 'skipped' {\n const fullPath = path.join(projectRoot, 'README.md')\n\n if (fs.existsSync(fullPath)) {\n return 'skipped'\n }\n\n fs.writeFileSync(fullPath, README(packageNameFrom(projectRoot)), 'utf-8')\n\n return 'created'\n}\n\nfunction git(projectRoot: string, args: string[]): void {\n execFileSync('git', args, { cwd: projectRoot, stdio: 'pipe' })\n}\n\n/** Whether the directory is already tracked \u2014 by its own repository or by one further up. */\nfunction insideRepository(projectRoot: string): boolean {\n try {\n git(projectRoot, ['rev-parse', '--is-inside-work-tree'])\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Start a repository, unless the directory is already in one.\n *\n * An existing repository is left completely alone \u2014 `init` has no business running `git init` inside a\n * monorepo subdirectory, and it must never touch a working tree that may hold someone's unrelated changes.\n */\nfunction gitInit(projectRoot: string, warn: Warn): 'created' | 'existing' | 'failed' {\n if (insideRepository(projectRoot)) {\n return 'existing'\n }\n\n try {\n // `-b main` also silences git's default-branch hint. Older gits do not know the flag.\n try {\n git(projectRoot, ['init', '-b', 'main'])\n } catch {\n git(projectRoot, ['init'])\n }\n\n return 'created'\n } catch {\n warn('git init failed \u2014 is git installed? The project files are fine either way.')\n\n return 'failed'\n }\n}\n\n/**\n * The first commit, made after `npm install` so the lockfile is part of it.\n *\n * Only ever runs in a repository this command just created, where staging everything is safe by\n * construction: there is nothing else in it.\n */\nfunction gitCommit(projectRoot: string, warn: Warn): boolean {\n try {\n git(projectRoot, ['add', '-A'])\n git(projectRoot, ['commit', '-m', 'Initial commit'])\n\n return true\n } catch {\n // Most often an unconfigured user.name / user.email. Setting one ourselves would stamp an identity the\n // user never chose onto their own history, so the files stay staged and they decide.\n warn('git commit failed \u2014 the files are staged; commit them once git knows who you are.')\n\n return false\n }\n}\n\nfunction npmInstall(projectRoot: string, warn: Warn): boolean {\n const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'\n\n try {\n execFileSync(npm, ['install'], { cwd: projectRoot, stdio: 'inherit' })\n\n return true\n } catch {\n // The project files are already correct, so a failed install is a warning and not a failed init: the\n // user can run `npm install` themselves once they have fixed whatever npm complained about.\n warn('npm install failed \u2014 run it yourself in the project directory.')\n\n return false\n }\n}\n\n/**\n * What the user is about to do to a directory, in the terms that would make them notice a mistake: the\n * absolute path, whether it exists, whether anything is in it, and whether it is already a project.\n */\nexport function describeTarget(projectRoot: string): TargetDescription {\n if (!fs.existsSync(projectRoot)) {\n return { projectRoot, lines: ['a new directory'], defaultYes: true }\n }\n\n if (!fs.statSync(projectRoot).isDirectory()) {\n return { projectRoot, lines: ['not a directory'], defaultYes: false }\n }\n\n const entries = fs.readdirSync(projectRoot).filter(entry => entry !== '.git')\n\n if (entries.length === 0) {\n return { projectRoot, lines: ['an empty directory'], defaultYes: true }\n }\n\n const lines = [`an existing directory \u2014 ${ entries.length } ${ entries.length === 1 ? 'entry' : 'entries' }`]\n\n if (entries.includes('package.json')) {\n lines.push('already an npm project \u2014 its package.json will be kept, with the CLI added as a devDependency')\n }\n\n if (entries.includes('services')) {\n lines.push('already has services/')\n }\n\n if (insideRepository(projectRoot)) {\n lines.push('already tracked by git \u2014 no repository will be created and nothing will be committed')\n }\n\n // Anything already in there is a reason to look twice: `init -d ..` or a mistyped path lands here, and\n // the files this writes would then join a project that never asked for them.\n return { projectRoot, lines, defaultYes: false }\n}\n\n/** Create the project the other operations assume, optionally with a first service in it. */\nexport async function init(options: InitOptions = {}): Promise<InitResult> {\n const projectRoot = path.resolve(options.cwd ?? '.')\n const emit = emitter(options)\n const warn = (message: string) => emit({ type: 'warning', message })\n\n // Both resolved before anything is written, so an unknown template or an unknown server fails without\n // leaving a half-made project behind.\n const template = options.template ? resolveTemplateId(options.template) : null\n const requestedServerUrl = options.server ? resolveServerTarget(options.server) : undefined\n\n const target = describeTarget(projectRoot)\n\n emit({ type: 'target', projectRoot, lines: target.lines })\n\n // A directory that already holds something, and no way to ask about it: neither answer can be assumed.\n // Writing would be a silent surprise, and doing nothing would be a silent no-op \u2014 so say what is needed.\n if (!options.acceptDefaults && !options.onConfirmTarget && !target.defaultYes) {\n throw new PromptRequiredError(\n 'confirm-target',\n `${ projectRoot } already has files in it, and there is no way to confirm writing a project there.`\n )\n }\n\n // `acceptDefaults` already means \"ask nothing\".\n if (!options.acceptDefaults && options.onConfirmTarget && !await options.onConfirmTarget(target)) {\n emit({ type: 'cancelled' })\n\n return {\n projectRoot,\n cancelled : true,\n created : [],\n skipped : [],\n serverUrl : '',\n testingFiles: [],\n installed : false,\n repository : 'skipped',\n committed : false,\n }\n }\n\n if (!fs.existsSync(projectRoot)) {\n fs.mkdirSync(projectRoot, { recursive: true })\n }\n\n if (!fs.statSync(projectRoot).isDirectory()) {\n throw new PromptAbortedError(`${ projectRoot } is not a directory.`)\n }\n\n const created: string[] = []\n const skipped: string[] = []\n\n const record = (file: string, outcome: 'created' | 'updated' | 'skipped') => {\n (outcome === 'skipped' ? skipped : created).push(outcome === 'updated' ? `${ file } (updated)` : file)\n }\n\n const tests = options.tests !== false\n\n record('package.json', writePackageJson(projectRoot, tests))\n record('.gitignore', writeGitignore(projectRoot))\n\n const server = ensureServerUrl(projectRoot, requestedServerUrl)\n\n record(CONFIG_FILE, server.created ? 'created' : server.updated ? 'updated' : 'skipped')\n record('README.md', writeReadme(projectRoot))\n\n // The harness is part of the project rather than something bolted on afterwards, so it is written with\n // the rest of the scaffolding and reported in the same list.\n const testing = tests ? writeTestingFiles(projectRoot) : { created: [], skipped: [] }\n\n testing.created.forEach(file => record(file, 'created'))\n testing.skipped.forEach(file => record(file, 'skipped'))\n\n emit({ type: 'files', created, skipped, serverUrl: server.serverUrl })\n\n const service = template\n ? await scaffoldFromTemplate(template, { ...options, onEvent: options.onServiceEvent }, projectRoot)\n : undefined\n\n // Before the install, so a repository exists to commit into; the commit itself waits until after it, so\n // package-lock.json lands in the first commit rather than as an immediate diff.\n const repository = options.git === false ? 'skipped' : gitInit(projectRoot, warn)\n const installed = options.install === false ? false : npmInstall(projectRoot, warn)\n const committed = repository === 'created' && gitCommit(projectRoot, warn)\n\n if (repository === 'created') {\n emit({ type: 'repository', committed })\n }\n\n return {\n projectRoot,\n cancelled : false,\n created,\n skipped,\n serverUrl : server.serverUrl,\n testingFiles: testing.created,\n service,\n installed,\n repository,\n committed,\n }\n}\n\nexport type { TestingFilesResult } from './testing'\nexport { testingFilesDirectory, writeTestingFiles } from './testing'\n", "import fs from 'fs'\nimport path from 'path'\n\n// The CLI runs from two places with different depths \u2014 bundled at `dist/index.js`, and straight from\n// `src/**` via tsx when `bin/flowrunner.js` finds the TypeScript entry (dev mode / npm link). Neither a\n// fixed `../` count nor `process.cwd()` (the *target* project) locates the shipped `templates/` folder, so\n// walk up to the package that owns this file.\n\n// Either name identifies our own package: the CLI moved to the `@flowrunner` org, and a copy installed\n// under the old name must still locate its own `templates/` and `ai-docs/`.\nconst PACKAGE_NAMES = ['@flowrunner/cli', 'flowrunner-cli']\n\nlet cached: string | null = null\n\nfunction findPackageRoot(): string {\n let dir = __dirname\n\n while (true) {\n const manifest = path.join(dir, 'package.json')\n\n if (fs.existsSync(manifest)) {\n try {\n if (PACKAGE_NAMES.includes(JSON.parse(fs.readFileSync(manifest, 'utf-8')).name)) {\n return dir\n }\n } catch {\n // A malformed package.json on the way up is not ours to complain about \u2014 keep walking.\n }\n }\n\n const parent = path.dirname(dir)\n\n if (parent === dir) {\n throw new Error(`Could not locate the \"${ PACKAGE_NAMES[0] }\" package root above ${ __dirname }`)\n }\n\n dir = parent\n }\n}\n\nexport function packageRoot(): string {\n cached ??= findPackageRoot()\n\n return cached\n}\n\n/** Absolute path of the shipped template content (`packages/cli/templates`). */\nexport function templatesRoot(): string {\n return path.join(packageRoot(), 'templates')\n}\n", "import fs from 'fs'\nimport path from 'path'\n\n// How the CLI tells a user to invoke it.\n//\n// `node_modules/.bin` is on PATH only inside npm's own lifecycle \u2014 `npm run`, `npm exec`, `npx` \u2014 never in\n// an interactive shell. So a bare `flowrunner \u2026` runs only when a GLOBAL install put it on PATH, and a\n// project that has the CLI as a dependency and nothing else answers `command not found`. That is the whole\n// bug: the hint was written by people who had a global install, for people who do not.\n//\n// Some terminals muddy this further by injecting `node_modules/.bin` themselves (JetBrains IDEs do), which\n// is why \"it works for me\" is not evidence either way.\n\n/**\n * The invocation for text written to FILES.\n *\n * A README is committed and read on machines other than the one that generated it, so it cannot encode this\n * machine's PATH. `npx` resolves `node_modules/.bin` first and falls back to PATH, so it is right for a\n * local install, a global one, and CI alike.\n */\nexport const PORTABLE_CLI_COMMAND = 'npx flowrunner'\n\n// npm installs global bins alongside the running node binary, so this one `existsSync` answers \"is there a\n// global flowrunner\" without spawning `npm prefix -g`.\nconst GLOBAL_BIN_NAMES = process.platform === 'win32'\n ? ['flowrunner.cmd', 'flowrunner.exe', 'flowrunner']\n : ['flowrunner']\n\nlet resolved: boolean | undefined\n\n/**\n * Whether a global install has put `flowrunner` on PATH.\n *\n * This is what makes the bare command usable at all \u2014 and, with the launcher in `bin/resolve-local.js`,\n * what lets it hand over to the project's own copy.\n */\nexport function hasGlobalInstall(): boolean {\n if (resolved === undefined) {\n const binDirectory = path.dirname(process.execPath)\n\n resolved = GLOBAL_BIN_NAMES.some(name => fs.existsSync(path.join(binDirectory, name)))\n }\n\n return resolved\n}\n\n/**\n * The invocation to PRINT, for the person at this keyboard right now.\n *\n * Bare when a global install makes it resolvable, `npx flowrunner` otherwise \u2014 so every hint the CLI prints\n * is one the reader can actually paste. Wrong only in the safe direction: a terminal that injects\n * `node_modules/.bin` gets the `npx` form, which still runs. It never prints a bare command that fails.\n *\n * Both forms run the same code: the bare one goes through the global launcher, which delegates to the\n * project's copy, and `npx` resolves that copy directly.\n */\nexport function cliCommand(): string {\n return hasGlobalInstall() ? 'flowrunner' : PORTABLE_CLI_COMMAND\n}\n\n/** Testing seam: the answer is cached because it cannot change within one run. */\nexport function resetCliCommandCache(): void {\n resolved = undefined\n}\n", "import type { ClusterName } from '../constants'\nimport { CLUSTERS } from '../constants'\nimport { UnknownServerError } from '../errors'\n\n// Turning what someone typed \u2014 `dev`, or a URL \u2014 into a server address. Shared by every command that takes\n// a server: `use`, and the `--server` option on `init` and `login`.\n\nexport const CLUSTER_NAMES = Object.keys(CLUSTERS) as ClusterName[]\n\n/** Trailing slashes are noise: the same server typed two ways must compare equal. */\nexport function normalizeServerUrl(serverUrl: string): string {\n return serverUrl.replace(/\\/+$/, '')\n}\n\n/** Which cluster a URL is, or null when it is not one of ours. */\nexport function clusterFor(serverUrl: string): ClusterName | null {\n const normalized = normalizeServerUrl(serverUrl)\n\n return CLUSTER_NAMES.find(name => CLUSTERS[name] === normalized) ?? null\n}\n\n/**\n * Resolve `prod` / `dev` / `local`, or an explicit URL, to a server URL.\n *\n * Anything that is not a known name and does not look like a URL is refused rather than passed through: a\n * mistyped `prd` would otherwise be stored as a server address and fail much later, against a host that\n * does not exist.\n */\nexport function resolveServerTarget(target: string): string {\n const known = CLUSTERS[target as ClusterName]\n\n if (known) {\n return known\n }\n\n if (/^https?:\\/\\//i.test(target)) {\n return normalizeServerUrl(target)\n }\n\n throw new UnknownServerError(target, [...CLUSTER_NAMES, 'or a full http(s):// URL'])\n}\n", "import path from 'path'\n\nimport { TemplateNotFoundError } from '../../errors'\nimport type { Answers, Template } from '../../templates/manifest'\nimport { DEFAULT_TEMPLATE_ALIAS, findTemplate, listTemplates } from '../../templates/registry'\nimport { scaffoldService } from '../../templates/scaffold'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport type { Ask } from './answers'\nimport { resolveAnswers } from './answers'\n\n// Scaffolding one service into an existing project.\n\nexport type CreateServiceEvent =\n | { type: 'template'; template: Template }\n | { type: 'created-services-directory' }\n | { type: 'created'; relativePath: string; files: string[] }\n\nexport interface CreateServiceOptions extends OperationOptions<CreateServiceEvent> {\n /** Answers the template's prompts, keyed by prompt name. `id` and `name` are expected by every template. */\n answers?: Answers\n /** Take every default rather than asking. */\n acceptDefaults?: boolean\n /** How to ask for anything still unanswered. Omitted means an unanswered prompt throws. */\n ask?: Ask\n}\n\nexport interface ScaffoldedService {\n serviceId: string\n serviceDirectory: string\n /** `serviceDirectory` relative to the project root, for printing. */\n relativePath: string\n files: string[]\n}\n\n/** Resolves a template id \u2014 the `demo` alias included \u2014 or throws naming what is available. */\nexport function resolveTemplateId(templateId: string, templates: Template[] = listTemplates()): Template {\n const template = findTemplate(templateId)\n\n if (!template) {\n throw new TemplateNotFoundError(\n templateId,\n [...templates.map(entry => entry.manifest.id), DEFAULT_TEMPLATE_ALIAS]\n )\n }\n\n return template\n}\n\n/**\n * Ask the template's questions and write the service \u2014 the part `createService` and `init` share.\n *\n * Reports the files it created; the caller owns the \"next steps\" it prints afterwards, since those differ\n * between scaffolding into an existing project and bootstrapping a new one.\n */\nexport async function scaffoldFromTemplate(\n template: Template,\n options: CreateServiceOptions = {},\n projectRoot: string = options.cwd ?? process.cwd()\n): Promise<ScaffoldedService> {\n const emit = emitter(options)\n\n emit({ type: 'template', template })\n\n const answers = await resolveAnswers(template.manifest.prompts, {\n prefilled : options.answers,\n constants : template.manifest.values,\n acceptDefaults: options.acceptDefaults,\n ask : options.ask,\n projectRoot,\n })\n\n // Every template is expected to collect the service id under this name \u2014 it is what the folder is\n // called and what `createExtension({ id })` freezes.\n const serviceId = String(answers.id)\n\n const { serviceDirectory, files, createdServicesDirectory } =\n scaffoldService(template, answers, serviceId, projectRoot)\n\n const relativePath = path.relative(projectRoot, serviceDirectory) || serviceDirectory\n const written = files.map(file => file.relativePath)\n\n if (createdServicesDirectory) {\n emit({ type: 'created-services-directory' })\n }\n\n emit({ type: 'created', relativePath, files: written })\n\n return { serviceId, serviceDirectory, relativePath, files: written }\n}\n\n/** Scaffold a service from the named template into the project. */\nexport async function createService(\n templateId: string,\n options: CreateServiceOptions = {}\n): Promise<ScaffoldedService> {\n return scaffoldFromTemplate(resolveTemplateId(templateId), options, options.cwd ?? process.cwd())\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { Template } from './manifest'\nimport { TemplateManifestSchema } from './manifest'\nimport { templatesRoot } from './package-root'\n\n// Templates are discovered from `templates/*/template.json`, so adding one is still just dropping in a\n// folder. Which of them is the *default* is decided here, by a single id \u2014 deliberately not a `default:\n// true` flag on each manifest, because two manifests could both set that and the winner would come down to\n// directory order.\n\nconst MANIFEST_FILE = 'template.json'\n\n/** The template `flowrunner cs demo` resolves to, and the one that heads the interactive picker. */\nexport const DEFAULT_TEMPLATE_ID = 'demo-todo-list'\n\n/**\n * A stable shorthand for \"whichever template is the default one\", so `flowrunner cs demo` keeps working\n * if the default moves. The default template's own id still resolves normally.\n */\nexport const DEFAULT_TEMPLATE_ALIAS = 'demo'\n\n// A manifest is checked the moment it is read, not when a file is finally written: a template that declares\n// a missing source or a `to` path escaping the service directory is broken for everyone, and finding that\n// out halfway through a render leaves the target project in a state the user has to clean up by hand.\nfunction loadTemplate(directory: string): Template {\n const manifestPath = path.join(directory, MANIFEST_FILE)\n\n let raw: unknown\n\n try {\n raw = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'))\n } catch (error) {\n throw new Error(`Template manifest ${ manifestPath } is not readable JSON: ${ (error as Error).message }`)\n }\n\n const parsed = TemplateManifestSchema.safeParse(raw)\n\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map(issue => ` ${ issue.path.join('.') || '<root>' }: ${ issue.message }`)\n .join('\\n')\n\n throw new Error(`Template manifest ${ manifestPath } is invalid:\\n${ issues }`)\n }\n\n const manifest = parsed.data\n\n // The folder is how a template is found; the manifest id is how it is addressed. A mismatch would make\n // `cs <folder>` fail while the template looks perfectly present on disk.\n if (manifest.id !== path.basename(directory)) {\n throw new Error(`Template in ${ directory } declares id \"${ manifest.id }\" \u2014 it must match the folder name`)\n }\n\n for (const prompt of manifest.prompts) {\n if (prompt.type === 'choice' && !prompt.options.some(option => option.value === prompt.default)) {\n throw new Error(`Template \"${ manifest.id }\" prompt \"${ prompt.name }\" defaults to \"${ prompt.default }\", ` +\n `which is not one of its options (${ prompt.options.map(option => option.value).join(', ') })`)\n }\n }\n\n const filesRoot = path.join(directory, 'files')\n\n for (const file of manifest.files) {\n const source = path.resolve(filesRoot, file.from)\n\n if (!source.startsWith(filesRoot + path.sep)) {\n throw new Error(`Template \"${ manifest.id }\" declares a source outside files/: ${ file.from }`)\n }\n\n if (!fs.existsSync(source)) {\n throw new Error(`Template \"${ manifest.id }\" declares a missing source file: files/${ file.from }`)\n }\n\n // The real destination is per-service, but whether it can escape is decided by the manifest alone.\n const destination = path.normalize(file.to)\n\n if (path.isAbsolute(destination) || destination.split(/[\\\\/]/).includes('..')) {\n throw new Error(`Template \"${ manifest.id }\" declares a destination outside the service folder: ${ file.to }`)\n }\n\n const gate = file.when &&\n (manifest.prompts.some(prompt => prompt.type === 'boolean' && prompt.name === file.when) ||\n typeof manifest.values[file.when] === 'boolean')\n\n if (file.when && !gate) {\n throw new Error(`Template \"${ manifest.id }\" gates files/${ file.from } on \"${ file.when }\", ` +\n 'which is neither a boolean prompt nor a boolean entry in `values`')\n }\n }\n\n return { manifest, directory, isDefault: manifest.id === DEFAULT_TEMPLATE_ID }\n}\n\n/** Every template shipped with the CLI \u2014 the default one first, then alphabetically. */\nexport function listTemplates(): Template[] {\n const root = templatesRoot()\n\n if (!fs.existsSync(root)) {\n return []\n }\n\n const templates = fs\n .readdirSync(root, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && fs.existsSync(path.join(root, entry.name, MANIFEST_FILE)))\n .map(entry => loadTemplate(path.join(root, entry.name)))\n\n // Catches a rename or a deletion of the default template, rather than quietly leaving `cs demo` broken.\n if (templates.length > 0 && !templates.some(template => template.isDefault)) {\n throw new Error(`DEFAULT_TEMPLATE_ID is \"${ DEFAULT_TEMPLATE_ID }\", but no template with that id is bundled`)\n }\n\n return templates.sort((a, b) => Number(b.isDefault) - Number(a.isDefault) ||\n a.manifest.id.localeCompare(b.manifest.id))\n}\n\nexport function defaultTemplate(): Template | null {\n return listTemplates().find(template => template.isDefault) ?? null\n}\n\n/** Resolves a template id, or the `demo` alias, to a template. */\nexport function findTemplate(id: string): Template | null {\n const templates = listTemplates()\n const match = templates.find(template => template.manifest.id === id)\n\n if (match) {\n return match\n }\n\n return id === DEFAULT_TEMPLATE_ALIAS\n ? templates.find(template => template.isDefault) ?? null\n : null\n}\n", "import fs from 'fs'\nimport { z } from 'zod'\n\nimport { serviceDirectory } from './paths'\n\n// A template is data, not code: `template.json` declares what the template asks the user, what it fixes for\n// them, and which files it writes \u2014 so adding a template never touches `src/`. Everything a manifest can\n// express is validated here; in particular `validate` names a built-in rule rather than shipping a pattern,\n// so a template cannot widen what counts as a legal service id.\n\nexport const SERVICE_ID_PATTERN = /^[a-z][a-z0-9-]*$/\n\n/**\n * The closest legal service id to free text: \"Token Generator\" \u2192 \"token-generator\", \"Caf\u00E9_Bot.v2\" \u2192\n * \"cafe-bot-v2\". Accents are folded, every run of anything else becomes one dash, and leading digits are\n * dropped because an id must start with a letter. Returns '' when nothing usable is left (\"\u65E5\u672C\u8A9E\"), so the\n * caller decides the fallback rather than this inventing one.\n */\nexport function toServiceId(value: string): string {\n return value\n .normalize('NFKD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^[^a-z]+/, '')\n .replace(/-+$/, '')\n}\n\n/**\n * `id` itself when no service uses it, otherwise the first free `id-2`, `id-3`, \u2026 \u2014 for a *suggested* id\n * only. An id the user typed or passed as a flag is never renamed behind their back; it is rejected as taken.\n */\nexport function availableServiceId(id: string, projectRoot: string): string {\n let candidate = id\n\n for (let suffix = 2; fs.existsSync(serviceDirectory(candidate, projectRoot)); suffix++) {\n candidate = `${ id }-${ suffix }`\n }\n\n return candidate\n}\n\nexport interface ValidationContext {\n /** The project being scaffolded into \u2014 an id is only \"taken\" relative to one project. */\n projectRoot: string\n}\n\n/** Returns an error message, or null when the value is acceptable. */\nexport type Validator = (value: string, context: ValidationContext) => string | null\n\nexport const VALIDATORS = {\n // Both halves of \"is this a usable id\" live together, so the prompt can re-ask on either. Availability is\n // checked here rather than at write time so the user finds out while they are still on that question.\n serviceId: (value, context) => {\n if (!SERVICE_ID_PATTERN.test(value)) {\n return 'must start with a lowercase letter and contain only lowercase letters, digits and dashes ' +\n '\u2014 it becomes the folder name and the service id, which is frozen once deployed'\n }\n\n if (fs.existsSync(serviceDirectory(value, context.projectRoot))) {\n return `is already taken \u2014 services/${ value } exists in this project`\n }\n\n return null\n },\n nonEmpty: value => (value.trim().length > 0 ? null : 'must not be empty'),\n} satisfies Record<string, Validator>\n\nexport type ValidatorName = keyof typeof VALIDATORS\n\n/**\n * Rules that can also repair a value, keyed like VALIDATORS. Applied only to what a person types at the\n * prompt \u2014 where they see the result echoed back \u2014 never to a flag, which a script expects to be taken\n * exactly as given or refused.\n */\nexport const NORMALIZERS: Partial<Record<ValidatorName, (value: string) => string>> = {\n serviceId: toServiceId,\n}\n\nconst VALIDATOR_NAMES = Object.keys(VALIDATORS) as [ValidatorName, ...ValidatorName[]]\n\nconst StringPromptSchema = z.object({\n name : z.string().min(1),\n label : z.string().min(1),\n type : z.literal('string'),\n hint : z.string().optional(),\n // May interpolate a value fixed by `values`, a value supplied up front (flag or `--set`), or an answer\n // collected *earlier* in the list: \"{{id}}\", \"{{name|serviceId}}\". A list is a chain of candidates: the\n // first whose placeholders all resolve to something non-empty wins \u2014 `[\"{{id|titleCase}}\", \"My Service\"]`\n // follows an `--id` flag when there is one and falls back to the literal when there is not.\n default : z.union([z.string(), z.array(z.string()).min(1)]).default(''),\n validate: z.enum(VALIDATOR_NAMES).optional(),\n})\n\nconst BooleanPromptSchema = z.object({\n name : z.string().min(1),\n label : z.string().min(1),\n type : z.literal('boolean'),\n hint : z.string().optional(),\n default: z.boolean().default(false),\n})\n\n// `default` must name one of the options \u2014 checked in the registry rather than here, because a refined\n// schema cannot sit inside a discriminated union.\nconst ChoicePromptSchema = z.object({\n name : z.string().min(1),\n label : z.string().min(1),\n type : z.literal('choice'),\n hint : z.string().optional(),\n default: z.string().min(1),\n options: z.array(z.object({\n value : z.string().min(1),\n label : z.string().min(1),\n description: z.string().optional(),\n })).min(2),\n})\n\nexport const PromptSchema = z.discriminatedUnion('type', [\n StringPromptSchema,\n BooleanPromptSchema,\n ChoicePromptSchema,\n])\n\nexport const TemplateFileSchema = z.object({\n from: z.string().min(1),\n to : z.string().min(1),\n /** Name of a boolean answer; the file is written only when that answer is true. */\n when: z.string().min(1).optional(),\n})\n\nexport const TemplateManifestSchema = z.object({\n id : z.string().regex(SERVICE_ID_PATTERN),\n label : z.string().min(1),\n description: z.string().min(1),\n prompts : z.array(PromptSchema).min(1),\n /**\n * Answers the template fixes instead of asking for. Available to the file templates exactly like a\n * prompted answer, and still overridable with `--set name=value`.\n */\n values : z.record(z.string(), z.union([z.string(), z.boolean()])).default({}),\n files : z.array(TemplateFileSchema).min(1),\n})\n\nexport type Prompt = z.infer<typeof PromptSchema>\nexport type TemplateFile = z.infer<typeof TemplateFileSchema>\nexport type TemplateManifest = z.infer<typeof TemplateManifestSchema>\n\nexport type Answers = Record<string, string | boolean>\n\n/** A manifest plus where it was loaded from, so file paths resolve against the right template. */\nexport interface Template {\n manifest: TemplateManifest\n /** Absolute path of the template directory (the one holding `template.json`). */\n directory: string\n /** Whether this is the default template. Decided by the registry, not declared by the manifest. */\n isDefault: boolean\n}\n\n", "import path from 'path'\n\n// Where a service lands in the target project. Shared by the id validator (which has to know whether an id\n// is already taken while the user is still typing it) and the scaffolder (which writes there).\n\nexport const SERVICES_DIRECTORY = 'services'\n\nexport function servicesDirectory(projectRoot: string = process.cwd()): string {\n return path.join(projectRoot, SERVICES_DIRECTORY)\n}\n\nexport function serviceDirectory(serviceId: string, projectRoot: string = process.cwd()): string {\n return path.join(servicesDirectory(projectRoot), serviceId)\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { Answers, Template } from './manifest'\nimport { serviceDirectory as resolveServiceDirectory, servicesDirectory } from './paths'\nimport { render } from './render'\n\n// Files whose bytes must survive untouched. Everything else is rendered as UTF-8 text \u2014 a template is\n// overwhelmingly source, and an icon is the one thing likely to be binary.\nconst BINARY_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.zip', '.woff', '.woff2'])\n\nexport interface RenderedFile {\n /** Path relative to the service directory, e.g. `src/index.js`. */\n relativePath: string\n contents: Buffer\n}\n\nexport interface ScaffoldResult {\n serviceDirectory: string\n files: RenderedFile[]\n createdServicesDirectory: boolean\n}\n\n/**\n * Render every file the template declares, in memory.\n *\n * Nothing touches disk here: a bad placeholder or an unknown flag must fail before the first `mkdir`, or\n * the user is left cleaning up a half-written service directory by hand.\n */\nexport function renderTemplate(template: Template, answers: Answers): RenderedFile[] {\n const filesRoot = path.join(template.directory, 'files')\n const rendered: RenderedFile[] = []\n\n for (const file of template.manifest.files) {\n if (file.when && !answers[file.when]) {\n continue\n }\n\n const source = path.join(filesRoot, file.from)\n const relativePath = render(file.to, answers, `destination of ${ file.from }`)\n\n if (BINARY_EXTENSIONS.has(path.extname(file.from).toLowerCase())) {\n rendered.push({ relativePath, contents: fs.readFileSync(source) })\n\n continue\n }\n\n const contents = render(fs.readFileSync(source, 'utf-8'), answers, `${ template.manifest.id }/files/${ file.from }`)\n\n rendered.push({ relativePath, contents: Buffer.from(contents, 'utf-8') })\n }\n\n return rendered\n}\n\n/**\n * Write a rendered template into `services/<serviceId>/` under `projectRoot`.\n *\n * Refuses an existing service directory outright \u2014 overwriting one would silently discard work, and the\n * service id is frozen once deployed, so a collision is far more likely to be a mistake than an intent.\n */\nexport function scaffoldService(\n template: Template,\n answers: Answers,\n serviceId: string,\n projectRoot: string = process.cwd()\n): ScaffoldResult {\n const files = renderTemplate(template, answers)\n\n const servicesRoot = servicesDirectory(projectRoot)\n const serviceDirectory = resolveServiceDirectory(serviceId, projectRoot)\n\n // The id prompt already refuses a taken id; this is the last line of defence for `--id` on a racing or\n // scripted run, and it keeps `scaffoldService` safe to call on its own.\n if (fs.existsSync(serviceDirectory)) {\n throw new Error(`services/${ serviceId } already exists \u2014 pick another service id, or remove it first.`)\n }\n\n // Second containment check, now against the real destination. The manifest was validated at load time;\n // this catches a `to` path made unsafe by interpolation.\n for (const file of files) {\n const target = path.resolve(serviceDirectory, file.relativePath)\n\n if (target !== serviceDirectory && !target.startsWith(serviceDirectory + path.sep)) {\n throw new Error(`Template \"${ template.manifest.id }\" resolved a path outside the service folder: ${ file.relativePath }`)\n }\n }\n\n const createdServicesDirectory = !fs.existsSync(servicesRoot)\n\n for (const file of files) {\n const target = path.join(serviceDirectory, file.relativePath)\n\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(target, file.contents)\n }\n\n return { serviceDirectory, files, createdServicesDirectory }\n}\n", "import type { Answers } from './manifest'\nimport { toServiceId } from './manifest'\n\n// Template files are stored under their real names (`index.js`, not `index.js.tpl`) so they stay readable\n// and syntax-highlighted while being edited. That constrains the substitution syntax: `{{name}}` only ever\n// appears inside a string literal, and anything structural is gated by a *line comment* pair, which keeps\n// the raw template valid JavaScript.\n//\n// // {{#if useFilesApi}}\n// usesFileStorage: true,\n// // {{/if}}\n//\n// A block may also test a specific value, for answers that are not booleans:\n//\n// // {{#if configMode=full}}\n\nconst PLACEHOLDER = /\\{\\{\\s*([a-zA-Z0-9_]+)\\s*(?:\\|\\s*([a-zA-Z0-9_]+)\\s*)?\\}\\}/g\nconst IF_OPEN = /^\\s*(?:\\/\\/|#|<!--)\\s*\\{\\{#if\\s+([a-zA-Z0-9_]+)\\s*(?:=\\s*([a-zA-Z0-9_.-]+)\\s*)?\\}\\}/\nconst IF_CLOSE = /^\\s*(?:\\/\\/|#|<!--)\\s*\\{\\{\\/if\\s*\\}\\}/\n\nconst FILTERS: Record<string, (value: string) => string> = {\n titleCase: value => value\n .split(/[-_\\s]+/)\n .filter(Boolean)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' '),\n upperCase: value => value.toUpperCase(),\n lowerCase: value => value.toLowerCase(),\n serviceId: toServiceId,\n}\n\nexport function applyFilter(name: string, value: string): string {\n const filter = FILTERS[name]\n\n if (!filter) {\n throw new Error(`Unknown template filter \"${ name }\" \u2014 known filters: ${ Object.keys(FILTERS).join(', ') }`)\n }\n\n return filter(value)\n}\n\n/**\n * Substitute `{{name}}` / `{{name|filter}}` against the answers.\n *\n * An unknown key is an error rather than an empty string: a typo in a template would otherwise ship a\n * silently broken service, and the generated file is the thing a user reads to learn the format.\n */\n/** Whether every placeholder in `source` names a known answer \u2014 i.e. whether `interpolate` would succeed. */\nexport function canInterpolate(source: string, answers: Answers): boolean {\n return [...source.matchAll(PLACEHOLDER)].every(([, name]) => name in answers)\n}\n\nexport function interpolate(source: string, answers: Answers, origin: string): string {\n return source.replace(PLACEHOLDER, (_match, name: string, filter?: string) => {\n if (!(name in answers)) {\n throw new Error(`Unresolved placeholder \"{{${ name }}}\" in ${ origin }`)\n }\n\n const value = String(answers[name])\n\n return filter ? applyFilter(filter, value) : value\n })\n}\n\n/** Drop the lines inside `{{#if flag}}` blocks whose flag is falsy, and the marker lines themselves. */\nexport function stripConditionals(source: string, answers: Answers, origin: string): string {\n const lines = source.split('\\n')\n const output: string[] = []\n const stack: { name: string, keep: boolean }[] = []\n\n for (const [index, line] of lines.entries()) {\n const open = IF_OPEN.exec(line)\n\n if (open) {\n const [, name, expected] = open\n\n if (!(name in answers)) {\n throw new Error(`Unknown flag \"${ name }\" in {{#if}} at ${ origin }:${ index + 1 }`)\n }\n\n // `{{#if name}}` is truthiness; `{{#if name=value}}` compares, for choice answers.\n const matches = expected === undefined\n ? Boolean(answers[name])\n : String(answers[name]) === expected\n\n // A nested block inside a dropped one stays dropped regardless of its own flag.\n stack.push({ name, keep: matches && stack.every(frame => frame.keep) })\n\n continue\n }\n\n if (IF_CLOSE.test(line)) {\n if (!stack.pop()) {\n throw new Error(`Unmatched {{/if}} at ${ origin }:${ index + 1 }`)\n }\n\n continue\n }\n\n if (stack.every(frame => frame.keep)) {\n output.push(line)\n }\n }\n\n if (stack.length > 0) {\n throw new Error(`Unclosed {{#if ${ stack[stack.length - 1].name }}} in ${ origin }`)\n }\n\n return output.join('\\n')\n}\n\n/** Full render of one template file: conditionals first, so a dropped block's placeholders never resolve. */\nexport function render(source: string, answers: Answers, origin: string): string {\n return interpolate(stripConditionals(source, answers, origin), answers, origin)\n}\n", "import { PromptAbortedError, PromptRequiredError } from '../../errors'\nimport type { Answers, Prompt, ValidationContext } from '../../templates/manifest'\nimport { availableServiceId, NORMALIZERS, VALIDATORS } from '../../templates/manifest'\nimport { canInterpolate, interpolate } from '../../templates/render'\n\n// Turning a template's declared prompts into a complete set of answers, without asking anybody anything.\n//\n// Everything that can be decided from what the caller already supplied \u2014 a prefill, a fixed value, a\n// default \u2014 is decided here. Only a prompt with no answer left needs a human, and that goes out through\n// `ask`. A caller with no `ask` gets PromptRequiredError naming the prompt, which is what makes a scripted\n// or programmatic scaffold possible: supply every answer and nothing ever needs a terminal.\n\n/** Shared with the standalone confirmations in `cli/prompts/confirm`, so both read a yes/no the same way. */\nexport const TRUTHY = ['y', 'yes', 'true', '1']\nexport const FALSY = ['n', 'no', 'false', '0']\n\nexport interface AskRequest {\n prompt: Prompt\n /** What the answer would be if the user just pressed Enter. */\n fallback: string | boolean\n /** Returns a message to show before asking again, or null when the value is acceptable. */\n validate: (value: string) => string | null\n /**\n * Repairs what the user typed into the closest acceptable value (\"Token Generator\" \u2192 \"token-generator\"),\n * or returns it unchanged. Run before `validate`; the asker should show the user a value it changed.\n */\n normalize: (value: string) => string\n}\n\nexport type Ask = (request: AskRequest) => Promise<string | boolean>\n\nexport interface ResolveAnswersOptions {\n /** Pre-supplied answers (CLI flags). A prompt with a prefill is not asked. */\n prefilled?: Answers\n /** Answers the template fixes rather than asking for \u2014 see `values` in the manifest. */\n constants?: Answers\n /** Ask nothing; take every default. */\n acceptDefaults?: boolean\n /** The project being scaffolded into; validators need it to tell whether an id is taken. */\n projectRoot?: string\n /** How to ask a human. Omitted means nothing can be asked, and an unanswered prompt is an error. */\n ask?: Ask\n}\n\n/**\n * Resolve a prompt's declared default, which may interpolate the answers known so far.\n *\n * A list default is tried in order and the first candidate that resolves to something non-empty wins. When\n * none does, the last one is interpolated anyway \u2014 an unresolvable placeholder then fails with the same\n * error a single-string default would, rather than being swallowed into an empty answer.\n */\nexport function resolveDefault(prompt: Prompt, answers: Answers): string | boolean {\n if (prompt.type === 'boolean' || prompt.type === 'choice') {\n return prompt.default\n }\n\n const origin = `default of \"${ prompt.name }\"`\n const candidates = Array.isArray(prompt.default) ? prompt.default : [prompt.default]\n\n for (const candidate of candidates) {\n const value = canInterpolate(candidate, answers) ? interpolate(candidate, answers, origin) : ''\n\n if (value) {\n return value\n }\n }\n\n return interpolate(candidates[candidates.length - 1], answers, origin)\n}\n\n/**\n * A prefill arrives as a raw string when it came from a flag; anything boolean has to interpret it.\n *\n * Skipping this for a fixed value would be quietly wrong rather than merely untidy: `--set flag=false`\n * would store the STRING \"false\", which is truthy, and the `{{#if flag}}` block would survive.\n */\nexport function coerceBoolean(label: string, value: string | boolean): boolean {\n if (typeof value === 'boolean') {\n return value\n }\n\n const normalized = value.trim().toLowerCase()\n\n if (TRUTHY.includes(normalized)) {\n return true\n }\n\n if (FALSY.includes(normalized)) {\n return false\n }\n\n throw new PromptAbortedError(`${ label }: expected true or false, got \"${ value }\"`)\n}\n\nfunction validator(prompt: Prompt, context: ValidationContext): (value: string) => string | null {\n return value => {\n if (prompt.type !== 'string' || !prompt.validate) {\n return null\n }\n\n const failure = VALIDATORS[prompt.validate](value, context)\n\n return failure && `${ prompt.label } ${ failure }`\n }\n}\n\nfunction normalizer(prompt: Prompt): (value: string) => string {\n const normalize = prompt.type === 'string' && prompt.validate ? NORMALIZERS[prompt.validate] : undefined\n\n return normalize ?? (value => value)\n}\n\n/**\n * The default offered to a person. A suggested service id that is already taken is moved on to the next\n * free one, so Enter still works on a second scaffold in the same project. Only the *offer* changes:\n * under `--yes` nobody sees it, so a taken default is still refused there rather than quietly renamed.\n */\nfunction offeredDefault(prompt: Prompt, fallback: string | boolean, context: ValidationContext): string | boolean {\n if (prompt.type === 'string' && prompt.validate === 'serviceId' && typeof fallback === 'string' && fallback) {\n return availableServiceId(fallback, context.projectRoot)\n }\n\n return fallback\n}\n\n/** Run a template's declared prompts in order, honouring prefills and `--yes`. */\nexport async function resolveAnswers(\n prompts: Prompt[],\n {\n prefilled = {},\n constants = {},\n acceptDefaults = false,\n projectRoot = process.cwd(),\n ask,\n }: ResolveAnswersOptions = {}\n): Promise<Answers> {\n const context: ValidationContext = { projectRoot }\n // Fixed values first, so a prompt default may interpolate one; a prompt of the same name wins over it.\n const answers: Answers = { ...constants }\n // What the caller supplied for prompts is known before anything is asked, so it is visible to the\n // defaults of *earlier* prompts too: the name is asked before the id, yet `--id acme-crm` should still\n // make \"Acme Crm\" the name on offer. Each prefill is still validated when its own prompt comes up.\n const prefilledDefaults: Answers = {}\n\n // A prefill naming neither a prompt nor a fixed value is a typo, not a no-op \u2014 silently ignoring it\n // would hand the user a service that quietly differs from what they asked for.\n const known = [...prompts.map(prompt => prompt.name), ...Object.keys(constants)]\n const unknown = Object.keys(prefilled).filter(name => !known.includes(name))\n\n if (unknown.length > 0) {\n throw new PromptAbortedError(\n `This template has no setting named ${ unknown.map(name => `\"${ name }\"`).join(', ') }. ` +\n `It accepts: ${ known.join(', ') }`\n )\n }\n\n for (const prompt of prompts) {\n if (prompt.name in prefilled && prompt.type === 'string') {\n prefilledDefaults[prompt.name] = String(prefilled[prompt.name])\n }\n }\n\n for (const prompt of prompts) {\n const fallback = resolveDefault(prompt, { ...prefilledDefaults, ...answers })\n const validate = validator(prompt, context)\n\n if (prompt.name in prefilled) {\n const supplied = prefilled[prompt.name]\n\n if (prompt.type === 'boolean') {\n answers[prompt.name] = coerceBoolean(prompt.label, supplied)\n\n continue\n }\n\n if (prompt.type === 'choice') {\n const values = prompt.options.map(option => option.value)\n\n if (!values.includes(String(supplied))) {\n throw new PromptAbortedError(`${ prompt.label }: \"${ supplied }\" is not one of ${ values.join(', ') }`)\n }\n\n answers[prompt.name] = String(supplied)\n\n continue\n }\n\n const failure = validate(String(supplied))\n\n if (failure) {\n throw new PromptAbortedError(failure)\n }\n\n answers[prompt.name] = String(supplied)\n\n continue\n }\n\n if (acceptDefaults) {\n // Validated like any other answer: under `--yes` a default service id can still be taken, and the\n // failure should read the same as it would have when typed.\n const failure = typeof fallback === 'string' ? validate(fallback) : null\n\n if (failure) {\n throw new PromptAbortedError(failure)\n }\n\n answers[prompt.name] = fallback\n\n continue\n }\n\n if (!ask) {\n throw new PromptRequiredError(\n prompt.name,\n `\"${ prompt.name }\" has no answer and there is no way to ask for one. ` +\n 'Supply it up front, or accept the defaults.'\n )\n }\n\n answers[prompt.name] = await ask({\n prompt,\n fallback : offeredDefault(prompt, fallback, context),\n validate,\n normalize: normalizer(prompt),\n })\n }\n\n // A `--set` for a fixed value overrides it; prompts have already had their turn above. The manifest's\n // own value tells us the intended type, so a boolean stays a boolean.\n for (const [name, value] of Object.entries(prefilled)) {\n if (prompts.some(prompt => prompt.name === name)) {\n continue\n }\n\n answers[name] = typeof constants[name] === 'boolean' ? coerceBoolean(name, value) : value\n }\n\n return answers\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport { PROJECT_FILES_DIRECTORY, TESTING_FILES } from '../../constants'\nimport { packageRoot } from '../../templates/package-root'\n\n// Copying the unit-test harness into a project.\n//\n// The harness is *copied*, not imported from the installed package, and that is the whole design. A test\n// harness is something a project owns: a service wrapping an awkward SDK needs a shim inside the HTTP mock,\n// and a project with its own conventions will want its own `jest.config.js`. A copy can be read and edited;\n// a module behind a package export cannot. The cost is that a copy does not move with the CLI \u2014 which is\n// why `init` is additive and safe to re-run, and why a project created before this existed picks the\n// harness up by running `flowrunner init` again.\n//\n// Nothing is overwritten, for the same reason as everywhere else in `init`: a customer's edit to their own\n// jest config must survive a command they ran for an unrelated reason.\n\nexport interface TestingFilesResult {\n created: string[]\n skipped: string[]\n}\n\n/** Where the shipped harness lives inside the installed package. */\nexport function testingFilesDirectory(): string {\n return path.join(packageRoot(), PROJECT_FILES_DIRECTORY)\n}\n\n/**\n * Copy the harness into `projectRoot`, leaving any file that is already there alone.\n *\n * Reports what it did per file so `init` can print the same `+ file` / `file \u2014 already there` lines it\n * prints for everything else it writes.\n */\nexport function writeTestingFiles(projectRoot: string): TestingFilesResult {\n const source = testingFilesDirectory()\n\n const created: string[] = []\n const skipped: string[] = []\n\n for (const file of TESTING_FILES) {\n const target = path.join(projectRoot, file)\n\n if (fs.existsSync(target)) {\n skipped.push(file)\n\n continue\n }\n\n const contents = fs.readFileSync(path.join(source, file))\n\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(target, contents)\n\n created.push(file)\n }\n\n return { created, skipped }\n}\n", "import fs from 'fs'\nimport path from 'path'\n\nimport type { ProviderLayout } from '../../constants'\nimport {\n AI_PROVIDERS_DIRECTORY,\n CLAUDE_PROVIDER,\n ORCHESTRATOR_SEGMENT_FILE,\n PROVIDER_AGENTS_DIRECTORY,\n PROVIDERS,\n} from '../../constants'\nimport { AiDocsMissingError } from '../../errors'\nimport { packageRoot } from '../../templates/package-root'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport type { SegmentOutcome } from './segment'\nimport { mergeSegment } from './segment'\n\n// `init-claude` connects a project to the FlowRunner agent instructions the CLI ships.\n//\n// Which files it writes, and where, comes from the provider layout in `constants/providers.ts` \u2014 Claude Code\n// reads `CLAUDE.md` and not `AGENTS.md`, and the next provider will differ again, so that knowledge is data\n// rather than something `init` could write once for everyone.\n//\n// Two halves, and they differ in who owns the file. The agent definitions under the provider's agents\n// directory are the CLI's: they are named `flowrunner-service-*`, they mean nothing without the instructions\n// they point at, and refreshing them on every run is the point of the command \u2014 so they are overwritten. The\n// provider's instructions file is the project's, and only the region between the CLI's own markers is ever\n// rewritten (see `segment.ts`).\n\nexport type InitClaudeEvent =\n | { type: 'agents'; directory: string; created: string[]; updated: string[]; unchanged: string[] }\n | { type: 'segment'; file: string; outcome: SegmentOutcome }\n | { type: 'warning'; message: string }\n\nexport type InitClaudeOptions = OperationOptions<InitClaudeEvent>\n\nexport interface InitClaudeResult {\n projectRoot: string\n /** Absolute path of the provider's agents directory. */\n agentsDirectory: string\n /** Agent file names, relative to `agentsDirectory`. */\n created: string[]\n updated: string[]\n unchanged: string[]\n /** Absolute path of the provider's instructions file. */\n claudeFile: string\n segment: SegmentOutcome\n}\n\n/** Where the packed docs for a provider live inside the installed package. */\nexport function providerDirectory(provider: string = CLAUDE_PROVIDER): string {\n return path.join(packageRoot(), AI_PROVIDERS_DIRECTORY, provider)\n}\n\n/**\n * The agent definitions the installed package ships, sorted so the reported list is stable.\n *\n * Only top-level `.md` files: an agent definition is one file, and anything else in there is not one.\n */\nfunction packedAgents(directory: string): string[] {\n if (!fs.existsSync(directory)) {\n return []\n }\n\n return fs.readdirSync(directory, { withFileTypes: true })\n .filter(entry => entry.isFile() && entry.name.endsWith('.md'))\n .map(entry => entry.name)\n .sort()\n}\n\n/**\n * Write the shipped agent definitions into `.claude/agents/`.\n *\n * Overwrites. These files are CLI-owned \u2014 a customer editing one would have it replaced by the next\n * `init-claude`, which is the same deal as any other generated file, and the alternative (skip what exists)\n * makes the command unable to ship a fix. Identical content is reported as `unchanged` rather than written,\n * so a re-run does not churn mtimes for no reason.\n */\nfunction writeAgents(sourceDirectory: string, projectRoot: string, layout: ProviderLayout): {\n directory: string\n created: string[]\n updated: string[]\n unchanged: string[]\n warnings: string[]\n} {\n const directory = path.join(projectRoot, layout.agentsDirectory)\n const agents = packedAgents(sourceDirectory)\n\n const created: string[] = []\n const updated: string[] = []\n const unchanged: string[] = []\n const warnings: string[] = []\n\n if (agents.length === 0) {\n warnings.push(`The installed CLI ships no agent definitions in ${ PROVIDER_AGENTS_DIRECTORY }/ \u2014 none were written.`)\n\n return { directory, created, updated, unchanged, warnings }\n }\n\n fs.mkdirSync(directory, { recursive: true })\n\n for (const agent of agents) {\n const contents = fs.readFileSync(path.join(sourceDirectory, agent), 'utf-8')\n const target = path.join(directory, agent)\n\n if (contents.length === 0) {\n // Shipped-but-unwritten: the file still lands, so the wiring is in place and filling it later is a\n // CLI upgrade rather than another manual step. Saying so is what stops it looking like a broken agent.\n warnings.push(`${ agent } is empty in the installed CLI \u2014 written as an empty file.`)\n }\n\n if (!fs.existsSync(target)) {\n fs.writeFileSync(target, contents, 'utf-8')\n created.push(agent)\n\n continue\n }\n\n if (fs.readFileSync(target, 'utf-8') === contents) {\n unchanged.push(agent)\n\n continue\n }\n\n fs.writeFileSync(target, contents, 'utf-8')\n updated.push(agent)\n }\n\n return { directory, created, updated, unchanged, warnings }\n}\n\n/** Merge the orchestrator segment into the provider's own instructions file. */\nfunction writeSegment(sourceDirectory: string, projectRoot: string, layout: ProviderLayout): {\n file: string\n outcome: SegmentOutcome\n warnings: string[]\n} {\n const file = path.join(projectRoot, layout.instructionsFile)\n const source = path.join(sourceDirectory, ORCHESTRATOR_SEGMENT_FILE)\n const warnings: string[] = []\n\n if (!fs.existsSync(source)) {\n warnings.push(`The installed CLI ships no ${ ORCHESTRATOR_SEGMENT_FILE } \u2014 ${ layout.instructionsFile } was left alone.`)\n\n return { file, outcome: 'unchanged', warnings }\n }\n\n const segment = fs.readFileSync(source, 'utf-8')\n\n if (segment.trim().length === 0) {\n warnings.push(`${ ORCHESTRATOR_SEGMENT_FILE } is empty in the installed CLI \u2014 the marked block is empty.`)\n }\n\n const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf-8') : null\n const merged = mergeSegment(current, segment, layout.instructionsFile)\n\n if (merged.outcome !== 'unchanged') {\n fs.writeFileSync(file, merged.contents, 'utf-8')\n }\n\n return { file, outcome: merged.outcome, warnings }\n}\n\n/**\n * Wire the shipped FlowRunner agent instructions into a project's Claude setup.\n *\n * Deliberately does not require a FlowRunner project: someone can reasonably run this in a repo before\n * `init`, and refusing would be a rule with nothing behind it \u2014 nothing here reads `flowrunner.json`.\n */\nexport async function initClaude(options: InitClaudeOptions = {}): Promise<InitClaudeResult> {\n const projectRoot = path.resolve(options.cwd ?? '.')\n const emit = emitter(options)\n // Each event first, then the warnings about it: a warning printed before its own heading reads as a\n // warning about whatever came before.\n const warnAll = (messages: string[]) => messages.forEach(message => emit({ type: 'warning', message }))\n\n const layout = PROVIDERS[CLAUDE_PROVIDER]\n const sourceDirectory = providerDirectory(layout.id)\n\n if (!fs.existsSync(sourceDirectory)) {\n throw new AiDocsMissingError(path.join(AI_PROVIDERS_DIRECTORY, CLAUDE_PROVIDER))\n }\n\n if (!fs.existsSync(projectRoot)) {\n fs.mkdirSync(projectRoot, { recursive: true })\n }\n\n const agents = writeAgents(path.join(sourceDirectory, PROVIDER_AGENTS_DIRECTORY), projectRoot, layout)\n\n emit({\n type : 'agents',\n directory: agents.directory,\n created : agents.created,\n updated : agents.updated,\n unchanged: agents.unchanged,\n })\n\n warnAll(agents.warnings)\n\n const segment = writeSegment(sourceDirectory, projectRoot, layout)\n\n emit({ type: 'segment', file: segment.file, outcome: segment.outcome })\n\n warnAll(segment.warnings)\n\n return {\n projectRoot,\n agentsDirectory: agents.directory,\n created : agents.created,\n updated : agents.updated,\n unchanged : agents.unchanged,\n claudeFile : segment.file,\n segment : segment.outcome,\n }\n}\n\nexport type { MergeResult, SegmentOutcome } from './segment'\nexport { BEGIN_MARKER, END_MARKER, mergeSegment } from './segment'\n", "// Merging one block of text into a file somebody else owns.\n//\n// `CLAUDE.md` belongs to the project, not to this CLI. It will hold a team's own instructions, and it will\n// be edited by hand between runs \u2014 so the segment cannot simply be written, and it cannot be appended twice.\n// Markers give the CLI a region it owns inside a file it does not: everything between them is replaced on\n// every run, everything outside them is never touched.\n\n// The exact strings matter: projects generated before this command carry these markers already, so matching\n// them is what makes `init-claude` *replace* an existing block there rather than append a second one.\nexport const BEGIN_MARKER = '<!-- flowrunner-cli:ai:start -->'\nexport const END_MARKER = '<!-- flowrunner-cli:ai:end -->'\n\n/**\n * What happened to the file.\n *\n * `inserted` and `replaced` are kept apart because they answer different questions: the first says the CLI\n * added something to a file that was already there, the second says it refreshed what it had added before.\n */\nexport type SegmentOutcome = 'created' | 'inserted' | 'replaced' | 'unchanged'\n\nexport interface MergeResult {\n contents: string\n outcome: SegmentOutcome\n}\n\n/** The owned region, marker lines included. */\nfunction block(segment: string): string {\n return `${ BEGIN_MARKER }\\n${ segment.trimEnd() }\\n${ END_MARKER }\\n`\n}\n\n/**\n * Compute the new contents of an instructions file with `segment` merged into it.\n *\n * Pure \u2014 takes the current contents (`null` when the file does not exist) and returns the new ones, so the\n * decision of what to write is testable without a filesystem, and the caller stays the only thing that\n * touches disk.\n *\n * An unbalanced marker pair throws. A half-marked file is either a bad hand-edit or a merge conflict\n * someone resolved wrongly, and both readings of \"repair it\" \u2014 treat the file as unmarked and append a\n * second block, or guess where the missing marker went \u2014 silently damage the user's own instructions.\n */\nexport function mergeSegment(current: string | null, segment: string, file: string): MergeResult {\n const marked = block(segment)\n\n if (current === null) {\n return { contents: marked, outcome: 'created' }\n }\n\n const begin = current.indexOf(BEGIN_MARKER)\n const end = current.indexOf(END_MARKER)\n\n if (begin === -1 && end === -1) {\n // A blank line between their content and ours, and never a second one.\n const separator = current.length === 0 ? '' : current.endsWith('\\n\\n') ? '' : current.endsWith('\\n') ? '\\n' : '\\n\\n'\n\n return { contents: `${ current }${ separator }${ marked }`, outcome: 'inserted' }\n }\n\n if (begin === -1 || end === -1 || end < begin) {\n throw new Error(\n `${ file } has an unbalanced flowrunner-cli marker pair. ` +\n `Restore both \"${ BEGIN_MARKER }\" and \"${ END_MARKER }\", or delete them and run this again.`\n )\n }\n\n const before = current.slice(0, begin)\n const after = current.slice(end + END_MARKER.length).replace(/^\\n/, '')\n const contents = `${ before }${ marked }${ after }`\n\n return { contents, outcome: contents === current ? 'unchanged' : 'replaced' }\n}\n", "import http from 'http'\n\nimport { callbackRoute } from './routes/callback'\nimport type { Route } from './types'\n\n// The CLI's own HTTP server. Today it exists for one reason \u2014 receiving the authorization redirect that a\n// browser cannot deliver any other way \u2014 but it is a route table rather than a single handler, so the next\n// thing that needs a local endpoint adds a file under `routes/` and one entry to the array.\n//\n// It always listens on a random free port on localhost. A fixed port would collide with whatever else the\n// developer is running, and binding anywhere but localhost would put an open endpoint on their network.\n\nexport { callbackRoute } from './routes/callback'\nexport type { Route, RouteContext } from './types'\n\nexport interface LocalServer {\n port: number\n close: () => void\n}\n\nexport function startLocalServer(routes: Route[]): Promise<LocalServer> {\n return new Promise((resolve, reject) => {\n const server = http.createServer((req, res) => {\n const url = new URL(req.url || '/', 'http://localhost')\n const route = routes.find(entry => entry.method === req.method && entry.path === url.pathname)\n\n if (!route) {\n res.writeHead(404)\n res.end()\n\n return\n }\n\n route.handle({ req, res, url })\n })\n\n server.listen(0, 'localhost', () => {\n const address = server.address()\n\n if (!address || typeof address === 'string') {\n reject(new Error('Failed to start the local callback server'))\n\n return\n }\n\n resolve({\n port: address.port,\n // `close()` alone only stops listening: the browser's keep-alive socket would hold the event loop\n // open, which is survivable for a command that exits straight after but not for one that carries on\n // into a deploy.\n close: () => {\n server.closeAllConnections?.()\n server.close()\n },\n })\n })\n\n server.on('error', reject)\n })\n}\n\nexport interface CallbackServer extends LocalServer {\n /** Resolves with the exchange code the console redirects back with. */\n waitForCode: () => Promise<string>\n}\n\n/** The one composition the login needs: a server whose only route is the authorization callback. */\nexport async function startCallbackServer(): Promise<CallbackServer> {\n const { route, waitForCode } = callbackRoute()\n const server = await startLocalServer([route])\n\n return { ...server, waitForCode }\n}\n", "// The two pages the browser lands on at the end of an authorization. They are the last thing the user sees\n// before switching back to the terminal, so they say which window to close and nothing else.\n\nconst PAGE_STYLES = `\n *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }\n body { font-family: Inter, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif; font-size: 14px; background: #F3F4F6; color: #111827; display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 16px; }\n .card { background: #fff; border-radius: 16px; box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075); width: 100%; max-width: 420px; padding: 32px; text-align: center; }\n .brand { font-size: 20px; font-weight: 700; color: #7f7fed; margin-bottom: 24px; }\n .icon { width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px; font-size: 24px; }\n .icon-success { background: rgba(16,185,129,0.1); color: #10B981; }\n .icon-error { background: rgba(220,38,38,0.1); color: #DC2626; }\n h1 { font-size: 20px; font-weight: 600; margin-bottom: 8px; }\n p { font-size: 14px; color: #6B7280; line-height: 1.5; }\n p + p { margin-top: 4px; }\n`\n\nexport const SUCCESS_HTML = `<!DOCTYPE html>\n<html><head><meta charset=\"UTF-8\"><title>Authorized \u2014 FlowRunner CLI</title>\n<style>${PAGE_STYLES}</style>\n</head><body>\n<div class=\"card\">\n <div class=\"brand\">FlowRunner</div>\n <div class=\"icon icon-success\">&#10003;</div>\n <h1>Authorization Successful</h1>\n <p>You can close this window and return to the terminal.</p>\n</div>\n</body></html>`\n\nexport const ERROR_HTML = (error: string) => `<!DOCTYPE html>\n<html><head><meta charset=\"UTF-8\"><title>Authorization Failed \u2014 FlowRunner CLI</title>\n<style>${PAGE_STYLES}</style>\n</head><body>\n<div class=\"card\">\n <div class=\"brand\">FlowRunner</div>\n <div class=\"icon icon-error\">&#10007;</div>\n <h1>Authorization Failed</h1>\n <p>${error}</p>\n <p>You can close this window and try again.</p>\n</div>\n</body></html>`\n", "import { ERROR_HTML, SUCCESS_HTML } from '../pages'\nimport type { Route } from '../types'\n\n// Where the console sends the browser once the user has authorized the CLI and picked a workspace. The\n// request carries either an exchange code or an error; both end the wait, and both render a page telling\n// the user they can close the window.\n\nexport interface CallbackRoute {\n route: Route\n waitForCode: () => Promise<string>\n}\n\nexport function callbackRoute(path = '/callback'): CallbackRoute {\n let resolveCode: ((code: string) => void) | null = null\n let rejectCode: ((error: Error) => void) | null = null\n\n const respond = (route: Parameters<Route['handle']>[0], html: string) => {\n route.res.writeHead(200, { 'Content-Type': 'text/html' })\n route.res.end(html)\n }\n\n const route: Route = {\n method: 'GET',\n path,\n handle: context => {\n const code = context.url.searchParams.get('code')\n const error = context.url.searchParams.get('error')\n\n if (error) {\n respond(context, ERROR_HTML(error))\n rejectCode?.(new Error(error))\n\n return\n }\n\n if (!code) {\n respond(context, ERROR_HTML('Missing exchange code'))\n rejectCode?.(new Error('Missing exchange code'))\n\n return\n }\n\n respond(context, SUCCESS_HTML)\n resolveCode?.(code)\n },\n }\n\n return {\n route,\n waitForCode: () => new Promise<string>((resolve, reject) => {\n resolveCode = resolve\n rejectCode = reject\n }),\n }\n}\n", "/** Hand a URL to whatever the operating system considers the browser. */\nexport function openBrowser(url: string): void {\n // eslint-disable-next-line @typescript-eslint/consistent-type-imports\n const { exec } = require('child_process') as typeof import('child_process')\n\n const command = process.platform === 'darwin'\n ? `open \"${ url }\"`\n : process.platform === 'win32'\n ? `start \"${ url }\"`\n : `xdg-open \"${ url }\"`\n\n // Detached from this process's lifetime: whether the browser is still open has nothing to do with whether\n // the CLI is finished, and an unreaped child handle would keep it running.\n exec(command).unref()\n}\n", "import { authorizeUrl, exchangeCodeForToken } from '../api/console-client'\nimport { LoginTimeoutError } from '../errors'\nimport { saveAuth } from '../project/auth'\nimport { getServerUrl, getWorkspaceId } from '../project/config'\nimport { startCallbackServer } from '../server'\nimport { openBrowser } from '../utils/open-browser'\nimport { normalizeServerUrl, resolveServerTarget } from './server-target'\nimport type { OperationOptions } from './types'\nimport { emitter } from './types'\n\n// Connecting a project to a workspace: stand up a local callback server, send the user to the console to\n// authorize, trade the code it redirects back with for a deploy token, write both down.\n//\n// The browser is the part that makes this awkward to automate, so it is behind `openUrl`: the default hands\n// the URL to the operating system, and a caller that wants to do something else \u2014 print it, drive a headless\n// browser, ignore it \u2014 passes their own and reads the URL off the `authorize` event.\n\nconst DEFAULT_TIMEOUT_MS = 2 * 60 * 1000\n\nexport type LoginEvent =\n | { type: 'connecting'; serverUrl: string }\n | { type: 'authorize'; url: string }\n | { type: 'waiting' }\n | { type: 'exchanging' }\n | { type: 'connected'; serverUrl: string; workspaceId: string; workspaceName: string }\n\nexport interface LoginOptions extends OperationOptions<LoginEvent> {\n /** Overrides the server in `flowrunner.json`. A cluster name (`prod`/`dev`/`local`) or a full URL. */\n server?: string\n /** How long to wait for the browser round-trip. */\n timeoutMs?: number\n /**\n * Called with the authorization URL after it is known and before `openUrl` runs.\n *\n * The CLI waits for Enter here when the login is a step inside another command: a browser window taking\n * focus out of nowhere, mid-deploy, is startling in a way that one typed `flowrunner login` is not.\n */\n onBeforeOpen?: (url: string) => Promise<void>\n /** How the user gets the URL. Defaults to opening their browser. */\n openUrl?: (url: string) => void | Promise<void>\n}\n\nexport interface LoginResult {\n serverUrl: string\n workspaceId: string\n workspaceName: string\n}\n\nexport async function login(options: LoginOptions = {}): Promise<LoginResult> {\n const projectRoot = options.cwd ?? process.cwd()\n const emit = emitter(options)\n\n // Never empty: `getServerUrl` falls back to the environment and then to DEFAULT_SERVER_URL, so a project\n // that has never been logged in \u2014 one with no flowrunner.json at all \u2014 still has somewhere to go.\n const serverUrl = options.server\n ? resolveServerTarget(options.server)\n : normalizeServerUrl(getServerUrl(projectRoot))\n\n // Pre-selects the workspace the project is already attached to. The page still offers \"use another\n // workspace\", so `flowrunner login` is also how you move a connected project somewhere else.\n const existingWorkspaceId = getWorkspaceId(projectRoot)\n\n emit({ type: 'connecting', serverUrl })\n\n const server = await startCallbackServer()\n const callbackUrl = `http://localhost:${ server.port }/callback`\n\n try {\n const authUrl = authorizeUrl({ serverUrl, callbackUrl, workspaceId: existingWorkspaceId })\n\n emit({ type: 'authorize', url: authUrl })\n\n await options.onBeforeOpen?.(authUrl)\n await (options.openUrl ?? openBrowser)(authUrl)\n\n emit({ type: 'waiting' })\n\n // The timer has to be cleared, not just lost: a pending two-minute timeout keeps the event loop alive,\n // so the CLI would sit there doing nothing after a successful login \u2014 invisible while this command\n // ended in `process.exit`, and a hang once a deploy runs after it.\n let timeout: NodeJS.Timeout | undefined\n\n const exchangeCode = await Promise.race([\n server.waitForCode(),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new LoginTimeoutError()), options.timeoutMs ?? DEFAULT_TIMEOUT_MS)\n }),\n ]).finally(() => clearTimeout(timeout))\n\n emit({ type: 'exchanging' })\n\n const { token, workspaceId, workspaceName } = await exchangeCodeForToken(serverUrl, exchangeCode)\n\n saveAuth({ serverUrl, workspaceId, deployToken: token, workspaceName }, projectRoot)\n\n emit({ type: 'connected', serverUrl, workspaceId, workspaceName: workspaceName || '' })\n\n return { serverUrl, workspaceId, workspaceName: workspaceName || '' }\n } finally {\n server.close()\n }\n}\n", "import { revokeToken } from '../api/console-client'\nimport { clearAuth, loadAuth } from '../project/auth'\nimport type { OperationOptions } from './types'\nimport { emitter } from './types'\n\nexport type LogoutEvent =\n /** Emitted once there is something to log out of, before the revoke goes over the network. */\n | { type: 'starting'; serverUrl: string }\n | { type: 'revoked' }\n | { type: 'cleared' }\n\nexport type LogoutOptions = OperationOptions<LogoutEvent>\n\nexport interface LogoutResult {\n /** False when there was nothing to log out of \u2014 not an error, just nothing to do. */\n wasLoggedIn: boolean\n /** The server the revoked token belonged to, when there was one. */\n serverUrl?: string\n}\n\nexport async function logout(options: LogoutOptions = {}): Promise<LogoutResult> {\n const projectRoot = options.cwd ?? process.cwd()\n const emit = emitter(options)\n const stored = loadAuth(projectRoot)\n\n if (!stored) {\n return { wasLoggedIn: false }\n }\n\n emit({ type: 'starting', serverUrl: stored.serverUrl })\n\n // Best effort, and deliberately not fatal: the local token is being deleted either way, and a revoke that\n // never reached the server is not a reason to leave the user still looking logged in.\n await revokeToken(stored.serverUrl, stored.deployToken)\n\n emit({ type: 'revoked' })\n\n clearAuth(projectRoot)\n\n emit({ type: 'cleared' })\n\n return { wasLoggedIn: true, serverUrl: stored.serverUrl }\n}\n", "import AdmZip from 'adm-zip'\nimport fs from 'fs'\nimport path from 'path'\n\nimport type { RemoteService } from '../../api/console-client'\nimport { downloadRemoteService, listRemoteServices } from '../../api/console-client'\nimport {\n HttpError,\n NotLoggedInError,\n NoWorkspaceError,\n SelectionRequiredError,\n TokenExpiredError,\n UnknownServiceError,\n} from '../../errors'\nimport type { AuthGap, StoredAuth } from '../../project/auth'\nimport { authGap, loadAuth } from '../../project/auth'\nimport { computeServiceHash } from '../deploy/hash'\nimport type { OperationOptions } from '../types'\nimport { emitter } from '../types'\nimport { declaredDependencies, extractService, isSafeServiceId } from './extract'\n\nexport { declaredDependencies, extractService, isSafeServiceId } from './extract'\n\n// Pulling: bring the workspace's services down into this project so they can be edited and deployed back.\n//\n// The mirror image of deploying, and it has to be, now that a workspace collects services from any number of\n// projects: a fresh checkout can connect to a workspace and get whatever is live there, whoever deployed it.\n//\n// A service is self-contained, so what lands on disk is nearly the whole archive \u2014 source, icons, and the\n// service's own `package.json`. Only `node_modules` stays behind, because `npm install` rebuilds it; a\n// service that declares dependencies is reported as needing one rather than having it run for it.\n\n/**\n * What the local copy of a service is, relative to the deployed one.\n *\n * Decided on `sourceHash`, which covers the service folder and nothing else \u2014 so the answer holds wherever\n * the service is checked out, and \"same version\" and \"same code\" are the same question.\n */\nexport type LocalState = 'absent' | 'same' | 'different'\n\nexport type PullEvent =\n | { type: 'listed'; services: RemoteService[]; workspace: Workspace }\n | { type: 'selected'; services: RemoteService[] }\n | { type: 'up-to-date'; serviceId: string; sourceHash: string }\n | { type: 'skipped'; serviceId: string; reason: string }\n | { type: 'pulled'; serviceId: string; sourceHash: string; files: number; directory: string }\n | { type: 'install-needed'; serviceId: string; dependencies: string[] }\n\nexport interface Workspace {\n workspaceId: string\n workspaceName: string\n}\n\nexport interface PullOptions extends OperationOptions<PullEvent> {\n /** Service ids to pull. Wins over `all`. */\n serviceIds?: string[]\n /** Pull every service in the workspace. */\n all?: boolean\n /** Overwrite `services/<id>/` when it already exists. Without this, existing folders are left alone. */\n force?: boolean\n onAuthRequired?: (gap: AuthGap) => Promise<void>\n onSelectionRequired?: (available: RemoteService[]) => Promise<{ serviceIds?: string[]; all?: boolean }>\n}\n\nexport interface PulledService {\n serviceId: string\n serviceName: string\n sourceHash: string\n files: number\n directory: string\n /** What the service declares. Non-empty means `npm install` is needed in its folder before it will run. */\n dependencies: string[]\n}\n\nexport interface PullResult {\n workspace: Workspace\n serverUrl: string\n /** Services written to disk. */\n services: PulledService[]\n /** Already identical to what is deployed \u2014 nothing to download, nothing to write. */\n upToDate: { serviceId: string; serviceName: string; sourceHash: string }[]\n /** Selected but not written: a local copy that differs, without `--force`. */\n skipped: { serviceId: string; reason: string }[]\n}\n\n/**\n * How the local `services/<id>/` compares to the deployed service.\n *\n * A folder that is not there is `absent`; anything else is decided on the hash a deploy would produce.\n */\nexport async function localState(\n projectRoot: string,\n service: RemoteService\n): Promise<LocalState> {\n if (!fs.existsSync(path.resolve(projectRoot, 'services', service.serviceId))) {\n return 'absent'\n }\n\n // A folder we cannot hash (unreadable, or something that is not a service) is treated as different, so the\n // pull refuses to overwrite it rather than assuming it is safe to replace.\n try {\n return await computeServiceHash(projectRoot, service.serviceId) === service.sourceHash ? 'same' : 'different'\n } catch {\n return 'different'\n }\n}\n\nasync function resolveAuth(projectRoot: string, onAuthRequired?: PullOptions['onAuthRequired']): Promise<StoredAuth> {\n const stored = loadAuth(projectRoot)\n const gap = authGap(stored)\n\n if (!gap) {\n return stored as StoredAuth\n }\n\n if (!onAuthRequired) {\n throw gap === 'not-logged-in' ? new NotLoggedInError() : new NoWorkspaceError()\n }\n\n await onAuthRequired(gap)\n\n const refreshed = loadAuth(projectRoot)\n const remaining = authGap(refreshed)\n\n if (remaining) {\n throw remaining === 'not-logged-in' ? new NotLoggedInError() : new NoWorkspaceError()\n }\n\n return refreshed as StoredAuth\n}\n\nexport async function pull(options: PullOptions = {}): Promise<PullResult> {\n const projectRoot = options.cwd ?? process.cwd()\n const emit = emitter(options)\n\n const { serverUrl, workspaceId, workspaceName, deployToken } = await resolveAuth(projectRoot, options.onAuthRequired)\n const credentials = { serverUrl, workspaceId, deployToken }\n\n const available = await guard(() => listRemoteServices(credentials))\n\n emit({ type: 'listed', services: available, workspace: { workspaceId, workspaceName } })\n\n const selected = await resolveSelection(available, options)\n\n emit({ type: 'selected', services: selected })\n\n const pulled: PulledService[] = []\n const upToDate: PullResult['upToDate'] = []\n const skipped: { serviceId: string; reason: string }[] = []\n\n for (const service of selected) {\n // The id decides where this writes, and it came from the server.\n if (!isSafeServiceId(service.serviceId)) {\n const reason = `\"${ service.serviceId }\" is not a usable folder name`\n\n skipped.push({ serviceId: service.serviceId, reason })\n emit({ type: 'skipped', serviceId: service.serviceId, reason })\n\n continue\n }\n\n const directory = path.resolve(projectRoot, 'services', service.serviceId)\n const state = await localState(projectRoot, service)\n\n // Identical code needs no download and no write \u2014 and `--force` changes nothing, since there is nothing\n // to overwrite it with. Reported rather than silently omitted: \"I checked, and it matches\" is an answer.\n if (state === 'same') {\n upToDate.push({\n serviceId : service.serviceId,\n serviceName: service.serviceName,\n sourceHash : service.sourceHash,\n })\n emit({ type: 'up-to-date', serviceId: service.serviceId, sourceHash: service.sourceHash })\n\n continue\n }\n\n if (state === 'different' && !options.force) {\n const reason = `services/${ service.serviceId }/ differs from the deployed version`\n\n skipped.push({ serviceId: service.serviceId, reason })\n emit({ type: 'skipped', serviceId: service.serviceId, reason })\n\n continue\n }\n\n const exists = state === 'different'\n const zipBuffer = await guard(() => downloadRemoteService(credentials, service.serviceId))\n const archive = new AdmZip(zipBuffer)\n\n // --force replaces rather than merges. Extracting over the top would leave behind files the remote\n // version no longer has, and the next deploy would quietly ship them \u2014 a version matching nothing.\n if (exists) {\n fs.rmSync(directory, { recursive: true, force: true })\n }\n\n const files = extractService(archive, directory)\n const dependencies = declaredDependencies(archive)\n\n emit({ type: 'pulled', serviceId: service.serviceId, sourceHash: service.sourceHash, files, directory })\n\n if (dependencies.length > 0) {\n emit({ type: 'install-needed', serviceId: service.serviceId, dependencies })\n }\n\n pulled.push({\n serviceId : service.serviceId,\n serviceName: service.serviceName,\n sourceHash : service.sourceHash,\n files,\n directory,\n dependencies,\n })\n }\n\n return { workspace: { workspaceId, workspaceName }, serverUrl, services: pulled, upToDate, skipped }\n}\n\nasync function resolveSelection(\n available: RemoteService[],\n options: PullOptions\n): Promise<RemoteService[]> {\n const ids = available.map(service => service.serviceId)\n\n const pick = (selection: { serviceIds?: string[]; all?: boolean }): RemoteService[] => {\n if (selection.serviceIds?.length) {\n return selection.serviceIds.map(serviceId => {\n const match = available.find(service => service.serviceId === serviceId)\n\n if (!match) {\n throw new UnknownServiceError(serviceId, ids)\n }\n\n return match\n })\n }\n\n if (selection.all || available.length <= 1) {\n return available\n }\n\n throw new SelectionRequiredError(ids, 'This workspace has more than one service, so the pull needs to know which.')\n }\n\n try {\n return pick(options)\n } catch (error) {\n if (!options.onSelectionRequired || (error as { code?: string }).code !== 'FR_SELECTION_REQUIRED') {\n throw error\n }\n\n return pick(await options.onSelectionRequired(available))\n }\n}\n\n/** Turns a rejected token into the same error the deploy path raises, so the advice is one sentence. */\nasync function guard<T>(call: () => Promise<T>): Promise<T> {\n try {\n return await call()\n } catch (error) {\n if (error instanceof HttpError && (error.status === 401 || error.body.includes('CLI_TOKEN_EXPIRED'))) {\n throw new TokenExpiredError()\n }\n\n throw error\n }\n}\n", "import type AdmZip from 'adm-zip'\nimport fs from 'fs'\nimport path from 'path'\n\nimport { HASH_EXCLUDED_FOLDERS } from '../../constants'\n\n// Turning a downloaded package back into a service folder.\n//\n// The archive's `package/` root IS the service, so nearly all of it belongs on disk \u2014 its source, its icons,\n// and its own `package.json`. The one thing left behind is `node_modules`: it is generated, it is the bulk of\n// the download, and `npm install` in the service folder rebuilds it from the lockfile that did come across.\n\nconst PACKAGE_PREFIX = 'package/'\n\n/** A service id is a folder name and nothing else \u2014 no separators, no `..`, no absolute path. */\nconst SAFE_SERVICE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/**\n * Whether `serviceId` is safe to use as a path segment.\n *\n * The id arrives from the server, so it is input: `../../etc` as a service id would otherwise decide where\n * this command writes.\n */\nexport function isSafeServiceId(serviceId: string): boolean {\n return SAFE_SERVICE_ID.test(serviceId) && serviceId !== '.' && serviceId !== '..'\n}\n\n/** Everything in the archive that is worth writing \u2014 the service, minus what `npm install` regenerates. */\nfunction serviceEntries(archive: AdmZip): AdmZip.IZipEntry[] {\n return archive.getEntries().filter(entry => {\n if (entry.isDirectory || !entry.entryName.startsWith(PACKAGE_PREFIX)) {\n return false\n }\n\n const [top] = entry.entryName.slice(PACKAGE_PREFIX.length).split('/')\n\n return !HASH_EXCLUDED_FOLDERS.includes(top)\n })\n}\n\n/**\n * Write the service's files into `directory`, returning how many were written.\n *\n * Entry names are confined to the target directory before anything is written: an archive is input, and a\n * `../` in a path is the oldest way to get a file written somewhere it was never meant to go.\n */\nexport function extractService(archive: AdmZip, directory: string): number {\n let written = 0\n\n for (const entry of serviceEntries(archive)) {\n const relativePath = entry.entryName.slice(PACKAGE_PREFIX.length)\n const target = path.resolve(directory, relativePath)\n\n if (target !== directory && !target.startsWith(directory + path.sep)) {\n continue\n }\n\n fs.mkdirSync(path.dirname(target), { recursive: true })\n fs.writeFileSync(target, entry.getData())\n\n written++\n }\n\n return written\n}\n\n/**\n * The dependencies the pulled service declares, if any.\n *\n * `node_modules` is not extracted, so a service that declares anything needs an install before it will run.\n * Reported rather than installed: running a package manager on someone's behalf, in a folder they have not\n * looked at yet, is a bigger act than unpacking it.\n */\nexport function declaredDependencies(archive: AdmZip): string[] {\n const raw = archive.getEntry(`${ PACKAGE_PREFIX }package.json`)?.getData().toString('utf-8')\n\n if (!raw) {\n return []\n }\n\n try {\n const manifest = JSON.parse(raw) as { dependencies?: Record<string, string> }\n\n return Object.keys(manifest.dependencies ?? {})\n } catch {\n // A manifest that will not parse tells us nothing, and must not fail a pull that already succeeded.\n return []\n }\n}\n", "import fs from 'fs'\n\nimport type { ClusterName } from '../constants'\nimport { NotAProjectError } from '../errors'\nimport { clearAuth, loadAuth } from '../project/auth'\nimport { configPath, readConfig, writeConfig } from '../project/config'\nimport { clusterFor, normalizeServerUrl, resolveServerTarget } from './server-target'\nimport type { OperationOptions } from './types'\n\n// Pointing a project at a different Flowrunner cluster.\n//\n// The reason this is a command rather than \"edit flowrunner.json\" is the login. A deploy token is issued by\n// one server and a workspace id only exists on that server, so a project carrying both across a switch is\n// carrying credentials that cannot work \u2014 and the failure would arrive later, as a 401 in the middle of a\n// deploy, rather than here where the cause is obvious. Switching therefore detaches both.\n\nexport { CLUSTER_NAMES, clusterFor, normalizeServerUrl, resolveServerTarget } from './server-target'\n\nexport interface UseServerResult {\n /** The cluster switched to, or null for a URL that is not one of ours. */\n cluster: ClusterName | null\n serverUrl: string\n previousServerUrl: string\n /** False when the project was already pointed at this server \u2014 nothing was touched. */\n changed: boolean\n /** A login existed for the previous server and was detached. */\n clearedLogin: boolean\n /** The workspace that was detached, if there was one. */\n clearedWorkspaceId: string\n}\n\n/** Point the project at `target`, detaching any login that belonged to the server it was on. */\nexport function useServer(target: string, options: OperationOptions = {}): UseServerResult {\n const projectRoot = options.cwd ?? process.cwd()\n\n if (!fs.existsSync(configPath(projectRoot))) {\n throw new NotAProjectError()\n }\n\n const serverUrl = resolveServerTarget(target)\n const config = readConfig(projectRoot)\n const previousServerUrl = normalizeServerUrl(config.serverUrl ?? '')\n\n // Switching to the server you are already on must not log you out \u2014 that would make an idempotent\n // command destructive, and `use dev` is exactly the thing someone types to check where they are.\n if (previousServerUrl === serverUrl) {\n return {\n cluster : clusterFor(serverUrl),\n serverUrl,\n previousServerUrl,\n changed : false,\n clearedLogin : false,\n clearedWorkspaceId: '',\n }\n }\n\n const clearedLogin = Boolean(loadAuth(projectRoot))\n const clearedWorkspaceId = config.workspaceId ?? ''\n\n // The workspace and the name go with the old server; only `serverUrl` survives the switch.\n const { workspaceId: _workspaceId, workspaceName: _workspaceName, ...rest } = config\n\n writeConfig({ ...rest, serverUrl }, projectRoot)\n clearAuth(projectRoot)\n\n return {\n cluster: clusterFor(serverUrl),\n serverUrl,\n previousServerUrl,\n changed: true,\n clearedLogin,\n clearedWorkspaceId,\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,wDAAAA,UAAA;AAAA;AAEA,WAAO,eAAeA,UAAS,cAAc;AAAA,MAC3C,OAAO;AAAA,IACT,CAAC;AACD,IAAAA,SAAQ,iBAAiB;AACzB,IAAAA,SAAQ,YAAY;AACpB,IAAAA,SAAQ,cAAc;AACtB,IAAAA,SAAQ,iBAAiB;AACzB,IAAAA,SAAQ,cAAc;AACtB,IAAAA,SAAQ,gBAAgBA,SAAQ,WAAWA,SAAQ,WAAWA,SAAQ,WAAWA,SAAQ,aAAaA,SAAQ,UAAUA,SAAQ,YAAYA,SAAQ,SAAS;AAC7J,IAAAA,SAAQ,oBAAoB;AAC5B,IAAAA,SAAQ,+BAA+B;AACvC,IAAAA,SAAQ,cAAc;AACtB,IAAAA,SAAQ,UAAU;AAClB,aAAS,QAAQ,GAAG;AAAE;AAA2B,aAAO,UAAU,cAAc,OAAO,UAAU,YAAY,OAAO,OAAO,WAAW,SAAUC,IAAG;AAAE,eAAO,OAAOA;AAAA,MAAG,IAAI,SAAUA,IAAG;AAAE,eAAOA,MAAK,cAAc,OAAO,UAAUA,GAAE,gBAAgB,UAAUA,OAAM,OAAO,YAAY,WAAW,OAAOA;AAAA,MAAG,GAAG,QAAQ,CAAC;AAAA,IAAG;AAK7T,QAAI,YAAYD,SAAQ,YAAY,SAASE,WAAU,OAAO;AAC5D,aAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAAA,IAC9C;AACA,QAAI,WAAWF,SAAQ,WAAW,SAASG,UAAS,OAAO;AACzD,aAAO,QAAQ,SAAS,QAAQ,KAAK,MAAM;AAAA,IAC7C;AACA,QAAI,aA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B;AAEA,UAAM;AAAA,EACR;AACF;;;AE1QA,IAAAE,cAAe;AAgCR,SAAS,UAAU,QAAgB,UAA4B,CAAC,GAAoB;AACzF,QAAM,cAAc,QAAQ,OAAO,QAAQ,IAAI;AAE/C,MAAI,CAAC,YAAAC,QAAG,WAAW,WAAW,WAAW,CAAC,GAAG;AAC3C,UAAM,IAAI,iBAAiB;AAAA,EAC7B;AAEA,QAAM,YAAY,oBAAoB,MAAM;AAC5C,QAAM,SAAS,WAAW,WAAW;AACrC,QAAM,oBAAoB,mBAAmB,OAAO,aAAa,EAAE;AAInE,MAAI,sBAAsB,WAAW;AACnC,WAAO;AAAA,MACL,SAAoB,WAAW,SAAS;AAAA,MACxC;AAAA,MACA;AAAA,MACA,SAAoB;AAAA,MACpB,cAAoB;AAAA,MACpB,oBAAoB;AAAA,IACtB;AAAA,EACF;AAEA,QAAM,eAAe,QAAQ,SAAS,WAAW,CAAC;AAClD,QAAM,qBAAqB,OAAO,eAAe;AAGjD,QAAM,EAAE,aAAa,cAAc,eAAe,gBAAgB,GAAG,KAAK,IAAI;AAE9E,cAAY,EAAE,GAAG,MAAM,UAAU,GAAG,WAAW;AAC/C,YAAU,WAAW;AAErB,SAAO;AAAA,IACL,SAAS,WAAW,SAAS;AAAA,IAC7B;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": ["exports", "o", "castArray", "isObject", "isFormData", "FormData", "isStream", "isNodeJS", "isBrowser", "path", "isBytes", "isBlob", "isWebFormData", "exports", "o", "hint", "_wrapNativeSuper", "Class", "_construct", "Parent", "args", "_setPrototypeOf", "p", "_getPrototypeOf", "ResponseError", "TLSError", "text", "exports", "path", "rejectWithError", "_send", "Buffer", "body", "headers", "send", "exports", "o", "hint", "EventEmitter", "exports", "stringify", "value", "exports", "o", "_getRequireWildcardCache", "nodeInterop", "r", "hint", "_setPrototypeOf", "p", "_getPrototypeOf", "Request", "path", "_loop", "formKey", "unwrap", "setTimeout", "unwrapBody", "exports", "path", "headers", "exports", "module", "path", "exports", "module", "exports", "require_utils", "exports", "module", "path", "err", "fd", "cb", "dir", "exports", "module", "path", "fs", "exports", "module", "exports", "module", "exports", "module", "exports", "module", "exports", "exports", "module", "exports", "module", "fail", "exports", "module", "exports", "exports", "module", "exports", "module", "exports", "module", "options", "err", "content", "fileAttr", "getPath", "ok", "import_fs", "import_path", "fetch", "FormData", "path", "fs", "resolved", "import_fs", "import_path", "path", "fs", "import_fs", "import_path", "import_backendless_request", "hint", "meta", "path", "text", "cached", "plan", "path", "plan", "EXPECTED", "path", "fail", "plan", "fail", "fail", "import_zod", "baseZod", "baseZod", "text", "toJsonValue", "toJsonValue", "WRAPPERS", "toJsonValue", "fail", "hint", "fail", "crypto", "path", "fetch", "path", "import_crypto", "crypto", "nodeCrypto", "BLRequest", "crypto", "getServiceConfigs", "getServiceConfigs", "buildServiceDefinition", "import_fs", "import_path", "path", "fs", "entry", "path", "fs", "services", "buildServiceDefinition", "getServiceConfigs", "import_crypto", "import_fs", "import_path", "path", "fs", "import_fs", "import_path", "services", "path", "fs", "import_path", "archiver", "path", "fs", "path", "import_fs", "import_path", "import_fs", "import_path", "path", "fs", "import_path", "import_fs", "import_path", "import_fs", "import_zod", "import_path", "path", "fs", "path", "fs", "import_fs", "import_path", "path", "fs", "serviceDirectory", "validate", "serviceDirectory", "path", "import_fs", "import_path", "path", "fs", "fs", "path", "manifest", "import_fs", "import_path", "path", "fs", "path", "route", "http", "import_fs", "import_path", "import_fs", "import_path", "path", "fs", "fs", "path", "resolveAuth", "resolveSelection", "AdmZip", "import_fs", "fs"]
7
7
  }