@tailor-platform/sdk 2.16.0 → 2.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/dist/{application-wYQ-ivDg.mjs → application-ChuNPwnl.mjs} +13 -13
- package/dist/application-ChuNPwnl.mjs.map +1 -0
- package/dist/application-Oh5dMmb5.mjs +1 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-files.d.mts +5 -1
- package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +2 -2
- package/dist/cli/lib.d.mts +2 -2
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +40 -40
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/error-json.d.mts +19 -0
- package/dist/cli/shared/logger.d.mts +18 -0
- package/dist/completion/zsh-worker.zsh +2 -2
- package/dist/configure/index.mjs +1 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/crashreport-CgymxQDu.mjs +1 -0
- package/dist/crashreport-Cyuz1qiu.mjs +42 -0
- package/dist/crashreport-Cyuz1qiu.mjs.map +1 -0
- package/dist/{errors-BtTxkzgy.mjs → errors-BjJnpXkK.mjs} +2 -2
- package/dist/{errors-BtTxkzgy.mjs.map → errors-BjJnpXkK.mjs.map} +1 -1
- package/dist/field-parse-CzlKC4b7.mjs +2 -0
- package/dist/field-parse-CzlKC4b7.mjs.map +1 -0
- package/dist/kysely-type-B_oA8D1k.mjs +43 -0
- package/dist/kysely-type-B_oA8D1k.mjs.map +1 -0
- package/dist/{logger-CEAxByN5.mjs → logger-72hM4JWZ.mjs} +4 -4
- package/dist/logger-72hM4JWZ.mjs.map +1 -0
- package/dist/{manager-E3ffRcCt.mjs → manager-C26Gi1bX.mjs} +2 -2
- package/dist/{manager-E3ffRcCt.mjs.map → manager-C26Gi1bX.mjs.map} +1 -1
- package/dist/plugin/builtin/kysely-type/index.d.mts +2 -0
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/plugin/index.mjs +1 -1
- package/dist/{register-ts-hook-DrHS-J1k.mjs → register-ts-hook-Dn-XlVSD.mjs} +108 -69
- package/dist/register-ts-hook-Dn-XlVSD.mjs.map +1 -0
- package/dist/schema-DRyQEabV.mjs +2 -0
- package/dist/schema-DRyQEabV.mjs.map +1 -0
- package/dist/service-B3OiWCYg.mjs +1 -0
- package/dist/{service-Cw7hb5HK.mjs → service-B4Gh_bbL.mjs} +2 -2
- package/dist/{service-Cw7hb5HK.mjs.map → service-B4Gh_bbL.mjs.map} +1 -1
- package/dist/{service-DaoW0kzo.mjs → service-eM7Fd8zS.mjs} +3 -3
- package/dist/{service-DaoW0kzo.mjs.map → service-eM7Fd8zS.mjs.map} +1 -1
- package/dist/tailordb-ddl-Fgm2cNvT.mjs +7 -0
- package/dist/tailordb-ddl-Fgm2cNvT.mjs.map +1 -0
- package/dist/utils/test/index.mjs +1 -1
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/tailordb-pglite.d.mts +5 -4
- package/docs/cli/tailordb.md +8 -8
- package/docs/cli-reference.md +7 -3
- package/docs/services/tailordb-migration.md +25 -24
- package/docs/testing.md +23 -21
- package/package.json +8 -7
- package/dist/application-Dw3t9p2f.mjs +0 -1
- package/dist/application-wYQ-ivDg.mjs.map +0 -1
- package/dist/crashreport-DF8YMIE5.mjs +0 -1
- package/dist/crashreport-Doz2Kuuq.mjs +0 -42
- package/dist/crashreport-Doz2Kuuq.mjs.map +0 -1
- package/dist/field-column-type-QMtF6lUp.mjs +0 -2
- package/dist/field-column-type-QMtF6lUp.mjs.map +0 -1
- package/dist/kysely-type-B-BOlXH7.mjs +0 -43
- package/dist/kysely-type-B-BOlXH7.mjs.map +0 -1
- package/dist/logger-CEAxByN5.mjs.map +0 -1
- package/dist/register-ts-hook-DrHS-J1k.mjs.map +0 -1
- package/dist/schema-BTioi2dP.mjs +0 -2
- package/dist/schema-BTioi2dP.mjs.map +0 -1
- package/dist/service-dn9jxC8c.mjs +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
# @tailor-platform/sdk
|
|
2
2
|
|
|
3
|
+
## 2.17.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#2330](https://github.com/tailor-platform/sdk/pull/2330) [`3e8dc24`](https://github.com/tailor-platform/sdk/commit/3e8dc24bf2a5b55c811e28570dffb763baf9030e) Thanks [@toiroakr](https://github.com/toiroakr)! - Add `logger.registerSecret(value)` to the CLI logger (`@tailor-platform/sdk/cli`). Values registered this way are automatically replaced with `<redacted>` in diagnostic log output (`info`/`success`/`warn`/`error`/`log`/`debug`), as a technical safety net on top of the existing convention of not passing secret values to the logger. `logger.out()` is unaffected, so commands that intentionally print a secret as their primary result (machine user tokens, OAuth2 client secrets) are unchanged. The CLI itself now registers access tokens, refresh tokens, OAuth2/IdP client secrets, and Secret Manager values as soon as they enter the process. Crash reports (written locally, and optionally sent remotely, when an unexpected error occurs) also redact registered secrets, in addition to their existing pattern-based sanitization of UUIDs, hex tokens, emails, and paths.
|
|
8
|
+
|
|
9
|
+
Fix: `tailor user pat create` / `tailor user pat update` now print their human-readable "token created/updated" message (including the new token value) to stdout instead of stderr. The new token is this command's primary output — the thing a script actually wants to capture — so printing it to stderr instead of stdout was inconsistent with every other command that returns a value (`--json` mode was unaffected and already used stdout). If a script was working around this by reading the token from stderr, switch it to stdout.
|
|
10
|
+
|
|
11
|
+
- [#2337](https://github.com/tailor-platform/sdk/pull/2337) [`f3289dd`](https://github.com/tailor-platform/sdk/commit/f3289dd9e373e479de8a1e0a9da8b026422d6fca) Thanks [@dqn](https://github.com/dqn)! - Write `db.pglite.ts` next to every generated migration `db.ts` with the `CREATE TABLE` script of the schema `migrate.ts` runs against, and let `tailordb migration script --with-test` also scaffold `migrate.pglite.test.ts` when `@electric-sql/pglite` is installed
|
|
12
|
+
|
|
13
|
+
Generate migration types that accept nested objects and object arrays instead of JSON strings.
|
|
14
|
+
|
|
15
|
+
- [#2335](https://github.com/tailor-platform/sdk/pull/2335) [`39f32f6`](https://github.com/tailor-platform/sdk/commit/39f32f64f3292e57691d6469fd81cecda5f45ee7) Thanks [@dqn](https://github.com/dqn)! - Add `pgliteSchemaPath` to `kyselyTypePlugin` to generate the PGlite `CREATE TABLE` script for every TailorDB table alongside the Kysely types, so tests using `mockTailordbWithPGlite` or `createKyselyPGlite` no longer hand-write DDL
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- [#2348](https://github.com/tailor-platform/sdk/pull/2348) [`18ac373`](https://github.com/tailor-platform/sdk/commit/18ac373d1d5eb863c9dabfc0f1a8c19c5a3a9422) Thanks [@toiroakr](https://github.com/toiroakr)! - Bump the pinned `tailor-platform/actions` version to v2.3.3 in workflows generated by `tailor setup` (branch, coordinate, preview, and tag workflows, and the `tailor-setup` composite action).
|
|
20
|
+
|
|
21
|
+
- [#2368](https://github.com/tailor-platform/sdk/pull/2368) [`4a03de8`](https://github.com/tailor-platform/sdk/commit/4a03de85d81f29fed5023b6ae6dab206521d0e90) Thanks [@dqn](https://github.com/dqn)! - Forward global flags typed before a CLI plugin command to the plugin.
|
|
22
|
+
|
|
23
|
+
`tailor --json tailordb erd export` now runs the plugin in JSON mode, the same as
|
|
24
|
+
`tailor tailordb erd export --json`. Previously only the arguments following the plugin name were
|
|
25
|
+
forwarded, so a global flag placed before it was consumed by the host CLI and never reached the
|
|
26
|
+
plugin. The same applies to `--verbose`, `--env-file`, and `--env-file-if-exists`, and the forwarded
|
|
27
|
+
flags now also feed the plugin's platform-context injection.
|
|
28
|
+
|
|
29
|
+
When the same flag appears on both sides of the plugin name, the later one wins. A flag the plugin
|
|
30
|
+
itself does not declare still has to be typed after the plugin's own subcommand.
|
|
31
|
+
|
|
32
|
+
- [#2328](https://github.com/tailor-platform/sdk/pull/2328) [`bbb817b`](https://github.com/tailor-platform/sdk/commit/bbb817b87b66963bf5840430665712db15cc4495) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update @inquirer
|
|
33
|
+
|
|
34
|
+
- [#2331](https://github.com/tailor-platform/sdk/pull/2331) [`73cb3fa`](https://github.com/tailor-platform/sdk/commit/73cb3fab10ee9f24d5ade55b1b497d610d8b99e6) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency pkg-types to v2.3.3
|
|
35
|
+
|
|
36
|
+
- [#2338](https://github.com/tailor-platform/sdk/pull/2338) [`98a9615`](https://github.com/tailor-platform/sdk/commit/98a96153bda73cbbb72f8b6090c948eef6ed0c13) Thanks [@renovate](https://github.com/apps/renovate)! - chore(deps): lock file maintenance
|
|
37
|
+
|
|
38
|
+
- [#2350](https://github.com/tailor-platform/sdk/pull/2350) [`4537014`](https://github.com/tailor-platform/sdk/commit/4537014882c2ff0115e09753158dc7eda0bcc767) Thanks [@renovate](https://github.com/apps/renovate)! - chore(deps): update dependency @types/node to v24.13.4
|
|
39
|
+
|
|
40
|
+
- [#2342](https://github.com/tailor-platform/sdk/pull/2342) [`54eafd9`](https://github.com/tailor-platform/sdk/commit/54eafd96ff0d860ca39674acc36e26839e338850) Thanks [@dqn](https://github.com/dqn)! - Stop seed validation from reporting missing required fields inside a nested object that a row leaves out or gives a non-object value, and report the wrong shape against the field itself instead. Applies to both single nested objects and elements of a nested array.
|
|
41
|
+
|
|
3
42
|
## 2.16.0
|
|
4
43
|
|
|
5
44
|
### Minor Changes
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from"./wait-point-registry-B-ESkTZX.mjs";import{t as a}from"./assert-WeXvmG4j.mjs";import{a as o,n as s,r as c}from"./logger-CEAxByN5.mjs";import{a as l,b as u,c as d,d as f,f as p,g as m,h,l as g,m as _,n as v,o as y,p as b,s as x,t as S,u as C,x as w}from"./service-DaoW0kzo.mjs";import{i as ee,n as te}from"./guards-ForsrxnH.mjs";import{t as T}from"./multiline-EyzjEwn9.mjs";import{t as E}from"./user-agent-vdHYF3QL.mjs";import{a as ne,t as D}from"./errors-BtTxkzgy.mjs";import{n as re,t as ie}from"./es-builtins-BHCXINQp.mjs";import{n as ae,r as O,t as oe}from"./node-builtins-DYfhPBnz.mjs";import{t as se}from"./type-source--ZNcV8RJ.mjs";import{createRequire as ce}from"node:module";import*as k from"pathe";import{resolve as le}from"pathe";import{resolveTSConfig as ue}from"pkg-types";import{z as A}from"zod";import{create as de}from"@bufbuild/protobuf";import*as j from"node:fs";import{readFileSync as fe}from"node:fs";import{MethodOptions_IdempotencyLevel as pe}from"@bufbuild/protobuf/wkt";import{OAuth2Client as me}from"@badgateway/oauth2-client";import{Code as M,ConnectError as N,createClient as he}from"@connectrpc/connect";import ge from"p-limit";import*as _e from"node:crypto";import*as P from"rolldown";import{parseSync as F}from"oxc-parser";import{createPathsMatcher as ve,getTsconfig as ye}from"get-tsconfig";import*as I from"inflection";import*as be from"node:os";const L=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return L.includes(e)}const xe=/^\d*[1-9]\d*$/;function parsePositiveInt(e){if(e===void 0)return;let t=e.trim();if(!xe.test(t))return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)?n:void 0}function resolveApplyConcurrency(){return parsePositiveInt(process.env.TAILOR_APPLY_CONCURRENCY)??16}function createApplyLimiter(){return ge(resolveApplyConcurrency())}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}const Se=new WeakMap;function withErrorDiagnostics(e,t){return Se.set(e,t),e}function getErrorDiagnostics(e){return{...e instanceof N?{suggestion:rpcSuggestion(e.code)}:{},...Se.get(e)}}function rpcSuggestion(e){switch(e){case M.Unauthenticated:return"Check the active token and profile with `tailor auth status` (include the same --profile option). For an environment token, replace TAILOR_PLATFORM_TOKEN; otherwise use the original browser or --machine-user login method with the same profile. See `tailor login --help`.";case M.PermissionDenied:return"Check the active identity and profile with `tailor auth status` (include the same --profile option), then verify its workspace role and token permissions.";case M.Unavailable:case M.DeadlineExceeded:return`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`;default:return}}const Ce=`https://api.tailor.tech`,we=`/.well-known/oauth-authorization-server/oauth2/platform`,R=new Map;function getEnvPlatformUrl(){return process.env.TAILOR_PLATFORM_URL??process.env.PLATFORM_URL}function getEnvOAuth2ClientId(){return process.env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID??process.env.PLATFORM_OAUTH2_CLIENT_ID}function normalizeBaseUrl(e){let t=new URL(e);return t.hash=``,t.search=``,t.toString().replace(/\/$/,``)}function getEffectivePlatformConfig(e={}){let t=e.platformUrl??getEnvPlatformUrl(),n=e.oauth2ClientId??getEnvOAuth2ClientId(),r=e.consoleUrl??process.env.TAILOR_PLATFORM_CONSOLE_URL,i={...t?{platformUrl:t}:{},...n?{oauth2ClientId:n}:{},...r?{consoleUrl:r}:{}};return Object.keys(i).length>0?i:void 0}function rememberPlatformConfigForToken(e,t){let n=getEffectivePlatformConfig(t);n?R.set(e,n):R.delete(e)}function getPlatformConfigForToken(e){return R.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(Ce)}function getOAuth2ClientId(e={}){return e.oauth2ClientId??getEnvOAuth2ClientId()??`cpoc_0Iudir72fqSpqC6GQ58ri1cLAqcq5vJl`}function inferConsoleBaseUrl(e){let t=new URL(e);return t.hostname.startsWith(`api.`)?(t.hostname=t.hostname.replace(/^api\./,`console.`),normalizeBaseUrl(t.toString())):`https://console.tailor.tech`}function applyConsoleNext(e){if(o(process.env.TAILOR_CONSOLE_NEXT)!==!0)return e;let t=new URL(e);return t.hostname=t.hostname.replace(/^console\./,`console-next.`),normalizeBaseUrl(t.toString())}function getConsoleBaseUrl(e={}){if(e.consoleUrl)return normalizeBaseUrl(e.consoleUrl);if(e.platformUrl){let t=inferConsoleBaseUrl(e.platformUrl);if(t!==`https://console.tailor.tech`)return applyConsoleNext(t)}return process.env.TAILOR_PLATFORM_CONSOLE_URL?normalizeBaseUrl(process.env.TAILOR_PLATFORM_CONSOLE_URL):applyConsoleNext(inferConsoleBaseUrl(getPlatformBaseUrl(e)))}function initOAuth2Client(e){return new me({clientId:getOAuth2ClientId(e),server:getPlatformBaseUrl(e),discoveryEndpoint:we})}async function initOperatorClient(e,t){let n=t??getPlatformConfigForToken(e),[{createTracingInterceptor:r},{OperatorService:i}]=await Promise.all([import(`./interceptor-DQg3cR_9.mjs`),import(`./service_pb-DKrsO1_u.mjs`)]),a=[await userAgentInterceptor(),await bearerTokenInterceptor(e),retryInterceptor(),errorHandlingInterceptor(),r(),concurrencyLimitInterceptor()],o=getPlatformBaseUrl(n),s=createPooledStreamTransport(await createTransport(o,a),()=>createTransport(o,a),4);return he(i,s)}async function createTransport(e,t){let{createConnectTransport:n}=await import(`@connectrpc/connect-node`);return n({httpVersion:`2`,baseUrl:e,interceptors:t})}const Te=new Set([`CreateFunctionRegistry`,`UpdateFunctionRegistry`,`UploadFile`]);function createPooledStreamTransport(e,t,n){if(!Number.isInteger(n)||n<1)throw Error(`createPooledStreamTransport: maxConnections must be a positive integer, got ${n}`);let r=[e],i=[0],a=[],o=0;function acquireTransportIndex(e,s){return new Promise((c,l)=>{let u=!1,d;function cleanup(){u=!0,clearTimeout(d),e?.removeEventListener(`abort`,onAbort);let t=a.indexOf(attempt);t!==-1&&a.splice(t,1)}function onAbort(){cleanup(),l(N.from(e?.reason,M.Canceled))}function onTimeout(){cleanup(),l(new N(`the operation timed out`,M.DeadlineExceeded))}function claim(e){if(u){release(e);return}cleanup(),c(e)}function attempt(){let e=i.pop();if(e!==void 0){claim(e);return}if(r.length+o<n){o++,t().then(e=>{o--;let t=r.length;r.push(e),claim(t)},e=>{o--,cleanup(),l(e instanceof Error?e:Error(String(e))),wakeOneWaiter()});return}a.push(attempt)}if(e?.aborted){onAbort();return}if(e?.addEventListener(`abort`,onAbort,{once:!0}),s!==void 0){let e=s-performance.now();if(e<=0){onTimeout();return}d=setTimeout(onTimeout,e)}attempt()})}function wakeOneWaiter(){a.shift()?.()}function release(e){i.push(e),wakeOneWaiter()}return{unary(t,n,r,i,a,o){return e.unary(t,n,r,i,a,o)},async stream(t,n,i,a,o,s){if(!Te.has(t.name))return e.stream(t,n,i,a,o,s);let c=i!==void 0&&i>0?performance.now()+i:void 0,l=await acquireTransportIndex(n,c),u=r[l],d;try{if(n?.aborted)throw N.from(n.reason,M.Canceled);let e=c===void 0?i:Math.ceil(c-performance.now());if(c!==void 0&&e!==void 0&&e<=0)throw new N(`the operation timed out`,M.DeadlineExceeded);d=await u.stream(t,n,e,a,o,s)}catch(e){throw release(l),e}return{...d,message:releaseAfter(d.message,()=>release(l))}}}}async function*releaseAfter(e,t){try{yield*e}finally{t()}}async function userAgentInterceptor(){let e=await E();return t=>async n=>(n.header.set(`User-Agent`,e),await t(n))}async function bearerTokenInterceptor(e){return t=>async n=>(n.header.set(`Authorization`,`Bearer ${e}`),await t(n))}function retryInterceptor(){return e=>async t=>{if(t.stream)return await e(t);let n;for(let r=0;r<De;r++){r>0&&await waitRetryBackoff(r);try{return await e(t)}catch(e){if(isRetrySafeCreateAlreadyExists(e,t.method.name)){if(r>0)return s.debug(`retry: ${t.method.name} returned AlreadyExists on attempt ${r+1}; treating as success (prior attempt likely committed)`),synthesizeEmptyUnaryResponse(t);let{reportCrash:n}=await import(`./crashreport-DF8YMIE5.mjs`);await n(e,`handledError`)}if(t.method.name!==`CreateWorkspace`&&isRetirable(e,t.method.idempotency)){n=e,s.debug(`retry: ${t.method.name} attempt ${r+1} failed with ${retryErrorCodeName(e)}; retrying`);continue}throw e}}throw n}}function concurrencyLimitInterceptor(){let e=createApplyLimiter();return t=>async n=>n.stream?await t(n):await e(()=>t(n))}function retryErrorCodeName(e){return e instanceof N?M[e.code]:isTransportDisconnectError(e)?e.code:`unknown`}const Ee=new Set([`CreateAIGateway`,`CreateApplication`,`CreateAuthConnection`,`CreateAuthHook`,`CreateAuthIDPConfig`,`CreateAuthMachineUser`,`CreateAuthOAuth2Client`,`CreateAuthSCIMConfig`,`CreateAuthSCIMResource`,`CreateAuthService`,`CreateExecutorExecutor`,`CreateIdPService`,`CreatePipelineResolver`,`CreatePipelineService`,`CreateSecretManagerSecret`,`CreateSecretManagerVault`,`CreateStaticWebsite`,`CreateTailorDBGQLPermission`,`CreateTailorDBService`,`CreateTailorDBType`,`CreateTenantConfig`,`CreateUserProfileConfig`,`CreateWorkflow`,`CreateWorkflowJobFunctionExecutionPolicy`]);function isRetrySafeCreateAlreadyExists(e,t){return e instanceof N&&e.code===M.AlreadyExists&&Ee.has(t)}function synthesizeEmptyUnaryResponse(e){return{stream:!1,service:e.service,method:e.method,header:new Headers,message:de(e.method.output),trailer:new Headers}}const De=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}const Oe=new Set([`ERR_STREAM_PREMATURE_CLOSE`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`]);function isTransportDisconnectError(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&Oe.has(e.code)}function isRetirable(e,t){let n=t===pe.NO_SIDE_EFFECTS||t===pe.IDEMPOTENT;if(!(e instanceof N))return isTransportDisconnectError(e)&&n;switch(e.code){case M.ResourceExhausted:case M.Unavailable:return!0;case M.Aborted:case M.Internal:return n;default:return!1}}function errorHandlingInterceptor(){return e=>async t=>{try{return await e(t)}catch(e){if(e instanceof N){let{operation:n,resourceType:r}=parseMethodName(t.method.name),i=requestIdentifiers(t.message,t.method.name),a=Object.entries(i).map(([e,t])=>`${e}: ${t}`),o=a.length===0?``:` (${a.join(`, `)})`;throw withErrorDiagnostics(new N(`Failed to ${n} ${r}${o}: ${e.rawMessage}`,e.code,e.metadata),{context:{method:t.method.name,identifiers:i}})}throw isTransportDisconnectError(e)?withErrorDiagnostics(e,{code:`TRANSPORT_DISCONNECTED`,suggestion:`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`,context:{method:t.method.name,transportCode:e.code,identifiers:requestIdentifiers(t.message,t.method.name)}}):e}}}function parseMethodName(e){let t=e.match(/^(Create|Update|Delete|Set|List|Get)(.+)$/);if(!t)return{operation:`perform`,resourceType:`resource`};let[,n,r]=t;return{operation:n.toLowerCase(),resourceType:r}}const ke=new Set([`name`,`id`]),Ae=[`Name`,`Id`,`Namespace`],je=`name`,Me={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:ke.has(e)||Ae.some(t=>e.endsWith(t))||(Me[t]?.includes(e)??!1)}function requestIdentifiers(e,t){if(typeof e!=`object`||!e)return{};let n={};for(let[r,i]of Object.entries(e))if(typeof i==`string`&&i!==``&&isIdentityKey(r,t))n[r]=i;else if(!r.startsWith(`$`)&&typeof i==`object`&&i&&!Array.isArray(i)&&typeof i.$typeName==`string`){let e=i[je];typeof e==`string`&&e!==``&&(n[`${r}.${je}`]=e)}return n}const z=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,z);if(t.push(...r),!i)break;n=i}return t}function isNotFoundError(e){return e instanceof N&&e.code===M.NotFound}async function fetchAllTolerant(e){return await fetchAll(async(t,n)=>{try{return await e(t,n)}catch(e){if(isNotFoundError(e))return[[],``];throw e}})}async function getOrNull(e){try{return await e()}catch(e){if(isNotFoundError(e))return;throw e}}async function fetchPaged(e,t){let n=t?.limit,r=n===void 0||n===0,i=[],a=``;for(;;){let t=r?z:Math.min(n-i.length,z);if(!r&&t<=0)break;let[o,s]=await e(a,t);if(i.push(...o),!r&&i.length>=n||!s)break;a=s}return!r&&i.length>n?i.slice(0,n):i}async function fetchUserInfo(e,t){let n=new URL(`/auth/platform/userinfo`,getPlatformBaseUrl(t)).href,r=await fetch(n,{headers:{Authorization:`Bearer ${e}`,"User-Agent":await E()}});if(!r.ok)throw Error(`Failed to fetch user info: ${r.statusText}`);let i=await r.json();return A.object({sub:A.string(),email:A.string()}).parse(i)}async function resolveStaticWebsiteUrls(e,t,n,r,i={}){if(!n)return[];let{expectedLocalNames:a}=i;return(await Promise.all(n.map(async n=>{let i=n.match(/:url(\/.*)?$/);if(i&&i.index!==void 0){let o=n.substring(0,i.index),c=i[1]||``;try{let n=await e.getStaticWebsite({workspaceId:t,name:o});return n.staticwebsite?.url?[n.staticwebsite.url+c]:(s.warn(`Static website "${o}" has no URL assigned yet. Excluding from ${r}.`),[])}catch(e){return isNotFoundError(e)&&a?.has(o)?[n]:(s.warn(`Static website "${o}" not found for ${r} configuration. Excluding from ${r}.`),[])}}return[n]}))).flat()}async function fetchMachineUserToken(e,t,n){let r=new URL(`/oauth2/token`,e).href,i=new URLSearchParams;i.append(`grant_type`,`client_credentials`),i.append(`client_id`,t),i.append(`client_secret`,n);let a={method:`POST`,headers:{"User-Agent":await E(),"Content-Type":`application/x-www-form-urlencoded`},body:i},o=await withConnectTimeoutRetry(`machine user token request`,()=>fetch(r,a));if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Failed to fetch machine user token: ${o.status} ${o.statusText} ${e.slice(0,500)}`)}let s=await o.json();return A.object({token_type:A.string(),access_token:A.string(),expires_in:A.number()}).parse(s)}function isUndiciConnectTimeout(e){if(!(e instanceof TypeError))return!1;let t=e.cause;return t instanceof Error&&`code`in t&&t.code===`UND_ERR_CONNECT_TIMEOUT`}async function withConnectTimeoutRetry(e,t){for(let n=1;;n++)try{return await t()}catch(t){if(!isUndiciConnectTimeout(t)||n>=3)throw t;s.debug(`retry: ${e} attempt ${n} failed with UND_ERR_CONNECT_TIMEOUT; retrying`),await waitRetryBackoff(n)}}async function fetchPlatformMachineUserToken(e,t,n){let r=getPlatformBaseUrl(n);return await withConnectTimeoutRetry(`platform machine user token request`,()=>new me({clientId:e,clientSecret:t,server:r,discoveryEndpoint:we}).clientCredentials())}async function closeConnectionPool(){let e=globalThis,t=e[Symbol.for(`undici.globalDispatcher.2`)]??e[Symbol.for(`undici.globalDispatcher.1`)];typeof t?.close==`function`&&await t.close()}function getPluginImportBaseDirs(e){return e?[k.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=k.resolve(n,e);if(j.existsSync(t))return t}return null}function generatePluginExecutorFiles(e,t,n,r,i){if(e.length===0)return[];let a=[],o=getPluginImportBaseDirs(i);for(let i of e){let e=generateSingleExecutorFile(i,t,n,r,o);a.push(e);let l=k.relative(process.cwd(),e);s.log(` Plugin Executor File: ${c.success(l)} from plugin ${c.info(i.pluginId)}`)}return a}function generateSingleExecutorFile(e,t,n,r,i=[]){let a=sanitizePluginId$1(e.pluginId),o=k.join(t,a,`executors`);j.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=k.join(o,`${s}.ts`),l;return l=ee(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),j.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=k.join(n,c,`executors`),u=resolveExecutorImportPath(o,e.pluginImportPath,l,a),d=collectTableImports(s,n,e.pluginId,r,i),f=[];for(let[,e]of d)f.push(`import { ${e.variableName} } from "${e.importPath}";`);let p=generateContextCode(s,d);return T`
|
|
1
|
+
import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from"./wait-point-registry-B-ESkTZX.mjs";import{t as a}from"./assert-WeXvmG4j.mjs";import{i as o,n as s,o as c}from"./logger-72hM4JWZ.mjs";import{a as l,b as u,c as d,d as f,f as p,g as m,h,l as g,m as _,n as v,o as y,p as b,s as x,t as S,u as C,x as w}from"./service-eM7Fd8zS.mjs";import{i as ee,n as te}from"./guards-ForsrxnH.mjs";import{t as T}from"./multiline-EyzjEwn9.mjs";import{t as E}from"./user-agent-vdHYF3QL.mjs";import{a as ne,t as D}from"./errors-BjJnpXkK.mjs";import{n as re,t as ie}from"./es-builtins-BHCXINQp.mjs";import{n as ae,r as O,t as oe}from"./node-builtins-DYfhPBnz.mjs";import{t as se}from"./type-source--ZNcV8RJ.mjs";import{createRequire as ce}from"node:module";import*as k from"pathe";import{resolve as le}from"pathe";import{resolveTSConfig as ue}from"pkg-types";import{z as A}from"zod";import{create as de}from"@bufbuild/protobuf";import*as j from"node:fs";import{readFileSync as fe}from"node:fs";import{MethodOptions_IdempotencyLevel as pe}from"@bufbuild/protobuf/wkt";import{OAuth2Client as me}from"@badgateway/oauth2-client";import{Code as M,ConnectError as N,createClient as he}from"@connectrpc/connect";import ge from"p-limit";import*as _e from"node:crypto";import*as P from"rolldown";import{parseSync as F}from"oxc-parser";import{createPathsMatcher as ve,getTsconfig as ye}from"get-tsconfig";import*as I from"inflection";import*as be from"node:os";const L=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return L.includes(e)}const xe=/^\d*[1-9]\d*$/;function parsePositiveInt(e){if(e===void 0)return;let t=e.trim();if(!xe.test(t))return;let n=Number.parseInt(t,10);return Number.isSafeInteger(n)?n:void 0}function resolveApplyConcurrency(){return parsePositiveInt(process.env.TAILOR_APPLY_CONCURRENCY)??16}function createApplyLimiter(){return ge(resolveApplyConcurrency())}function byName(e,t){return e.name<t.name?-1:+(e.name>t.name)}const Se=new WeakMap;function withErrorDiagnostics(e,t){return Se.set(e,t),e}function getErrorDiagnostics(e){return{...e instanceof N?{suggestion:rpcSuggestion(e.code)}:{},...Se.get(e)}}function rpcSuggestion(e){switch(e){case M.Unauthenticated:return"Check the active token and profile with `tailor auth status` (include the same --profile option). For an environment token, replace TAILOR_PLATFORM_TOKEN; otherwise use the original browser or --machine-user login method with the same profile. See `tailor login --help`.";case M.PermissionDenied:return"Check the active identity and profile with `tailor auth status` (include the same --profile option), then verify its workspace role and token permissions.";case M.Unavailable:case M.DeadlineExceeded:return`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`;default:return}}const Ce=`https://api.tailor.tech`,we=`/.well-known/oauth-authorization-server/oauth2/platform`,R=new Map;function getEnvPlatformUrl(){return process.env.TAILOR_PLATFORM_URL??process.env.PLATFORM_URL}function getEnvOAuth2ClientId(){return process.env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID??process.env.PLATFORM_OAUTH2_CLIENT_ID}function normalizeBaseUrl(e){let t=new URL(e);return t.hash=``,t.search=``,t.toString().replace(/\/$/,``)}function getEffectivePlatformConfig(e={}){let t=e.platformUrl??getEnvPlatformUrl(),n=e.oauth2ClientId??getEnvOAuth2ClientId(),r=e.consoleUrl??process.env.TAILOR_PLATFORM_CONSOLE_URL,i={...t?{platformUrl:t}:{},...n?{oauth2ClientId:n}:{},...r?{consoleUrl:r}:{}};return Object.keys(i).length>0?i:void 0}function rememberPlatformConfigForToken(e,t){let n=getEffectivePlatformConfig(t);n?R.set(e,n):R.delete(e)}function getPlatformConfigForToken(e){return R.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(Ce)}function getOAuth2ClientId(e={}){return e.oauth2ClientId??getEnvOAuth2ClientId()??`cpoc_0Iudir72fqSpqC6GQ58ri1cLAqcq5vJl`}function inferConsoleBaseUrl(e){let t=new URL(e);return t.hostname.startsWith(`api.`)?(t.hostname=t.hostname.replace(/^api\./,`console.`),normalizeBaseUrl(t.toString())):`https://console.tailor.tech`}function applyConsoleNext(e){if(c(process.env.TAILOR_CONSOLE_NEXT)!==!0)return e;let t=new URL(e);return t.hostname=t.hostname.replace(/^console\./,`console-next.`),normalizeBaseUrl(t.toString())}function getConsoleBaseUrl(e={}){if(e.consoleUrl)return normalizeBaseUrl(e.consoleUrl);if(e.platformUrl){let t=inferConsoleBaseUrl(e.platformUrl);if(t!==`https://console.tailor.tech`)return applyConsoleNext(t)}return process.env.TAILOR_PLATFORM_CONSOLE_URL?normalizeBaseUrl(process.env.TAILOR_PLATFORM_CONSOLE_URL):applyConsoleNext(inferConsoleBaseUrl(getPlatformBaseUrl(e)))}function initOAuth2Client(e){return new me({clientId:getOAuth2ClientId(e),server:getPlatformBaseUrl(e),discoveryEndpoint:we})}async function initOperatorClient(e,t){let n=t??getPlatformConfigForToken(e),[{createTracingInterceptor:r},{OperatorService:i}]=await Promise.all([import(`./interceptor-DQg3cR_9.mjs`),import(`./service_pb-DKrsO1_u.mjs`)]),a=[await userAgentInterceptor(),await bearerTokenInterceptor(e),retryInterceptor(),errorHandlingInterceptor(),r(),concurrencyLimitInterceptor()],o=getPlatformBaseUrl(n),s=createPooledStreamTransport(await createTransport(o,a),()=>createTransport(o,a),4);return he(i,s)}async function createTransport(e,t){let{createConnectTransport:n}=await import(`@connectrpc/connect-node`);return n({httpVersion:`2`,baseUrl:e,interceptors:t})}const Te=new Set([`CreateFunctionRegistry`,`UpdateFunctionRegistry`,`UploadFile`]);function createPooledStreamTransport(e,t,n){if(!Number.isInteger(n)||n<1)throw Error(`createPooledStreamTransport: maxConnections must be a positive integer, got ${n}`);let r=[e],i=[0],a=[],o=0;function acquireTransportIndex(e,s){return new Promise((c,l)=>{let u=!1,d;function cleanup(){u=!0,clearTimeout(d),e?.removeEventListener(`abort`,onAbort);let t=a.indexOf(attempt);t!==-1&&a.splice(t,1)}function onAbort(){cleanup(),l(N.from(e?.reason,M.Canceled))}function onTimeout(){cleanup(),l(new N(`the operation timed out`,M.DeadlineExceeded))}function claim(e){if(u){release(e);return}cleanup(),c(e)}function attempt(){let e=i.pop();if(e!==void 0){claim(e);return}if(r.length+o<n){o++,t().then(e=>{o--;let t=r.length;r.push(e),claim(t)},e=>{o--,cleanup(),l(e instanceof Error?e:Error(String(e))),wakeOneWaiter()});return}a.push(attempt)}if(e?.aborted){onAbort();return}if(e?.addEventListener(`abort`,onAbort,{once:!0}),s!==void 0){let e=s-performance.now();if(e<=0){onTimeout();return}d=setTimeout(onTimeout,e)}attempt()})}function wakeOneWaiter(){a.shift()?.()}function release(e){i.push(e),wakeOneWaiter()}return{unary(t,n,r,i,a,o){return e.unary(t,n,r,i,a,o)},async stream(t,n,i,a,o,s){if(!Te.has(t.name))return e.stream(t,n,i,a,o,s);let c=i!==void 0&&i>0?performance.now()+i:void 0,l=await acquireTransportIndex(n,c),u=r[l],d;try{if(n?.aborted)throw N.from(n.reason,M.Canceled);let e=c===void 0?i:Math.ceil(c-performance.now());if(c!==void 0&&e!==void 0&&e<=0)throw new N(`the operation timed out`,M.DeadlineExceeded);d=await u.stream(t,n,e,a,o,s)}catch(e){throw release(l),e}return{...d,message:releaseAfter(d.message,()=>release(l))}}}}async function*releaseAfter(e,t){try{yield*e}finally{t()}}async function userAgentInterceptor(){let e=await E();return t=>async n=>(n.header.set(`User-Agent`,e),await t(n))}async function bearerTokenInterceptor(e){return t=>async n=>(n.header.set(`Authorization`,`Bearer ${e}`),await t(n))}function retryInterceptor(){return e=>async t=>{if(t.stream)return await e(t);let n;for(let r=0;r<De;r++){r>0&&await waitRetryBackoff(r);try{return await e(t)}catch(e){if(isRetrySafeCreateAlreadyExists(e,t.method.name)){if(r>0)return s.debug(`retry: ${t.method.name} returned AlreadyExists on attempt ${r+1}; treating as success (prior attempt likely committed)`),synthesizeEmptyUnaryResponse(t);let{reportCrash:n}=await import(`./crashreport-CgymxQDu.mjs`);await n(e,`handledError`)}if(t.method.name!==`CreateWorkspace`&&isRetirable(e,t.method.idempotency)){n=e,s.debug(`retry: ${t.method.name} attempt ${r+1} failed with ${retryErrorCodeName(e)}; retrying`);continue}throw e}}throw n}}function concurrencyLimitInterceptor(){let e=createApplyLimiter();return t=>async n=>n.stream?await t(n):await e(()=>t(n))}function retryErrorCodeName(e){return e instanceof N?M[e.code]:isTransportDisconnectError(e)?e.code:`unknown`}const Ee=new Set([`CreateAIGateway`,`CreateApplication`,`CreateAuthConnection`,`CreateAuthHook`,`CreateAuthIDPConfig`,`CreateAuthMachineUser`,`CreateAuthOAuth2Client`,`CreateAuthSCIMConfig`,`CreateAuthSCIMResource`,`CreateAuthService`,`CreateExecutorExecutor`,`CreateIdPService`,`CreatePipelineResolver`,`CreatePipelineService`,`CreateSecretManagerSecret`,`CreateSecretManagerVault`,`CreateStaticWebsite`,`CreateTailorDBGQLPermission`,`CreateTailorDBService`,`CreateTailorDBType`,`CreateTenantConfig`,`CreateUserProfileConfig`,`CreateWorkflow`,`CreateWorkflowJobFunctionExecutionPolicy`]);function isRetrySafeCreateAlreadyExists(e,t){return e instanceof N&&e.code===M.AlreadyExists&&Ee.has(t)}function synthesizeEmptyUnaryResponse(e){return{stream:!1,service:e.service,method:e.method,header:new Headers,message:de(e.method.output),trailer:new Headers}}const De=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}const Oe=new Set([`ERR_STREAM_PREMATURE_CLOSE`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`]);function isTransportDisconnectError(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&Oe.has(e.code)}function isRetirable(e,t){let n=t===pe.NO_SIDE_EFFECTS||t===pe.IDEMPOTENT;if(!(e instanceof N))return isTransportDisconnectError(e)&&n;switch(e.code){case M.ResourceExhausted:case M.Unavailable:return!0;case M.Aborted:case M.Internal:return n;default:return!1}}function errorHandlingInterceptor(){return e=>async t=>{try{return await e(t)}catch(e){if(e instanceof N){let{operation:n,resourceType:r}=parseMethodName(t.method.name),i=requestIdentifiers(t.message,t.method.name),a=Object.entries(i).map(([e,t])=>`${e}: ${t}`),o=a.length===0?``:` (${a.join(`, `)})`;throw withErrorDiagnostics(new N(`Failed to ${n} ${r}${o}: ${e.rawMessage}`,e.code,e.metadata),{context:{method:t.method.name,identifiers:i}})}throw isTransportDisconnectError(e)?withErrorDiagnostics(e,{code:`TRANSPORT_DISCONNECTED`,suggestion:`Check network connectivity and platform availability. A write may already have completed; inspect the current resource state before retrying.`,context:{method:t.method.name,transportCode:e.code,identifiers:requestIdentifiers(t.message,t.method.name)}}):e}}}function parseMethodName(e){let t=e.match(/^(Create|Update|Delete|Set|List|Get)(.+)$/);if(!t)return{operation:`perform`,resourceType:`resource`};let[,n,r]=t;return{operation:n.toLowerCase(),resourceType:r}}const ke=new Set([`name`,`id`]),Ae=[`Name`,`Id`,`Namespace`],je=`name`,Me={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:ke.has(e)||Ae.some(t=>e.endsWith(t))||(Me[t]?.includes(e)??!1)}function requestIdentifiers(e,t){if(typeof e!=`object`||!e)return{};let n={};for(let[r,i]of Object.entries(e))if(typeof i==`string`&&i!==``&&isIdentityKey(r,t))n[r]=i;else if(!r.startsWith(`$`)&&typeof i==`object`&&i&&!Array.isArray(i)&&typeof i.$typeName==`string`){let e=i[je];typeof e==`string`&&e!==``&&(n[`${r}.${je}`]=e)}return n}const z=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,z);if(t.push(...r),!i)break;n=i}return t}function isNotFoundError(e){return e instanceof N&&e.code===M.NotFound}async function fetchAllTolerant(e){return await fetchAll(async(t,n)=>{try{return await e(t,n)}catch(e){if(isNotFoundError(e))return[[],``];throw e}})}async function getOrNull(e){try{return await e()}catch(e){if(isNotFoundError(e))return;throw e}}async function fetchPaged(e,t){let n=t?.limit,r=n===void 0||n===0,i=[],a=``;for(;;){let t=r?z:Math.min(n-i.length,z);if(!r&&t<=0)break;let[o,s]=await e(a,t);if(i.push(...o),!r&&i.length>=n||!s)break;a=s}return!r&&i.length>n?i.slice(0,n):i}async function fetchUserInfo(e,t){let n=new URL(`/auth/platform/userinfo`,getPlatformBaseUrl(t)).href,r=await fetch(n,{headers:{Authorization:`Bearer ${e}`,"User-Agent":await E()}});if(!r.ok)throw Error(`Failed to fetch user info: ${r.statusText}`);let i=await r.json();return A.object({sub:A.string(),email:A.string()}).parse(i)}async function resolveStaticWebsiteUrls(e,t,n,r,i={}){if(!n)return[];let{expectedLocalNames:a}=i;return(await Promise.all(n.map(async n=>{let i=n.match(/:url(\/.*)?$/);if(i&&i.index!==void 0){let o=n.substring(0,i.index),c=i[1]||``;try{let n=await e.getStaticWebsite({workspaceId:t,name:o});return n.staticwebsite?.url?[n.staticwebsite.url+c]:(s.warn(`Static website "${o}" has no URL assigned yet. Excluding from ${r}.`),[])}catch(e){return isNotFoundError(e)&&a?.has(o)?[n]:(s.warn(`Static website "${o}" not found for ${r} configuration. Excluding from ${r}.`),[])}}return[n]}))).flat()}async function fetchMachineUserToken(e,t,n){s.registerSecret(n);let r=new URL(`/oauth2/token`,e).href,i=new URLSearchParams;i.append(`grant_type`,`client_credentials`),i.append(`client_id`,t),i.append(`client_secret`,n);let a={method:`POST`,headers:{"User-Agent":await E(),"Content-Type":`application/x-www-form-urlencoded`},body:i},o=await withConnectTimeoutRetry(`machine user token request`,()=>fetch(r,a));if(!o.ok){let e=await o.text().catch(()=>``);throw Error(`Failed to fetch machine user token: ${o.status} ${o.statusText} ${e.slice(0,500)}`)}let c=await o.json(),l=A.object({token_type:A.string(),access_token:A.string(),expires_in:A.number()}).parse(c);return s.registerSecret(l.access_token),l}function isUndiciConnectTimeout(e){if(!(e instanceof TypeError))return!1;let t=e.cause;return t instanceof Error&&`code`in t&&t.code===`UND_ERR_CONNECT_TIMEOUT`}async function withConnectTimeoutRetry(e,t){for(let n=1;;n++)try{return await t()}catch(t){if(!isUndiciConnectTimeout(t)||n>=3)throw t;s.debug(`retry: ${e} attempt ${n} failed with UND_ERR_CONNECT_TIMEOUT; retrying`),await waitRetryBackoff(n)}}async function fetchPlatformMachineUserToken(e,t,n){s.registerSecret(t);let r=getPlatformBaseUrl(n),i=await withConnectTimeoutRetry(`platform machine user token request`,()=>new me({clientId:e,clientSecret:t,server:r,discoveryEndpoint:we}).clientCredentials());return s.registerSecret(i.accessToken),i.refreshToken&&s.registerSecret(i.refreshToken),i}async function closeConnectionPool(){let e=globalThis,t=e[Symbol.for(`undici.globalDispatcher.2`)]??e[Symbol.for(`undici.globalDispatcher.1`)];typeof t?.close==`function`&&await t.close()}function getPluginImportBaseDirs(e){return e?[k.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=k.resolve(n,e);if(j.existsSync(t))return t}return null}function generatePluginExecutorFiles(e,t,n,r,i){if(e.length===0)return[];let a=[],c=getPluginImportBaseDirs(i);for(let i of e){let e=generateSingleExecutorFile(i,t,n,r,c);a.push(e);let l=k.relative(process.cwd(),e);s.log(` Plugin Executor File: ${o.success(l)} from plugin ${o.info(i.pluginId)}`)}return a}function generateSingleExecutorFile(e,t,n,r,i=[]){let a=sanitizePluginId$1(e.pluginId),o=k.join(t,a,`executors`);j.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=k.join(o,`${s}.ts`),l;return l=ee(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),j.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=k.join(n,c,`executors`),u=resolveExecutorImportPath(o,e.pluginImportPath,l,a),d=collectTableImports(s,n,e.pluginId,r,i),f=[];for(let[,e]of d)f.push(`import { ${e.variableName} } from "${e.importPath}";`);let p=generateContextCode(s,d);return T`
|
|
2
2
|
/**
|
|
3
3
|
* Auto-generated executor by plugin: ${e.pluginId}
|
|
4
4
|
* DO NOT EDIT - This file is generated by @tailor-platform/sdk
|
|
@@ -49,7 +49,7 @@ import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from
|
|
|
49
49
|
}`;case`workflow`:return`{
|
|
50
50
|
kind: "workflow",
|
|
51
51
|
workflowName: ${JSON.stringify(e.workflowName)},
|
|
52
|
-
}`;default:throw ne(`Unknown operation kind: ${e.kind}`)}}function escapeTemplateLiteral(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}const Ne=ce(import.meta.url);function resolveExecutorImportPath(e,t,n,r){let i=extractDynamicImportSpecifier(e);if(!i.startsWith(`.`))return i;let a=resolvePluginBaseDir(t,r);if(!a)throw D({code:`PLUGIN_IMPORT_UNRESOLVED`,message:`Unable to resolve plugin import base for "${t}".`,details:`Tried base dirs: ${r.join(`, `)||`(none)`}.`,suggestion:`Use an absolute import specifier in resolve(), or ensure the plugin path is resolvable.`});let o=k.resolve(a,i),s=k.relative(n,o).replace(/\\/g,`/`);return s=stripSourceExtension(s),s.startsWith(`.`)||(s=`./${s}`),s}function extractDynamicImportSpecifier(e){let t=e.toString().match(/import\s*\(\s*["']([^"']+)["']\s*\)/);if(!t)throw D({code:`PLUGIN_RESOLVE_INVALID`,message:'resolve() must return a dynamic import, e.g. `async () => await import("./executors/on-create")`.'});return a(t[1],`dynamic import specifier capture group missing`)}function resolvePluginBaseDir(e,t){if(e.startsWith(`.`)){let n=resolveRelativePluginImportPath(e,t)??k.resolve(t[0]??process.cwd(),e);return j.existsSync(n)?j.statSync(n).isDirectory()?n:k.dirname(n):k.extname(n)?k.dirname(n):n}for(let n of t)try{let t=Ne.resolve(e,{paths:[n]});return k.dirname(t)}catch{continue}return null}function stripSourceExtension(e){return e.replace(/\.(ts|tsx)$/,``)}function sanitizePluginId$1(e){return e.replace(/^@/,``).replace(/\//g,`-`)}function sanitizeExecutorFileName(e){let t=k.basename(e).replace(/\.[^/.]+$/,``).replace(/[^a-zA-Z0-9_-]/g,`-`);if(!t)throw D({code:`PLUGIN_EXECUTOR_NAME_INVALID`,message:`Invalid executor name: "${e}"`});return t}function toCamelCase$1(e){let t=e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``);return t.charAt(0).toLowerCase()+t.slice(1)}function toKebabCase$1(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function isFieldDefinition(e){return typeof e==`object`&&!!e}function generatePluginTableFiles(e,t){let n=new Map,r=[];if(e.length===0)return{tableFilePaths:n,generatedFiles:r};let i=new Map;for(let a of e){let e=i.get(a.table.name);if(e)throw D({code:`PLUGIN_TABLE_NAME_DUPLICATE`,message:`Duplicate plugin-generated table name "${a.table.name}" detected. First: plugin "${e.pluginId}" (kind: "${e.kind}", source: "${e.sourceTableName}"), Second: plugin "${a.pluginId}" (kind: "${a.kind}", source: "${a.sourceTableName}"). Plugin-generated table names must be unique.`});i.set(a.table.name,a);let
|
|
52
|
+
}`;default:throw ne(`Unknown operation kind: ${e.kind}`)}}function escapeTemplateLiteral(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}const Ne=ce(import.meta.url);function resolveExecutorImportPath(e,t,n,r){let i=extractDynamicImportSpecifier(e);if(!i.startsWith(`.`))return i;let a=resolvePluginBaseDir(t,r);if(!a)throw D({code:`PLUGIN_IMPORT_UNRESOLVED`,message:`Unable to resolve plugin import base for "${t}".`,details:`Tried base dirs: ${r.join(`, `)||`(none)`}.`,suggestion:`Use an absolute import specifier in resolve(), or ensure the plugin path is resolvable.`});let o=k.resolve(a,i),s=k.relative(n,o).replace(/\\/g,`/`);return s=stripSourceExtension(s),s.startsWith(`.`)||(s=`./${s}`),s}function extractDynamicImportSpecifier(e){let t=e.toString().match(/import\s*\(\s*["']([^"']+)["']\s*\)/);if(!t)throw D({code:`PLUGIN_RESOLVE_INVALID`,message:'resolve() must return a dynamic import, e.g. `async () => await import("./executors/on-create")`.'});return a(t[1],`dynamic import specifier capture group missing`)}function resolvePluginBaseDir(e,t){if(e.startsWith(`.`)){let n=resolveRelativePluginImportPath(e,t)??k.resolve(t[0]??process.cwd(),e);return j.existsSync(n)?j.statSync(n).isDirectory()?n:k.dirname(n):k.extname(n)?k.dirname(n):n}for(let n of t)try{let t=Ne.resolve(e,{paths:[n]});return k.dirname(t)}catch{continue}return null}function stripSourceExtension(e){return e.replace(/\.(ts|tsx)$/,``)}function sanitizePluginId$1(e){return e.replace(/^@/,``).replace(/\//g,`-`)}function sanitizeExecutorFileName(e){let t=k.basename(e).replace(/\.[^/.]+$/,``).replace(/[^a-zA-Z0-9_-]/g,`-`);if(!t)throw D({code:`PLUGIN_EXECUTOR_NAME_INVALID`,message:`Invalid executor name: "${e}"`});return t}function toCamelCase$1(e){let t=e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``);return t.charAt(0).toLowerCase()+t.slice(1)}function toKebabCase$1(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function isFieldDefinition(e){return typeof e==`object`&&!!e}function generatePluginTableFiles(e,t){let n=new Map,r=[];if(e.length===0)return{tableFilePaths:n,generatedFiles:r};let i=new Map;for(let a of e){let e=i.get(a.table.name);if(e)throw D({code:`PLUGIN_TABLE_NAME_DUPLICATE`,message:`Duplicate plugin-generated table name "${a.table.name}" detected. First: plugin "${e.pluginId}" (kind: "${e.kind}", source: "${e.sourceTableName}"), Second: plugin "${a.pluginId}" (kind: "${a.kind}", source: "${a.sourceTableName}"). Plugin-generated table names must be unique.`});i.set(a.table.name,a);let c=sanitizePluginId(a.pluginId),l=k.join(t,c,`types`);j.mkdirSync(l,{recursive:!0});let u=`${toKebabCase(a.table.name)}.ts`,d=k.join(l,u),f=generateTableFileContent(a);j.writeFileSync(d,f),r.push(d);let p=k.relative(t,d);n.set(a.table.name,p);let m=k.relative(process.cwd(),d);s.log(` Plugin Table File: ${o.success(m)} (${o.dim(a.kind)}) from plugin ${o.info(a.pluginId)}`)}return{tableFilePaths:n,generatedFiles:r}}function generateTableFileContent(e){let{table:t,pluginId:n,sourceTableName:r,kind:i}=e,a=toCamelCase(t.name),o=generateFieldsCode(t);return T`
|
|
53
53
|
/**
|
|
54
54
|
* Auto-generated table by plugin: ${n}
|
|
55
55
|
* Source: ${r}
|
|
@@ -63,17 +63,17 @@ import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from
|
|
|
63
63
|
|
|
64
64
|
export type ${t.name} = typeof ${a};
|
|
65
65
|
`}function generateFieldsCode(e){let t=[];for(let[n,r]of Object.entries(e.fields)){if(!isFieldDefinition(r))continue;let e=generateSingleFieldCode(r);e&&t.push(` ${n}: ${e}`)}return`{\n${t.join(`,
|
|
66
|
-
`)},\n}`}const Pe={string:`string`,integer:`int`,float:`float`,boolean:`bool`,uuid:`uuid`,datetime:`datetime`,date:`date`,time:`time`,enum:`enum`,nested:`nested`};function generateSingleFieldCode(e){let t=e.type;if(!t)return null;let n=Pe[t]??t,r=e._metadata??e.metadata??{},i=[];r.required===!1&&i.push(`optional: true`);let a=i.length>0?`{ ${i.join(`, `)} }`:``;if(t===`enum`){let e=r.allowedValues,t=[];Array.isArray(e)&&(t=e.map(e=>e.value));let n=`db.enum(${JSON.stringify(t)}${a?`, ${a}`:``})`;return r.index&&(n+=`.index()`),r.unique&&(n+=`.unique()`),r.description&&(n+=`.description(${JSON.stringify(r.description)})`),n}let o=`db.${n}(${a})`;return r.index&&(o+=`.index()`),r.unique&&(o+=`.unique()`),r.description&&(o+=`.description(${JSON.stringify(r.description)})`),o}function sanitizePluginId(e){return e.replace(/^@/,``).replace(/\//g,`-`)}function toKebabCase(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function toCamelCase(e){let t=e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``);return t.charAt(0).toLowerCase()+t.slice(1)}function createDepCollectorPlugin(){let e=new Set,t={name:`cache-dep-collector`,load:{filter:{id:{include:[/\.[^/]+$/]}},handler(t){return!t.includes(`node_modules`)&&!t.endsWith(`.entry.js`)&&e.add(t),null}}};function getResult(){return Array.from(e).toSorted()}return{plugin:t,getResult}}function hashContent(e){return _e.createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function hashFile(e){let t=j.readFileSync(e);return _e.createHash(`sha256`).update(t).digest(`hex`)}function hashFiles(e){return hashContent(e.toSorted().map(e=>hashFileOrMissing(e)).join(``))}function hashFileOrMissing(e){try{return hashFile(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return`<missing>`;throw e}}function buildCacheKey(e,t,n){return n?`${e}:${n}:${t}`:`${e}:${t}`}function combineHash(e,t){return t?hashContent(e+t):e}function computeBundlerContextHash(e){let{sourceFile:t,extraContext:n,tsconfig:r,inlineSourcemap:i,bundleLogLevel:a,prefix:o}=e;return hashContent((o??``)+k.resolve(t)+n+(r?hashFile(r):``)+String(i??!1)+(a??``))}async function withCache(e){let{cache:t,kind:n,namespace:r,name:i,sourceFile:a,contextHash:
|
|
66
|
+
`)},\n}`}const Pe={string:`string`,integer:`int`,float:`float`,boolean:`bool`,uuid:`uuid`,datetime:`datetime`,date:`date`,time:`time`,enum:`enum`,nested:`nested`};function generateSingleFieldCode(e){let t=e.type;if(!t)return null;let n=Pe[t]??t,r=e._metadata??e.metadata??{},i=[];r.required===!1&&i.push(`optional: true`);let a=i.length>0?`{ ${i.join(`, `)} }`:``;if(t===`enum`){let e=r.allowedValues,t=[];Array.isArray(e)&&(t=e.map(e=>e.value));let n=`db.enum(${JSON.stringify(t)}${a?`, ${a}`:``})`;return r.index&&(n+=`.index()`),r.unique&&(n+=`.unique()`),r.description&&(n+=`.description(${JSON.stringify(r.description)})`),n}let o=`db.${n}(${a})`;return r.index&&(o+=`.index()`),r.unique&&(o+=`.unique()`),r.description&&(o+=`.description(${JSON.stringify(r.description)})`),o}function sanitizePluginId(e){return e.replace(/^@/,``).replace(/\//g,`-`)}function toKebabCase(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function toCamelCase(e){let t=e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``);return t.charAt(0).toLowerCase()+t.slice(1)}function createDepCollectorPlugin(){let e=new Set,t={name:`cache-dep-collector`,load:{filter:{id:{include:[/\.[^/]+$/]}},handler(t){return!t.includes(`node_modules`)&&!t.endsWith(`.entry.js`)&&e.add(t),null}}};function getResult(){return Array.from(e).toSorted()}return{plugin:t,getResult}}function hashContent(e){return _e.createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function hashFile(e){let t=j.readFileSync(e);return _e.createHash(`sha256`).update(t).digest(`hex`)}function hashFiles(e){return hashContent(e.toSorted().map(e=>hashFileOrMissing(e)).join(``))}function hashFileOrMissing(e){try{return hashFile(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return`<missing>`;throw e}}function buildCacheKey(e,t,n){return n?`${e}:${n}:${t}`:`${e}:${t}`}function combineHash(e,t){return t?hashContent(e+t):e}function computeBundlerContextHash(e){let{sourceFile:t,extraContext:n,tsconfig:r,inlineSourcemap:i,bundleLogLevel:a,prefix:o}=e;return hashContent((o??``)+k.resolve(t)+n+(r?hashFile(r):``)+String(i??!1)+(a??``))}async function withCache(e){let{cache:t,kind:n,namespace:r,name:i,sourceFile:a,contextHash:c,build:l}=e;if(!t)return await l([],()=>{});let u=t.tryRestore({kind:n,namespace:r,name:i,contextHash:c});if(u!==void 0)return s.debug(` ${o.dim(`cached`)}: ${i}`),u;let d=new Set,{plugin:f,getResult:p}=createDepCollectorPlugin(),m=await l([f],e=>d.add(e));return t.save({kind:n,namespace:r,name:i,sourceFile:a,content:m,dependencyPaths:[...p(),...d],contextHash:c}),m}function createBundleCache(e){function tryRestore(t){let n=buildCacheKey(t.kind,t.name,t.namespace),r=e.getEntry(n);if(!r)return;let i;try{i=combineHash(hashFiles(r.dependencyPaths),t.contextHash)}catch{return}if(i!==r.inputHash)return;let a=e.restoreBundleContent(n),o=r.outputFiles.find(e=>e.outputPath===n);if(a!==void 0&&o&&hashContent(a)===o.contentHash)return a}function save(t){let{kind:n,namespace:r,name:i,sourceFile:a,content:o,dependencyPaths:s,contextHash:c}=t,l=buildCacheKey(n,i,r),u=s.includes(a)?s:[a,...s],d;try{d=combineHash(hashFiles(u),c)}catch{return}let f=hashContent(o);e.storeBundleContent(l,o),e.setEntry(l,{kind:`bundle`,inputHash:d,dependencyPaths:u,outputFiles:[{outputPath:l,contentHash:f}],createdAt:new Date().toISOString()})}return{tryRestore,save}}function getModuleExportName(e){if(!e||typeof e!=`object`)return;let t=e;return t.name?t.name:typeof t.value==`string`?t.value:void 0}function isTailorSdkSource(e){return/^@tailor-platform\/sdk(\/|$)/.test(e)}function getImportSource(e){if(!e)return null;if(e.type===`ImportExpression`){let t=e.source;if(t.type===`Literal`&&typeof t.value==`string`)return t.value}if(e.type===`CallExpression`){let t=e;if(t.callee.type===`Identifier`&&t.callee.name===`require`){let e=t.arguments[0];if(e&&`type`in e&&e.type===`Literal`&&`value`in e&&typeof e.value==`string`)return e.value}}return null}function argumentSourceText(e,t){if(e&&typeof e==`object`&&`start`in e&&`end`in e)return t.slice(e.start,e.end)}function getStartCallInfo(e,t){if(!e||typeof e!=`object`||e.type!==`CallExpression`)return null;let n=e,r=n.callee;if(r.type!==`MemberExpression`)return null;let i=r;return i.computed||i.property.name!==`start`||i.object.type!==`Identifier`?null:{identifierName:i.object.name,callRange:{start:n.start,end:n.end},argsText:argumentSourceText(n.arguments[0],t)??``,optionsText:argumentSourceText(n.arguments[1],t)}}function unwrapAwait(e){return e?.type===`AwaitExpression`?e.argument:e}function isStringLiteral(e){return e?.type===`Literal`&&typeof e.value==`string`}function isFunctionExpression(e){return e?.type===`ArrowFunctionExpression`||e?.type===`FunctionExpression`}function findProperty(e,t){for(let n of e)if(n.type===`Property`){let e=n;if((e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`?e.key.value:null)===t)return{key:e.key,value:e.value,start:e.start,end:e.end}}return null}function applyReplacements(e,t){let n=t.toSorted((e,t)=>t.start-e.start);for(let e=0;e+1<n.length;e++){let t=a(n[e],`replacement missing at index ${e}`),r=a(n[e+1],`replacement missing at index ${e+1}`);if(r.end>t.start)throw Error(`applyReplacements: overlapping replacement ranges [${r.start}, ${r.end}) and [${t.start}, ${t.end})`)}let r=e;for(let e of n)r=r.slice(0,e.start)+e.text+r.slice(e.end);return r}function findStatementEnd(e,t){let n=t;for(;n<e.length&&(e[n]===`;`||e[n]===` `||e[n]===` `);)n++;return n<e.length&&e[n]===`
|
|
67
67
|
`&&n++,n}function collectSdkBindings(e,t){let n=new Set;function walk(e){if(!e||typeof e!=`object`)return;let r=e.type;if(r===`ImportDeclaration`){let r=e,i=r.source.value;if(typeof i==`string`&&isTailorSdkSource(i)){for(let e of r.specifiers)if(e.type===`ImportSpecifier`){let r=e;(r.imported.type===`Identifier`?r.imported.name:r.imported.value)===t&&n.add(r.local.name)}else if(e.type===`ImportDefaultSpecifier`||e.type===`ImportNamespaceSpecifier`){let t=e;n.add(`__namespace__:${t.local.name}`)}}}if(r===`VariableDeclaration`){let r=e;for(let e of r.declarations){let r=getImportSource(unwrapAwait(e.init));if(r&&isTailorSdkSource(r)){let r=e.id;if(r.type===`Identifier`)n.add(`__namespace__:${r.name}`);else if(r.type===`ObjectPattern`){let e=r;for(let r of e.properties)if(r.type===`Property`){let e=r,i=e.key.type===`Identifier`?e.key.name:e.key.value;if(i===t){let t=e.value.type===`Identifier`?e.value.name:i;n.add(t)}}}}}}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}return walk(e),n}function isSdkFunctionCall(e,t,n){if(e.type!==`CallExpression`)return!1;let r=e.callee;if(r.type===`Identifier`){let e=r;return t.has(e.name)}if(r.type===`MemberExpression`){let e=r;if(!e.computed){let r=e.object,i=e.property;if(r.type===`Identifier`&&t.has(`__namespace__:${r.name}`)&&i.name===n)return!0}}return!1}function findAllJobs(e,t){let n=[],r=collectSdkBindings(e,`createWorkflowJob`);function walk(e,t=[]){if(!e||typeof e!=`object`)return;if(isSdkFunctionCall(e,r,`createWorkflowJob`)){let r=e.arguments,i=r[0];if(r.length>=1&&i?.type===`ObjectExpression`){let e=a(i,`createWorkflowJob first argument missing`),r=findProperty(e.properties,`name`),o=findProperty(e.properties,`body`);if(r&&isStringLiteral(r.value)&&o&&isFunctionExpression(o.value)){let e,i;for(let n=t.length-1;n>=0;n--){let r=a(t[n],`parent at index ${n} missing`);if(r.type===`VariableDeclarator`){let e=r;e.id?.type===`Identifier`&&(i=e.id.name)}(r.type===`ExportNamedDeclaration`||r.type===`VariableDeclaration`)&&(e={start:r.start,end:r.end})}n.push({name:r.value.value,exportName:i,nameRange:{start:r.start,end:r.end},bodyValueRange:{start:o.value.start,end:o.value.end},statementRange:e})}}}let i=[...t,e];for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e,i)):n&&typeof n==`object`&&walk(n,i)}}return walk(e),n}function findAllWorkflows(e,t){let n=[],r=collectSdkBindings(e,`createWorkflow`);function walk(e,t=[]){if(!e||typeof e!=`object`)return;if(isSdkFunctionCall(e,r,`createWorkflow`)){let r=e.arguments,i=r[0];if(r.length>=1&&i?.type===`ObjectExpression`){let e=findProperty(a(i,`createWorkflow first argument missing`).properties,`name`);if(e&&isStringLiteral(e.value)){let r,i=!1;for(let e=t.length-1;e>=0;e--){let n=a(t[e],`parent at index ${e} missing`);if(n.type===`VariableDeclarator`){let e=n;if(e.id?.type===`Identifier`){r=e.id.name;break}}n.type===`ExportDefaultDeclaration`&&(i=!0)}n.push({name:e.value.value,exportName:r,isDefaultExport:i})}}}let i=[...t,e];for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e,i)):n&&typeof n==`object`&&walk(n,i)}}return walk(e),n}function normalizeFilePath(e){return k.resolve(e.replace(/[?#].*$/,``)).replace(/\.(ts|mts|cts|js|mjs|cjs)$/,``)}function createModuleBindings(e,t,n){let r=new Map,i=new Map;for(let e of findAllWorkflows(t,n)){let t={kind:`workflow`,name:e.name};e.exportName&&r.set(e.exportName,t),e.isDefaultExport&&i.set(`default`,t)}for(let e of findAllJobs(t,n))e.exportName&&r.set(e.exportName,{kind:`job`,name:e.name});for(let e of t.body){if(e.type===`ExportDefaultDeclaration`){let t=e.declaration;if(t?.type===`Identifier`){let e=r.get(t.name);e&&i.set(`default`,e)}continue}if(e.type!==`ExportNamedDeclaration`)continue;let t=e.declaration;if(t?.type===`VariableDeclaration`)for(let e of t.declarations){let t=e.id;if(t?.type!==`Identifier`)continue;let n=t.name,a=r.get(n);a&&i.set(n,a)}if(!e.source)for(let t of e.specifiers??[]){let e=getModuleExportName(t.local),n=getModuleExportName(t.exported);if(!e||!n)continue;let a=r.get(e);a&&i.set(n,a)}}return{sourceFile:e,localBindings:r,exports:i}}async function buildStartContext(e,t,n=process.cwd()){let r=new Map;if(!e)return{modules:r,authNamespace:t};for(let t of m(e,n))try{let e=await j.promises.readFile(t,`utf-8`),{program:n,errors:i}=F(t,e);if(i.length>0){s.warn(`Failed to parse workflow file ${t}: ${i.map(e=>e.message).join(`; `)}`,{mode:`stream`});continue}r.set(normalizeFilePath(t),createModuleBindings(t,n,e))}catch(e){let n=e instanceof Error?e.message:String(e);s.warn(`Failed to process workflow file ${t}: ${n}`,{mode:`stream`})}return{modules:r,authNamespace:t}}function sortedTargets(e){return[...e].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.kind,t.name])}function serializeStartContext(e){if(!e)return``;let t=[...e.modules].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,sortedTargets(t.localBindings),sortedTargets(t.exports)]);return JSON.stringify(t)+(e.authNamespace??``)}const Fe=/\.start(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*\(/;function hasStartCall(e){return Fe.test(e)}const Ie=`__tailor_normalizeStartOptions`;function buildNormalizerHelperSource(e){return`const ${Ie} = (o) => { if (!o) return o; const { invoker, ...rest } = o; return typeof invoker === "string" ? { ...rest, authInvoker: { namespace: ${JSON.stringify(e)}, machineUserName: invoker } } : typeof invoker === "object" ? { ...rest, authInvoker: invoker } : o; };\n`}function collectBindingNames(e,t){if(e&&typeof e==`object`)switch(e.type){case`Identifier`:t.add(e.name);return;case`ObjectPattern`:for(let n of e.properties)collectBindingNames(n.type===`RestElement`?n.argument:n.value,t);return;case`ArrayPattern`:for(let n of e.elements)collectBindingNames(n,t);return;case`AssignmentPattern`:collectBindingNames(e.left,t);return;case`RestElement`:collectBindingNames(e.argument,t);return;case`TSParameterProperty`:collectBindingNames(e.parameter,t)}}function declarationNode(e){return e.type===`ExportNamedDeclaration`||e.type===`ExportDefaultDeclaration`?e.declaration:e}function collectBlockBindings(e,t){for(let n of e){let e=declarationNode(n);if(e){if(e.type===`VariableDeclaration`){if(e.kind===`var`)continue;for(let n of e.declarations)collectBindingNames(n.id,t)}else(e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&collectBindingNames(e.id,t)}}}function collectFunctionVarBindings(e,t){function walk(n){if(n&&typeof n==`object`&&(n===e||n.type!==`FunctionDeclaration`&&n.type!==`FunctionExpression`&&n.type!==`ArrowFunctionExpression`&&n.type!==`StaticBlock`)){if(n.type===`VariableDeclaration`&&n.kind===`var`)for(let e of n.declarations)collectBindingNames(e.id,t);for(let e of Object.keys(n)){if(e===`parent`)continue;let t=n[e];if(Array.isArray(t))for(let e of t)walk(e);else t&&typeof t==`object`&&walk(t)}}}walk(e)}function collectScopeBindings(e){let t=new Set;if(e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`){collectBindingNames(e.id,t);for(let n of e.params)collectBindingNames(n,t);return collectFunctionVarBindings(e,t),t}if(e.type===`BlockStatement`)return collectBlockBindings(e.body,t),t;if(e.type===`CatchClause`)return collectBindingNames(e.param,t),t;if(e.type===`ForStatement`||e.type===`ForInStatement`||e.type===`ForOfStatement`){let n=e.init??e.left;if(n?.type===`VariableDeclaration`&&n.kind!==`var`)for(let e of n.declarations)collectBindingNames(e.id,t);return t}}function addShadowedBindings(e,t,n){if(!t)return e;let r=[...t].filter(e=>n.has(e));return r.length===0?e:new Set([...e,...r])}function walkBindingAware(e,t,n){function walk(e,r,i,a){if(!e||typeof e!=`object`||e.type===`ImportDeclaration`)return;let o=e.type===`Program`?r:addShadowedBindings(r,collectScopeBindings(e),t);n(e,o,i,a);for(let t of Object.keys(e)){if(t===`parent`)continue;let n=e[t];if(Array.isArray(n))for(let r of n)walk(r,o,e,t);else n&&typeof n==`object`&&walk(n,o,e,t)}}walk(e,new Set)}function resolveRelativeImport(e,t,n){if(!n.startsWith(`.`))return;let r=k.dirname(t.replace(/[?#].*$/,``)),i=normalizeFilePath(k.resolve(r,n));return e.modules.get(i)??e.modules.get(k.join(i,`index`))}function collectLocalTargets(e,t,n){let r=new Map,i=t.modules.get(normalizeFilePath(n));if(i)for(let[e,t]of i.localBindings)r.set(e,t);for(let i of e.body){if(i.type!==`ImportDeclaration`||i.importKind===`type`)continue;let e=i.source.value;if(typeof e!=`string`)continue;let a=resolveRelativeImport(t,n,e);if(a)for(let e of i.specifiers){if(e.type===`ImportNamespaceSpecifier`||e.type===`ImportSpecifier`&&e.importKind===`type`)continue;let t=e.type===`ImportDefaultSpecifier`?`default`:getModuleExportName(e.imported);if(!t)continue;let n=a.exports.get(t);n&&r.set(e.local.name,n)}}return r}function detectStartCallsWithTargets(e,t,n){let r=[];return walkBindingAware(e,new Set(n.keys()),(e,i)=>{let a=getStartCallInfo(e,t);if(!a||i.has(a.identifierName))return;let o=n.get(a.identifierName);o&&r.push({...a,kind:o.kind,targetName:o.name})}),r}function detectResolvedStartCalls(e,t,n,r){return detectStartCallsWithTargets(e,t,collectLocalTargets(e,n,r))}function transformStartCalls(e,t,n){let{program:r}=F(`input.ts`,e),i=collectLocalTargets(r,t,n),{authNamespace:a}=t,o=detectStartCallsWithTargets(r,e,i),c=[],l=o.filter(e=>{let t=o.find(t=>t!==e&&t.callRange.start<=e.callRange.start&&e.callRange.end<=t.callRange.end);return!t||(c.push({call:e,parent:t}),!1)});for(let{call:e,parent:t}of c)s.warn(`Nested start call "${e.identifierName}.start(...)" inside "${t.identifierName}.start(...)" cannot be converted. Move it to a separate statement and pass the result instead.`);let u=[],d=!1;for(let e of l){let t;if(e.kind===`workflow`){let n=``;e.optionsText!==void 0&&(a?(n=`, ${Ie}(${e.optionsText})`,d=!0):n=`, ${e.optionsText}`),t=`tailor.workflow.startWorkflow(${JSON.stringify(e.targetName)}, ${e.argsText||`undefined`}${n})`}else{let n=e.optionsText===void 0?``:`, ${e.optionsText}`;t=`tailor.workflow.execJobFunction(${JSON.stringify(e.targetName)}, ${e.argsText||`undefined`}${n})`}u.push({start:e.callRange.start,end:e.callRange.end,text:t})}let f=applyReplacements(e,u);return d&&a?buildNormalizerHelperSource(a)+f:f}function createStartTransformPlugin(e){if(e&&e.modules.size!==0)return{name:`start-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){return hasStartCall(t)?{code:transformStartCalls(t,e,n)}:null}}}}function isForbiddenGlobal(e){return re.has(e)}function createBundleLog(e={}){let t=new Map;return{options:{logLevel:`warn`,onLog:(e,n)=>{n.code===`UNRESOLVED_IMPORT`&&t.set(JSON.stringify([n.exporter,n.id]),n)}},assertAllResolved(){if(t.size>0)throw unresolvedImportError([...t.values()],e.tsconfig)}}}function unresolvedImportError(e,t){let n=e.map(formatUnresolvedImport),r=n.length===1?`Could not resolve ${n[0]}.`:`Could not resolve ${n.length} imports.`,i=n.length===1?void 0:n.map(e=>`- ${e}`).join(`
|
|
68
68
|
`),a=unresolvedImportSuggestion(e,t);return D({code:`UNRESOLVED_IMPORT`,message:r,details:i,suggestion:a})}function unresolvedImportSuggestion(e,t){let n=e.map(e=>e.exporter).filter(e=>e!==void 0).filter(O).map(ae),r=e.some(e=>e.exporter===void 0||!O(e.exporter)),i=t?`Check that each import path is correct, and that a \`compilerOptions.paths\` entry covering it is declared in the importing file's own tsconfig.json or an ancestor. The build used "${t}".`:"No tsconfig.json was found, so `compilerOptions.paths` aliases were not applied. Add a tsconfig.json declaring the aliases these files import.";return[...new Set([...n,...r?[i]:[]])].join(`
|
|
69
|
-
`)}function formatUnresolvedImport(e){let t=e.exporter??`an imported module`,n=e.id?.startsWith(`\0`)?`a generated entry (${e.id.slice(1)})`:e.id&&`"${e.id}"`;return`"${t}"${n?` imported from ${n}`:``}`}const B=[`console.info`,`console.table`,`console.dir`,`console.dirxml`,`console.count`,`console.countReset`,`console.time`,`console.timeLog`,`console.timeEnd`,`console.group`,`console.groupCollapsed`,`console.groupEnd`,`console.clear`],V=[`console.debug`,`console.log`,`console.trace`],Le=[`console.warn`],Re=[`console.error`],H=[`globalThis.tailor.logger.debug`],U=[`globalThis.tailor.logger.info`],ze=[`globalThis.tailor.logger.warn`],Be=[`globalThis.tailor.logger.error`],Ve={DEBUG:[],INFO:[...V,...H],WARN:[...V,...B,...H,...U],ERROR:[...V,...B,...Le,...H,...U,...ze],SILENT:[...V,...B,...Le,...Re,...H,...U,...ze,...Be]};function normalizeBundleLogLevel(e){let t=e.trim().toUpperCase();return isLogLevel(t)?t:void 0}function resolveBundleLogLevel(e){if(e===void 0)return`DEBUG`;let t=normalizeBundleLogLevel(e);if(t)return t;throw Error(`Invalid logLevel "${e}". Expected one of: ${L.join(`, `)}`)}function manualPureFunctionsForLogLevel(e){return Ve[e]}function createLogLevelTreeshakeOptions(e){let t=manualPureFunctionsForLogLevel(e);return t.length>0?{manualPureFunctions:t}:{}}const He={moduleSideEffects:!1,annotations:!0,unknownGlobalSideEffects:!1};function mergeFunctionTreeshakeOptions(e){let t={},n=new Set;for(let r of e){Object.assign(t,r);for(let e of r.manualPureFunctions??[])n.add(e)}return n.size>0?t.manualPureFunctions=[...n]:delete t.manualPureFunctions,t}function composeFunctionTreeshakeOptions(e=[]){return mergeFunctionTreeshakeOptions([He,...e])}const Ue=/(?<![\w$.])process\.env\.__TAILOR_PLATFORM_BUNDLE\b/g,W={name:`tailor-platform-bundle-define`,transform(e){return e.includes(`process.env.__TAILOR_PLATFORM_BUNDLE`)?{code:e.replace(Ue,`true`)}:null},resolveId(e){return e===`node:async_hooks`?{id:e,external:!0}:null}},We=new Set;async function resolveTSConfigWithFallback(e){let t=await tryResolve(e);if(t||e===process.cwd())return t;let n=await tryResolve(process.cwd());return n&&!We.has(e)&&(We.add(e),s.warn(`No tsconfig found from "${e}"; falling back to the tsconfig resolved from process.cwd(). Move (or extend) a tsconfig into this directory before v2, when this fallback will be removed.`)),n}async function tryResolve(e){try{return await ue(e)}catch{return}}function createTsconfigLookupCache(){return{tsconfigCache:new Map,contextCache:new Map}}function createTsconfigPathsPlugin(e={}){let{tsconfigCache:t,contextCache:n}=e.cache??createTsconfigLookupCache();return{name:`tailor-tsconfig-paths`,resolveId:{order:`post`,async handler(r,i){if(!i||r.startsWith(`.`)||r.startsWith(`/`)||r.startsWith(`\0`))return null;let a=i.startsWith(`\0`)?e.virtualEntrySourceFile:i;if(!a)return null;let o=getResolutionContext(k.dirname(a),t,n,e.onTsconfigRead);if(!o)return null;let s=o.matcher(r);if(s.length===0||await this.resolve(r,i,{skipSelf:!0}))return null;for(let e of s){let t=await this.resolve(e,i,{skipSelf:!0});if(t)return t}return null}}}}function getResolutionContext(e,t,n,r){let i=n.get(e);if(i!==void 0)return reportTsconfigDependencies(t,r),i;let a=ye(e,`tsconfig.json`,t);reportTsconfigDependencies(t,r);let o=a?.config.compilerOptions?.paths,s=o&&Object.keys(o).length>0?ve(a):null,c=s?{matcher:s}:null;return n.set(e,c),c}function reportTsconfigDependencies(e,t){if(!t)return;let n=new Set,r=new Set;for(let[t,i]of e){let e=dependencyPathFromCacheKey(t);e&&(t.startsWith(`statSync:`)&&isDirectoryStat(i)?n.add(e):r.add(e))}for(let e of r)n.has(e)||t(e)}function dependencyPathFromCacheKey(e){if(e.startsWith(`readFileSync:`)&&e.endsWith(`:utf8`))return e.slice(13,-5);for(let t of[`existsSync:`,`statSync:`])if(e.startsWith(t))return e.slice(t.length)}function isDirectoryStat(e){return typeof e==`object`&&!!e&&`isDirectory`in e&&typeof e.isDirectory==`function`&&e.isDirectory()}function createVirtualEntry(e,t,n=`js`,r){let i=`tailor-entry:${e}.${n}`,a=`\0${i}`;return{input:i,plugin:{name:`tailor-virtual-entry`,async resolveId(e,t){return e===i&&t===void 0?a:t!==a||!r||e.startsWith(`.`)||k.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})},load(e){return e===a?t:null}}}}function createGeneratedEntryResolverPlugin(e,t){let n=k.resolve(e),r=k.join(k.resolve(t),`__tailor_sdk_generated_entry__.js`);return{name:`tailor-generated-entry-resolver`,async resolveId(e,t){return t===void 0||k.resolve(t)!==n||e.startsWith(`.`)||k.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})}}}async function bundleAuthHooks(e){let{configPath:t,authName:n,handlerAccessPath:r,env:i={},startContext:a,cache:
|
|
69
|
+
`)}function formatUnresolvedImport(e){let t=e.exporter??`an imported module`,n=e.id?.startsWith(`\0`)?`a generated entry (${e.id.slice(1)})`:e.id&&`"${e.id}"`;return`"${t}"${n?` imported from ${n}`:``}`}const B=[`console.info`,`console.table`,`console.dir`,`console.dirxml`,`console.count`,`console.countReset`,`console.time`,`console.timeLog`,`console.timeEnd`,`console.group`,`console.groupCollapsed`,`console.groupEnd`,`console.clear`],V=[`console.debug`,`console.log`,`console.trace`],Le=[`console.warn`],Re=[`console.error`],H=[`globalThis.tailor.logger.debug`],U=[`globalThis.tailor.logger.info`],ze=[`globalThis.tailor.logger.warn`],Be=[`globalThis.tailor.logger.error`],Ve={DEBUG:[],INFO:[...V,...H],WARN:[...V,...B,...H,...U],ERROR:[...V,...B,...Le,...H,...U,...ze],SILENT:[...V,...B,...Le,...Re,...H,...U,...ze,...Be]};function normalizeBundleLogLevel(e){let t=e.trim().toUpperCase();return isLogLevel(t)?t:void 0}function resolveBundleLogLevel(e){if(e===void 0)return`DEBUG`;let t=normalizeBundleLogLevel(e);if(t)return t;throw Error(`Invalid logLevel "${e}". Expected one of: ${L.join(`, `)}`)}function manualPureFunctionsForLogLevel(e){return Ve[e]}function createLogLevelTreeshakeOptions(e){let t=manualPureFunctionsForLogLevel(e);return t.length>0?{manualPureFunctions:t}:{}}const He={moduleSideEffects:!1,annotations:!0,unknownGlobalSideEffects:!1};function mergeFunctionTreeshakeOptions(e){let t={},n=new Set;for(let r of e){Object.assign(t,r);for(let e of r.manualPureFunctions??[])n.add(e)}return n.size>0?t.manualPureFunctions=[...n]:delete t.manualPureFunctions,t}function composeFunctionTreeshakeOptions(e=[]){return mergeFunctionTreeshakeOptions([He,...e])}const Ue=/(?<![\w$.])process\.env\.__TAILOR_PLATFORM_BUNDLE\b/g,W={name:`tailor-platform-bundle-define`,transform(e){return e.includes(`process.env.__TAILOR_PLATFORM_BUNDLE`)?{code:e.replace(Ue,`true`)}:null},resolveId(e){return e===`node:async_hooks`?{id:e,external:!0}:null}},We=new Set;async function resolveTSConfigWithFallback(e){let t=await tryResolve(e);if(t||e===process.cwd())return t;let n=await tryResolve(process.cwd());return n&&!We.has(e)&&(We.add(e),s.warn(`No tsconfig found from "${e}"; falling back to the tsconfig resolved from process.cwd(). Move (or extend) a tsconfig into this directory before v2, when this fallback will be removed.`)),n}async function tryResolve(e){try{return await ue(e)}catch{return}}function createTsconfigLookupCache(){return{tsconfigCache:new Map,contextCache:new Map}}function createTsconfigPathsPlugin(e={}){let{tsconfigCache:t,contextCache:n}=e.cache??createTsconfigLookupCache();return{name:`tailor-tsconfig-paths`,resolveId:{order:`post`,async handler(r,i){if(!i||r.startsWith(`.`)||r.startsWith(`/`)||r.startsWith(`\0`))return null;let a=i.startsWith(`\0`)?e.virtualEntrySourceFile:i;if(!a)return null;let o=getResolutionContext(k.dirname(a),t,n,e.onTsconfigRead);if(!o)return null;let s=o.matcher(r);if(s.length===0||await this.resolve(r,i,{skipSelf:!0}))return null;for(let e of s){let t=await this.resolve(e,i,{skipSelf:!0});if(t)return t}return null}}}}function getResolutionContext(e,t,n,r){let i=n.get(e);if(i!==void 0)return reportTsconfigDependencies(t,r),i;let a=ye(e,`tsconfig.json`,t);reportTsconfigDependencies(t,r);let o=a?.config.compilerOptions?.paths,s=o&&Object.keys(o).length>0?ve(a):null,c=s?{matcher:s}:null;return n.set(e,c),c}function reportTsconfigDependencies(e,t){if(!t)return;let n=new Set,r=new Set;for(let[t,i]of e){let e=dependencyPathFromCacheKey(t);e&&(t.startsWith(`statSync:`)&&isDirectoryStat(i)?n.add(e):r.add(e))}for(let e of r)n.has(e)||t(e)}function dependencyPathFromCacheKey(e){if(e.startsWith(`readFileSync:`)&&e.endsWith(`:utf8`))return e.slice(13,-5);for(let t of[`existsSync:`,`statSync:`])if(e.startsWith(t))return e.slice(t.length)}function isDirectoryStat(e){return typeof e==`object`&&!!e&&`isDirectory`in e&&typeof e.isDirectory==`function`&&e.isDirectory()}function createVirtualEntry(e,t,n=`js`,r){let i=`tailor-entry:${e}.${n}`,a=`\0${i}`;return{input:i,plugin:{name:`tailor-virtual-entry`,async resolveId(e,t){return e===i&&t===void 0?a:t!==a||!r||e.startsWith(`.`)||k.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})},load(e){return e===a?t:null}}}}function createGeneratedEntryResolverPlugin(e,t){let n=k.resolve(e),r=k.join(k.resolve(t),`__tailor_sdk_generated_entry__.js`);return{name:`tailor-generated-entry-resolver`,async resolveId(e,t){return t===void 0||k.resolve(t)!==n||e.startsWith(`.`)||k.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})}}}async function bundleAuthHooks(e){let{configPath:t,authName:n,handlerAccessPath:r,env:i={},startContext:a,cache:c,inlineSourcemap:l,bundleLogLevel:u=`DEBUG`,baseDir:d,tsconfigCache:f}=e;s.newline(),s.log(`Bundling auth hook for ${o.info(`"${n}"`)}`);let p=k.resolve(t),m=await resolveTSConfigWithFallback(d),h=`auth-hook--${n}--before-login`,g=await withCache({cache:c,kind:`auth-hook`,name:h,sourceFile:p,contextHash:computeBundlerContextHash({sourceFile:p,extraContext:serializeStartContext(a),tsconfig:m,inlineSourcemap:l,bundleLogLevel:u,prefix:JSON.stringify(Object.fromEntries(Object.entries(i).toSorted(([e],[t])=>e.localeCompare(t))))}),async build(e,t){let n=T`
|
|
70
70
|
import _config from "${p}";
|
|
71
71
|
const __auth_hook_function = _config.${r};
|
|
72
72
|
export async function main(args) {
|
|
73
73
|
const env = ${JSON.stringify(i)};
|
|
74
74
|
return await __auth_hook_function({ ...args, env });
|
|
75
75
|
}
|
|
76
|
-
`,o=createVirtualEntry(`auth-hook:${h}`,n,`js`,p),s=createStartTransformPlugin(a),c=[o.plugin];s&&c.push(s),c.push(createTsconfigPathsPlugin({onTsconfigRead:t,cache:f}),W,...e);let d=createBundleLog({tsconfig:m}),g=await P.build({input:o.input,write:!1,output:{format:`esm`,sourcemap:!l||`inline`,minify:!l||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:m,plugins:c,transform:{define:{"process.env.TAILOR_APP_LOG_LEVEL":JSON.stringify(u)}},treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(u)]),...d.options});return d.assertAllResolved(),g.output[0].code}});s.log(`${
|
|
76
|
+
`,o=createVirtualEntry(`auth-hook:${h}`,n,`js`,p),s=createStartTransformPlugin(a),c=[o.plugin];s&&c.push(s),c.push(createTsconfigPathsPlugin({onTsconfigRead:t,cache:f}),W,...e);let d=createBundleLog({tsconfig:m}),g=await P.build({input:o.input,write:!1,output:{format:`esm`,sourcemap:!l||`inline`,minify:!l||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:m,plugins:c,transform:{define:{"process.env.TAILOR_APP_LOG_LEVEL":JSON.stringify(u)}},treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(u)]),...d.options});return d.assertAllResolved(),g.output[0].code}});s.log(`${o.success(`Bundled`)} auth hook for ${o.info(`"${n}"`)}`);let _=new Map;return _.set(h,g),_}const G=2e3;function formatGeneratedCode(e){return e.length<=G?`Generated code:\n${e}`:`Generated code (truncated to ${G} of ${e.length} characters):\n${e.slice(0,G)}\n...`}function assertParsableExpression(e,t){let{errors:n}=F(`generated-expr.js`,`(${e}\n);`);if(n.length===0)return e;let r=n.map(e=>` - ${e.message}`).join(`
|
|
77
77
|
`);throw Error(`Generated ${t} script is not valid JavaScript.\nParse errors:\n${r}\n`+formatGeneratedCode(e))}const K=`_principal`;function buildHookCallArgs(e){switch(e){case`validate`:return`{ value: _value }`;case`hooks.create`:return`{ input: _value, invoker: ${K}, now: _now }`;case`hooks.update`:return`{ input: _value, oldValue: _oldValue, invoker: ${K}, now: _now }`;case`typeHook.create`:case`typeHook.update`:return`{ input: _input, oldRecord: _oldRecord, invoker: ${K}, now: _now }`;case`typeValidate`:return`{ newRecord: _newRecord, oldRecord: _oldRecord, invoker: ${K} }, __issues`;default:throw Error(`Unknown script expr kind: ${e}`)}}const Ge=Symbol.for(`tailor-platform/sdk:precompiled-script-expr`),Ke=new WeakMap;function setPrecompiledScriptExpr(e,t,n){let r=Ke.get(e)??{};r[t]=n,Ke.set(e,r)}function getPrecompiledScriptExpr(e,t){let n=Object.hasOwn(e,Ge)?e[Ge]:void 0;if(typeof n==`object`&&n&&Object.hasOwn(n,t)){let e=n[t];if(typeof e==`string`)return e}return Ke.get(e)?.[t]}function makePrincipalExpr(e){let{source:t,fields:n,normalize:r,requireId:i=!1}=e,a=`{
|
|
78
78
|
id,
|
|
79
79
|
type,
|
|
@@ -111,9 +111,9 @@ ${e}\n return module.exports.main(${t});\n})()`}function buildMinimalEntryFromR
|
|
|
111
111
|
`)}async function bundleScriptTarget(e){let{fn:t,kind:n,sourceFilePath:r,sourceBindings:i,tableName:a,targetIndex:o,tsconfig:s}=e,c=`${n} in ${r}`,l=stringifyFunction(t);if((n===`typeValidate`||n===`validate`)&&t.constructor.name===`AsyncFunction`)throw Error(`${c} must be synchronous — the generated validator runs synchronously, so issues reported after an await are silently lost. Remove the async keyword.`);let u=assertParsableExpression(`(${l})(${buildHookCallArgs(n)})`,c),d=findUndefinedReferences(`const __fn = ${l};`);if(d.size===0)return u;let{imports:f,declarations:p,unresolved:m}=resolveNeededBindings(d,i);if(m.length>0)throw Error(`${c} captures unresolvable variables (${m.join(`, `)}). Hooks and validators must not reference variables that cannot be resolved from the source file.
|
|
112
112
|
${n}: ${l}`);let h=buildMinimalEntryFromResolved(f,p,l,r,n===`typeValidate`),g=createVirtualEntry(`tailordb-script:${a}:${o}`,h,`ts`,r),_=createBundleLog({tsconfig:s}),v=await P.build({plugins:[g.plugin,createTsconfigPathsPlugin({virtualEntrySourceFile:r}),W],input:g.input,write:!1,output:{format:`cjs`,sourcemap:!1,minify:!0,codeSplitting:!1},tsconfig:s,treeshake:{moduleSideEffects:!1,annotations:!0,unknownGlobalSideEffects:!1},..._.options});_.assertAllResolved();let y=v.output[0].code;return assertParsableExpression(buildPrecompiledExpr(y,buildHookCallArgs(n)),c)}async function precompileTailorDBTypeScripts(e,t,n){let r=collectScriptTargets(e);if(r.length===0)return;let i=collectSourceBindings(t),o=await Promise.allSettled(r.map((r,a)=>bundleScriptTarget({fn:r.fn,kind:r.kind,sourceFilePath:t,sourceBindings:i,tableName:e.name,targetIndex:a,tsconfig:n}))),s=o.find(e=>e.status===`rejected`);if(s)throw s.reason;for(let[e,t]of o.entries())if(t.status===`fulfilled`){let n=a(r[e],`bundle target at index ${e} missing`);setPrecompiledScriptExpr(n.fn,n.kind,t.value)}}function formatTailorDBTypeSourceInfo(e){if(e){if(se(e)){let t=[`plugin ${e.pluginId}`];return e.generatedTableKind&&t.push(`kind ${e.generatedTableKind}`),e.originalFilePath&&t.push(`source ${e.originalFilePath}`),e.originalExportName&&t.push(`export ${e.originalExportName}`),t.join(`, `)}return`${e.filePath} export ${e.exportName}`}}function collectLocalTailorDBTypeNameSources(e){let t=[];for(let n of e.tailorDBServices)for(let e of Object.keys(n.types))t.push({namespace:n.namespace,tableName:e,kind:`local`,detail:formatTailorDBTypeSourceInfo(n.typeSourceInfo[e])});return t}async function fetchExternalTailorDBTypeNameSources(e){return(await Promise.all(e.externalTailorDBNamespaces.map(async t=>{let n=[],r=await fetchAll(async(n,r)=>{try{let{tailordbTypes:i,nextPageToken:a}=await e.client.listTailorDBTypes({workspaceId:e.workspaceId,namespaceName:t,pageToken:n,pageSize:r});return[i,a??``]}catch(e){if(isNotFoundError(e))return[[],``];throw e}});for(let e of r)n.push({namespace:t,tableName:e.name,kind:`external`});return n}))).flat()}function assertUniqueTailorDBTypeNames(e){let t=new Map;for(let n of e.sources){let e=t.get(n.tableName);e?e.push(n):t.set(n.tableName,[n])}let n=[];for(let[e,r]of t){if(r.length<=1)continue;let t=r.map(formatTailorDBTypeNameSource).join(`, `);n.push(`Table "${e}" is defined more than once: ${t}`)}if(n.length>0)throw Error(`Duplicate TailorDB table names detected.
|
|
113
113
|
${n.map(e=>` - ${e}`).join(`
|
|
114
|
-
`)}\nTailorDB table names must be unique across all TailorDB namespaces in an application.`)}function assertUniqueLocalTailorDBTypeNames(e){assertUniqueTailorDBTypeNames({sources:collectLocalTailorDBTypeNameSources(e)})}async function assertUniqueTailorDBTypeNamesWithExternal(e){let t=collectLocalTailorDBTypeNameSources(e),n=e.plannedExternalTailorDBServices??[],r=new Set(n.map(e=>e.namespace)),i=collectLocalTailorDBTypeNameSources({tailorDBServices:n}).map(e=>({...e,kind:`external`})),a=e.externalTailorDBNamespaces.filter(e=>!r.has(e)),o=a.length>0?await fetchExternalTailorDBTypeNameSources({client:e.client,workspaceId:e.workspaceId,externalTailorDBNamespaces:a}):[];assertUniqueTailorDBTypeNames({sources:[...t,...i,...o]})}function formatTailorDBTypeNameSource(e){let t=e.kind===`external`?`external namespace "${e.namespace}"`:`namespace "${e.namespace}"`;return e.detail?`${t} (${e.detail})`:t}function createTailorDBService(t){let{namespace:n,config:r,pluginManager:i,baseDir:
|
|
114
|
+
`)}\nTailorDB table names must be unique across all TailorDB namespaces in an application.`)}function assertUniqueLocalTailorDBTypeNames(e){assertUniqueTailorDBTypeNames({sources:collectLocalTailorDBTypeNameSources(e)})}async function assertUniqueTailorDBTypeNamesWithExternal(e){let t=collectLocalTailorDBTypeNameSources(e),n=e.plannedExternalTailorDBServices??[],r=new Set(n.map(e=>e.namespace)),i=collectLocalTailorDBTypeNameSources({tailorDBServices:n}).map(e=>({...e,kind:`external`})),a=e.externalTailorDBNamespaces.filter(e=>!r.has(e)),o=a.length>0?await fetchExternalTailorDBTypeNameSources({client:e.client,workspaceId:e.workspaceId,externalTailorDBNamespaces:a}):[];assertUniqueTailorDBTypeNames({sources:[...t,...i,...o]})}function formatTailorDBTypeNameSource(e){let t=e.kind===`external`?`external namespace "${e.namespace}"`:`namespace "${e.namespace}"`;return e.detail?`${t} (${e.detail})`:t}function createTailorDBService(t){let{namespace:n,config:r,pluginManager:i,baseDir:c}=t,createRawTypesByName=()=>Object.create(null),l=Object.create(null),p={},h=Object.create(null),_=new Map,v,registerRawType=(e,t,r,i)=>{let o=Object.hasOwn(h,t)?h[t]:void 0;if(o){let e=formatTailorDBTypeSourceInfo(o)??`unknown source`,r=formatTailorDBTypeSourceInfo(i)??`unknown source`;throw Error(`Duplicate TailorDB table name "${t}" detected in TailorDB service "${n}". First: ${e}. Second: ${r}. TailorDB table names must be unique across all TailorDB files in a service.`)}a(l[e],`raw table entry missing for key: ${e}`)[t]=r,h[t]=i},parsePluginTable=(e,t)=>{let r=f.safeParse(d(e));if(!r.success){let e=r.error.issues.map(e=>` - ${e.path.map(String).join(`.`)||`(root)`}: ${e.message}`).join(`
|
|
115
115
|
`);throw Error(`TailorDB table ${t} in TailorDB service "${n}" failed schema validation:\n${e}`,{cause:r.error})}return r.data},describeGeneratedTable=(e,t,n)=>`${typeof e==`string`&&e.length>0?`"${e}" `:``}generated as "${t}" by plugin "${n}"`,doParseTypes=()=>{let e=createRawTypesByName();for(let t of Object.values(l))for(let[n,r]of Object.entries(t))e[n]=r;p=parseTypes(e,n,h)},warnOmittedPermit=()=>{for(let e of Object.values(l))for(let[t,n]of Object.entries(e)){let e=findOmittedPermitRules(n.metadata.permissions);e.length>0&&s.warn(`TailorDB table "${t}" has permission rule(s) ${e.join(`, `)} in object form without an explicit "permit"; they default to "deny". Set permit: true (allow) or permit: false (deny) to silence this warning.`)}},validateRequiredPermissions=()=>{let e=[];for(let t of Object.values(l))for(let[n,i]of Object.entries(t)){let t=i.metadata.settings?.gqlOperations??r.gqlOperations,{missingPermission:a,missingGqlPermission:o}=findMissingPermissionConfig(i.metadata.permissions,t);if(!a&&!o)continue;let s=formatTailorDBTypeSourceInfo(h[n]),c=s?` (${s})`:``;a&&e.push(`TailorDB table "${n}"${c} has no .permission() configured. TailorDB denies all record operations for tables without permission; call .permission(...) to grant access explicitly.`),o&&e.push(`TailorDB table "${n}"${c} has no .gqlPermission() configured, but GraphQL operations are enabled for it. Call .gqlPermission(...) to grant GraphQL access explicitly, or disable GraphQL exposure with .features({ gqlOperations: { create: false, update: false, delete: false, read: false } }).`)}if(e.length>0)throw Error(`TailorDB permission configuration errors in service "${n}":\n${e.map(e=>` - ${e}`).join(`
|
|
116
|
-
`)}`)},processPluginsForTable=async(e,t,r)=>{if(!i)return;let{extendedTable:
|
|
116
|
+
`)}`)},processPluginsForTable=async(e,t,r)=>{if(!i)return;let{extendedTable:c,generatedTables:u,events:d}=await i.processAttachmentsForTable({rawTable:e,attachments:t,namespace:n}),f=[...new Set(d.filter(e=>e.kind===`extended`).map(e=>e.pluginId))],p=c===void 0?void 0:parsePluginTable(c,`"${e.name}" extended by ${f.length===1?`plugin`:`plugins`} ${f.map(e=>`"${e}"`).join(`, `)}`),m=u.map(e=>({...e,table:parsePluginTable(e.table,describeGeneratedTable(e.tableName,e.kind,e.pluginId))}));p&&(a(l[r],`raw table entry missing for file: ${r}`)[e.name]=p);for(let t of m){let i={exportName:t.tableName,pluginId:t.pluginId,pluginImportPath:t.pluginImportPath,originalFilePath:r,originalExportName:h[e.name]?.exportName||e.name,generatedTableKind:t.kind,pluginConfig:t.pluginConfig,namespace:n};registerRawType(r,t.tableName,t.table,i)}for(let e of d)e.kind===`extended`?s.debug(` Extended: ${o.success(e.tableName)} with ${o.highlight(e.fieldCount.toString())} fields by plugin ${o.info(e.pluginId)}`):s.debug(` Generated: ${o.success(e.tableName)} by plugin ${o.info(e.pluginId)}`)},loadTypeFile=async(t,n)=>{l[t]=createRawTypesByName();let r=createRawTypesByName();try{let i=await u(t);for(let a of Object.keys(i)){let c=i[a],l=f.safeParse(g(c));if(!l.success){if(e(c,`tailordb-type`))throw l.error;continue}let u=k.relative(process.cwd(),t);s.debug(`Type: ${o.successBright(`"${l.data.name}"`)} loaded from ${o.path(u)}`),await precompileTailorDBTypeScripts(l.data,t,n),r[l.data.name]=l.data,registerRawType(t,l.data.name,l.data,{filePath:t,exportName:a});let d=c;d.plugins&&Array.isArray(d.plugins)&&d.plugins.length>0&&(_.set(d.name,[...d.plugins]),s.debug(` Plugin attachments: ${o.info(d.plugins.map(e=>e.pluginId).join(`, `))}`),await processPluginsForTable(d,d.plugins,t))}}catch(e){let n=k.relative(process.cwd(),t);throw s.error(`Failed to load table from ${o.bold(n)}`),s.error(String(e)),e}return r};return{namespace:n,config:r,get types(){return p},get typeSourceInfo(){return h},get pluginAttachments(){return _},loadTypes:async()=>(v||=(async()=>{if(r.files.length===0)return;let e=[...new Set(m(r,c))],t=await resolveTSConfigWithFallback(c);if(s.newline(),s.log(`Found ${o.highlight(e.length.toString())} table files for TailorDB service ${o.highlight(`"${n}"`)}`),i)for(let n of e)await loadTypeFile(n,t);else await Promise.all(e.map(e=>loadTypeFile(e,t)));return doParseTypes(),warnOmittedPermit(),validateRequiredPermissions(),p})(),v),processNamespacePlugins:async()=>{if(!i)return;let e=await i.processNamespacePlugins(n),t=`__plugin_generated__`,r=e.map(({pluginId:e,config:t,result:n})=>{if(!n.success)throw s.error(n.error),Error(n.error);return{pluginId:e,config:t,output:n.output}}).flatMap(({pluginId:e,config:t,output:n})=>Object.entries(n.tables??{}).map(([n,r])=>({pluginId:e,config:t,kind:n,table:parsePluginTable(r,describeGeneratedTable(te(r),n,e))}))),a=Object.hasOwn(l,t),c=l[t],u=c?Object.keys(c):[],d=u.length>0;if(a)for(let e of u)delete h[e];l[t]=createRawTypesByName();for(let{pluginId:e,config:a,kind:c,table:l}of r){let r={exportName:l.name,pluginId:e,pluginImportPath:i.getPluginImportPath(e)??``,originalFilePath:``,originalExportName:``,generatedTableKind:c,pluginConfig:a,namespace:n};registerRawType(t,l.name,l,r),s.debug(` Generated: ${o.success(l.name)} by namespace plugin ${o.info(e)}`)}(r.length>0||d)&&(doParseTypes(),validateRequiredPermissions())}}}function createAuthService(e,t,n){let r=e.connections?{...e.connections}:{},i;return{config:e,tailorDBServices:t,externalTailorDBNamespaces:n,connections:r,get userProfile(){return i},resolveNamespaces:async()=>{if(!e.userProfile)return;if(e.userProfile.namespace){i={...e.userProfile,namespace:e.userProfile.namespace};return}let r=t.length+n.length,o;if(r===1)o=t[0]?.namespace??a(n[0],`external TailorDB namespace missing`);else{await Promise.all(t.map(e=>e.loadTypes()));let n=typeof e.userProfile.type==`object`&&`name`in e.userProfile.type?e.userProfile.type.name:void 0;if(n)for(let e of t){let t=e.types;if(Object.prototype.hasOwnProperty.call(t,n)){o=e.namespace;break}}if(!o)throw Error(`userProfile type "${e.userProfile.type.name}" not found in any TailorDB namespace`)}i={...e.userProfile,namespace:o}}}}function resolveBundleConcurrency(){return parsePositiveInt(process.env.TAILOR_BUNDLE_CONCURRENCY)??Math.max(1,be.cpus().length)}async function withBundleConcurrency(e,t){let n=[];n.length=e.length;let r=ge(resolveBundleConcurrency()),i;if(await Promise.all(e.flatMap((e,a)=>[r(async()=>{if(!i)try{n[a]=await t(e)}catch(e){i??={reason:e}}})])),i)throw i.reason;return n}function assertNoForbiddenRuntimeGlobals(e,t){let n=[...findUndefinedReferences(e)].filter(isForbiddenGlobal).toSorted();if(n.length===0)return;let r=n.length===1?`a global`:`globals`;throw D({code:`FORBIDDEN_RUNTIME_GLOBAL`,message:`${t} references ${r} unavailable in the Tailor Platform runtime: ${n.join(`, `)}.`,details:n.map(oe).join(`
|
|
117
117
|
`)})}const q=makePrincipalExpr({source:`tailor.context.getInvoker()`,normalize:!1,fields:{type:{raw:`$raw.type`},id:`$raw.id`,workspaceId:`$raw.workspaceId`,attributes:`$raw.attributeMap`,attributeList:`$raw.attributes`}}),J=`actor: ${makePrincipalExpr({source:`args.actor`,normalize:!0,requireId:!0,fields:{type:{raw:`$raw?.userType`,fallback:`$raw?.type`},id:`$raw?.userId ?? $raw?.id`,workspaceId:`$raw.workspaceId`,attributes:`$raw.attributeMap ?? {}`,attributeList:`$raw.attributes ?? []`}})}`;function buildExecutorArgsExpr(e,t){let n=`env: ${JSON.stringify(t)}`;switch(e){case`schedule`:return`({ ...args, appNamespace: args.namespaceName, ${J}, ${n} })`;case`resolverExecuted`:return`({ ...args, appNamespace: args.namespaceName, ${J}, success: !!args.succeeded, result: args.succeeded?.result.resolver, error: args.failed?.error, ${n} })`;case`incomingWebhook`:return`({ ...args, appNamespace: args.namespaceName, rawBody: args.raw_body, ${n} })`;case`workflowExecution`:case`workflowJobExecution`:return`({ ...args, event: args.eventType?.split(".").pop(), rawEvent: args.eventType, ${J}, ...(args.succeeded ? { success: true } : args.failed ? { success: false, error: args.failed.error ?? "" } : {}), ${n} })`;default:return`({ ...args, event: args.eventType?.split(".").pop(), rawEvent: args.eventType, appNamespace: args.namespaceName, ${J}, ${n} })`}}function buildResolverOperationHookExpr(e){return`({ ...context.pipeline, input: context.args, caller: ${qe}, env: ${JSON.stringify(e)} });`}function isSingleResolverCondition(e){return e.length===3&&typeof e[1]==`string`}function resolverPermissionOperandExpr(e){return typeof e==`object`?e.user===`_loggedIn`?`(context.caller !== null)`:e.user===`id`?`context.caller?.id`:`context.caller?.attributes?.[${JSON.stringify(e.user)}]`:JSON.stringify(e)}function isArbitraryAttributeOperand(e){return typeof e==`object`&&e.user!==`_loggedIn`}function resolverPermissionConditionExpr(e){let[t,n,r]=e,i=resolverPermissionOperandExpr(t),a=resolverPermissionOperandExpr(r);if(n===`!=`){let e=isArbitraryAttributeOperand(t)?i:isArbitraryAttributeOperand(r)?a:void 0;if(e)return`(${e} !== undefined && ${i} !== ${a})`}return`(${i} ${n===`=`?`===`:`!==`} ${a})`}function resolverPermissionPolicyExpr(e){let t=isSingleResolverCondition(e.conditions)?[e.conditions]:e.conditions;if(t.length===0)throw Error(`Resolver permission policy must have at least one condition, got an empty array.`);return t.map(resolverPermissionConditionExpr).join(` && `)}function policyEntryExpr(e){return`{ matched: ${resolverPermissionPolicyExpr(e)}, description: ${JSON.stringify(e.description??``)} }`}function buildResolverPermissionGuardExpr(e){if(!e||e===`allowAnonymous`)return;if(e.length===0)throw Error(`Resolver permission must have at least one policy, got an empty array.`);let t=e.filter(e=>e.permit===!1),n=e.filter(e=>e.permit!==!1);return`{
|
|
118
118
|
const $denyPolicies = ${`[${t.map(policyEntryExpr).join(`, `)}]`};
|
|
119
119
|
const $allowPolicies = ${`[${n.map(policyEntryExpr).join(`, `)}]`};
|
|
@@ -144,7 +144,7 @@ ${n.map(e=>` - ${e}`).join(`
|
|
|
144
144
|
}
|
|
145
145
|
return result.value;
|
|
146
146
|
})()
|
|
147
|
-
`}async function bundleExecutors(e){let t=new Map,{config:n,startContext:r,additionalFiles:i=[],cache:a,inlineSourcemap:
|
|
147
|
+
`}async function bundleExecutors(e){let t=new Map,{config:n,startContext:r,additionalFiles:i=[],cache:a,inlineSourcemap:c,bundleLogLevel:l=`DEBUG`,baseDir:u,tsconfigCache:d}=e,f=[...m(n,u),...i];if(f.length===0)return s.warn(`No executor files found for patterns: ${n.files.join(`, `)}`),t;s.newline(),s.log(`Bundling ${o.highlight(f.length.toString())} files for ${o.info(`"executor"`)}`);let p=[];for(let e of f){let t=await v(e);if(!t){s.debug(` Skipping: ${e} (could not be loaded)`);continue}if(![`function`,`jobFunction`].includes(t.operation.kind)){s.debug(` Skipping: ${t.name} (not a function executor)`);continue}p.push({name:t.name,sourceFile:e})}if(p.length===0)return s.debug(` No function executors to bundle`),t;let h=await resolveTSConfigWithFallback(u),g=await withBundleConcurrency(p,e=>bundleSingleExecutor(e,h,r,a,c,l,d));for(let[e,n]of g)t.set(e,n);return s.log(`${o.success(`Bundled`)} ${o.info(`"executor"`)}`),t}async function bundleSingleExecutor(e,t,n,r,i,a=`DEBUG`,o){let s=serializeStartContext(n),c=computeBundlerContextHash({sourceFile:e.sourceFile,extraContext:s,tsconfig:t,inlineSourcemap:i,bundleLogLevel:a}),l=await withCache({cache:r,kind:`executor`,name:e.name,sourceFile:e.sourceFile,contextHash:c,async build(r,s){let c=k.resolve(e.sourceFile),l=T`
|
|
148
148
|
import _internalExecutor from "${c}";
|
|
149
149
|
|
|
150
150
|
const __executor_function = async (args) => {
|
|
@@ -153,7 +153,7 @@ ${n.map(e=>` - ${e}`).join(`
|
|
|
153
153
|
};
|
|
154
154
|
|
|
155
155
|
export { __executor_function as main };
|
|
156
|
-
`,u=createVirtualEntry(`executor:${e.name}`,l,`js`,c),d=createStartTransformPlugin(n),f=[u.plugin];d&&f.push(d),f.push(createTsconfigPathsPlugin({onTsconfigRead:s,cache:o}),W,...r);let p=createBundleLog({tsconfig:t}),m=await P.build({input:u.input,write:!1,output:{format:`esm`,sourcemap:!i||`inline`,minify:!i||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:t,plugins:f,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(a)]),...p.options});p.assertAllResolved();let h=m.output[0].code;return assertNoForbiddenRuntimeGlobals(h,`Executor "${e.name}"`),h}});return[e.name,l]}const Y={get:`GET`,post:`POST`,put:`PUT`,patch:`PATCH`,delete:`DELETE`},$e=Object.keys(Y),et=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,tt=A.strictObject({get:w.optional().describe(`Handler for GET requests`),post:w.optional().describe(`Handler for POST requests`),put:w.optional().describe(`Handler for PUT requests`),patch:w.optional().describe(`Handler for PATCH requests`),delete:w.optional().describe(`Handler for DELETE requests`)}).refine(e=>Object.values(e).some(e=>e!==void 0),`input must declare at least one HTTP method handler`).describe(`Per-method functions that transform HTTP requests to GraphQL requests`),nt=A.strictObject({name:A.string().regex(et,`name must be 3-63 chars, lowercase alphanumeric with hyphens, not starting or ending with a hyphen`).describe(`Unique adapter name within the domain`),pathPattern:A.string().min(1).describe(`Path pattern with segment wildcards (trailing or single-segment)`),enabled:A.boolean().default(!0).describe(`Whether the adapter is active`),priority:A.number().int().min(0).default(0).describe(`Matching priority; the lowest value wins when multiple adapters match`),input:tt,output:w.optional().describe(`Function that transforms GraphQL response to HTTP response`)}),rt=65536,it=262144,at=ce(import.meta.url).resolve(`@0no-co/graphql.web`);async function bundleHttpAdapters(e,t,n,r=`DEBUG`,i){if(e.length===0)return{bundledInputs:new Map,bundledOutputs:new Map};s.newline(),s.log(`Bundling ${
|
|
156
|
+
`,u=createVirtualEntry(`executor:${e.name}`,l,`js`,c),d=createStartTransformPlugin(n),f=[u.plugin];d&&f.push(d),f.push(createTsconfigPathsPlugin({onTsconfigRead:s,cache:o}),W,...r);let p=createBundleLog({tsconfig:t}),m=await P.build({input:u.input,write:!1,output:{format:`esm`,sourcemap:!i||`inline`,minify:!i||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:t,plugins:f,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(a)]),...p.options});p.assertAllResolved();let h=m.output[0].code;return assertNoForbiddenRuntimeGlobals(h,`Executor "${e.name}"`),h}});return[e.name,l]}const Y={get:`GET`,post:`POST`,put:`PUT`,patch:`PATCH`,delete:`DELETE`},$e=Object.keys(Y),et=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,tt=A.strictObject({get:w.optional().describe(`Handler for GET requests`),post:w.optional().describe(`Handler for POST requests`),put:w.optional().describe(`Handler for PUT requests`),patch:w.optional().describe(`Handler for PATCH requests`),delete:w.optional().describe(`Handler for DELETE requests`)}).refine(e=>Object.values(e).some(e=>e!==void 0),`input must declare at least one HTTP method handler`).describe(`Per-method functions that transform HTTP requests to GraphQL requests`),nt=A.strictObject({name:A.string().regex(et,`name must be 3-63 chars, lowercase alphanumeric with hyphens, not starting or ending with a hyphen`).describe(`Unique adapter name within the domain`),pathPattern:A.string().min(1).describe(`Path pattern with segment wildcards (trailing or single-segment)`),enabled:A.boolean().default(!0).describe(`Whether the adapter is active`),priority:A.number().int().min(0).default(0).describe(`Matching priority; the lowest value wins when multiple adapters match`),input:tt,output:w.optional().describe(`Function that transforms GraphQL response to HTTP response`)}),rt=65536,it=262144,at=ce(import.meta.url).resolve(`@0no-co/graphql.web`);async function bundleHttpAdapters(e,t,n,r=`DEBUG`,i){if(e.length===0)return{bundledInputs:new Map,bundledOutputs:new Map};s.newline(),s.log(`Bundling ${o.highlight(e.length.toString())} files for ${o.info(`"http-adapter"`)}`);let a=await resolveTSConfigWithFallback(t),c=await withBundleConcurrency(e.flatMap(e=>(e.hasOutput?[`input`,`output`]:[`input`]).map(t=>({adapter:e,kind:t}))),({adapter:e,kind:t})=>bundleAdapterScript(e,t,a,n,r,i)),l=new Map,u=new Map;for(let[e,t,n]of c)t===`input`?l.set(e,n):u.set(e,n);return s.log(`${o.success(`Bundled`)} ${o.info(`"http-adapter"`)}`),{bundledInputs:l,bundledOutputs:u}}async function bundleAdapterScript(e,t,n,r,i=`DEBUG`,a){let o=computeBundlerContextHash({sourceFile:e.sourceFile,extraContext:t===`input`?e.methods.join(`,`):``,tsconfig:n,inlineSourcemap:!1,bundleLogLevel:i,prefix:`${t}:document-query-normalize-v1`}),c=await withCache({cache:r,kind:t===`input`?`http-adapter-input`:`http-adapter-output`,name:e.name,sourceFile:e.sourceFile,contextHash:o,async build(r,o){let c=k.resolve(e.sourceFile),l=t===`input`?buildInputEntry(c,e.methods,at):buildOutputEntry(c),u=createVirtualEntry(`http-adapter:${e.name}:${t}`,l,`js`,c),d=[u.plugin,{name:`http-adapter-reject-node-imports`,resolveId(t){if(O(t))throw Error(`HTTP adapter "${e.name}": ${ae(t)}`);return null}},{name:`http-adapter-stub-sdk`,resolveId(e){return e===`@tailor-platform/sdk`||e.startsWith(`@tailor-platform/sdk/`)?{id:`\0http-adapter-sdk-stub`,moduleSideEffects:!1}:null},load(e){return e===`\0http-adapter-sdk-stub`?`export const createHttpAdapter = (cfg) => cfg;
|
|
157
157
|
export default { createHttpAdapter };
|
|
158
158
|
`:null}},createTsconfigPathsPlugin({onTsconfigRead:o,cache:a}),...r],f=createBundleLog({tsconfig:n}),p=await P.build({input:u.input,write:!1,output:{format:`iife`,sourcemap:!1,minify:!0,codeSplitting:!1},tsconfig:n,plugins:d,transform:{target:`es2017`},treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(i)]),...f.options});f.assertAllResolved();let m=p.output[0].code,h=Buffer.byteLength(m,`utf8`);if(h>it)throw Error(`HTTP adapter "${e.name}" ${t} script is ${h} bytes, exceeding the ${it} byte limit`);return h>rt&&s.warn(`HTTP adapter "${e.name}" ${t} script is ${h} bytes, larger than the recommended ${rt} byte limit`),rejectAsyncInBundle(m,e.name,t),m}});return[e.name,t,c]}function buildInputEntry(e,t,n){let r=t.map(e=>{let t=`__normalizeHttpAdapterGraphQLRequest(${`__adapter.input.${e}(req)`})`;return` case "${Y[e]}": return ${t};`}).join(`
|
|
159
159
|
`),i=t.map(e=>Y[e]).join(`, `);return`${`import { print as __printHttpAdapterDocument } from ${JSON.stringify(n)};
|
|
@@ -172,7 +172,7 @@ ${r}
|
|
|
172
172
|
};
|
|
173
173
|
`}function buildOutputEntry(e){return`import __adapter from ${JSON.stringify(e)};
|
|
174
174
|
globalThis.transform = __adapter.output;
|
|
175
|
-
`}function rejectAsyncInBundle(e,t,n){let{program:r}=F(`${t}.${n}.bundle.js`,e),i=!1,a=[r];for(;a.length>0;){let e=a.pop();if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:``;if(n===`AwaitExpression`){i=!0;break}if((n===`FunctionDeclaration`||n===`FunctionExpression`||n===`ArrowFunctionExpression`)&&t.async===!0){i=!0;break}if((n===`ForOfStatement`||n===`ForStatement`)&&t.await===!0){i=!0;break}for(let e of Object.keys(t)){let n=t[e];if(Array.isArray(n))for(let e of n)a.push(e);else n&&typeof n==`object`&&a.push(n)}}if(i)throw Error(`HTTP adapter "${t}" ${n} bundle contains async/await, which is unavailable in the gateway runtime. Check imported helper modules — even if your handler is synchronous, an async helper will fail at runtime.`)}function createHttpAdapterService(e){let{config:t,baseDir:n}=e,r=[],i=0,a=!1;return{config:t,get adapters(){return r},get fileCount(){return i},loadAdapters:async()=>{if(a)return;let e=await loadAdapterFiles(t,n);r=e.adapters,i=e.fileCount,a=!0},printLoadedAdapters:()=>{if(r.length!==0){s.newline(),s.log(`Found ${
|
|
175
|
+
`}function rejectAsyncInBundle(e,t,n){let{program:r}=F(`${t}.${n}.bundle.js`,e),i=!1,a=[r];for(;a.length>0;){let e=a.pop();if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:``;if(n===`AwaitExpression`){i=!0;break}if((n===`FunctionDeclaration`||n===`FunctionExpression`||n===`ArrowFunctionExpression`)&&t.async===!0){i=!0;break}if((n===`ForOfStatement`||n===`ForStatement`)&&t.await===!0){i=!0;break}for(let e of Object.keys(t)){let n=t[e];if(Array.isArray(n))for(let e of n)a.push(e);else n&&typeof n==`object`&&a.push(n)}}if(i)throw Error(`HTTP adapter "${t}" ${n} bundle contains async/await, which is unavailable in the gateway runtime. Check imported helper modules — even if your handler is synchronous, an async helper will fail at runtime.`)}function createHttpAdapterService(e){let{config:t,baseDir:n}=e,r=[],i=0,a=!1;return{config:t,get adapters(){return r},get fileCount(){return i},loadAdapters:async()=>{if(a)return;let e=await loadAdapterFiles(t,n);r=e.adapters,i=e.fileCount,a=!0},printLoadedAdapters:()=>{if(r.length!==0){s.newline(),s.log(`Found ${o.highlight(r.length.toString())} HTTP adapters`);for(let{adapter:e,sourceFile:t}of r){let n=k.relative(process.cwd(),t);s.debug(`HTTP adapter: ${o.successBright(`"${e.name}"`)} loaded from ${o.path(n)}`)}}}}}async function loadAdapterFiles(e,t){if(e.files.length===0)return{adapters:[],fileCount:0};let n=m(e,t),r=await Promise.all(n.map(loadAdapterFromFile)),i=[],a=new Map;for(let e of r){if(!e)continue;let t=a.get(e.adapter.name);if(t)throw Error(`Duplicate HTTP adapter name "${e.adapter.name}" found:\n - ${t}\n - ${e.sourceFile}\nEach HTTP adapter must have a unique name.`);a.set(e.adapter.name,e.sourceFile),i.push(e)}return{adapters:i,fileCount:n.length}}async function loadAdapterFromFile(t){try{let n=await u(t);if(!e(n.default,`http-adapter`)){let t=Object.entries(n).find(([t,n])=>t!=="default"&&e(n,`http-adapter`));if(t)throw Error(`HTTP adapter must be the default export, but it is exported as \`${t[0]}\`. Re-export it: \`export default createHttpAdapter({...})\`.`);return null}let r=nt.safeParse(n.default);if(!r.success)throw r.error;let i=r.data,a=collectMethodKeys(i);return rejectAsyncHandlers(i,a,t),{adapter:i,sourceFile:t,methods:a,hasOutput:i.output!==void 0}}catch(e){let n=k.relative(process.cwd(),t);throw s.error(`${o.error(`Failed to load HTTP adapter from`)} ${o.errorBright(n)}`),s.error(String(e)),e}}function collectMethodKeys(e){let t=e.input;return $e.filter(e=>typeof t[e]==`function`)}function rejectAsyncHandlers(e,t,n){let r=e.input;for(let i of t)if(isAsyncFunction(r[i]))throw Error(`HTTP adapter "${e.name}" in ${n} has an async \`input.${i}\` function. Handlers must be synchronous; async/await is not supported.`);if(e.output!==void 0&&isAsyncFunction(e.output))throw Error(`HTTP adapter "${e.name}" in ${n} has an async \`output\` function. Handlers must be synchronous; async/await is not supported.`)}function isAsyncFunction(e){return typeof e==`function`&&e.constructor.name===`AsyncFunction`}const ot=A.union([A.literal(`query`),A.literal(`mutation`)]).describe(`GraphQL operation type`),st=A.union([A.strictObject({user:A.string()}),A.string(),A.boolean()]),ct=A.union([A.literal(`=`),A.literal(`!=`)]),isUserOperand=e=>typeof e==`object`,lt={_loggedIn:`boolean`,id:`string`},operandTypeMismatch=(e,t)=>{if(typeof e!=`object`)return;let n=lt[e.user];if(n!==void 0&&typeof t!=`object`&&typeof t!==n)return{key:e.user,expected:n}},ut=A.tuple([st,ct,st]).refine(([e,,t])=>isUserOperand(e)!==isUserOperand(t),"Resolver permission condition must reference a `user` operand on exactly one side (comparing two `user` operands to each other can match on `undefined === undefined`)").superRefine(([e,,t],n)=>{for(let r of[operandTypeMismatch(e,t),operandTypeMismatch(t,e)])r&&n.addIssue({code:`custom`,message:`\`${r.key}\` must compare to a ${r.expected}`})}).readonly(),dt=A.strictObject({conditions:A.union([ut,A.array(ut).min(1,`Resolver permission policy must have at least one condition`).readonly()]),permit:A.boolean(),description:A.string().optional().describe(`Reason recorded for this policy, used in the access-denied error message`)}),ft=A.union([A.array(dt).min(1,`Resolver permission must have at least one policy`).refine(e=>e.some(e=>e.permit===!0),"Resolver permission must include at least one `permit: true` policy — a policy array with only `permit: false` policies still lets any caller through by simply not authenticating, since none of the deny conditions apply to a caller with no user attributes at all").readonly(),A.literal(`allowAnonymous`)]).describe('Access requirement for this resolver, evaluated against the original caller (unaffected by `invoker`) before `body` runs. "allowAnonymous" documents that anonymous callers are allowed. Omitted (default): unchanged, anonymous callers can reach the resolver'),pt=A.strictObject({operation:ot.describe(`GraphQL operation type (query or mutation)`),name:A.string().describe(`Resolver name`),description:A.string().optional().describe(`Resolver description`),input:A.record(A.string(),x).optional().describe(`Input field definitions`),body:w.describe(`Resolver implementation function`),output:x.describe(`Output field definition`),publishEvents:A.boolean().optional().describe(`Enable publishing events from this resolver`),invoker:y.optional().describe(`Machine user to execute this resolver as`),permission:ft.optional()});async function loadResolver(e){let t=(await u(e)).default,n=pt.safeParse(t);return n.success?n.data:null}async function bundleResolvers(e){let{namespace:t,config:n,baseDir:r,defaultPermission:i,startContext:a,cache:c,inlineSourcemap:l,bundleLogLevel:u=`DEBUG`,tsconfigCache:d}=e,f=new Map,p=m(n,r);if(p.length===0)return s.warn(`No resolver files found for patterns: ${n.files.join(`, `)}`),f;s.newline(),s.log(`Bundling ${o.highlight(p.length.toString())} files for ${o.info(`"${t}"`)}`);let h=[];for(let e of p){let t=await loadResolver(e);if(!t){s.debug(` Skipping: ${e} (could not be loaded)`);continue}h.push({name:t.name,sourceFile:e,permission:t.permission})}let g=await resolveTSConfigWithFallback(r),_=await withBundleConcurrency(h,e=>bundleSingleResolver({namespace:t,resolver:e,tsconfig:g,defaultPermission:i,startContext:a,cache:c,inlineSourcemap:l,bundleLogLevel:u,tsconfigCache:d}));for(let[e,t]of _)f.set(e,t);return s.log(`${o.success(`Bundled`)} ${o.info(`"${t}"`)}`),f}async function bundleSingleResolver(e){let{namespace:t,resolver:n,tsconfig:r,defaultPermission:i,startContext:a,cache:o,inlineSourcemap:s,bundleLogLevel:c=`DEBUG`,tsconfigCache:l}=e,u=serializeStartContext(a),d=computeBundlerContextHash({sourceFile:n.sourceFile,extraContext:JSON.stringify([u,i??null]),tsconfig:r,inlineSourcemap:s,bundleLogLevel:c}),f=await withCache({cache:o,kind:`resolver`,namespace:t,name:n.name,sourceFile:n.sourceFile,contextHash:d,async build(e,t){let o=k.resolve(n.sourceFile),u=buildResolverValidatedInputExpr({permission:n.permission,defaultPermission:i}),d=T`
|
|
176
176
|
import _internalResolver from "${o}";
|
|
177
177
|
import { t } from "@tailor-platform/sdk";
|
|
178
178
|
import { serializeDateFields } from "@tailor-platform/sdk/runtime";
|
|
@@ -185,7 +185,7 @@ globalThis.transform = __adapter.output;
|
|
|
185
185
|
};
|
|
186
186
|
|
|
187
187
|
export { $tailor_resolver_body as main };
|
|
188
|
-
`,f=createVirtualEntry(`resolver:${n.name}`,d,`js`,o),p=createStartTransformPlugin(a),m=[f.plugin];p&&m.push(p),m.push(createTsconfigPathsPlugin({onTsconfigRead:t,cache:l}),W,...e);let h=createBundleLog({tsconfig:r}),g=await P.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:r,plugins:m,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(c)]),...h.options});h.assertAllResolved();let _=g.output[0].code;return assertNoForbiddenRuntimeGlobals(_,`Resolver "${n.name}"`),_}});return[n.name,f]}function parseResolverDefaultPermission(e){let{namespace:t,config:n}=e;if(n.defaultPermission===void 0)return;let r=ft.safeParse(n.defaultPermission);if(!r.success)throw Error(`Invalid \`defaultPermission\` for resolver namespace "${t}": `+r.error.issues.map(e=>e.message).join(`; `));return r.data}function resolveResolverDefaultPermissionForFile(e){let{config:t,filePath:n,baseDir:r}=e;if(!t)return;let i=k.resolve(n),a=[];for(let[e,n]of Object.entries(t))`external`in n||m(n,r).some(e=>k.resolve(e)===i)&&a.push({namespace:e,config:n});if(a.length>1)throw Error(`Resolver ${k.relative(process.cwd(),i)} matches more than one resolver namespace: ${a.map(e=>`"${e.namespace}"`).join(`, `)}. Each namespace applies its own \`defaultPermission\`, so narrow the \`files\`/\`ignores\` patterns until exactly one namespace claims this file.`);let[o]=a;return o?parseResolverDefaultPermission(o):void 0}function createResolverService(t,n,r){let i={},a=parseResolverDefaultPermission({namespace:t,config:n}),o=!1,loadResolverForFile=async t=>{try{let n=await u(t),r=pt.safeParse(n.default);if(r.success){let e=k.relative(process.cwd(),t);return s.debug(`Resolver: ${c.successBright(`"${r.data.name}"`)} loaded from ${c.path(e)}`),i[t]=r.data,r.data}if(e(n.default,`resolver`))throw r.error}catch(e){let n=k.relative(process.cwd(),t);throw s.error(`Failed to load resolver from ${c.bold(n)}`),s.error(String(e)),e}};return{namespace:t,config:n,defaultPermission:a,get resolvers(){return i},loadResolvers:async()=>{if(o||n.files.length===0)return;let e=m(n,r);s.log(`Found ${c.highlight(e.length.toString())} resolver files for service ${c.highlight(`"${t}"`)}`),await Promise.all(e.map(e=>loadResolverForFile(e))),assertUniqueResolverNames(i,t),warnUndeclaredPermissions({namespace:t,defaultPermission:a,resolvers:i}),o=!0}}}function warnUndeclaredPermissions(e){let{namespace:t,defaultPermission:n,resolvers:r}=e;if(n!==void 0)return;let i=Object.values(r),a=i.filter(e=>e.permission===void 0);if(a.length===0)return;s.warn(`Resolver namespace ${c.highlight(`"${t}"`)}: ${a.length} of ${i.length} resolvers declare no \`permission\`, so anonymous callers can reach them. Set \`defaultPermission\` on the namespace, or declare \`permission\` on each resolver ("allowAnonymous" if public access is intended).`);let o=a.map(e=>e.name).toSorted();s.debug(` Resolvers without \`permission\`: ${o.join(`, `)}`)}function assertUniqueResolverNames(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=k.relative(process.cwd(),r),a=n.get(i.name);if(a)throw Error(`Duplicate resolver name "${i.name}" found in namespace "${t}":\n - ${a}\n - ${e}\nEach resolver must have a unique name within a namespace.`);n.set(i.name,e)}}function findVariableDeclarationsByName(e){let t=new Map;for(let n of e.body){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e?.type!==`VariableDeclaration`)continue;let r=e;for(let e of r.declarations)e.id.type===`Identifier`&&t.set(e.id.name,{start:n.start,end:n.end})}return t}function findWorkflowDefaultExport(e){let t=collectSdkBindings(e,`createWorkflow`);for(let n of e.body)if(n.type===`ExportDefaultDeclaration`){let e=n,r=e.declaration;if(isSdkFunctionCall(r,t,`createWorkflow`)||r.type===`Identifier`)return{start:e.start,end:e.end}}return null}function transformWorkflowSource(e,t,n,r){let{program:i}=F(`input.ts`,e),a=findAllJobs(i,e);if(!a.some(e=>e.name===t))return e;let o=findVariableDeclarationsByName(i),s=[],c=new Set;for(let n of a)if(n.name!==t){if(n.statementRange&&!c.has(n.statementRange.start)){let t=findStatementEnd(e,n.statementRange.end);c.add(n.statementRange.start),s.push({start:n.statementRange.start,end:t,text:``})}else n.statementRange||(c.add(n.bodyValueRange.start),s.push({start:n.bodyValueRange.start,end:n.bodyValueRange.end,text:`() => {}`}))}if(r)for(let t of r){if(t===n)continue;let r=o.get(t);if(r&&!c.has(r.start)){let t=findStatementEnd(e,r.end);c.add(r.start),s.push({start:r.start,end:t,text:``})}}let l=findWorkflowDefaultExport(i);if(l&&!c.has(l.start)){let t=findStatementEnd(e,l.end);c.add(l.start),s.push({start:l.start,end:t,text:``})}return applyReplacements(e,s)}function safeRealpath(e){let t=k.resolve(e);try{return j.realpathSync(t)}catch(e){return s.debug(`realpathSync failed for ${t}: ${e instanceof Error?e.message:e}`),t}}var WorkflowJobDetectionError=class extends Error{};function isExecJobFunctionCallee(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.type!==`MemberExpression`)return!1;let n=t.property;if(n?.type!==`Identifier`||n.name!==`execJobFunction`)return!1;let r=t.object;if(r?.type!==`MemberExpression`)return!1;let i=r.property;if(i?.type!==`Identifier`||i.name!==`workflow`)return!1;let a=r.object;return a?.type===`Identifier`&&a.name===`tailor`}function extractStaticStringValue(e){if(!e||typeof e!=`object`)return;let t=e;if(t.type===`Literal`&&typeof t.value==`string`)return t.value;if(t.type===`TemplateLiteral`){let e=t.quasis,n=t.expressions;if(e?.length===1&&(n?.length??0)===0)return e[0]?.value?.cooked}}const mt=new Set([`@tailor-platform/sdk/runtime`,`@tailor-platform/sdk/runtime/workflow`]);function collectRuntimeWorkflowImportBindings(e){let t=new Set;for(let n of e.body??[]){if(n.type!==`ImportDeclaration`||n.importKind===`type`)continue;let e=n.source;if(typeof e?.value==`string`&&mt.has(e.value))for(let e of n.specifiers??[]){if(e.type!==`ImportSpecifier`||e.importKind===`type`)continue;let n=getModuleExportName(e.imported),r=getModuleExportName(e.local);n===`workflow`&&r&&t.add(r)}}return t}function isDirectExecJobFunctionCallee(e,t){if(isExecJobFunctionCallee(e))return!0;if(!e||typeof e!=`object`)return!1;let n=e;if(n.type!==`MemberExpression`)return!1;let r=n.property;if(r?.type!==`Identifier`||r.name!==`execJobFunction`)return!1;let i=n.object;return i?.type===`Identifier`&&t.has(i.name)}function findDirectExecJobFunctionCalls(e){let t=collectRuntimeWorkflowImportBindings(e),n=[];function walk(e){if(e&&typeof e==`object`){if(e.type===`CallExpression`&&isDirectExecJobFunctionCallee(e.callee,t)){let t=e.arguments;n.push({targetName:extractStaticStringValue(t?.[0])})}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}}return walk(e),n}function buildDirectExecJobFunctionErrorMessage(e,t){return t.targetName===void 0?`Workflow file ${e} calls execJobFunction(...) directly with a job name that isn't a string literal, so the target can't be resolved at build time. Call the target job's own .start(...) method from inside a job body instead of calling execJobFunction directly.`:`Workflow file ${e} calls execJobFunction("${t.targetName}", ...) directly. A direct call is never recognized as a dependency, so "${t.targetName}" would silently be dropped from the bundle unless something else happens to reference it. Call the "${t.targetName}" job's .start(...) method from inside a job body instead.`}function collectExecJobFunctionTargets(e){let{program:t,errors:n}=F(`input.js`,e);if(n.length>0)throw new WorkflowJobDetectionError(`Failed to parse bundled job code while checking for missed dependencies: ${n.map(e=>e.message).join(`; `)}`);let r=[];function walk(e){if(e&&typeof e==`object`){if(e.type===`CallExpression`&&isExecJobFunctionCallee(e.callee)){let t=e.arguments,n=extractStaticStringValue(t?.[0]);n!==void 0&&r.push(n)}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}}return walk(t),r}function validateBundledDependencies(e,t){let n=new Set(t);for(let[t,r]of e){let e;try{e=collectExecJobFunctionTargets(r)}catch(e){throw new WorkflowJobDetectionError(`Failed to check the bundled output of workflow job "${t}" for missed dependencies: ${e instanceof Error?e.message:String(e)}`)}for(let r of e)if(!n.has(r))throw new WorkflowJobDetectionError(`Workflow job "${t}" calls execJobFunction("${r}", ...) — usually the result of a rewritten "${r}" job .start() call — but "${r}" was not detected as a dependency and is not included in the bundle. Call the "${r}" job's .start() method from inside the body of workflow job "${t}" (a nested function inside body works too), or make sure the file containing the call is covered by the workflow service's "files" pattern.`)}}async function bundleWorkflowJobs(e,t,n={},r,i,a,o,l=`DEBUG`,u){if(e.length===0)return s.warn(`No workflow jobs to bundle`),{mainJobDeps:{},usedJobNames:[],bundledCode:new Map};let{usedJobs:d,mainJobDeps:f}=await filterUsedJobs(e,t,r);s.newline(),s.log(`Bundling ${c.highlight(d.length.toString())} files for ${c.info(`"workflow-job"`)}`);let p=await resolveTSConfigWithFallback(i),m=await withBundleConcurrency(d,e=>bundleSingleJob(e,d,p,n,r,a,o,l,u)),h=new Map;for(let[e,t]of m)h.set(e,t);return validateBundledDependencies(h,d.map(e=>e.name)),s.log(`${c.success(`Bundled`)} ${c.info(`"workflow-job"`)}`),{mainJobDeps:f,usedJobNames:d.map(e=>e.name),bundledCode:h}}async function filterUsedJobs(e,t,n){if(e.length===0||t.length===0)return{usedJobs:[],mainJobDeps:{}};let r=new Map;for(let t of e){let e=r.get(t.sourceFile)||[];e.push(t),r.set(t.sourceFile,e)}let i=new Map(r),a=new Set([...r.keys()].map(safeRealpath));for(let e of n.modules.values())a.has(safeRealpath(e.sourceFile))||i.set(e.sourceFile,[]);let o=new Map,s=await Promise.all(Array.from(i.entries()).map(async([e,t])=>{try{let r=await j.promises.readFile(e,`utf-8`),{program:i,errors:a}=F(e,r);if(a.length>0)throw new WorkflowJobDetectionError(`Failed to parse ${e}: ${a.map(e=>e.message).join(`; `)}`);let[o]=findDirectExecJobFunctionCalls(i);if(o)throw new WorkflowJobDetectionError(buildDirectExecJobFunctionErrorMessage(e,o));let s=findAllJobs(i,r),c=detectResolvedStartCalls(i,r,n,e),l=[];for(let n of t){let t=s.find(e=>e.name===n.name);if(!t)throw new WorkflowJobDetectionError(`Workflow job "${n.name}" (export "${n.exportName}" in ${e}) could not be statically detected: createWorkflowJob's "name" must be a string literal and "body" must be a function expression. Dynamic or computed values (e.g. body: someWrapper(fn)) cannot be bundled and would be silently dropped.`);let r=new Set;for(let e of c)e.kind===`job`&&e.callRange.start>=t.bodyValueRange.start&&e.callRange.end<=t.bodyValueRange.end&&r.add(e.targetName);r.size>0&&l.push({jobName:n.name,deps:r})}for(let t of c)if(t.kind===`job`&&!s.some(e=>t.callRange.start>=e.bodyValueRange.start&&t.callRange.end<=e.bodyValueRange.end))throw new WorkflowJobDetectionError(`Call to job "${t.targetName}".start() in ${e} is not inside any workflow job's body: it was factored into a function defined outside the calling job's body. Dependency detection only sees .start() calls lexically inside a job body, so this call would silently drop "${t.targetName}" from the bundle. Move the call to a function defined inside the calling job's body.`);return l}catch(e){if(e instanceof WorkflowJobDetectionError)throw e;return[]}}));for(let e of s)for(let{jobName:t,deps:n}of e)o.set(t,n);let c=new Set,l={};function collectDeps(e,t){if(t.has(e))return;t.add(e);let n=o.get(e);if(n)for(let e of n)collectDeps(e,t)}for(let e of t){let t=new Set;collectDeps(e,t),l[e]=Array.from(t);for(let e of t)c.add(e)}return{usedJobs:e.filter(e=>c.has(e.name)),mainJobDeps:l}}async function bundleSingleJob(e,t,n,r,i,a,o,s=`DEBUG`,c){let l=serializeStartContext(i),u=JSON.stringify(Object.fromEntries(Object.entries(r).toSorted(([e],[t])=>e.localeCompare(t)))),d=computeBundlerContextHash({sourceFile:e.sourceFile,extraContext:l,tsconfig:n,inlineSourcemap:o,bundleLogLevel:s,prefix:u}),f=await withCache({cache:a,kind:`workflow-job`,name:e.name,sourceFile:e.sourceFile,contextHash:d,async build(a,l){let u=k.resolve(e.sourceFile),d=T`
|
|
188
|
+
`,f=createVirtualEntry(`resolver:${n.name}`,d,`js`,o),p=createStartTransformPlugin(a),m=[f.plugin];p&&m.push(p),m.push(createTsconfigPathsPlugin({onTsconfigRead:t,cache:l}),W,...e);let h=createBundleLog({tsconfig:r}),g=await P.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:r,plugins:m,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(c)]),...h.options});h.assertAllResolved();let _=g.output[0].code;return assertNoForbiddenRuntimeGlobals(_,`Resolver "${n.name}"`),_}});return[n.name,f]}function parseResolverDefaultPermission(e){let{namespace:t,config:n}=e;if(n.defaultPermission===void 0)return;let r=ft.safeParse(n.defaultPermission);if(!r.success)throw Error(`Invalid \`defaultPermission\` for resolver namespace "${t}": `+r.error.issues.map(e=>e.message).join(`; `));return r.data}function resolveResolverDefaultPermissionForFile(e){let{config:t,filePath:n,baseDir:r}=e;if(!t)return;let i=k.resolve(n),a=[];for(let[e,n]of Object.entries(t))`external`in n||m(n,r).some(e=>k.resolve(e)===i)&&a.push({namespace:e,config:n});if(a.length>1)throw Error(`Resolver ${k.relative(process.cwd(),i)} matches more than one resolver namespace: ${a.map(e=>`"${e.namespace}"`).join(`, `)}. Each namespace applies its own \`defaultPermission\`, so narrow the \`files\`/\`ignores\` patterns until exactly one namespace claims this file.`);let[o]=a;return o?parseResolverDefaultPermission(o):void 0}function createResolverService(t,n,r){let i={},a=parseResolverDefaultPermission({namespace:t,config:n}),c=!1,loadResolverForFile=async t=>{try{let n=await u(t),r=pt.safeParse(n.default);if(r.success){let e=k.relative(process.cwd(),t);return s.debug(`Resolver: ${o.successBright(`"${r.data.name}"`)} loaded from ${o.path(e)}`),i[t]=r.data,r.data}if(e(n.default,`resolver`))throw r.error}catch(e){let n=k.relative(process.cwd(),t);throw s.error(`Failed to load resolver from ${o.bold(n)}`),s.error(String(e)),e}};return{namespace:t,config:n,defaultPermission:a,get resolvers(){return i},loadResolvers:async()=>{if(c||n.files.length===0)return;let e=m(n,r);s.log(`Found ${o.highlight(e.length.toString())} resolver files for service ${o.highlight(`"${t}"`)}`),await Promise.all(e.map(e=>loadResolverForFile(e))),assertUniqueResolverNames(i,t),warnUndeclaredPermissions({namespace:t,defaultPermission:a,resolvers:i}),c=!0}}}function warnUndeclaredPermissions(e){let{namespace:t,defaultPermission:n,resolvers:r}=e;if(n!==void 0)return;let i=Object.values(r),a=i.filter(e=>e.permission===void 0);if(a.length===0)return;s.warn(`Resolver namespace ${o.highlight(`"${t}"`)}: ${a.length} of ${i.length} resolvers declare no \`permission\`, so anonymous callers can reach them. Set \`defaultPermission\` on the namespace, or declare \`permission\` on each resolver ("allowAnonymous" if public access is intended).`);let c=a.map(e=>e.name).toSorted();s.debug(` Resolvers without \`permission\`: ${c.join(`, `)}`)}function assertUniqueResolverNames(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=k.relative(process.cwd(),r),a=n.get(i.name);if(a)throw Error(`Duplicate resolver name "${i.name}" found in namespace "${t}":\n - ${a}\n - ${e}\nEach resolver must have a unique name within a namespace.`);n.set(i.name,e)}}function findVariableDeclarationsByName(e){let t=new Map;for(let n of e.body){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e?.type!==`VariableDeclaration`)continue;let r=e;for(let e of r.declarations)e.id.type===`Identifier`&&t.set(e.id.name,{start:n.start,end:n.end})}return t}function findWorkflowDefaultExport(e){let t=collectSdkBindings(e,`createWorkflow`);for(let n of e.body)if(n.type===`ExportDefaultDeclaration`){let e=n,r=e.declaration;if(isSdkFunctionCall(r,t,`createWorkflow`)||r.type===`Identifier`)return{start:e.start,end:e.end}}return null}function transformWorkflowSource(e,t,n,r){let{program:i}=F(`input.ts`,e),a=findAllJobs(i,e);if(!a.some(e=>e.name===t))return e;let o=findVariableDeclarationsByName(i),s=[],c=new Set;for(let n of a)if(n.name!==t){if(n.statementRange&&!c.has(n.statementRange.start)){let t=findStatementEnd(e,n.statementRange.end);c.add(n.statementRange.start),s.push({start:n.statementRange.start,end:t,text:``})}else n.statementRange||(c.add(n.bodyValueRange.start),s.push({start:n.bodyValueRange.start,end:n.bodyValueRange.end,text:`() => {}`}))}if(r)for(let t of r){if(t===n)continue;let r=o.get(t);if(r&&!c.has(r.start)){let t=findStatementEnd(e,r.end);c.add(r.start),s.push({start:r.start,end:t,text:``})}}let l=findWorkflowDefaultExport(i);if(l&&!c.has(l.start)){let t=findStatementEnd(e,l.end);c.add(l.start),s.push({start:l.start,end:t,text:``})}return applyReplacements(e,s)}function safeRealpath(e){let t=k.resolve(e);try{return j.realpathSync(t)}catch(e){return s.debug(`realpathSync failed for ${t}: ${e instanceof Error?e.message:e}`),t}}var WorkflowJobDetectionError=class extends Error{};function isExecJobFunctionCallee(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.type!==`MemberExpression`)return!1;let n=t.property;if(n?.type!==`Identifier`||n.name!==`execJobFunction`)return!1;let r=t.object;if(r?.type!==`MemberExpression`)return!1;let i=r.property;if(i?.type!==`Identifier`||i.name!==`workflow`)return!1;let a=r.object;return a?.type===`Identifier`&&a.name===`tailor`}function extractStaticStringValue(e){if(!e||typeof e!=`object`)return;let t=e;if(t.type===`Literal`&&typeof t.value==`string`)return t.value;if(t.type===`TemplateLiteral`){let e=t.quasis,n=t.expressions;if(e?.length===1&&(n?.length??0)===0)return e[0]?.value?.cooked}}const mt=new Set([`@tailor-platform/sdk/runtime`,`@tailor-platform/sdk/runtime/workflow`]);function collectRuntimeWorkflowImportBindings(e){let t=new Set;for(let n of e.body??[]){if(n.type!==`ImportDeclaration`||n.importKind===`type`)continue;let e=n.source;if(typeof e?.value==`string`&&mt.has(e.value))for(let e of n.specifiers??[]){if(e.type!==`ImportSpecifier`||e.importKind===`type`)continue;let n=getModuleExportName(e.imported),r=getModuleExportName(e.local);n===`workflow`&&r&&t.add(r)}}return t}function isDirectExecJobFunctionCallee(e,t){if(isExecJobFunctionCallee(e))return!0;if(!e||typeof e!=`object`)return!1;let n=e;if(n.type!==`MemberExpression`)return!1;let r=n.property;if(r?.type!==`Identifier`||r.name!==`execJobFunction`)return!1;let i=n.object;return i?.type===`Identifier`&&t.has(i.name)}function findDirectExecJobFunctionCalls(e){let t=collectRuntimeWorkflowImportBindings(e),n=[];function walk(e){if(e&&typeof e==`object`){if(e.type===`CallExpression`&&isDirectExecJobFunctionCallee(e.callee,t)){let t=e.arguments;n.push({targetName:extractStaticStringValue(t?.[0])})}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}}return walk(e),n}function buildDirectExecJobFunctionErrorMessage(e,t){return t.targetName===void 0?`Workflow file ${e} calls execJobFunction(...) directly with a job name that isn't a string literal, so the target can't be resolved at build time. Call the target job's own .start(...) method from inside a job body instead of calling execJobFunction directly.`:`Workflow file ${e} calls execJobFunction("${t.targetName}", ...) directly. A direct call is never recognized as a dependency, so "${t.targetName}" would silently be dropped from the bundle unless something else happens to reference it. Call the "${t.targetName}" job's .start(...) method from inside a job body instead.`}function collectExecJobFunctionTargets(e){let{program:t,errors:n}=F(`input.js`,e);if(n.length>0)throw new WorkflowJobDetectionError(`Failed to parse bundled job code while checking for missed dependencies: ${n.map(e=>e.message).join(`; `)}`);let r=[];function walk(e){if(e&&typeof e==`object`){if(e.type===`CallExpression`&&isExecJobFunctionCallee(e.callee)){let t=e.arguments,n=extractStaticStringValue(t?.[0]);n!==void 0&&r.push(n)}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}}return walk(t),r}function validateBundledDependencies(e,t){let n=new Set(t);for(let[t,r]of e){let e;try{e=collectExecJobFunctionTargets(r)}catch(e){throw new WorkflowJobDetectionError(`Failed to check the bundled output of workflow job "${t}" for missed dependencies: ${e instanceof Error?e.message:String(e)}`)}for(let r of e)if(!n.has(r))throw new WorkflowJobDetectionError(`Workflow job "${t}" calls execJobFunction("${r}", ...) — usually the result of a rewritten "${r}" job .start() call — but "${r}" was not detected as a dependency and is not included in the bundle. Call the "${r}" job's .start() method from inside the body of workflow job "${t}" (a nested function inside body works too), or make sure the file containing the call is covered by the workflow service's "files" pattern.`)}}async function bundleWorkflowJobs(e,t,n={},r,i,a,c,l=`DEBUG`,u){if(e.length===0)return s.warn(`No workflow jobs to bundle`),{mainJobDeps:{},usedJobNames:[],bundledCode:new Map};let{usedJobs:d,mainJobDeps:f}=await filterUsedJobs(e,t,r);s.newline(),s.log(`Bundling ${o.highlight(d.length.toString())} files for ${o.info(`"workflow-job"`)}`);let p=await resolveTSConfigWithFallback(i),m=await withBundleConcurrency(d,e=>bundleSingleJob(e,d,p,n,r,a,c,l,u)),h=new Map;for(let[e,t]of m)h.set(e,t);return validateBundledDependencies(h,d.map(e=>e.name)),s.log(`${o.success(`Bundled`)} ${o.info(`"workflow-job"`)}`),{mainJobDeps:f,usedJobNames:d.map(e=>e.name),bundledCode:h}}async function filterUsedJobs(e,t,n){if(e.length===0||t.length===0)return{usedJobs:[],mainJobDeps:{}};let r=new Map;for(let t of e){let e=r.get(t.sourceFile)||[];e.push(t),r.set(t.sourceFile,e)}let i=new Map(r),a=new Set([...r.keys()].map(safeRealpath));for(let e of n.modules.values())a.has(safeRealpath(e.sourceFile))||i.set(e.sourceFile,[]);let o=new Map,s=await Promise.all(Array.from(i.entries()).map(async([e,t])=>{try{let r=await j.promises.readFile(e,`utf-8`),{program:i,errors:a}=F(e,r);if(a.length>0)throw new WorkflowJobDetectionError(`Failed to parse ${e}: ${a.map(e=>e.message).join(`; `)}`);let[o]=findDirectExecJobFunctionCalls(i);if(o)throw new WorkflowJobDetectionError(buildDirectExecJobFunctionErrorMessage(e,o));let s=findAllJobs(i,r),c=detectResolvedStartCalls(i,r,n,e),l=[];for(let n of t){let t=s.find(e=>e.name===n.name);if(!t)throw new WorkflowJobDetectionError(`Workflow job "${n.name}" (export "${n.exportName}" in ${e}) could not be statically detected: createWorkflowJob's "name" must be a string literal and "body" must be a function expression. Dynamic or computed values (e.g. body: someWrapper(fn)) cannot be bundled and would be silently dropped.`);let r=new Set;for(let e of c)e.kind===`job`&&e.callRange.start>=t.bodyValueRange.start&&e.callRange.end<=t.bodyValueRange.end&&r.add(e.targetName);r.size>0&&l.push({jobName:n.name,deps:r})}for(let t of c)if(t.kind===`job`&&!s.some(e=>t.callRange.start>=e.bodyValueRange.start&&t.callRange.end<=e.bodyValueRange.end))throw new WorkflowJobDetectionError(`Call to job "${t.targetName}".start() in ${e} is not inside any workflow job's body: it was factored into a function defined outside the calling job's body. Dependency detection only sees .start() calls lexically inside a job body, so this call would silently drop "${t.targetName}" from the bundle. Move the call to a function defined inside the calling job's body.`);return l}catch(e){if(e instanceof WorkflowJobDetectionError)throw e;return[]}}));for(let e of s)for(let{jobName:t,deps:n}of e)o.set(t,n);let c=new Set,l={};function collectDeps(e,t){if(t.has(e))return;t.add(e);let n=o.get(e);if(n)for(let e of n)collectDeps(e,t)}for(let e of t){let t=new Set;collectDeps(e,t),l[e]=Array.from(t);for(let e of t)c.add(e)}return{usedJobs:e.filter(e=>c.has(e.name)),mainJobDeps:l}}async function bundleSingleJob(e,t,n,r,i,a,o,s=`DEBUG`,c){let l=serializeStartContext(i),u=JSON.stringify(Object.fromEntries(Object.entries(r).toSorted(([e],[t])=>e.localeCompare(t)))),d=computeBundlerContextHash({sourceFile:e.sourceFile,extraContext:l,tsconfig:n,inlineSourcemap:o,bundleLogLevel:s,prefix:u}),f=await withCache({cache:a,kind:`workflow-job`,name:e.name,sourceFile:e.sourceFile,contextHash:d,async build(a,l){let u=k.resolve(e.sourceFile),d=T`
|
|
189
189
|
import { ${e.exportName} } from "${u}";
|
|
190
190
|
|
|
191
191
|
export async function main(input) {
|
|
@@ -193,7 +193,7 @@ globalThis.transform = __adapter.output;
|
|
|
193
193
|
const invoker = ${q};
|
|
194
194
|
return await ${e.exportName}.body(input, { env, invoker });
|
|
195
195
|
}
|
|
196
|
-
`,f=createVirtualEntry(`workflow-job:${e.name}`,d,`js`,u),p=safeRealpath(e.sourceFile),m=t.filter(t=>t.name!==e.name&&safeRealpath(t.sourceFile)===p).map(e=>e.exportName),h=[f.plugin,{name:`workflow-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){if(!t.includes(`createWorkflowJob`)&&!t.includes(`createWorkflow`)&&!hasStartCall(t))return null;let r=t;return safeRealpath(n)===p&&(r=transformWorkflowSource(t,e.name,e.exportName,m)),hasStartCall(r)&&(r=transformStartCalls(r,i,n)),r===t?null:{code:r}}}},createTsconfigPathsPlugin({onTsconfigRead:l,cache:c}),W,...a],g=createBundleLog({tsconfig:n}),_=await P.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!o||`inline`,minify:!o||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:n,plugins:h,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(s)]),...g.options});g.assertAllResolved();let v=_.output[0].code;return assertNoForbiddenRuntimeGlobals(v,`Workflow job "${e.name}"`),v}});return[e.name,f]}const ht=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,gt=/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9*]$/,_t=`key must not end with '*'; omit the '*' and set matchType: "prefix" for wildcard policies (the SDK appends '*' automatically).`;function toPlatformExecutionPolicyKey(e,t){return t===`prefix`?`${e}*`:e}const vt=[`ms`,`s`,`m`],yt={ms:1/1e3,s:1,m:60};function durationToSeconds(e){let t=/^(\d+)(ms|s|m)$/.exec(e);return t?.[1]===void 0||t[2]===void 0?null:parseInt(t[1],10)*yt[t[2]]}const X={maxRetries:{min:1,max:10},initialBackoffMaxSeconds:3600,maxBackoffMaxSeconds:86400,backoffMultiplierMin:1},bt=A.strictObject({name:A.string().describe(`Job name (must be unique across the project)`),start:w.describe(`Start function that initiates the job`),body:w.describe(`Job implementation function`),publishEvents:A.boolean().optional().describe(`Enable publishing job execution events for this job`)}),seconds=e=>durationToSeconds(e)??0,xt=A.templateLiteral([A.number().int().positive(),A.enum(vt)]),durationSchema=e=>xt.refine(t=>seconds(t)<=e,{message:`Duration must be at most ${e} seconds`}),St=A.strictObject({maxRetries:A.number().int().min(X.maxRetries.min).max(X.maxRetries.max).describe(`Maximum number of retries (1-10)`),initialBackoff:durationSchema(X.initialBackoffMaxSeconds).describe(`Initial backoff duration (e.g., '1s', '500ms', '1m', max 1h)`),maxBackoff:durationSchema(X.maxBackoffMaxSeconds).describe(`Maximum backoff duration (e.g., '30s', '5m', max 24h)`),backoffMultiplier:A.number().min(X.backoffMultiplierMin).describe(`Backoff multiplier (>= 1)`)}).refine(e=>seconds(e.initialBackoff)<=seconds(e.maxBackoff),{message:`initialBackoff must be less than or equal to maxBackoff`,path:[`initialBackoff`]}).refine(e=>seconds(e.initialBackoff)>0,{message:`initialBackoff must be greater than 0`,path:[`initialBackoff`]}),Ct=A.strictObject({maxConcurrentExecutions:A.number().int().min(1).max(1e3).describe(`Maximum number of concurrent executions (1-1000)`)}),wt=A.string().regex(ht,`Invalid execution policy name: must match [a-z0-9-] (3-63 chars; must start and end with [a-z0-9])`).describe(`Workspace-unique execution policy name embedded in the resource TRN`),Tt=A.string().regex(gt,`Invalid execution policy key: must match [a-z0-9_:.-] (2-64 chars; must start with [a-z0-9] and end with [a-z0-9] or a trailing '*')`).describe(`Execution policy key passed to execJobFunction's executionPolicyKey option`),Et=A.strictObject({name:wt,key:Tt,concurrencyPolicy:Ct.optional().describe(`Optional per-key concurrency cap for job function dispatches matching this policy`)}),Dt=A.strictObject({name:A.string().describe(`Workflow name`),mainJob:bt.describe(`Main job that starts the workflow`),retryPolicy:St.optional().describe(`Retry policy for the workflow`),concurrencyPolicy:Ct.optional().describe(`Concurrency policy for the workflow`),publishEvents:A.boolean().optional().describe(`Enable publishing workflow execution events for this workflow`)});function stripRuntimeStart(t){if(!e(t,`workflow`)||typeof t!=`object`||!t||!(`start`in t))return t;let{start:n,...r}=t;return r}function createWorkflowService(e){let{config:t,baseDir:n}=e,r={},i=[],a=[],
|
|
196
|
+
`,f=createVirtualEntry(`workflow-job:${e.name}`,d,`js`,u),p=safeRealpath(e.sourceFile),m=t.filter(t=>t.name!==e.name&&safeRealpath(t.sourceFile)===p).map(e=>e.exportName),h=[f.plugin,{name:`workflow-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){if(!t.includes(`createWorkflowJob`)&&!t.includes(`createWorkflow`)&&!hasStartCall(t))return null;let r=t;return safeRealpath(n)===p&&(r=transformWorkflowSource(t,e.name,e.exportName,m)),hasStartCall(r)&&(r=transformStartCalls(r,i,n)),r===t?null:{code:r}}}},createTsconfigPathsPlugin({onTsconfigRead:l,cache:c}),W,...a],g=createBundleLog({tsconfig:n}),_=await P.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!o||`inline`,minify:!o||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:n,plugins:h,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(s)]),...g.options});g.assertAllResolved();let v=_.output[0].code;return assertNoForbiddenRuntimeGlobals(v,`Workflow job "${e.name}"`),v}});return[e.name,f]}const ht=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,gt=/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9*]$/,_t=`key must not end with '*'; omit the '*' and set matchType: "prefix" for wildcard policies (the SDK appends '*' automatically).`;function toPlatformExecutionPolicyKey(e,t){return t===`prefix`?`${e}*`:e}const vt=[`ms`,`s`,`m`],yt={ms:1/1e3,s:1,m:60};function durationToSeconds(e){let t=/^(\d+)(ms|s|m)$/.exec(e);return t?.[1]===void 0||t[2]===void 0?null:parseInt(t[1],10)*yt[t[2]]}const X={maxRetries:{min:1,max:10},initialBackoffMaxSeconds:3600,maxBackoffMaxSeconds:86400,backoffMultiplierMin:1},bt=A.strictObject({name:A.string().describe(`Job name (must be unique across the project)`),start:w.describe(`Start function that initiates the job`),body:w.describe(`Job implementation function`),publishEvents:A.boolean().optional().describe(`Enable publishing job execution events for this job`)}),seconds=e=>durationToSeconds(e)??0,xt=A.templateLiteral([A.number().int().positive(),A.enum(vt)]),durationSchema=e=>xt.refine(t=>seconds(t)<=e,{message:`Duration must be at most ${e} seconds`}),St=A.strictObject({maxRetries:A.number().int().min(X.maxRetries.min).max(X.maxRetries.max).describe(`Maximum number of retries (1-10)`),initialBackoff:durationSchema(X.initialBackoffMaxSeconds).describe(`Initial backoff duration (e.g., '1s', '500ms', '1m', max 1h)`),maxBackoff:durationSchema(X.maxBackoffMaxSeconds).describe(`Maximum backoff duration (e.g., '30s', '5m', max 24h)`),backoffMultiplier:A.number().min(X.backoffMultiplierMin).describe(`Backoff multiplier (>= 1)`)}).refine(e=>seconds(e.initialBackoff)<=seconds(e.maxBackoff),{message:`initialBackoff must be less than or equal to maxBackoff`,path:[`initialBackoff`]}).refine(e=>seconds(e.initialBackoff)>0,{message:`initialBackoff must be greater than 0`,path:[`initialBackoff`]}),Ct=A.strictObject({maxConcurrentExecutions:A.number().int().min(1).max(1e3).describe(`Maximum number of concurrent executions (1-1000)`)}),wt=A.string().regex(ht,`Invalid execution policy name: must match [a-z0-9-] (3-63 chars; must start and end with [a-z0-9])`).describe(`Workspace-unique execution policy name embedded in the resource TRN`),Tt=A.string().regex(gt,`Invalid execution policy key: must match [a-z0-9_:.-] (2-64 chars; must start with [a-z0-9] and end with [a-z0-9] or a trailing '*')`).describe(`Execution policy key passed to execJobFunction's executionPolicyKey option`),Et=A.strictObject({name:wt,key:Tt,concurrencyPolicy:Ct.optional().describe(`Optional per-key concurrency cap for job function dispatches matching this policy`)}),Dt=A.strictObject({name:A.string().describe(`Workflow name`),mainJob:bt.describe(`Main job that starts the workflow`),retryPolicy:St.optional().describe(`Retry policy for the workflow`),concurrencyPolicy:Ct.optional().describe(`Concurrency policy for the workflow`),publishEvents:A.boolean().optional().describe(`Enable publishing workflow execution events for this workflow`)});function stripRuntimeStart(t){if(!e(t,`workflow`)||typeof t!=`object`||!t||!(`start`in t))return t;let{start:n,...r}=t;return r}function createWorkflowService(e){let{config:t,baseDir:n}=e,r={},i=[],a=[],c=0,l=!1;return{config:t,get workflows(){return r},get workflowSources(){return i},get jobs(){return a},get fileCount(){return c},loadWorkflows:async()=>{if(l)return;let e=await loadAndCollectJobs(t,n);r=e.workflows,i=e.workflowSources,a=e.jobs,c=e.fileCount,l=!0},printLoadedWorkflows:()=>{if(c!==0){s.newline(),s.log(`Found ${o.highlight(c.toString())} workflow files`);for(let{workflow:e,sourceFile:t}of i){let n=k.relative(process.cwd(),t);s.debug(`Workflow: ${o.successBright(`"${e.name}"`)} loaded from ${o.path(n)}`)}}}}}async function loadAndCollectJobs(e,t){let n={},r=[],i=[];if(e.files.length===0)return{workflows:n,workflowSources:r,jobs:i,fileCount:0};let a=m(e,t),o=a.length,s=new Map,c=await Promise.all(a.map(async e=>{let{jobs:t,workflow:n}=await loadFileContent(e);return{workflowFile:e,jobs:t,workflow:n}}));for(let{workflowFile:e,jobs:t,workflow:a}of c){a&&(r.push({workflow:a,sourceFile:e}),n[e]=a);for(let e of t){let t=s.get(e.name);if(t)throw Error(`Duplicate job name "${e.name}" found:\n - ${t.sourceFile} (export: ${t.exportName})\n - ${e.sourceFile} (export: ${e.exportName})\nEach job must have a unique name.`);s.set(e.name,e),i.push(e)}}return{workflows:n,workflowSources:r,jobs:i,fileCount:o}}async function loadFileContent(t){let n=[],r=null;try{let i=await u(t);for(let[a,o]of Object.entries(i)){if(a==="default"){let t=Dt.safeParse(stripRuntimeStart(o));if(t.success)r=t.data;else if(e(o,[`workflow`,`workflow-job`]))throw t.error;continue}let i=bt.safeParse(o);if(i.success)n.push({name:i.data.name,exportName:a,sourceFile:t,...i.data.publishEvents===void 0?{}:{publishEvents:i.data.publishEvents}});else if(e(o,[`workflow`,`workflow-job`]))throw i.error}}catch(e){let n=k.relative(process.cwd(),t);throw s.error(`${o.error(`Failed to load workflow from`)} ${o.errorBright(n)}`),s.error(String(e)),e}return{jobs:n,workflow:r}}function getApplicationAuthNamespace(e){return e.authService?.config.name??e.config?.auth?.name}function requireApplicationAuthNamespace(e){let t=getApplicationAuthNamespace(e);if(!t)throw Error(`No Auth service configured`);return t}let Z=null;const getDistDir=()=>{let e=process.env.TAILOR_BUILD_OUTPUT_DIR;return e&&e!==Z?Z=e:Z===null&&(Z=e||`.tailor`),Z};function resolveInlineSourcemap(e){if(e!==void 0)return e;let t=c(process.env.TAILOR_INLINE_SOURCEMAP);return t===void 0||t}function resolverBundleKey(e,t){return`${e}:${t}`}const Ot=A.strictObject({name:A.string().regex(/^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/,`Must be 3-30 lowercase alphanumeric characters or hyphens`).describe(`AI Gateway name`),authNamespace:A.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,`Must be 3-63 lowercase alphanumeric characters or hyphens`).optional().describe(`Auth namespace used to resolve request tokens against the workspace's auth. Defaults to the application's own auth service when omitted; omitting it without an Auth service configured is rejected.`),cors:A.array(A.string()).optional().describe("Allowed CORS origins for browser-based clients. Each entry is `*`, `http(s)://*`, `http(s)://*.example.com`, or `http(s)://app.example.com`, optionally with `:port`. Empty list disables cross-origin access.")}),kt=/^(\*|[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;function containsAllEmailDomains(e){return e.some(e=>e.trim()===`*`)}function hasImplicitAllEmailDomains(e){return e?.useNonEmailIdentifier===!0?!1:!e?.allowedEmailDomains||e.allowedEmailDomains.length===0}function normalizeIdPGqlOperations(e){return e===`query`?{create:!1,update:!1,delete:!1,read:!0,sendPasswordResetEmail:!1,requestMfaSettingsUrl:!0,unenrollMfa:!1}:e}const At=A.union([A.literal(`query`),A.strictObject({create:A.boolean().optional().describe(`Enable _createUser mutation (default: true)`),update:A.boolean().optional().describe(`Enable _updateUser mutation (default: true)`),delete:A.boolean().optional().describe(`Enable _deleteUser mutation (default: true)`),read:A.boolean().optional().describe(`Enable _users and _user queries (default: true)`),sendPasswordResetEmail:A.boolean().optional().describe(`Enable _sendPasswordResetEmail mutation (default: true)`),requestMfaSettingsUrl:A.boolean().optional().describe(`Enable _requestMfaSettingsUrl query (default: true)`),unenrollMfa:A.boolean().optional().describe(`Enable _unenrollMfa mutation (default: true)`)})]).describe(`Configuration for GraphQL operations on IdP users.
|
|
197
197
|
All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeIdPGqlOperations(e)),jt=A.enum([`en`,`ja`]).describe(`IdP UI language`),Mt=A.strictObject({useNonEmailIdentifier:A.boolean().optional().describe(`Use non-email identifier for usernames`),allowSelfPasswordReset:A.boolean().optional().describe(`Allow users to reset their own passwords`),passwordRequireUppercase:A.boolean().optional().describe(`Require uppercase letters in passwords`),passwordRequireLowercase:A.boolean().optional().describe(`Require lowercase letters in passwords`),passwordRequireNonAlphanumeric:A.boolean().optional().describe(`Require non-alphanumeric characters in passwords`),passwordRequireNumeric:A.boolean().optional().describe(`Require numeric characters in passwords`),passwordMinLength:A.number().int().refine(e=>e>=6&&e<=30,{message:`passwordMinLength must be between 6 and 30`}).optional().describe(`Minimum password length (6-30)`),passwordMaxLength:A.number().int().refine(e=>e>=6&&e<=4096,{message:`passwordMaxLength must be between 6 and 4096`}).optional().describe(`Maximum password length (6-4096)`),allowedEmailDomains:A.array(A.string().regex(kt,`must be a hostname, or * to allow all email domains`)).max(100,`allowedEmailDomains accepts at most 100 entries`).refine(e=>new Set(e.map(e=>e.toLowerCase())).size===e.length,{message:`allowedEmailDomains entries must be unique, compared case-insensitively`}).refine(e=>e.length<=1||!containsAllEmailDomains(e),{message:`allowedEmailDomains cannot contain other entries when * is set`}).optional().describe(`Restrict registration to these email domains. A lone * entry allows every domain`),allowGoogleOauth:A.boolean().optional().describe(`Enable Google OAuth login`),allowMicrosoftOauth:A.boolean().optional().describe(`Enable Microsoft OAuth login`),disablePasswordAuth:A.boolean().optional().describe(`Disable password-based authentication`),enableMfa:A.boolean().optional().describe(`Make TOTP MFA available for users in this namespace`),requireMfa:A.boolean().optional().describe(`Require TOTP MFA enrollment and challenge for password-authenticated users (requires enableMfa)`),allowedReturnOrigins:A.array(A.string().regex(/^(https?:\/\/[a-zA-Z0-9.-]+(:[0-9]+)?|[a-z0-9][a-z0-9-]{1,61}[a-z0-9]:url)$/,`must be an http(s) origin like "https://app.example.com" (scheme + host + optional port, no path/query/fragment) or a static-website placeholder like "<name>:url"`)).optional().describe(`Application origins (scheme + host + optional port) allowed as MFA self-service return targets`),mfaIssuer:A.string().max(64,`mfaIssuer must be 64 characters or less`).optional().describe(`Label shown next to the user account in authenticator apps`)}).refine(e=>e.passwordMinLength===void 0||e.passwordMaxLength===void 0||e.passwordMinLength<=e.passwordMaxLength,{message:`passwordMinLength must be less than or equal to passwordMaxLength`,path:[`passwordMinLength`]}).refine(e=>!e.allowedEmailDomains||e.allowedEmailDomains.length===0||!e.useNonEmailIdentifier,{message:`allowedEmailDomains cannot be set when useNonEmailIdentifier is true`,path:[`allowedEmailDomains`]}).refine(e=>e.allowGoogleOauth===void 0||e.allowGoogleOauth===!1||!e.useNonEmailIdentifier,{message:`allowGoogleOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowGoogleOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowGoogleOauth requires a non-empty allowedEmailDomains (["*"] to allow every domain)`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowMicrosoftOauth||!e.useNonEmailIdentifier,{message:`allowMicrosoftOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowMicrosoftOauth requires a non-empty allowedEmailDomains (["*"] to allow every domain)`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.disablePasswordAuth===!0,{message:`allowMicrosoftOauth requires disablePasswordAuth to be enabled`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.disablePasswordAuth||e.allowGoogleOauth===!0||e.allowMicrosoftOauth===!0,{message:`disablePasswordAuth requires allowGoogleOauth or allowMicrosoftOauth to be enabled`,path:[`disablePasswordAuth`]}).refine(e=>!e.disablePasswordAuth||!e.allowSelfPasswordReset,{message:`disablePasswordAuth cannot be used with allowSelfPasswordReset`,path:[`disablePasswordAuth`]}).refine(e=>!e.requireMfa||e.enableMfa===!0,{message:`requireMfa requires enableMfa to be enabled`,path:[`requireMfa`]}).refine(e=>!e.enableMfa||e.allowedReturnOrigins&&e.allowedReturnOrigins.length>0,{message:`enableMfa requires allowedReturnOrigins to list at least one origin so MFA self-service has a valid return target`,path:[`enableMfa`]}),Nt=A.string().max(200,`must be 200 characters or less`).regex(/^[^\r\n]*$/,`must not contain newline characters`),Pt=A.strictObject({fromName:Nt.optional().describe(`Default sender display name for emails`),passwordResetSubject:Nt.optional().describe(`Default subject for password reset emails`)}).describe(`Namespace-level email configuration defaults`),Q=A.union([A.string(),A.boolean(),A.array(A.string()).readonly(),A.array(A.boolean()).readonly(),A.strictObject({user:A.string()}),A.strictObject({idpUser:A.enum([`id`,`name`,`disabled`])}),A.strictObject({oldIdpUser:A.enum([`id`,`name`,`disabled`])}),A.strictObject({newIdpUser:A.enum([`id`,`name`,`disabled`])})]),Ft=A.enum([`=`,`!=`,`in`,`not in`]),It=A.tuple([Q,Ft,Q]).readonly(),$=A.union([A.strictObject({conditions:A.union([It,A.array(It).readonly()]),description:A.string().optional(),permit:A.boolean().optional()}),A.tuple([Q,Ft,Q]).readonly(),A.tuple([Q,Ft,Q,A.boolean()]).readonly(),A.array(A.union([It,A.boolean()])).refine(e=>{let t=e.findIndex(e=>typeof e==`boolean`);return t===-1||t===e.length-1},{message:`Boolean permit flag must only appear at the end`}).readonly()]),Lt=A.strictObject({create:A.array($).readonly(),read:A.array($).readonly(),update:A.array($).readonly(),delete:A.array($).readonly(),sendPasswordResetEmail:A.array($).readonly().optional(),unenrollMfa:A.array($).readonly().optional()}).describe(`Per-operation permission policies for IdP users`),Rt=A.strictObject({name:A.string().describe(`IdP service name`),authorization:A.union([A.literal(`insecure`),A.literal(`loggedIn`),A.strictObject({cel:A.string()})]).optional().describe(`Authorization mode for IdP API access`),clients:A.array(A.string()).describe(`OAuth2 client names that can use this IdP`),lang:jt.optional().describe(`UI language for IdP pages`),userAuthPolicy:Mt.transform(e=>Mt.parse(e??{})).optional().describe(`User authentication policy configuration`),publishEvents:A.boolean().optional().describe(`Enable publishing user lifecycle events`),gqlOperations:At.optional().describe(`Configure which GraphQL operations are enabled`),emailConfig:Pt.optional().describe(`Namespace-level email configuration defaults`),permission:Lt.optional().describe(`Per-operation permission policies for IdP users`)}).refine(e=>!e.userAuthPolicy?.enableMfa||e.gqlOperations?.unenrollMfa===!1||e.permission!==void 0&&e.permission.unenrollMfa!==void 0,{message:`permission.unenrollMfa must be set explicitly when userAuthPolicy.enableMfa is true (set [{ conditions: [...], permit: true }] to allow, or [] to deny all). permission itself must also be defined. The requirement is only relaxed when gqlOperations.unenrollMfa is false.`,path:[`permission`,`unenrollMfa`]}).refine(e=>!e.permission||e.userAuthPolicy?.disablePasswordAuth===!0||e.gqlOperations?.sendPasswordResetEmail===!1||e.permission.sendPasswordResetEmail!==void 0,{message:`permission.sendPasswordResetEmail must be set explicitly when password authentication is enabled (set [{ conditions: [...], permit: true }] to allow, or [] to deny; only optional when userAuthPolicy.disablePasswordAuth is true or gqlOperations.sendPasswordResetEmail is false)`,path:[`permission`,`sendPasswordResetEmail`]}),zt=A.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/),Bt=A.record(zt,A.string().nullish()),Vt=A.strictObject({vaults:A.record(zt,Bt),options:A.strictObject({ignoreNullishValues:A.boolean()})}),Ht=A.strictObject({name:A.string().describe(`Static website name`),description:A.string().optional().describe(`Static website description`),allowedIpAddresses:A.array(A.string()).optional().describe(`IP addresses allowed to access the website`),customDomains:A.array(A.string()).optional().describe(`Custom domains for the static website`)}),Ut=/^[a-z0-9]+$/,Wt=/^[A-Za-z_][A-Za-z0-9_]*$/;function checkWaitPointKey(e){let{key:r,declaredBy:a}=e,o=r.split(`-`),s=o.filter(i);if(s.length>0&&a!==`define`)return a===`property`?`Invalid wait point key "${r}": $params cannot come from a property name. Pass the key to define instead, e.g. define.for("${r}")<Payload, Result>().`:`Invalid wait point key "${r}": createWaitPoint takes its type arguments first, which stops TypeScript inferring the key as a literal, so it cannot type the $params. Declare it through createWaitPoints instead: createWaitPoints((define) => ({ myWaitPoint: define.for("${r}")<Payload, Result>() })).`;let c=new Set,l=0;for(let e of o){if(e.startsWith(`$`)){let t=e.slice(1);if(!Wt.test(t))return`Invalid wait point key "${r}": "${e}" is not a usable parameter name. Use letters, digits and underscores, starting with a letter or underscore.`;if(c.has(t))return`Invalid wait point key "${r}": parameter "$${t}" appears more than once.`;c.add(t);continue}if(e!==``){if(!Ut.test(e))return`Invalid wait point key "${r}": segment "${e}" may only contain [a-z0-9]. Wait point keys accept ${n}, with $params standing in for runtime values.`;l+=1}}if(l===0&&s.length>0)return r.startsWith(`-`)||r.endsWith(`-`)?`Invalid wait point key "${r}": must match ${n}.`:`Invalid wait point key "${r}": it needs at least one literal segment alongside its $params, otherwise the key carries no identity of its own and can collide with an unrelated wait point.`;if(s.length===0)return t.test(r)?void 0:`Invalid wait point key "${r}": must match ${n}.`;let u=o.map(e=>e.startsWith(`$`)?`0`:e).join(`-`);return u.length>63?`Wait point key "${r}" cannot fit in 63 characters: even single-character parameter values produce ${u.length}.`:t.test(u)?void 0:`Invalid wait point key "${r}": must match ${n}.`}function collectWaitPointKeyFailures(e){let t=[],n=new Set;for(let r of e){let e=`${r.declaredBy} ${r.key}`;if(n.has(e))continue;n.add(e);let i=checkWaitPointKey(r);i&&t.push(i)}return t}function defineTailorDB(e,t,n){let r=[],i=[],a=[];if(!e)return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a};for(let[o,s]of Object.entries(e)){if(`external`in s)i.push(o);else{let e=createTailorDBService({namespace:o,config:C.parse(s),pluginManager:n,baseDir:t});r.push(e)}a.push({Type:`tailordb`,Name:o})}return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a}}function defineResolver(e,t){let n=[],r=[];if(!e)return{resolverServices:n,subgraphs:r};for(let[i,a]of Object.entries(e)){if(!(`external`in a)){let e=createResolverService(i,a,t);n.push(e)}r.push({Type:`pipeline`,Name:i})}return{resolverServices:n,subgraphs:r}}function stripIdpProviderHelper(e){let t=e;if(typeof t.provider!=`function`)return e;let{provider:n,...r}=t;return r}function defineIdp(e){let t=[],n=[];if(!e)return{idpServices:t,subgraphs:n};let r=new Set;return e.forEach(e=>{let i=e.name;if(r.has(i))throw Error(`IdP with name "${i}" already defined.`);if(r.add(i),!(`external`in e)){let n=Rt.parse(stripIdpProviderHelper(e));t.push(n)}n.push({Type:`idp`,Name:i})}),{idpServices:t,subgraphs:n}}function defineAuth(e,t,n){let r=[];if(!e)return{authService:void 0,subgraphs:r};let i;return`external`in e||(i=createAuthService(l.parse(e),t,n)),r.push({Type:`auth`,Name:e.name}),{authService:i,subgraphs:r}}function defineExecutor(e,t,n){if(e||n)return S({config:e??{files:[]},baseDir:t})}function defineWorkflow(e,t){if(e)return createWorkflowService({config:e,baseDir:t})}function defineHttpAdapterService(e,t){if(e)return createHttpAdapterService({config:e,baseDir:t})}function stripStaticWebsiteUrlHelper(e){let t=e;if(t.url!==`${e.name}:url`)return e;let{url:n,...r}=t;return r}function defineStaticWebsites(e){let t=[],n=new Set;return(e??[]).forEach(e=>{let r=Ht.parse(stripStaticWebsiteUrlHelper(e));if(n.has(r.name))throw Error(`Static website with name "${r.name}" already defined.`);n.add(r.name),t.push(r)}),t}function defineAIGateways(e,t){let n=[],r=new Set;return(e??[]).forEach(e=>{let i=Ot.parse(e);if(r.has(i.name))throw Error(`AI Gateway with name "${i.name}" already defined.`);if(r.add(i.name),i.authNamespace===void 0){if(!t)throw Error(`AI Gateway "${i.name}" has no "authNamespace" and no Auth service is configured to default to. Define an Auth service, or set "authNamespace" explicitly.`);i.authNamespace=t}n.push(i)}),n}function parseSecretManager(e){if(!e)return{secrets:[],ignoreNullishValues:!1};let t=Vt.parse(e),{ignoreNullishValues:n}=t.options,r=Object.entries(t.vaults).map(([e,t])=>({vaultName:e,secrets:Object.entries(t).map(([e,t])=>({name:e,value:t}))}));if(!n){for(let e of r)for(let t of e.secrets)if(t.value==null)throw Error(`Secret "${e.vaultName}/${t.name}" has no value. Use { ignoreNullishValues: true } option in defineSecretManager() to skip secrets without values.`)}return{secrets:r,ignoreNullishValues:n}}function defineServices(e,t,n){let r=defineTailorDB(e.db,t,n),i=defineResolver(e.resolver,t),a=defineIdp(e.idp),o=defineAuth(e.auth,r.tailorDBServices,r.externalTailorDBNamespaces),s=defineStaticWebsites(e.staticWebsites),c=defineAIGateways(e.aiGateways,getApplicationAuthNamespace({authService:o.authService,config:e})),{secrets:l,ignoreNullishValues:u}=parseSecretManager(e.secrets);return{tailordbResult:r,resolverResult:i,idpResult:a,authResult:o,staticWebsiteServices:s,aiGatewayServices:c,secrets:l,ignoreNullishValues:u}}function buildApplication(e){let t={name:e.config.name,id:e.config.id,config:e.config,subgraphs:[...e.tailordbResult.subgraphs,...e.resolverResult.subgraphs,...e.idpResult.subgraphs,...e.authResult.subgraphs],tailorDBServices:e.tailordbResult.tailorDBServices,externalTailorDBNamespaces:e.tailordbResult.externalTailorDBNamespaces,resolverServices:e.resolverResult.resolverServices,idpServices:e.idpResult.idpServices,authService:e.authResult.authService,executorService:e.executorService,workflowService:e.workflowService,httpAdapterService:e.httpAdapterService,staticWebsiteServices:e.staticWebsiteServices,aiGatewayServices:e.aiGatewayServices,secrets:e.secrets,ignoreNullishValues:e.ignoreNullishValues,env:e.env,get applications(){return[t]}};return t}function defineApplication(e){let{config:t,pluginManager:n}=e,r=k.dirname(t.path),i=defineServices(t,r,n),a=defineExecutor(t.executor,r,!1),o=defineWorkflow(t.workflow,r),s=defineHttpAdapterService(t.httpAdapter,r);return buildApplication({config:t,...i,executorService:a,workflowService:o,httpAdapterService:s,env:t.env??{}})}function generatePluginFilesIfNeeded(e,t,n){if(!e)return[];let r=new Map;for(let e of t){let t=e.typeSourceInfo;for(let[e,n]of Object.entries(t))n.filePath&&r.set(e,{filePath:n.filePath,exportName:n.exportName})}return e.generatePluginFiles({outputDir:k.join(getDistDir(),`plugin`),sourceTableInfoMap:r,configPath:n,tableGenerator:generatePluginTableFiles,executorGenerator:generatePluginExecutorFiles})}function assertWaitPointKeys(){let e=collectWaitPointKeyFailures(r());if(e.length!==0)throw Error(e.join(`
|
|
198
198
|
`))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r}=e,i=k.dirname(t.path),{tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p}=defineServices(t,i,n);for(let e of a.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();assertUniqueLocalTailorDBTypeNames({tailorDBServices:a.tailorDBServices});let m=generatePluginFilesIfNeeded(n,a.tailorDBServices,t.path),h=defineExecutor(t.executor,i,m.length>0),g=defineWorkflow(t.workflow,i);g&&await g.loadWorkflows();let _=defineHttpAdapterService(t.httpAdapter,i);_&&await _.loadAdapters();let v=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:l.authService,config:t}),i),y=resolveInlineSourcemap(t.inlineSourcemap),b=resolveBundleLogLevel(t.logLevel),x=createTsconfigLookupCache(),S={resolvers:new Map,executors:new Map,workflowJobs:new Map,authHooks:new Map};for(let e of o.resolverServices){let t=await bundleResolvers({namespace:e.namespace,config:e.config,baseDir:i,defaultPermission:e.defaultPermission,startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,tsconfigCache:x});for(let[n,r]of t)S.resolvers.set(resolverBundleKey(e.namespace,n),r)}h&&(S.executors=await bundleExecutors({config:h.config,startContext:v,additionalFiles:[...m],cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x}));let C;if(g&&g.jobs.length>0){let e=g.workflowSources.map(e=>e.workflow.mainJob.name);C=await bundleWorkflowJobs(g.jobs,e,t.env??{},v,i,r,y,b,x),S.workflowJobs=C.bundledCode}let w;if(_&&_.adapters.length>0&&(w=await bundleHttpAdapters(_.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),i,r,b,x)),l.authService?.config.hooks?.beforeLogin){let e=l.authService.config.name;S.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:t.env??{},startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x})}for(let e of o.resolverServices)await e.loadResolvers();return h&&(await h.loadExecutors(),m.length>0&&await h.loadPluginExecutorFiles([...m])),assertWaitPointKeys(),g&&g.printLoadedWorkflows(),_&&_.printLoadedAdapters(),s.newline(),{application:buildApplication({config:t,tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,executorService:h,workflowService:g,httpAdapterService:_,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p,env:t.env??{}}),workflowBuildResult:C,httpAdapterBuildResult:w,bundledScripts:S}}export{isDefaultPlatform as $,resolveTSConfigWithFallback as A,Ce as B,createPermissionNormalizer as C,K as D,qe as E,createBundleLog as F,fetchPlatformMachineUserToken as G,fetchAllTolerant as H,createBundleCache as I,getOAuth2ClientId as J,fetchUserInfo as K,hashContent as L,composeFunctionTreeshakeOptions as M,createLogLevelTreeshakeOptions as N,createGeneratedEntryResolverPlugin as O,resolveBundleLogLevel as P,initOperatorClient as Q,hashFile as R,assertUniqueTailorDBTypeNamesWithExternal as S,stringifyFunction as T,fetchMachineUserToken as U,fetchAll as V,fetchPaged as W,getPlatformBaseUrl as X,getOrNull as Y,initOAuth2Client as Z,q as _,resolverBundleKey as a,withErrorDiagnostics as at,buildResolverValidatedInputExpr as b,getApplicationAuthNamespace as c,L as ct,bt as d,isNotFoundError as et,_t as f,Y as g,pt as h,hasImplicitAllEmailDomains as i,getErrorDiagnostics as it,W as j,createTsconfigPathsPlugin as k,requireApplicationAuthNamespace as l,resolveResolverDefaultPermissionForFile as m,generatePluginFilesIfNeeded as n,rememberPlatformConfigForToken as nt,resolveInlineSourcemap as o,byName as ot,toPlatformExecutionPolicyKey as p,getConsoleBaseUrl as q,loadApplication as r,resolveStaticWebsiteUrls as rt,getDistDir as s,createApplyLimiter as st,defineApplication as t,normalizeBaseUrl as tt,Et as u,buildExecutorArgsExpr as v,hasOmittedPermit as w,assertUniqueLocalTailorDBTypeNames as x,buildResolverOperationHookExpr as y,closeConnectionPool as z};
|
|
199
|
-
//# sourceMappingURL=application-
|
|
199
|
+
//# sourceMappingURL=application-ChuNPwnl.mjs.map
|