@tailor-platform/sdk 2.18.0 → 2.19.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 +14 -0
- package/dist/{application-DEkgf2w1.mjs → application-BYlhYQyh.mjs} +2 -2
- package/dist/{application-DEkgf2w1.mjs.map → application-BYlhYQyh.mjs.map} +1 -1
- package/dist/application-KZRJHv2j.mjs +1 -0
- package/dist/cli/commands/deploy/event-subscriptions.d.mts +1 -0
- package/dist/cli/commands/generate/service.d.mts +1 -0
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/main.mjs +3 -3
- package/dist/cli/services/executor/service.d.mts +1 -0
- package/dist/completion/zsh-worker.zsh +1 -1
- package/dist/configure/index.d.mts +7 -7
- package/dist/configure/index.mjs +1 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/types/field.types.d.mts +24 -4
- package/dist/configure/types/type.d.mts +1 -0
- package/dist/date-B7-oyTGE.mjs +2 -0
- package/dist/date-B7-oyTGE.mjs.map +1 -0
- package/dist/field-parse-BbNyotv5.mjs +2 -0
- package/dist/field-parse-BbNyotv5.mjs.map +1 -0
- package/dist/{manager-C26Gi1bX.mjs → manager-qfbUL7ru.mjs} +2 -2
- package/dist/{manager-C26Gi1bX.mjs.map → manager-qfbUL7ru.mjs.map} +1 -1
- package/dist/parser/service/auth/schema.d.mts +1 -0
- package/dist/plugin/index.mjs +1 -1
- package/dist/{register-ts-hook-BD3ArLqY.mjs → register-ts-hook-Djjnj5R8.mjs} +3 -3
- package/dist/{register-ts-hook-BD3ArLqY.mjs.map → register-ts-hook-Djjnj5R8.mjs.map} +1 -1
- package/dist/runtime/date.d.mts +3 -3
- package/dist/runtime/field-parse.d.mts +1 -0
- package/dist/runtime/index.d.mts +2 -1
- package/dist/runtime/index.mjs +1 -1
- package/dist/runtime/temporal.d.mts +31 -0
- package/dist/{schema-DRyQEabV.mjs → schema-BKvcWdVf.mjs} +2 -2
- package/dist/{schema-DRyQEabV.mjs.map → schema-BKvcWdVf.mjs.map} +1 -1
- package/dist/service-BgrEteZ2.mjs +1 -0
- package/dist/service-CuqkHP1r.mjs +7 -0
- package/dist/service-CuqkHP1r.mjs.map +1 -0
- package/dist/types/field.generated.d.mts +1 -1
- package/dist/types/helpers.d.mts +8 -6
- package/dist/utils/test/index.mjs +1 -1
- package/dist/vitest/environment.mjs +1 -1
- package/dist/vitest/environment.mjs.map +1 -1
- package/docs/github-actions.md +22 -15
- package/docs/migration/v3.md +0 -33
- package/docs/services/resolver.md +53 -1
- package/docs/testing.md +17 -0
- package/package.json +5 -3
- package/dist/application-Dl94fzpm.mjs +0 -1
- package/dist/date-CGBZbMW5.mjs +0 -2
- package/dist/date-CGBZbMW5.mjs.map +0 -1
- package/dist/field-parse-CzlKC4b7.mjs +0 -2
- package/dist/field-parse-CzlKC4b7.mjs.map +0 -1
- package/dist/service-B3OiWCYg.mjs +0 -1
- package/dist/service-eM7Fd8zS.mjs +0 -7
- package/dist/service-eM7Fd8zS.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @tailor-platform/sdk
|
|
2
2
|
|
|
3
|
+
## 2.19.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#2369](https://github.com/tailor-platform/sdk/pull/2369) [`f5a3ad8`](https://github.com/tailor-platform/sdk/commit/f5a3ad8212dc5eec1ce54265d7a841aea96c7944) Thanks [@toiroakr](https://github.com/toiroakr)! - Add `as: "temporal"` to `t.date`, `t.datetime`, and `t.time`, using `Temporal.PlainDate`, `Temporal.Instant`, and `Temporal.PlainTime` respectively. Extend `as: "date"` to datetime and time fields, converting datetime input to a `Date` and time input to a `Date` on 1970-01-01 UTC. Time output uses hours/minutes (UTC for Date) and truncates seconds and fractions without rounding. Existing defaults remain unchanged. Import `Temporal` from `@tailor-platform/sdk/runtime` for constructors and types without changing TypeScript `lib` settings. The `tailor-runtime` Vitest environment installs a Temporal polyfill only when the runtime lacks it; deployed functions use native Temporal.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#2332](https://github.com/tailor-platform/sdk/pull/2332) [`766a3f9`](https://github.com/tailor-platform/sdk/commit/766a3f91acaf7fa9cd643f7c2bf9fe6055d578c5) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @clack/prompts to v1.8.0
|
|
12
|
+
|
|
13
|
+
- [#2378](https://github.com/tailor-platform/sdk/pull/2378) [`867d586`](https://github.com/tailor-platform/sdk/commit/867d586a8b08a27f0b1a26dec2f18efa7963e375) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency zod to v4.6.5
|
|
14
|
+
|
|
15
|
+
- [#2383](https://github.com/tailor-platform/sdk/pull/2383) [`8d65e44`](https://github.com/tailor-platform/sdk/commit/8d65e44c5f4462637a9f3b60a2c0241b8edbb098) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @napi-rs/keyring to v2.1.0
|
|
16
|
+
|
|
3
17
|
## 2.18.0
|
|
4
18
|
|
|
5
19
|
### 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{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 R=new WeakMap;function withErrorDiagnostics(e,t){return R.set(e,{...R.get(e),...t}),e}function getErrorDiagnostics(e){return{...e instanceof N?{suggestion:rpcSuggestion(e.code)}:{},...R.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 Se=`https://api.tailor.tech`,Ce=`/.well-known/oauth-authorization-server/oauth2/platform`,z=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?z.set(e,n):z.delete(e)}function getPlatformConfigForToken(e){return z.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(Se)}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:Ce})}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 we=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(!we.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<Ee;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 Te=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&&Te.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 Ee=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}const De=new Set([`ERR_STREAM_PREMATURE_CLOSE`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`]);function isTransportDisconnectError(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&De.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 Oe=new Set([`name`,`id`]),ke=[`Name`,`Id`,`Namespace`],Ae=`name`,je={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:Oe.has(e)||ke.some(t=>e.endsWith(t))||(je[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[Ae];typeof e==`string`&&e!==``&&(n[`${r}.${Ae}`]=e)}return n}const B=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,B);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?B:Math.min(n-i.length,B);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:Ce}).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`
|
|
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-CuqkHP1r.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 R=new WeakMap;function withErrorDiagnostics(e,t){return R.set(e,{...R.get(e),...t}),e}function getErrorDiagnostics(e){return{...e instanceof N?{suggestion:rpcSuggestion(e.code)}:{},...R.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 Se=`https://api.tailor.tech`,Ce=`/.well-known/oauth-authorization-server/oauth2/platform`,z=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?z.set(e,n):z.delete(e)}function getPlatformConfigForToken(e){return z.get(e)}function getPlatformBaseUrl(e={}){return normalizeBaseUrl(e.platformUrl??getEnvPlatformUrl()??`https://api.tailor.tech`)}function isDefaultPlatform(e){return getPlatformBaseUrl(e)===normalizeBaseUrl(Se)}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:Ce})}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 we=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(!we.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<Ee;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 Te=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&&Te.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 Ee=3;function waitRetryBackoff(e){let t=500*2**(e-1)*(1+.1*(Math.random()*2-1));return new Promise(e=>setTimeout(e,t))}const De=new Set([`ERR_STREAM_PREMATURE_CLOSE`,`ECONNRESET`,`ETIMEDOUT`,`EPIPE`]);function isTransportDisconnectError(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`&&De.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 Oe=new Set([`name`,`id`]),ke=[`Name`,`Id`,`Namespace`],Ae=`name`,je={GetMetadata:[`trn`],SetMetadata:[`trn`],AddCustomDomain:[`domain`],GetCustomDomain:[`domain`],RemoveCustomDomain:[`domain`],CreateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],UpdateWorkflowJobFunctionExecutionPolicy:[`executionPolicyKey`],GetWorkflowJobFunctionExecutionPolicyByKey:[`executionPolicyKey`]};function isIdentityKey(e,t){return e.startsWith(`$`)?!1:Oe.has(e)||ke.some(t=>e.endsWith(t))||(je[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[Ae];typeof e==`string`&&e!==``&&(n[`${r}.${Ae}`]=e)}return n}const B=1e3;async function fetchAll(e){let t=[],n=``;for(;;){let[r,i]=await e(n,B);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?B:Math.min(n-i.length,B);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:Ce}).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
|
|
@@ -196,4 +196,4 @@ globalThis.transform = __adapter.output;
|
|
|
196
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}),G,...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{initOAuth2Client as $,createGeneratedEntryResolverPlugin as A,hashFile as B,findUndefinedReferences as C,qe as D,stringifyFunction as E,createLogLevelTreeshakeOptions as F,fetchMachineUserToken as G,Se as H,resolveBundleLogLevel as I,fetchUserInfo as J,fetchPaged as K,createBundleLog as L,resolveTSConfigWithFallback as M,G as N,K as O,composeFunctionTreeshakeOptions as P,getPlatformBaseUrl as Q,createBundleCache as R,assertUniqueTailorDBTypeNamesWithExternal as S,hasOmittedPermit as T,fetchAll as U,closeConnectionPool as V,fetchAllTolerant as W,getOAuth2ClientId as X,getConsoleBaseUrl as Y,getOrNull as Z,q as _,resolverBundleKey as a,resolveStaticWebsiteUrls as at,buildResolverValidatedInputExpr as b,getApplicationAuthNamespace as c,byName as ct,bt as d,initOperatorClient as et,_t as f,Y as g,pt as h,hasImplicitAllEmailDomains as i,rememberPlatformConfigForToken as it,createTsconfigPathsPlugin as j,assertParsableExpression as k,requireApplicationAuthNamespace as l,createApplyLimiter as lt,resolveResolverDefaultPermissionForFile as m,generatePluginFilesIfNeeded as n,isNotFoundError as nt,resolveInlineSourcemap as o,getErrorDiagnostics as ot,toPlatformExecutionPolicyKey as p,fetchPlatformMachineUserToken as q,loadApplication as r,normalizeBaseUrl as rt,getDistDir as s,withErrorDiagnostics as st,defineApplication as t,isDefaultPlatform as tt,Et as u,L as ut,buildExecutorArgsExpr as v,createPermissionNormalizer as w,assertUniqueLocalTailorDBTypeNames as x,buildResolverOperationHookExpr as y,hashContent as z};
|
|
199
|
-
//# sourceMappingURL=application-
|
|
199
|
+
//# sourceMappingURL=application-BYlhYQyh.mjs.map
|