@tailor-platform/sdk 2.38.0 → 2.39.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 +64 -0
- package/dist/{application-Bz80INH4.mjs → application-OeNMQzOC.mjs} +1 -1
- package/dist/{application-CeqD1OK-.mjs → application-mNOJx9Y2.mjs} +4 -4
- package/dist/{application-CeqD1OK-.mjs.map → application-mNOJx9Y2.mjs.map} +1 -1
- package/dist/cli/commands/executor/trigger.d.mts +1 -0
- package/dist/cli/commands/generate/seed/bundler.d.mts +7 -5
- package/dist/cli/commands/workspace/transform.d.mts +1 -2
- package/dist/cli/lib.d.mts +4 -2
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +30 -30
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/build-options.d.mts +13 -0
- package/dist/cli/shared/client.d.mts +1 -0
- package/dist/cli/shared/script-workflow.d.mts +65 -0
- package/dist/cli/shared/seed-chunker.d.mts +3 -3
- package/dist/{client-DOQv-BP8.mjs → client-CqiPQgMG.mjs} +2 -2
- package/dist/client-CqiPQgMG.mjs.map +1 -0
- package/dist/client-DO2_Xz_z.mjs +1 -0
- package/dist/completion/zsh-worker.zsh +61 -6
- package/dist/configure/index.mjs +1 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/auth/types.d.mts +20 -3
- package/dist/configure/services/executor/trigger/webhook.d.mts +8 -1
- package/dist/{context-OOASEQLA.mjs → context-CYBcQZyO.mjs} +1 -1
- package/dist/{context-DSi5kfqr.mjs → context-aAgFGDBD.mjs} +4 -4
- package/dist/{context-DSi5kfqr.mjs.map → context-aAgFGDBD.mjs.map} +1 -1
- package/dist/{register-ts-hook-CXYYYgCl.mjs → register-ts-hook-CORbtrSN.mjs} +82 -71
- package/dist/register-ts-hook-CORbtrSN.mjs.map +1 -0
- package/dist/{service-DB-RHn25.mjs → service-Bkz_TB5v.mjs} +2 -2
- package/dist/{service-DB-RHn25.mjs.map → service-Bkz_TB5v.mjs.map} +1 -1
- package/dist/service-Dffd4how.mjs +1 -0
- package/dist/syntax-diagnostic-BQgOV8Fz.mjs +2 -0
- package/dist/syntax-diagnostic-BQgOV8Fz.mjs.map +1 -0
- package/dist/validation-errors-ChvCG6wT.mjs +3 -0
- package/dist/validation-errors-ChvCG6wT.mjs.map +1 -0
- package/dist/vitest/index.mjs +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/docs/cli/application.md +3 -3
- package/docs/cli/executor.md +13 -17
- package/docs/cli/function.md +1 -1
- package/docs/cli/workspace.md +2 -3
- package/docs/configuration.md +28 -0
- package/docs/github-actions.md +82 -15
- package/docs/migration/v2.md +5 -3
- package/docs/services/auth.md +5 -0
- package/docs/services/executor.md +2 -0
- package/docs/services/tailordb/migration.md +3 -3
- package/package.json +12 -12
- package/dist/client-CHXix4LD.mjs +0 -1
- package/dist/client-DOQv-BP8.mjs.map +0 -1
- package/dist/register-ts-hook-CXYYYgCl.mjs.map +0 -1
- package/dist/service-DsAWXbVX.mjs +0 -1
- package/dist/validation-errors-DqCeUW4L.mjs +0 -3
- package/dist/validation-errors-DqCeUW4L.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,69 @@
|
|
|
1
1
|
# @tailor-platform/sdk
|
|
2
2
|
|
|
3
|
+
## 2.39.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#2958](https://github.com/tailor-platform/sdk/pull/2958) [`a955502`](https://github.com/tailor-platform/sdk/commit/a955502ee55cdb231d1a89276c6d3a8d240c58c6) Thanks [@toiroakr](https://github.com/toiroakr)! - `defineAuth` results now have `asExternal()`, which references an Auth service defined in another app of the same repository as an external one: `auth: coreAuth.asExternal()`. It takes over the name and the machine users, so the referencing app follows renames of both and gets the machine user names in its generated `tailor.d.ts`. A misspelled `invoker` there is then a type error, which `{ name: "...", external: true }` could not provide because it leaves the names empty. Hooks, OAuth2 clients, and the rest of the definition are not taken over, so the referencing app does not deploy them again.
|
|
8
|
+
|
|
9
|
+
- [#2952](https://github.com/tailor-platform/sdk/pull/2952) [`93c373f`](https://github.com/tailor-platform/sdk/commit/93c373f539154c65474531579c14391420c374aa) Thanks [@toiroakr](https://github.com/toiroakr)! - `tailor deploy` now stops with `INVOKER_MACHINE_USER_NOT_FOUND` when a string `invoker` of a resolver or an executor names a machine user that does not exist in its Auth service. Before, a misspelled name passed `tsc` and `deploy`, and failed with `machine user not found` when the resolver or executor first ran. When a config deployed in the same run defines the Auth service, the machine users it lists are the ones accepted, because deploy removes the ones it no longer lists. When the Auth service is only referenced as `external`, the machine users that exist in the workspace are accepted. An existing config that names a machine user that exists nowhere now fails at deploy; add the machine user to the Auth service or fix the name. If you create the machine user of an externally referenced Auth service after deploying the app that uses it, deploy the Auth service first, or deploy both configs in the same run (`tailor deploy --config a,b`).
|
|
10
|
+
|
|
11
|
+
- [#2975](https://github.com/tailor-platform/sdk/pull/2975) [`5889f05`](https://github.com/tailor-platform/sdk/commit/5889f057fe1fc0e2c0c8cadd3c08bb8674324fb7) Thanks [@jackchuka](https://github.com/jackchuka)! - **Breaking change**: `tailor workspace prune` no longer accepts `--personal`. Every workspace now belongs to an organization, so there are no workspaces outside an organization and folder for it to select. Replace `--personal` with `--organization-root` or `--folder-id` naming the locations to sweep. Do not just delete it: a `--name` or `--older-than` sweep without a location considers every workspace visible to the login, even with `--yes`.
|
|
12
|
+
|
|
13
|
+
- [#2739](https://github.com/tailor-platform/sdk/pull/2739) [`8b69e57`](https://github.com/tailor-platform/sdk/commit/8b69e571df0972a96e0e4c971472aa9ade44d9b3) Thanks [@toiroakr](https://github.com/toiroakr)! - `tailor seed apply` now runs the TailorDB seed and the IdP `_User` seed, list and delete scripts as temporary workflows instead of synchronous script executions, so they are no longer cut off by the 60-second execution limit. For each namespace it registers a function, a job function and a workflow named `tailor-seed-<kind>--<namespace>` (`<kind>` is `tailordb`, `idp-seed`, `idp-list` or `idp-truncate`), runs every chunk through them, and removes them afterwards. A namespace too long for the platform's 63-character name limit is cut short and followed by a hash. A run interrupted before cleanup leaves them behind, and the next run of the same script (the TailorDB seed, or the IdP `_User` seed, list or delete) for that namespace removes them first.
|
|
14
|
+
|
|
15
|
+
If `tailor seed apply` finds the workflow of an earlier run still executing (for example, a chunk that keeps running on the platform after Ctrl-C), it stops with an error naming the execution instead of removing it. `tailor seed apply --truncate` runs this check for every seed workflow of the namespaces it touches before it deletes anything, so an interrupted run no longer leaves a truncated table that is not reseeded. Wait for that execution to finish and run the command again. Running `tailor seed apply` for the same namespace in two processes at once is not supported: if one of them fails while registering the function, it removes the resources of the other. If the command loses track of a running chunk (for example, a timeout while starting it), it removes the resources and cannot tell whether the chunk was applied, so check the table, then re-run with `--upsert`.
|
|
16
|
+
|
|
17
|
+
A TailorDB chunk that fails now stops the remaining chunks of that namespace, so later chunks do not fail on foreign keys of the rolled-back chunk or leave a gap in a table split across chunks.
|
|
18
|
+
|
|
19
|
+
The seed and seed dump scripts are now minified and, like other bundled functions, embed an inline sourcemap by default so error stack traces stay readable. Set `buildOptions.inlineSourcemap` to `false` in `defineConfig` to drop the sourcemap.
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- [#2981](https://github.com/tailor-platform/sdk/pull/2981) [`1a4dca2`](https://github.com/tailor-platform/sdk/commit/1a4dca29c783de43b2eec7485e685e9f1d2a3415) Thanks [@dqn](https://github.com/dqn)! - `tailor executor trigger --data` now delivers the JSON to an incoming-webhook executor as its `body`, as a request to the webhook URL does. Since a Platform change, the data had arrived one level deeper, under `body.body`, so reading a field such as `body.email` returned `undefined` without an error. If an executor reads `body.body` to work around this, change it back to `body`. `--header` values are not passed to the executor, which receives empty `headers`, and the command now warns when `--header` is given. `--header` without `--data` no longer sends a body, so the executor receives `body` as `null`, as with no options. To test an executor that reads headers, send the request to its webhook URL, which `tailor executor webhook list` shows. The programmatic `triggerExecutor` passes `payload` to the executor as `body` unchanged, so pass the body itself rather than `{ body, headers }`.
|
|
24
|
+
|
|
25
|
+
- [#2959](https://github.com/tailor-platform/sdk/pull/2959) [`ebb62b6`](https://github.com/tailor-platform/sdk/commit/ebb62b641112a94b3f1880b6fa8eadf3602bf114) Thanks [@dqn](https://github.com/dqn)! - `tailor generate` and `tailor function run` now read the config path from `TAILOR_CONFIG_PATH` when `--config` is not given, like other commands that take a single config file. If `TAILOR_CONFIG_PATH` holds comma-separated paths for `tailor deploy`, pass `--config` to these commands.
|
|
26
|
+
|
|
27
|
+
- [#2960](https://github.com/tailor-platform/sdk/pull/2960) [`61dbc34`](https://github.com/tailor-platform/sdk/commit/61dbc34ade56c14faa3ee9cfce7b15bc59c21ae1) Thanks [@dqn](https://github.com/dqn)! - `tailorRuntime({ config })` now names the file, line, and parse error when `tailor.config.ts` or a file it imports does not parse, instead of reporting `[object Object]` against `tailor.config.ts`.
|
|
28
|
+
|
|
29
|
+
- [#2983](https://github.com/tailor-platform/sdk/pull/2983) [`d4faf97`](https://github.com/tailor-platform/sdk/commit/d4faf97d8886c15d95a25f36b9a4baf2f0e0ab1f) Thanks [@dqn](https://github.com/dqn)! - Document that an executor with an incoming webhook trigger, when triggered manually with `tailor executor trigger` or `triggerExecutor`, receives no `rawBody` and empty `headers`, in the executor guide and in the JSDoc of the webhook `rawBody` and `headers` args. An executor that verifies a signature over `rawBody` rejects such a run, so test it through its webhook URL.
|
|
30
|
+
|
|
31
|
+
- [#2957](https://github.com/tailor-platform/sdk/pull/2957) [`b79b113`](https://github.com/tailor-platform/sdk/commit/b79b1138846318d3a366c28be4aea1c67d36c99f) Thanks [@dqn](https://github.com/dqn)! - Fix `tailor deploy --no-schema-check` leaving a table removed from the local definitions without a migration until the next deploy when its namespace has pending migrations. The table is now deleted in the same deploy, after those migrations complete.
|
|
32
|
+
|
|
33
|
+
- [#2941](https://github.com/tailor-platform/sdk/pull/2941) [`7a5c244`](https://github.com/tailor-platform/sdk/commit/7a5c24497528b197439779ba83813f9d4f490135) Thanks [@dqn](https://github.com/dqn)! - `tailor deploy` now prints the pending-migration summary and the other notices about the migration state (a checkpoint reset, tables left to delete, a migration to run again, a skipped script, ignored `steps`) once, before the plan, instead of repeating them after the confirmation. When the pending migrations change after the plan, for example because another deploy applied one, the deploy now stops with `DEPLOY_PLAN_STALE` instead of applying a different set than the one it showed.
|
|
34
|
+
|
|
35
|
+
- [#2987](https://github.com/tailor-platform/sdk/pull/2987) [`67f8539`](https://github.com/tailor-platform/sdk/commit/67f853968141dcf8806f5e240eff54f0d8e72779) Thanks [@dqn](https://github.com/dqn)! - `tailor query --engine sql` and `query()` from `@tailor-platform/sdk/cli` now report how many rows an `INSERT`, `UPDATE`, or `DELETE` changed. For these statements the result adds `affectedRows` and sets `rowCount` to the same count, which was 0 when the statement had no `RETURNING`. When such a statement returns no rows, the text output prints the count (for example "3 rows affected.") instead of "No rows returned."
|
|
36
|
+
|
|
37
|
+
- [#2988](https://github.com/tailor-platform/sdk/pull/2988) [`818debc`](https://github.com/tailor-platform/sdk/commit/818debc8631fdd093cff6ccad9cc7a2e9f04e26b) Thanks [@dqn](https://github.com/dqn)! - Speed up `tailor seed apply` and `tailor tailordb migration test` for a seed table too large for one chunk: splitting it took tens of seconds for a few MB of small records and now takes milliseconds
|
|
38
|
+
|
|
39
|
+
- [#2961](https://github.com/tailor-platform/sdk/pull/2961) [`f30a654`](https://github.com/tailor-platform/sdk/commit/f30a65440c9c54a932884cf2d4be64c2245ccd1c) Thanks [@dqn](https://github.com/dqn)! - Add `--codemod` to `tailor setup ci autofix`, so the autofix workflow handles the codemods of a pull request that upgrades `@tailor-platform/sdk`, such as one from Renovate. It upgrades each app from the version the base branch's lockfile resolves, or from 2.37.0 when the base branch has no such lockfile, to the version the pull request installs. `warn` reports what `tailor upgrade` would rewrite and the changes it leaves for review, `error` reports them as errors and fails the `tailor-codemod-result` job, which also fails when the autofix job fails or is cancelled, and `deterministic` commits the rewrites with what `tailor generate` changes and reports the rest. `tailor setup update` keeps the `--codemod` value, and without `--codemod` the workflow is the same as before. With `error`, a review that still matches after you finish the migration keeps the check failing until the base branch has the new version. `deterministic` leaves files under `.github/workflows` out of the fix commit and reports them for you to commit, and a bun repository needs `bun.lock` instead of `bun.lockb`.
|
|
40
|
+
|
|
41
|
+
- [#2947](https://github.com/tailor-platform/sdk/pull/2947) [`d372640`](https://github.com/tailor-platform/sdk/commit/d372640551b3540b3afaa3f6f96b2f9d2a7b5185) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency kysely to v0.29.8
|
|
42
|
+
|
|
43
|
+
- [#2951](https://github.com/tailor-platform/sdk/pull/2951) [`ef7e152`](https://github.com/tailor-platform/sdk/commit/ef7e15252e54a27b767cc583b5e77845dd9b3541) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update @connectrpc to v2.3.0
|
|
44
|
+
|
|
45
|
+
- [#2954](https://github.com/tailor-platform/sdk/pull/2954) [`d065035`](https://github.com/tailor-platform/sdk/commit/d065035f6adc3b131bb8bb08d70a458acf20da15) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @opentelemetry/semantic-conventions to v1.44.0
|
|
46
|
+
|
|
47
|
+
- [#2955](https://github.com/tailor-platform/sdk/pull/2955) [`0e86776`](https://github.com/tailor-platform/sdk/commit/0e867766a8b5daa17927f6018c59281457bfebb9) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @politty/zod to v0.7.1
|
|
48
|
+
|
|
49
|
+
- [#2956](https://github.com/tailor-platform/sdk/pull/2956) [`5f2bfc5`](https://github.com/tailor-platform/sdk/commit/5f2bfc50e1770931bad639ba809853bedc7b8b4c) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency globals to v17.14.0
|
|
50
|
+
|
|
51
|
+
- [#2973](https://github.com/tailor-platform/sdk/pull/2973) [`c0ae913`](https://github.com/tailor-platform/sdk/commit/c0ae913259e1b51c7df799f3c023e4dd4ea567c9) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency semver to v7.8.6
|
|
52
|
+
|
|
53
|
+
- [#2978](https://github.com/tailor-platform/sdk/pull/2978) [`4dc187c`](https://github.com/tailor-platform/sdk/commit/4dc187c9d8e86065f7e352e179ebd0809c62f1ff) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update oxc to v0.157.0
|
|
54
|
+
|
|
55
|
+
- [#2997](https://github.com/tailor-platform/sdk/pull/2997) [`d396c09`](https://github.com/tailor-platform/sdk/commit/d396c09b4164c81bc0ecf8f91f487a6cf2fa886b) Thanks [@renovate](https://github.com/apps/renovate)! - chore(deps): lock file maintenance
|
|
56
|
+
|
|
57
|
+
- [#2739](https://github.com/tailor-platform/sdk/pull/2739) [`8b69e57`](https://github.com/tailor-platform/sdk/commit/8b69e571df0972a96e0e4c971472aa9ade44d9b3) Thanks [@toiroakr](https://github.com/toiroakr)! - `tailor seed apply` now runs each seed chunk in a single transaction. If any table fails, every table inserted earlier in that chunk is rolled back instead of being left committed, and Executors triggered by create events no longer run mid-chunk, which could deadlock on self-referencing tables.
|
|
58
|
+
|
|
59
|
+
Seed data is split into chunks of about 3.5 MiB, and the transaction covers one chunk. A table that does not fit in one chunk is split across chunks and is committed chunk by chunk.
|
|
60
|
+
|
|
61
|
+
- [#2984](https://github.com/tailor-platform/sdk/pull/2984) [`eb76277`](https://github.com/tailor-platform/sdk/commit/eb7627714f60f41e3c1833b150a2098dd7fdf58c) Thanks [@dqn](https://github.com/dqn)! - Labeling a closed pull request, such as one already merged, no longer deploys a preview workspace from the preview workflow that `tailor setup ci preview --require label` generates. The cleanup workflow had already run when the pull request closed, so such a workspace stayed until a later cleanup run deleted it after its 7-day `ttl` expired. The `tailor-preview-deploy` job of every preview workflow now skips events on a closed pull request, and your jobs that need it are skipped with it.
|
|
62
|
+
|
|
63
|
+
This release also raises the workflow template version, so `tailor setup check` reports a template-version finding for existing workflows until you run `tailor setup update`. With `TAILOR_PLATFORM_FAIL_ON_DRIFT` set to `true`, the drift check fails until then.
|
|
64
|
+
|
|
65
|
+
- [#2982](https://github.com/tailor-platform/sdk/pull/2982) [`cd33cdb`](https://github.com/tailor-platform/sdk/commit/cd33cdb901bf2eb4ee57e77ba8d62b134c1064d1) Thanks [@dqn](https://github.com/dqn)! - The v2 migration guide and `tailor upgrade` prompt for the programmatic CLI functions no longer say that `triggerExecutor`'s `payload` is typed from the executor definition. `payload` is accepted only for an executor with an incoming webhook trigger, and its shape is not checked; `startWorkflow`'s `arg` is still typed from the workflow definition.
|
|
66
|
+
|
|
3
67
|
## 2.38.0
|
|
4
68
|
|
|
5
69
|
### Minor Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{t as defineApplication,r as generatePluginFilesIfNeeded}from"./application-
|
|
1
|
+
export{t as defineApplication,r as generatePluginFilesIfNeeded}from"./application-mNOJx9Y2.mjs";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as e}from"./date-CgP7gMG_.mjs";import{n as t}from"./brand-C8nMKhJC.mjs";import{a as n,i as r,n as i,o as a}from"./wait-point-registry-B-ESkTZX.mjs";import{t as o}from"./assert-WeXvmG4j.mjs";import{n as s,o as c,r as l,s as u,t as d}from"./validation-errors-
|
|
1
|
+
import{r as e}from"./date-CgP7gMG_.mjs";import{n as t}from"./brand-C8nMKhJC.mjs";import{a as n,i as r,n as i,o as a}from"./wait-point-registry-B-ESkTZX.mjs";import{t as o}from"./assert-WeXvmG4j.mjs";import{n as s,o as c,r as l,s as u,t as d}from"./validation-errors-ChvCG6wT.mjs";import{S as f,b as p,i as m,p as h,t as g}from"./errors-9OOL3xOM.mjs";import{n as _,t as v}from"./es-builtins-SfvXRVoG.mjs";import{n as y,r as b,t as x}from"./node-builtins-DYfhPBnz.mjs";import{C as S,S as C,_ as w,a as T,c as E,d as D,f as O,g as k,h as A,l as j,m as M,n as N,o as P,p as F,s as ee,t as te,u as ne,x as I}from"./service-Bkz_TB5v.mjs";import{t as L}from"./multiline-EyzjEwn9.mjs";import{B as re,F as ie,O as ae,f as oe}from"./client-CqiPQgMG.mjs";import{r as se,t as ce}from"./guards-CiFVxoXR.mjs";import{t as le}from"./type-source--ZNcV8RJ.mjs";import{createRequire as ue}from"node:module";import*as R from"pathe";import{resolve as de}from"pathe";import{resolveTSConfig as fe}from"pkg-types";import{z}from"zod";import*as B from"node:fs";import{readFileSync as pe}from"node:fs";import me from"p-limit";import*as he from"node:crypto";import{createHash as ge}from"node:crypto";import*as _e from"node:os";import*as ve from"rolldown";import{RolldownMagicString as ye}from"rolldown";import{parseSync as V}from"oxc-parser";import{createPathsMatcher as be,getTsconfig as xe}from"get-tsconfig";import{matchesGlob as Se}from"node:path/posix";import*as H from"inflection";function isForbiddenGlobal(e){return _.has(e)}const Ce=[`DEBUG`,`INFO`,`WARN`,`ERROR`,`SILENT`];function isLogLevel(e){return Ce.includes(e)}function getPluginImportBaseDirs(e){return e?[R.dirname(e)]:[process.cwd()]}function resolveRelativePluginImportPath(e,t){if(!e.startsWith(`.`))return null;for(let n of t){let t=R.resolve(n,e);if(B.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 s=R.relative(process.cwd(),e);h.log(` Plugin Executor File: ${p.success(s)} from plugin ${p.info(i.pluginId)}`)}return a}function generateSingleExecutorFile(e,t,n,r,i=[]){let a=sanitizePluginId$1(e.pluginId),o=R.join(t,a,`executors`);B.mkdirSync(o,{recursive:!0});let s=sanitizeExecutorFileName(e.executor.name),c=R.join(o,`${s}.ts`),l;return l=se(e.executor)?generateExecutorFileContentNew(e,e.executor,t,n,r,i):generateExecutorFileContentLegacy(e.executor),B.writeFileSync(c,l),c}function generateExecutorFileContentNew(e,t,n,r,i,a=[]){let{resolve:o,context:s}=t,c=sanitizePluginId$1(e.pluginId),l=R.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 L`
|
|
2
2
|
/**
|
|
3
3
|
* Auto-generated executor by plugin: ${e.pluginId}
|
|
4
4
|
* DO NOT EDIT - This file is generated by @tailor-platform/sdk
|
|
@@ -111,10 +111,10 @@ import{r as e}from"./date-CgP7gMG_.mjs";import{n as t}from"./brand-C8nMKhJC.mjs"
|
|
|
111
111
|
const exports = module.exports;
|
|
112
112
|
${e}\n return module.exports.main(${t});\n})()`}function buildMinimalEntryFromResolved(e,t,n,r,i=!1){let a=de(r,`..`).replace(/\\/g,`/`);return[...e.map(e=>e.replace(/from\s+["'](\.[^"']+)["']/g,(e,t)=>`from "${de(a,t).replace(/\\/g,`/`)}"`)),...t,i?`export function main(...args) { return (${n})(...args); }`:`export function main(input) { return (${n})(input); }`].join(`
|
|
113
113
|
`)}async function bundleScriptTarget(e){let{fn:t,kind:n,sourceFilePath:r,sourceBindings:i,tableName:a,targetIndex:o,tsconfig:s,dateDefault:c}=e,l=`${n} in ${r}`,u=stringifyFunction(t);if((n===`typeValidate`||n===`validate`)&&t.constructor.name===`AsyncFunction`)throw Error(`${l} must be synchronous — the generated validator runs synchronously, so issues reported after an await are silently lost. Remove the async keyword.`);let d=assertParsableExpression(`(${u})(${buildHookCallArgs(n)})`,l),f=`const __fn = ${u};`,p=findUndefinedReferences(f,{includeGuardedReferences:!0});if(p.size===0)return d;let{imports:m,declarations:h,unresolved:g}=resolveNeededBindings(p,i),_=findUndefinedReferences(f),v=g.filter(e=>_.has(e));if(m.length===0&&h.length===0&&v.length===0)return d;if(v.length>0)throw Error(`${l} captures unresolvable variables (${v.join(`, `)}). Hooks and validators must not reference variables that cannot be resolved from the source file.
|
|
114
|
-
${n}: ${u}`);let y=buildMinimalEntryFromResolved(m,h,u,r,n===`typeValidate`),b=createVirtualEntry(`tailordb-script:${a}:${o}`,y,`ts`,r),x=createBundleLog({tsconfig:s}),S=await ve.build({plugins:[b.plugin,createTsconfigPathsPlugin({virtualEntrySourceFile:r}),createPlatformBundleDefinePlugin(void 0,c)],input:b.input,write:!1,output:{format:`cjs`,sourcemap:!1,minify:!0,codeSplitting:!1},tsconfig:s,treeshake:{moduleSideEffects:!1,annotations:!0,unknownGlobalSideEffects:!1},...x.options});x.assertAllResolved();let C=S.output[0].code;return assertParsableExpression(buildPrecompiledExpr(C,buildHookCallArgs(n)),l)}async function precompileTailorDBTypeScripts(e,t,n,r=`legacy`){let i=collectScriptTargets(e,r);if(i.length===0)return;let a=collectSourceBindings(t),s=await Promise.allSettled(i.map((i,o)=>bundleScriptTarget({fn:i.fn,kind:i.kind,sourceFilePath:t,sourceBindings:a,tableName:e.name,targetIndex:o,tsconfig:n,dateDefault:r}))),c=s.find(e=>e.status===`rejected`);if(c)throw c.reason;for(let[e,t]of s.entries())if(t.status===`fulfilled`){let n=o(i[e],`bundle target at index ${e} missing`);setPrecompiledScriptExpr(n.fn,n.kind,t.value,r)}}function formatTailorDBTypeSourceInfo(e){if(e){if(le(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
|
|
114
|
+
${n}: ${u}`);let y=buildMinimalEntryFromResolved(m,h,u,r,n===`typeValidate`),b=createVirtualEntry(`tailordb-script:${a}:${o}`,y,`ts`,r),x=createBundleLog({tsconfig:s}),S=await ve.build({plugins:[b.plugin,createTsconfigPathsPlugin({virtualEntrySourceFile:r}),createPlatformBundleDefinePlugin(void 0,c)],input:b.input,write:!1,output:{format:`cjs`,sourcemap:!1,minify:!0,codeSplitting:!1},tsconfig:s,treeshake:{moduleSideEffects:!1,annotations:!0,unknownGlobalSideEffects:!1},...x.options});x.assertAllResolved();let C=S.output[0].code;return assertParsableExpression(buildPrecompiledExpr(C,buildHookCallArgs(n)),l)}async function precompileTailorDBTypeScripts(e,t,n,r=`legacy`){let i=collectScriptTargets(e,r);if(i.length===0)return;let a=collectSourceBindings(t),s=await Promise.allSettled(i.map((i,o)=>bundleScriptTarget({fn:i.fn,kind:i.kind,sourceFilePath:t,sourceBindings:a,tableName:e.name,targetIndex:o,tsconfig:n,dateDefault:r}))),c=s.find(e=>e.status===`rejected`);if(c)throw c.reason;for(let[e,t]of s.entries())if(t.status===`fulfilled`){let n=o(i[e],`bundle target at index ${e} missing`);setPrecompiledScriptExpr(n.fn,n.kind,t.value,r)}}function formatTailorDBTypeSourceInfo(e){if(e){if(le(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 oe(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(ae(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=/* @__PURE__ */ 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.
|
|
115
115
|
${n.map(e=>` - ${e}`).join(`
|
|
116
116
|
`)}\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(e){let{namespace:n,config:r,pluginManager:i,baseDir:a,dateDefault:s=`legacy`}=e,createRawTypesByName=()=>Object.create(null),d=Object.create(null),f={},m=Object.create(null),g=/* @__PURE__ */ new Map,_,registerRawType=(e,t,r,i)=>{let a=Object.hasOwn(m,t)?m[t]:void 0;if(a){let e=formatTailorDBTypeSourceInfo(a)??`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.`)}o(d[e],`raw table entry missing for key: ${e}`)[t]=r,m[t]=i},parsePluginTable=(e,t)=>{let r=D.safeParse(E(e));if(!r.success)throw Error(`TailorDB table ${t} in TailorDB service "${n}" failed schema validation:\n${u(c(r.error.issues))}`,{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(d))for(let[n,r]of Object.entries(t))e[n]=r;f=parseTypes(e,n,m,s)},warnOmittedPermit=()=>{for(let e of Object.values(d))for(let[t,n]of Object.entries(e)){let e=findOmittedPermitRules(n.metadata.permissions);e.length>0&&h.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(d))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(m[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(`
|
|
117
|
-
`)}`)},processPluginsForTable=async(e,t,r)=>{if(!i)return;let{extendedTable:a,generatedTables:s,events:c}=await i.processAttachmentsForTable({rawTable:e,attachments:t,namespace:n}),l=[...new Set(c.filter(e=>e.kind===`extended`).map(e=>e.pluginId))],u=a===void 0?void 0:parsePluginTable(a,`"${e.name}" extended by ${l.length===1?`plugin`:`plugins`} ${l.map(e=>`"${e}"`).join(`, `)}`),f=s.map(e=>({...e,table:parsePluginTable(e.table,describeGeneratedTable(e.tableName,e.kind,e.pluginId))}));u&&(o(d[r],`raw table entry missing for file: ${r}`)[e.name]=u);for(let t of f){let i={exportName:t.tableName,pluginId:t.pluginId,pluginImportPath:t.pluginImportPath,originalFilePath:r,originalExportName:m[e.name]?.exportName||e.name,generatedTableKind:t.kind,pluginConfig:t.pluginConfig,namespace:n};registerRawType(r,t.tableName,t.table,i)}for(let e of c)e.kind===`extended`?h.debug(` Extended: ${p.success(e.tableName)} with ${p.highlight(e.fieldCount.toString())} fields by plugin ${p.info(e.pluginId)}`):h.debug(` Generated: ${p.success(e.tableName)} by plugin ${p.info(e.pluginId)}`)},loadTypeFile=async(e,n)=>{d[e]=createRawTypesByName();let r=createRawTypesByName();try{let i=await I(e);for(let a of Object.keys(i)){let o=i[a],c=D.safeParse(j(o));if(!c.success){if(t(o,`tailordb-type`))throw l({kind:`tailordb-type`,file:e,exportName:a,error:c.error});continue}let u=R.relative(process.cwd(),e);h.debug(`Type: ${p.successBright(`"${c.data.name}"`)} loaded from ${p.path(u)}`),await precompileTailorDBTypeScripts(c.data,e,n,s),r[c.data.name]=c.data,registerRawType(e,c.data.name,c.data,{filePath:e,exportName:a});let d=o;d.plugins&&Array.isArray(d.plugins)&&d.plugins.length>0&&(g.set(d.name,[...d.plugins]),h.debug(` Plugin attachments: ${p.info(d.plugins.map(e=>e.pluginId).join(`, `))}`),await processPluginsForTable(d,d.plugins,e))}}catch(t){let n=R.relative(process.cwd(),e);throw h.error(`Failed to load table from ${p.bold(n)}`),h.error(String(t)),t}return r};return{namespace:n,config:r,get types(){return f},get typeSourceInfo(){return m},get pluginAttachments(){return g},loadTypes:async()=>(_||=(async()=>{if(r.files.length===0)return;let e=[...new Set(w(r,a))],t=await resolveTSConfigWithFallback(a);if(h.newline(),h.log(`Found ${p.highlight(e.length.toString())} table files for TailorDB service ${p.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(),f})(),_),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 h.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(ce(r),n,e))}))),a=Object.hasOwn(d,t),o=d[t],s=o?Object.keys(o):[],c=s.length>0;if(a)for(let e of s)delete m[e];d[t]=createRawTypesByName();for(let{pluginId:e,config:a,kind:o,table:s}of r){let r={exportName:s.name,pluginId:e,pluginImportPath:i.getPluginImportPath(e)??``,originalFilePath:``,originalExportName:``,generatedTableKind:o,pluginConfig:a,namespace:n};registerRawType(t,s.name,s,r),h.debug(` Generated: ${p.success(s.name)} by namespace plugin ${p.info(e)}`)}(r.length>0||c)&&(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,a;if(r===1)a=t[0]?.namespace??o(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)){a=e.namespace;break}}if(!a)throw Error(`userProfile type "${e.userProfile.type.name}" not found in any TailorDB namespace`)}i={...e.userProfile,namespace:a}}}}function resolveBundleConcurrency(){return
|
|
117
|
+
`)}`)},processPluginsForTable=async(e,t,r)=>{if(!i)return;let{extendedTable:a,generatedTables:s,events:c}=await i.processAttachmentsForTable({rawTable:e,attachments:t,namespace:n}),l=[...new Set(c.filter(e=>e.kind===`extended`).map(e=>e.pluginId))],u=a===void 0?void 0:parsePluginTable(a,`"${e.name}" extended by ${l.length===1?`plugin`:`plugins`} ${l.map(e=>`"${e}"`).join(`, `)}`),f=s.map(e=>({...e,table:parsePluginTable(e.table,describeGeneratedTable(e.tableName,e.kind,e.pluginId))}));u&&(o(d[r],`raw table entry missing for file: ${r}`)[e.name]=u);for(let t of f){let i={exportName:t.tableName,pluginId:t.pluginId,pluginImportPath:t.pluginImportPath,originalFilePath:r,originalExportName:m[e.name]?.exportName||e.name,generatedTableKind:t.kind,pluginConfig:t.pluginConfig,namespace:n};registerRawType(r,t.tableName,t.table,i)}for(let e of c)e.kind===`extended`?h.debug(` Extended: ${p.success(e.tableName)} with ${p.highlight(e.fieldCount.toString())} fields by plugin ${p.info(e.pluginId)}`):h.debug(` Generated: ${p.success(e.tableName)} by plugin ${p.info(e.pluginId)}`)},loadTypeFile=async(e,n)=>{d[e]=createRawTypesByName();let r=createRawTypesByName();try{let i=await I(e);for(let a of Object.keys(i)){let o=i[a],c=D.safeParse(j(o));if(!c.success){if(t(o,`tailordb-type`))throw l({kind:`tailordb-type`,file:e,exportName:a,error:c.error});continue}let u=R.relative(process.cwd(),e);h.debug(`Type: ${p.successBright(`"${c.data.name}"`)} loaded from ${p.path(u)}`),await precompileTailorDBTypeScripts(c.data,e,n,s),r[c.data.name]=c.data,registerRawType(e,c.data.name,c.data,{filePath:e,exportName:a});let d=o;d.plugins&&Array.isArray(d.plugins)&&d.plugins.length>0&&(g.set(d.name,[...d.plugins]),h.debug(` Plugin attachments: ${p.info(d.plugins.map(e=>e.pluginId).join(`, `))}`),await processPluginsForTable(d,d.plugins,e))}}catch(t){let n=R.relative(process.cwd(),e);throw h.error(`Failed to load table from ${p.bold(n)}`),h.error(String(t)),t}return r};return{namespace:n,config:r,get types(){return f},get typeSourceInfo(){return m},get pluginAttachments(){return g},loadTypes:async()=>(_||=(async()=>{if(r.files.length===0)return;let e=[...new Set(w(r,a))],t=await resolveTSConfigWithFallback(a);if(h.newline(),h.log(`Found ${p.highlight(e.length.toString())} table files for TailorDB service ${p.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(),f})(),_),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 h.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(ce(r),n,e))}))),a=Object.hasOwn(d,t),o=d[t],s=o?Object.keys(o):[],c=s.length>0;if(a)for(let e of s)delete m[e];d[t]=createRawTypesByName();for(let{pluginId:e,config:a,kind:o,table:s}of r){let r={exportName:s.name,pluginId:e,pluginImportPath:i.getPluginImportPath(e)??``,originalFilePath:``,originalExportName:``,generatedTableKind:o,pluginConfig:a,namespace:n};registerRawType(t,s.name,s,r),h.debug(` Generated: ${p.success(s.name)} by namespace plugin ${p.info(e)}`)}(r.length>0||c)&&(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,a;if(r===1)a=t[0]?.namespace??o(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)){a=e.namespace;break}}if(!a)throw Error(`userProfile type "${e.userProfile.type.name}" not found in any TailorDB namespace`)}i={...e.userProfile,namespace:a}}}}function resolveBundleConcurrency(){return re(process.env.TAILOR_BUNDLE_CONCURRENCY)??Math.max(1,_e.cpus().length)}async function withBundleConcurrency(e,t){let n=[];n.length=e.length;let r=me(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}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: ${et}, 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(`, `)}]`};
|
|
120
120
|
const $matchedDeny = $denyPolicies.filter((p) => p.matched);
|
|
@@ -204,4 +204,4 @@ globalThis.transform = __adapter.output;
|
|
|
204
204
|
`});return[t.name,n]}),g=/* @__PURE__ */ new Map;for(let[e,t]of m)g.set(e,t);return validateBundledDependencies(g,u.map(e=>e.name)),h.log(`${p.success(`Bundled`)} ${p.info(`"workflow-job"`)}`),{mainJobDeps:d,usedJobNames:u.map(e=>e.name),bundledCode:g,sourceFileState:l}}function collectExtraStartCallFiles(e,t){let n=new Set([...e].map(safeRealpath)),r=[];for(let e of t.modules.values())n.has(safeRealpath(e.sourceFile))||r.push(e.sourceFile);return r}function hashReachabilitySourceFiles(e){let t=ge(`sha256`);for(let n of[...new Set(e)].toSorted()){t.update(n),t.update(`\0`);try{t.update(B.readFileSync(n))}catch{t.update(`<missing>`)}t.update(`\0`)}return t.digest(`hex`)}async function filterUsedJobs(e,t,n){if(e.length===0||t.length===0)return{usedJobs:[],mainJobDeps:{}};let r=/* @__PURE__ */ 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);for(let e of collectExtraStartCallFiles(r.keys(),n))i.set(e,[]);let a=/* @__PURE__ */ new Map,o=await Promise.all(Array.from(i.entries()).map(async([e,t])=>{try{let r=await B.promises.readFile(e,`utf-8`),{program:i,errors:a}=V(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=/* @__PURE__ */ 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 o)for(let{jobName:t,deps:n}of e)a.set(t,n);let s=/* @__PURE__ */ new Set,c={};function collectDeps(e,t){if(t.has(e))return;t.add(e);let n=a.get(e);if(n)for(let e of n)collectDeps(e,t)}for(let e of t){let t=/* @__PURE__ */ new Set;collectDeps(e,t),c[e]=Array.from(t);for(let e of t)s.add(e)}return{usedJobs:e.filter(e=>s.has(e.name)),mainJobDeps:c}}function createWorkflowTransformPlugin(e,t,n){let r=safeRealpath(e.sourceFile),i=t.filter(t=>t.name!==e.name&&safeRealpath(t.sourceFile)===r).map(e=>e.exportName);return{name:`workflow-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,a){if(!t.includes(`createWorkflowJob`)&&!t.includes(`createWorkflow`)&&!hasStartCall(t))return null;let o=t;return safeRealpath(a)===r&&(o=transformWorkflowSource(t,e.name,e.exportName,i)),hasStartCall(o)&&(o=transformStartCalls(o,n,a)),o===t?null:{code:o}}}}}const bt=/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,xt=/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9*]$/,St=`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 Ct=[`ms`,`s`,`m`],wt={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)*wt[t[2]]}const Z={maxRetries:{min:1,max:10},initialBackoffMaxSeconds:3600,maxBackoffMaxSeconds:86400,backoffMultiplierMin:1},Tt=z.strictObject({name:z.string().describe(`Job name (must be unique across the project)`),start:C.describe(`Start function that initiates the job`),body:C.describe(`Job implementation function`),publishEvents:z.boolean().optional().describe(`Enable publishing job execution events for this job`)}),seconds=e=>durationToSeconds(e)??0,Et=z.templateLiteral([z.number().int().positive(),z.enum(Ct)]),durationSchema=e=>Et.refine(t=>seconds(t)<=e,{message:`Duration must be at most ${e} seconds`}),Dt=z.strictObject({maxRetries:z.number().int().min(Z.maxRetries.min).max(Z.maxRetries.max).describe(`Maximum number of retries (1-10)`),initialBackoff:durationSchema(Z.initialBackoffMaxSeconds).describe(`Initial backoff duration (e.g., '1s', '500ms', '1m', max 1h)`),maxBackoff:durationSchema(Z.maxBackoffMaxSeconds).describe(`Maximum backoff duration (e.g., '30s', '5m', max 24h)`),backoffMultiplier:z.number().min(Z.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`]}),Ot=z.strictObject({maxConcurrentExecutions:z.number().int().min(1).max(1e3).describe(`Maximum number of concurrent executions (1-1000)`)}),kt=z.string().regex(bt,`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`),At=z.string().regex(xt,`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`),jt=z.strictObject({name:kt,key:At,concurrencyPolicy:Ot.optional().describe(`Optional per-key concurrency cap for job function dispatches matching this policy`)}),Mt=z.strictObject({name:z.string().describe(`Workflow name`),mainJob:Tt.describe(`Main job that starts the workflow`),retryPolicy:Dt.optional().describe(`Retry policy for the workflow`),concurrencyPolicy:Ot.optional().describe(`Concurrency policy for the workflow`),publishEvents:z.boolean().optional().describe(`Enable publishing workflow execution events for this workflow`)});function stripRuntimeStart(e){if(!t(e,`workflow`)||typeof e!=`object`||!e||!(`start`in e))return e;let{start:n,...r}=e;return r}function createWorkflowService(e){let{config:t,baseDir:n}=e,r={},i=[],a=[],o=0,s=!1;return{config:t,get workflows(){return r},get workflowSources(){return i},get jobs(){return a},get fileCount(){return o},loadWorkflows:async()=>{if(s)return;let e=await loadAndCollectJobs(t,n);r=e.workflows,i=e.workflowSources,a=e.jobs,o=e.fileCount,s=!0},printLoadedWorkflows:()=>{if(o!==0){h.newline(),h.log(`Found ${p.highlight(o.toString())} workflow files`);for(let{workflow:e,sourceFile:t}of i){let n=R.relative(process.cwd(),t);h.debug(`Workflow: ${p.successBright(`"${e.name}"`)} loaded from ${p.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=w(e,t),o=a.length,s=/* @__PURE__ */ 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(e){let n=[],r=null;try{let i=await I(e);for(let[a,o]of Object.entries(i)){if(a==="default"){let n=Mt.safeParse(stripRuntimeStart(o));if(n.success)r=n.data;else if(t(o,`workflow`))throw l({kind:`workflow`,file:e,exportName:a,error:n.error});else if(t(o,`workflow-job`))throw s({kind:`workflow-job`,file:e,exportName:a});continue}let i=Tt.safeParse(o);if(i.success)n.push({name:i.data.name,exportName:a,sourceFile:e,...i.data.publishEvents===void 0?{}:{publishEvents:i.data.publishEvents}});else if(t(o,`workflow-job`))throw l({kind:`workflow-job`,file:e,exportName:a,error:i.error});else if(t(o,`workflow`))throw s({kind:`workflow`,file:e,exportName:a})}}catch(t){let n=R.relative(process.cwd(),e);throw h.error(`${p.error(`Failed to load workflow from`)} ${p.errorBright(n)}`),h.error(String(t)),t}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}function buildOptionsOf(e){let{buildOptions:t={}}=e;return{inlineSourcemap:t.inlineSourcemap??e.inlineSourcemap,inlineSourcemapDependencySources:t.inlineSourcemapDependencySources,inlineSourcemapProjectSources:t.inlineSourcemapProjectSources,logLevel:t.logLevel??e.logLevel,allowedRuntimeGlobals:t.allowedRuntimeGlobals,treeshake:t.treeshake}}function projectSourcesOf(e){let{buildOptions:t,baseDir:n}=e;return{...t.inlineSourcemapProjectSources,root:n}}function effectiveDateDefault(e){return e.defaultDateRepresentation??`legacy`}function resolveInlineSourcemap(e){if(e!==void 0)return e;let t=f(process.env.TAILOR_INLINE_SOURCEMAP);return t===void 0||t}function resolverBundleKey(e,t){return`${e}:${t}`}const Nt=z.strictObject({name:z.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:z.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:z.array(z.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.")}),Pt=/^(\*|[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 Ft=z.union([z.literal(`query`),z.strictObject({create:z.boolean().optional().describe(`Enable _createUser mutation (default: true)`),update:z.boolean().optional().describe(`Enable _updateUser mutation (default: true)`),delete:z.boolean().optional().describe(`Enable _deleteUser mutation (default: true)`),read:z.boolean().optional().describe(`Enable _users and _user queries (default: true)`),sendPasswordResetEmail:z.boolean().optional().describe(`Enable _sendPasswordResetEmail mutation (default: true)`),requestMfaSettingsUrl:z.boolean().optional().describe(`Enable _requestMfaSettingsUrl query (default: true)`),unenrollMfa:z.boolean().optional().describe(`Enable _unenrollMfa mutation (default: true)`)})]).describe(`Configuration for GraphQL operations on IdP users.
|
|
205
205
|
All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeIdPGqlOperations(e)),It=z.enum([`en`,`ja`]).describe(`IdP UI language`),Lt=z.strictObject({useNonEmailIdentifier:z.boolean().optional().describe(`Use non-email identifier for usernames`),allowSelfPasswordReset:z.boolean().optional().describe(`Allow users to reset their own passwords`),passwordRequireUppercase:z.boolean().optional().describe(`Require uppercase letters in passwords`),passwordRequireLowercase:z.boolean().optional().describe(`Require lowercase letters in passwords`),passwordRequireNonAlphanumeric:z.boolean().optional().describe(`Require non-alphanumeric characters in passwords`),passwordRequireNumeric:z.boolean().optional().describe(`Require numeric characters in passwords`),passwordMinLength:z.number().int().refine(e=>e>=6&&e<=30,{message:`passwordMinLength must be between 6 and 30`}).optional().describe(`Minimum password length (6-30)`),passwordMaxLength:z.number().int().refine(e=>e>=6&&e<=4096,{message:`passwordMaxLength must be between 6 and 4096`}).optional().describe(`Maximum password length (6-4096)`),allowedEmailDomains:z.array(z.string().regex(Pt,`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:z.boolean().optional().describe(`Enable Google OAuth login`),allowMicrosoftOauth:z.boolean().optional().describe(`Enable Microsoft OAuth login`),disablePasswordAuth:z.boolean().optional().describe(`Disable password-based authentication`),enableMfa:z.boolean().optional().describe(`Make TOTP MFA available for users in this namespace`),requireMfa:z.boolean().optional().describe(`Require TOTP MFA enrollment and challenge for password-authenticated users (requires enableMfa)`),allowedReturnOrigins:z.array(z.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:z.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`]}),Rt=z.string().max(200,`must be 200 characters or less`).regex(/^[^\r\n]*$/,`must not contain newline characters`),zt=z.strictObject({fromName:Rt.optional().describe(`Default sender display name for emails`),passwordResetSubject:Rt.optional().describe(`Default subject for password reset emails`)}).describe(`Namespace-level email configuration defaults`),Q=z.union([z.string(),z.boolean(),z.array(z.string()).readonly(),z.array(z.boolean()).readonly(),z.strictObject({user:z.string()}),z.strictObject({idpUser:z.enum([`id`,`name`,`disabled`])}),z.strictObject({oldIdpUser:z.enum([`id`,`name`,`disabled`])}),z.strictObject({newIdpUser:z.enum([`id`,`name`,`disabled`])})]),Bt=z.enum([`=`,`!=`,`in`,`not in`]),Vt=z.tuple([Q,Bt,Q]).readonly(),$=z.union([z.strictObject({conditions:z.union([Vt,z.array(Vt).readonly()]),description:z.string().optional(),permit:z.boolean().optional()}),z.tuple([Q,Bt,Q]).readonly(),z.tuple([Q,Bt,Q,z.boolean()]).readonly(),z.array(z.union([Vt,z.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()]),Ht=z.strictObject({create:z.array($).readonly(),read:z.array($).readonly(),update:z.array($).readonly(),delete:z.array($).readonly(),sendPasswordResetEmail:z.array($).readonly().optional(),unenrollMfa:z.array($).readonly().optional()}).describe(`Per-operation permission policies for IdP users`),Ut=z.strictObject({name:z.string().describe(`IdP service name`),authorization:z.union([z.literal(`insecure`),z.literal(`loggedIn`),z.strictObject({cel:z.string()})]).optional().describe(`Authorization mode for IdP API access`),clients:z.array(S).describe(`OAuth2 client names that can use this IdP`),lang:It.optional().describe(`UI language for IdP pages`),userAuthPolicy:Lt.transform(e=>Lt.parse(e??{})).optional().describe(`User authentication policy configuration`),publishEvents:z.boolean().optional().describe(`Enable publishing user lifecycle events`),gqlOperations:Ft.optional().describe(`Configure which GraphQL operations are enabled`),emailConfig:zt.optional().describe(`Namespace-level email configuration defaults`),permission:Ht.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`]}),Wt=z.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/),Gt=z.record(Wt,z.string().nullish()),Kt=z.strictObject({vaults:z.record(Wt,Gt),options:z.strictObject({ignoreNullishValues:z.boolean()})}),qt=z.strictObject({domain:z.string().describe(`Custom domain to move to another workspace`),transferTo:z.strictObject({workspaceId:z.string().describe(`Workspace that receives the domain`)}).describe(`Where the domain should move`)}),Jt=z.union([z.string(),qt]),Yt=z.strictObject({name:z.string().describe(`Static website name`),description:z.string().optional().describe(`Static website description`),allowedIpAddresses:z.array(z.string()).optional().describe(`IP addresses allowed to access the website`),customDomains:z.array(Jt).superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;e.forEach((e,r)=>{let i=typeof e==`string`?e:e.domain;n.has(i)&&t.addIssue({code:`custom`,path:[r],message:`Duplicate custom domain "${i}"`}),n.add(i)})}).optional().describe(`Custom domains for the static website`)}),Xt=/^[a-z0-9]+$/,Zt=/^[A-Za-z_][A-Za-z0-9_]*$/;function checkWaitPointKey(e){let{key:t,declaredBy:i}=e,o=t.split(`-`),s=o.filter(a);if(s.length>0&&i!==`define`)return i===`property`?`Invalid wait point key "${t}": $params cannot come from a property name. Pass the key to define instead, e.g. define.for("${t}")<Payload, Result>().`:`Invalid wait point key "${t}": 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("${t}")<Payload, Result>() })).`;let c=/* @__PURE__ */ new Set,l=0;for(let e of o)if(e.startsWith(`$`)){let n=e.slice(1);if(!Zt.test(n))return`Invalid wait point key "${t}": "${e}" is not a usable parameter name. Use letters, digits and underscores, starting with a letter or underscore.`;if(c.has(n))return`Invalid wait point key "${t}": parameter "$${n}" appears more than once.`;c.add(n)}else if(e!==``){if(!Xt.test(e))return`Invalid wait point key "${t}": segment "${e}" may only contain [a-z0-9]. Wait point keys accept ${r}, with $params standing in for runtime values.`;l+=1}if(l===0&&s.length>0)return t.startsWith(`-`)||t.endsWith(`-`)?`Invalid wait point key "${t}": must match ${r}.`:`Invalid wait point key "${t}": 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 n.test(t)?void 0:`Invalid wait point key "${t}": must match ${r}.`;let u=o.map(e=>e.startsWith(`$`)?`0`:e).join(`-`);return u.length>63?`Wait point key "${t}" cannot fit in 63 characters: even single-character parameter values produce ${u.length}.`:n.test(u)?void 0:`Invalid wait point key "${t}": must match ${r}.`}function collectWaitPointKeyFailures(e){let t=[],n=/* @__PURE__ */ 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}const Qt={db:`TailorDB service`,idp:`IdP`,auth:`Auth service`,staticWebsites:`static website`,aiGateways:`AI Gateway`,secrets:`secret manager`};function parseServiceConfig(e,t,n){let r=e.safeParse(t);if(r.success)return r.data;let{file:i,configKey:a,key:o,name:s}=n;throw d({file:i,exportName:`default`,subject:`config for ${Qt[a]}${s===void 0?``:` "${s}"`}`,error:r.error,pathPrefix:o===void 0?[a]:[a,o],service:{configKey:a,name:s}})}function defineTailorDB(e,t,n,r,i){let a=[],o=[],s=[];if(!e)return{tailorDBServices:a,externalTailorDBNamespaces:o,subgraphs:s};for(let[c,l]of Object.entries(e)){if(`external`in l)o.push(c);else{let e=createTailorDBService({namespace:c,config:parseServiceConfig(ne,l,{file:t,configKey:`db`,key:c,name:c}),pluginManager:i,baseDir:n,dateDefault:r});a.push(e)}s.push({Type:`tailordb`,Name:c})}return{tailorDBServices:a,externalTailorDBNamespaces:o,subgraphs:s}}function pluginResolverSource(e,t){return t&&{pluginManager:t,appName:e.name,configPath:e.path}}function defineResolver(e,t,n){let r=[],i=[];if(!e)return{resolverServices:r,subgraphs:i};for(let[a,o]of Object.entries(e)){if(!(`external`in o)){let e=createResolverService(a,o,t,n);r.push(e)}i.push({Type:`pipeline`,Name:a})}return{resolverServices:r,subgraphs:i}}function definePluginResolverServices(e,t){let n=R.dirname(e.path),r=[];for(let{namespace:i,pluginId:a}of t?.getPluginGeneratedResolvers()??[]){let o=e.resolver?.[i];if(o&&`external`in o)throw g({code:`PLUGIN_RESOLVER_NAMESPACE_EXTERNAL`,message:`Plugin "${a}" cannot generate resolvers in external namespace "${i}".`,context:{pluginId:a,namespace:i,resourceType:`pipeline.service`}});o||r.some(e=>e.namespace===i)||r.push(createResolverService(i,{files:[]},n,pluginResolverSource(e,t)))}return r}function stripIdpProviderHelper(e){let t=e;if(typeof t.provider!=`function`)return e;let{provider:n,...r}=t;return r}function defineIdp(e,t){let n=[],r=[];if(!e)return{idpServices:n,subgraphs:r};let i=/* @__PURE__ */ new Set;return e.forEach((e,a)=>{let o=e.name;if(i.has(o))throw Error(`IdP with name "${o}" already defined.`);if(i.add(o),!(`external`in e)){let r=parseServiceConfig(Ut,stripIdpProviderHelper(e),{file:t,configKey:`idp`,key:a,name:o});n.push(r)}r.push({Type:`idp`,Name:o})}),{idpServices:n,subgraphs:r}}function defineAuth(e,t,n,r){let i=[];if(!e)return{authService:void 0,subgraphs:i};let a;return`external`in e||(a=createAuthService(parseServiceConfig(T,e,{file:t,configKey:`auth`,name:e.name}),n,r)),i.push({Type:`auth`,Name:e.name}),{authService:a,subgraphs:i}}function defineExecutor(e,t,n){if(e||n)return te({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,t){let n=[],r=/* @__PURE__ */ new Set;return(e??[]).forEach((e,i)=>{let a=parseServiceConfig(Yt,stripStaticWebsiteUrlHelper(e),{file:t,configKey:`staticWebsites`,key:i,name:e.name});if(r.has(a.name))throw Error(`Static website with name "${a.name}" already defined.`);r.add(a.name),n.push(a)}),n}function defineAIGateways(e,t,n){let r=[],i=/* @__PURE__ */ new Set;return(e??[]).forEach((e,a)=>{let o=parseServiceConfig(Nt,e,{file:t,configKey:`aiGateways`,key:a,name:e.name});if(i.has(o.name))throw Error(`AI Gateway with name "${o.name}" already defined.`);if(i.add(o.name),o.authNamespace===void 0){if(!n)throw Error(`AI Gateway "${o.name}" has no "authNamespace" and no Auth service is configured to default to. Define an Auth service, or set "authNamespace" explicitly.`);o.authNamespace=n}r.push(o)}),r}function parseSecretManager(e,t){if(!e)return{secrets:[],ignoreNullishValues:!1};let n=parseServiceConfig(Kt,e,{file:t,configKey:`secrets`}),{ignoreNullishValues:r}=n.options,i=Object.entries(n.vaults).map(([e,t])=>({vaultName:e,secrets:Object.entries(t).map(([e,t])=>({name:e,value:t}))}));if(!r){for(let e of i)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:i,ignoreNullishValues:r}}function defineServices(e,t,n){let r=defineTailorDB(e.db,e.path,t,effectiveDateDefault(e),n),i=defineResolver(e.resolver,t,pluginResolverSource(e,n)),a=defineIdp(e.idp,e.path),o=defineAuth(e.auth,e.path,r.tailorDBServices,r.externalTailorDBNamespaces),s=defineStaticWebsites(e.staticWebsites,e.path),c=defineAIGateways(e.aiGateways,e.path,getApplicationAuthNamespace({authService:o.authService,config:e})),{secrets:l,ignoreNullishValues:u}=parseSecretManager(e.secrets,e.path);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=R.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=/* @__PURE__ */ 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:R.join(getDistDir(),`plugin`),sourceTableInfoMap:r,configPath:n,tableGenerator:generatePluginTableFiles,executorGenerator:generatePluginExecutorFiles})}function assertWaitPointKeys(){let e=collectWaitPointKeyFailures(i());if(e.length!==0)throw Error(e.join(`
|
|
206
206
|
`))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r,client:i,workspaceId:a,expectedLocalStaticWebsiteNames:o,previous:s}=e,c=R.dirname(t.path);if(s)return reloadEnvDependentBundles({config:t,baseDir:c,client:i,workspaceId:a,expectedLocalStaticWebsiteNames:o,bundleCache:r,previous:s});let{tailordbResult:l,resolverResult:u,idpResult:d,authResult:f,staticWebsiteServices:p,aiGatewayServices:m,secrets:g,ignoreNullishValues:_}=defineServices(t,c,n),v=i&&a?await ie(i,a,t.env??{},{expectedLocalNames:o??new Set(p.map(e=>e.name))}):t.env??{};for(let e of l.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();assertUniqueLocalTailorDBTypeNames({tailorDBServices:l.tailorDBServices});let y=definePluginResolverServices(t,n),b={resolverServices:[...u.resolverServices,...y],subgraphs:[...u.subgraphs,...y.map(({namespace:e})=>({Type:`pipeline`,Name:e}))]},x=generatePluginFilesIfNeeded(n,l.tailorDBServices,t.path),S=defineExecutor(t.executor,c,x.length>0),C=defineWorkflow(t.workflow,c);C&&await C.loadWorkflows();let w=defineHttpAdapterService(t.httpAdapter,c);w&&await w.loadAdapters();let T=createTsconfigLookupCache(),E=/* @__PURE__ */ new Map,D=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:f.authService,config:t}),c,C?.workflowSources,T),O=buildOptionsOf(t),k=resolveInlineSourcemap(O.inlineSourcemap),A=O.inlineSourcemapDependencySources??!1,j=projectSourcesOf({buildOptions:O,baseDir:c}),M=resolveBundleLogLevel(O.logLevel),N=effectiveDateDefault(t),P={resolvers:/* @__PURE__ */ new Map,executors:/* @__PURE__ */ new Map,workflowJobs:/* @__PURE__ */ new Map,authHooks:/* @__PURE__ */ new Map};for(let e of b.resolverServices){await e.loadResolvers();let t=await bundleResolvers({namespace:e.namespace,files:Object.keys(e.resolvers),baseDir:c,defaultPermission:e.defaultPermission,startContext:D,cache:r,inlineSourcemap:k,inlineSourcemapDependencySources:A,inlineSourcemapProjectSources:j,bundleLogLevel:M,bundleTreeshake:O.treeshake,tsconfigCache:T,sdkBuilderAnnotationCache:E,allowedRuntimeGlobals:O.allowedRuntimeGlobals,dateDefault:N});for(let[n,r]of t)P.resolvers.set(resolverBundleKey(e.namespace,n),r)}S&&(P.executors=await bundleExecutors({config:S.config,startContext:D,additionalFiles:[...x],cache:r,inlineSourcemap:k,inlineSourcemapDependencySources:A,inlineSourcemapProjectSources:j,bundleLogLevel:M,bundleTreeshake:O.treeshake,baseDir:c,tsconfigCache:T,sdkBuilderAnnotationCache:E,allowedRuntimeGlobals:O.allowedRuntimeGlobals,dateDefault:N}));let F;if(C&&C.jobs.length>0){let e=C.workflowSources.map(e=>e.workflow.mainJob.name);F=await bundleWorkflowJobs({allJobs:C.jobs,mainJobNames:e,env:v,startContext:D,baseDir:c,cache:r,inlineSourcemap:k,inlineSourcemapDependencySources:A,inlineSourcemapProjectSources:j,bundleLogLevel:M,bundleTreeshake:O.treeshake,tsconfigCache:T,sdkBuilderAnnotationCache:E,allowedRuntimeGlobals:O.allowedRuntimeGlobals,dateDefault:N}),P.workflowJobs=F.bundledCode}let ee;if(w&&w.adapters.length>0&&(ee=await bundleHttpAdapters(w.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),c,r,M,T,O.treeshake)),f.authService?.config.hooks?.beforeLogin){let e=f.authService.config.name;P.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:v,startContext:D,cache:r,inlineSourcemap:k,inlineSourcemapDependencySources:A,inlineSourcemapProjectSources:j,bundleLogLevel:M,bundleTreeshake:O.treeshake,baseDir:c,tsconfigCache:T,sdkBuilderAnnotationCache:E,dateDefault:N})}for(let e of b.resolverServices)await e.loadResolvers();return S&&(await S.loadExecutors(),x.length>0&&await S.loadPluginExecutorFiles([...x])),assertWaitPointKeys(),C&&C.printLoadedWorkflows(),w&&w.printLoadedAdapters(),h.newline(),{application:buildApplication({config:t,tailordbResult:l,resolverResult:b,idpResult:d,authResult:f,executorService:S,workflowService:C,httpAdapterService:w,staticWebsiteServices:p,aiGatewayServices:m,secrets:g,ignoreNullishValues:_,env:v}),workflowBuildResult:F,httpAdapterBuildResult:ee,bundledScripts:P,reusableBuildState:{startContext:D,tsconfigCache:T,sdkBuilderAnnotationCache:E,inlineSourcemap:k,inlineSourcemapDependencySources:A,inlineSourcemapProjectSources:j,bundleLogLevel:M}}}async function reloadEnvDependentBundles(e){let{config:t,baseDir:n,client:r,workspaceId:i,expectedLocalStaticWebsiteNames:a,bundleCache:o,previous:s}=e,{application:c,reusableBuildState:l}=s,{startContext:u,tsconfigCache:d,sdkBuilderAnnotationCache:f,inlineSourcemap:p,inlineSourcemapDependencySources:m,inlineSourcemapProjectSources:h,bundleLogLevel:g}=l,_=r&&i?await ie(r,i,t.env??{},{expectedLocalNames:a??new Set(c.staticWebsiteServices.map(e=>e.name))}):t.env??{},v={...s.bundledScripts},y=c.workflowService,b=s.workflowBuildResult;if(y&&y.jobs.length>0){let e=y.workflowSources.map(e=>e.workflow.mainJob.name);b=await bundleWorkflowJobs({allJobs:y.jobs,mainJobNames:e,env:_,startContext:u,baseDir:n,cache:o,inlineSourcemap:p,inlineSourcemapDependencySources:m,inlineSourcemapProjectSources:h,bundleLogLevel:g,bundleTreeshake:buildOptionsOf(t).treeshake,tsconfigCache:d,sdkBuilderAnnotationCache:f,previousUsedJobs:s.workflowBuildResult,allowedRuntimeGlobals:buildOptionsOf(t).allowedRuntimeGlobals,dateDefault:effectiveDateDefault(t)}),v.workflowJobs=b.bundledCode}if(c.authService?.config.hooks?.beforeLogin){let e=c.authService.config.name;v.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:_,startContext:u,cache:o,inlineSourcemap:p,inlineSourcemapDependencySources:m,inlineSourcemapProjectSources:h,bundleLogLevel:g,bundleTreeshake:buildOptionsOf(t).treeshake,baseDir:n,tsconfigCache:d,sdkBuilderAnnotationCache:f,dateDefault:effectiveDateDefault(t)})}let x={...c,env:_,get applications(){return[x]}};return{application:x,workflowBuildResult:b,httpAdapterBuildResult:s.httpAdapterBuildResult,bundledScripts:v,reusableBuildState:l}}export{Ce as $,hasOmittedPermit as A,createPlatformBundleDefinePlugin as B,buildResolverOperationHookExpr as C,assertUniqueLocalTailorDBTypeNames as D,resolverDateRepresentations as E,resolveTSConfigWithFallback as F,findUndefinedReferences as G,ze as H,createGeneratedEntryResolverPlugin as I,createBundleLog as J,createLogLevelTreeshakeOptions as K,chunkCodeWithSourcemap as L,et as M,K as N,assertUniqueTailorDBTypeNamesWithExternal as O,assertParsableExpression as P,hashFile as Q,isDependencySource as R,buildExecutorArgsExpr as S,buildResolverValidatedInputExpr as T,composeFunctionTreeshakeOptions as U,We as V,createUserTreeshakeOptions as W,createBundleCache as X,createTsconfigPathsPlugin as Y,hashContent as Z,getDistDir as _,hasImplicitAllEmailDomains as a,Y as b,effectiveDateDefault as c,getApplicationAuthNamespace as d,isForbiddenGlobal as et,requireApplicationAuthNamespace as f,toPlatformExecutionPolicyKey as g,St as h,loadApplication as i,stringifyFunction as j,createPermissionNormalizer as k,buildOptionsOf as l,Tt as m,definePluginResolverServices as n,resolverBundleKey as o,jt as p,resolveBundleLogLevel as q,generatePluginFilesIfNeeded as r,resolveInlineSourcemap as s,defineApplication as t,projectSourcesOf as u,resolveResolverDefaultPermissionForFile as v,buildResolverResultSerialization as w,q as x,_t as y,createSdkBuilderPurePlugin as z};
|
|
207
|
-
//# sourceMappingURL=application-
|
|
207
|
+
//# sourceMappingURL=application-mNOJx9Y2.mjs.map
|