@ptkl/toolkit 0.9.3 → 0.10.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.
@@ -5,6 +5,7 @@ import { resolve, join, dirname } from "path";
5
5
  import { rollup } from "rollup";
6
6
  import util from "../lib/util.js";
7
7
  import { Platform as Api } from "@ptkl/sdk";
8
+ import OutputFormatCommand from "./outputCommand.js";
8
9
  import { mkdirSync, writeFileSync, rmSync, readdirSync, existsSync, readFileSync } from "fs";
9
10
  import { nodeResolve } from '@rollup/plugin-node-resolve';
10
11
  // @ts-ignore
@@ -25,7 +26,164 @@ class ComponentCommand {
25
26
  .addCommand(new Command("build")
26
27
  .description("Build templates for component")
27
28
  .requiredOption("-p, --path <path>", "Path to the source files", "./")
28
- .action(this.build));
29
+ .action(this.build))
30
+ .addCommand(new Command("models")
31
+ .description("Interact with component models")
32
+ .addCommand(new OutputFormatCommand(new Command("find")
33
+ .description("Find models in a component")
34
+ .requiredOption("-r, --ref <ref>", "Component ref (e.g. ecommerce::order)")
35
+ .option("--page <page>", "Current page (default: 0)")
36
+ .option("--per-page <perPage>", "Items per page (default: 10)")
37
+ .option("--filter <filter>", "Filter string")
38
+ .option("-s, --sort-by <sortBy>", "Field to sort by")
39
+ .option("--sort-desc", "Sort descending")
40
+ .option("-a, --adv <adv>", "Advanced filter as JSON object")).action(this.modelsFind))
41
+ .addCommand(new OutputFormatCommand(new Command("get")
42
+ .description("Get model by UUID")
43
+ .requiredOption("-r, --ref <ref>", "Component ref")
44
+ .requiredOption("-u, --uuid <uuid>", "Model UUID")).action(this.modelsGet))
45
+ .addCommand(new OutputFormatCommand(new Command("create")
46
+ .description("Create a new model")
47
+ .requiredOption("-r, --ref <ref>", "Component ref")
48
+ .option("-d, --data <data>", "Model data as JSON string")
49
+ .option("-i, --file <file>", "Path to a JSON file containing the model data")).action(this.modelsCreate))
50
+ .addCommand(new OutputFormatCommand(new Command("update")
51
+ .description("Update model by UUID")
52
+ .requiredOption("-r, --ref <ref>", "Component ref")
53
+ .requiredOption("-u, --uuid <uuid>", "Model UUID")
54
+ .option("-d, --data <data>", "Model data as JSON string")
55
+ .option("-i, --file <file>", "Path to a JSON file containing the model data")).action(this.modelsUpdate))
56
+ .addCommand(new OutputFormatCommand(new Command("delete")
57
+ .description("Delete model by UUID")
58
+ .requiredOption("-r, --ref <ref>", "Component ref")
59
+ .requiredOption("-u, --uuid <uuid>", "Model UUID")).action(this.modelsDelete))
60
+ .addCommand(new OutputFormatCommand(new Command("aggregate")
61
+ .description("Run aggregation pipeline")
62
+ .requiredOption("-r, --ref <ref>", "Component ref")
63
+ .option("-p, --pipeline <pipeline>", "Aggregation pipeline as JSON array")
64
+ .option("-i, --file <file>", "Path to a JSON file containing the aggregation pipeline")).action(this.modelsAggregate))
65
+ .addCommand(new OutputFormatCommand(new Command("revisions")
66
+ .description("Get revisions for a model")
67
+ .requiredOption("-r, --ref <ref>", "Component ref")
68
+ .requiredOption("-u, --uuid <uuid>", "Model UUID")).action(this.modelsRevisions))
69
+ .addCommand(new OutputFormatCommand(new Command("bulk-create")
70
+ .description("Create multiple models at once")
71
+ .requiredOption("-r, --ref <ref>", "Component ref")
72
+ .option("-d, --data <data>", "Array of model objects as JSON string")
73
+ .option("-i, --file <file>", "Path to a JSON file containing array of model objects")).action(this.modelsBulkCreate))
74
+ .addCommand(new OutputFormatCommand(new Command("bulk-update")
75
+ .description("Update multiple models at once (by UUID in each object)")
76
+ .requiredOption("-r, --ref <ref>", "Component ref")
77
+ .option("-d, --data <data>", "Array of model objects as JSON string")
78
+ .option("-i, --file <file>", "Path to a JSON file containing array of model objects")).action(this.modelsBulkUpdate))
79
+ .addCommand(new OutputFormatCommand(new Command("modify")
80
+ .description("Update models matching a filter")
81
+ .requiredOption("-r, --ref <ref>", "Component ref")
82
+ .option("--filters <filters>", "Filter object as JSON string")
83
+ .option("-d, --data <data>", "Update data as JSON string")
84
+ .option("-i, --file <file>", "Path to a JSON file with { filters, data, options? }")).action(this.modelsModify)))
85
+ .addCommand(new OutputFormatCommand(new Command("settings")
86
+ .description("Get component settings")
87
+ .requiredOption("-r, --ref <ref>", "Component ref")
88
+ .option("-v, --version <version>", "Component version")).action(this.getSettings))
89
+ .addCommand(new Command("publish")
90
+ .description("Publish component version")
91
+ .requiredOption("-r, --ref <ref>", "Component ref")
92
+ .requiredOption("-v, --version <version>", "Component version to publish")
93
+ .requiredOption("-e, --env <env>", "Environment to publish to")
94
+ .action(this.publishComponent))
95
+ .addCommand(new OutputFormatCommand(new Command("function")
96
+ .description("Call a component function")
97
+ .requiredOption("-r, --ref <ref>", "Component ref")
98
+ .requiredOption("-n, --name <name>", "Function name")
99
+ .option("-d, --data <data>", "Function input as JSON string")).action(this.callFunction))
100
+ .addCommand(new OutputFormatCommand(new Command("workflow")
101
+ .description("Trigger a component workflow event")
102
+ .requiredOption("-r, --ref <ref>", "Component ref")
103
+ .requiredOption("-e, --event <event>", "Workflow event name")
104
+ .option("-d, --data <data>", "Event input as JSON string")).action(this.triggerWorkflow))
105
+ .addCommand(new OutputFormatCommand(new Command("create")
106
+ .description("Create a new component")
107
+ .requiredOption("-n, --name <name>", "Component name")
108
+ .requiredOption("-t, --tag <tag>", "Component tag (unique identifier)")
109
+ .option("--label <label>", "Label locales as JSON object, e.g. '{\"en_US\":\"My Component\"}'")
110
+ .option("--initial-version <initialVersion>", "Initial version string", "0.1.0")
111
+ .option("--workspaces <workspaces...>", "Workspaces to attach the component to")
112
+ .option("--scope <scope>", "Component scope")
113
+ .option("--publish", "Publish the initial version immediately")
114
+ .option("-d, --data <data>", "Full create payload as JSON string (overrides other options)")
115
+ .option("-i, --file <file>", "Path to a JSON file containing the full create payload")).action(this.createComponent))
116
+ .addCommand(new Command("update-settings")
117
+ .description("Save/update component settings for a version")
118
+ .requiredOption("-r, --ref <ref>", "Component ref")
119
+ .requiredOption("-v, --version <version>", "Component version")
120
+ .option("-d, --data <data>", "Settings as JSON string")
121
+ .option("-i, --file <file>", "Path to a JSON file containing the settings")
122
+ .action(this.updateSettings))
123
+ .addCommand(new OutputFormatCommand(new Command("fork-version")
124
+ .description("Fork a component version to create a new one")
125
+ .requiredOption("-r, --ref <ref>", "Component ref")
126
+ .option("-n, --name <name>", "New version name")
127
+ .option("--from <from>", "Source version to fork from")
128
+ .option("-d, --data <data>", "Full fork payload as JSON string (overrides other options)")
129
+ .option("-i, --file <file>", "Path to a JSON file containing the full fork payload")).action(this.forkVersion))
130
+ .addCommand(new OutputFormatCommand(new Command("fork-schema")
131
+ .description("Fork a component schema from another component or schema ref")
132
+ .requiredOption("-r, --ref <ref>", "Component ref")
133
+ .option("-v, --version <version>", "Target version to apply the forked schema to")
134
+ .option("-s, --schema <schema>", "Source schema ref to fork from")
135
+ .option("-d, --data <data>", "Full fork-schema payload as JSON string (overrides other options)")
136
+ .option("-i, --file <file>", "Path to a JSON file containing the full fork-schema payload")).action(this.forkSchema))
137
+ .addCommand(new Command("extensions")
138
+ .description("Manage component extensions")
139
+ .addCommand(new OutputFormatCommand(new Command("get")
140
+ .description("Get an extension by name")
141
+ .requiredOption("-r, --ref <ref>", "Component ref")
142
+ .requiredOption("-n, --name <name>", "Extension name")
143
+ .option("-v, --version <version>", "Component version (uses active env if omitted)")).action(this.extensionGet))
144
+ .addCommand(new OutputFormatCommand(new Command("install")
145
+ .description("Install a new extension on a component version")
146
+ .requiredOption("-r, --ref <ref>", "Component ref")
147
+ .requiredOption("-v, --version <version>", "Component version")
148
+ .option("-d, --data <data>", "Extension definition as JSON string")
149
+ .option("-i, --file <file>", "Path to a JSON file containing the extension definition")).action(this.extensionInstall))
150
+ .addCommand(new OutputFormatCommand(new Command("update")
151
+ .description("Update an existing extension")
152
+ .requiredOption("-r, --ref <ref>", "Component ref")
153
+ .requiredOption("-v, --version <version>", "Component version")
154
+ .requiredOption("-n, --name <name>", "Extension name")
155
+ .option("-d, --data <data>", "Partial extension data as JSON string")
156
+ .option("-i, --file <file>", "Path to a JSON file containing the partial extension data")).action(this.extensionUpdate))
157
+ .addCommand(new OutputFormatCommand(new Command("delete")
158
+ .description("Delete an extension from a component version")
159
+ .requiredOption("-r, --ref <ref>", "Component ref")
160
+ .requiredOption("-v, --version <version>", "Component version")
161
+ .requiredOption("-n, --name <name>", "Extension name")).action(this.extensionDelete)))
162
+ .addCommand(new Command("policies")
163
+ .description("Manage component policies")
164
+ .addCommand(new OutputFormatCommand(new Command("get")
165
+ .description("Get a policy by name")
166
+ .requiredOption("-r, --ref <ref>", "Component ref")
167
+ .requiredOption("-v, --version <version>", "Component version")
168
+ .requiredOption("-n, --name <name>", "Policy name")).action(this.policyGet))
169
+ .addCommand(new OutputFormatCommand(new Command("install")
170
+ .description("Install a new policy on a component version")
171
+ .requiredOption("-r, --ref <ref>", "Component ref")
172
+ .requiredOption("-v, --version <version>", "Component version")
173
+ .option("-d, --data <data>", "Policy definition as JSON string")
174
+ .option("-i, --file <file>", "Path to a JSON file containing the policy definition")).action(this.policyInstall))
175
+ .addCommand(new OutputFormatCommand(new Command("update")
176
+ .description("Update an existing policy")
177
+ .requiredOption("-r, --ref <ref>", "Component ref")
178
+ .requiredOption("-v, --version <version>", "Component version")
179
+ .requiredOption("-n, --name <name>", "Policy name")
180
+ .option("-d, --data <data>", "Partial policy data as JSON string")
181
+ .option("-i, --file <file>", "Path to a JSON file containing the partial policy data")).action(this.policyUpdate))
182
+ .addCommand(new OutputFormatCommand(new Command("delete")
183
+ .description("Delete a policy from a component version")
184
+ .requiredOption("-r, --ref <ref>", "Component ref")
185
+ .requiredOption("-v, --version <version>", "Component version")
186
+ .requiredOption("-n, --name <name>", "Policy name")).action(this.policyDelete)));
29
187
  }
30
188
  nodesToActualFiles(nodes, basePath) {
31
189
  nodes.forEach((node) => {
@@ -374,5 +532,304 @@ class ComponentCommand {
374
532
  return;
375
533
  }
376
534
  }
535
+ async modelsFind(opts) {
536
+ const { ref, page, perPage, filter, sortBy, sortDesc, adv } = opts;
537
+ const profile = util.getCurrentProfile();
538
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
539
+ const filters = {
540
+ currentPage: page !== undefined ? parseInt(page) : 0,
541
+ perPage: perPage !== undefined ? parseInt(perPage) : 10,
542
+ filter,
543
+ sortBy,
544
+ sortDesc: sortDesc ?? false,
545
+ };
546
+ if (adv) {
547
+ filters.$adv = JSON.parse(adv);
548
+ }
549
+ const { data } = await client.find(filters);
550
+ return data;
551
+ }
552
+ async modelsGet(opts) {
553
+ const { ref, uuid } = opts;
554
+ const profile = util.getCurrentProfile();
555
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
556
+ const { data } = await client.get(uuid);
557
+ return data;
558
+ }
559
+ async modelsCreate(opts) {
560
+ const { ref, data: dataStr, file } = opts;
561
+ if (!dataStr && !file)
562
+ throw new Error("Provide model data via --data or --file");
563
+ const profile = util.getCurrentProfile();
564
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
565
+ const modelData = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(dataStr);
566
+ return await client.create(modelData);
567
+ }
568
+ async modelsUpdate(opts) {
569
+ const { ref, uuid, data: dataStr, file } = opts;
570
+ if (!dataStr && !file)
571
+ throw new Error("Provide model data via --data or --file");
572
+ const profile = util.getCurrentProfile();
573
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
574
+ const modelData = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(dataStr);
575
+ return await client.update(uuid, modelData);
576
+ }
577
+ async modelsDelete(opts) {
578
+ const { ref, uuid } = opts;
579
+ const profile = util.getCurrentProfile();
580
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
581
+ return await client.delete(uuid);
582
+ }
583
+ async modelsAggregate(opts) {
584
+ const { ref, pipeline: pipelineStr, file } = opts;
585
+ if (!pipelineStr && !file)
586
+ throw new Error("Provide pipeline via --pipeline or --file");
587
+ const profile = util.getCurrentProfile();
588
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
589
+ const pipeline = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(pipelineStr);
590
+ return await client.aggregate(pipeline);
591
+ }
592
+ async modelsRevisions(opts) {
593
+ const { ref, uuid } = opts;
594
+ const profile = util.getCurrentProfile();
595
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
596
+ const { data } = await client.revisions(uuid);
597
+ return data;
598
+ }
599
+ async getSettings(opts) {
600
+ const { ref, version } = opts;
601
+ const profile = util.getCurrentProfile();
602
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
603
+ const { data } = version
604
+ ? await client.settingsForVersion(version)
605
+ : await client.settings();
606
+ return data;
607
+ }
608
+ async publishComponent(opts) {
609
+ const { ref, version, env } = opts;
610
+ const profile = util.getCurrentProfile();
611
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
612
+ const { data } = await client.publish(version, env);
613
+ console.log(`Published component ${ref} version ${version} to ${env}`);
614
+ return data;
615
+ }
616
+ async callFunction(opts) {
617
+ const { ref, name, data: dataStr } = opts;
618
+ const profile = util.getCurrentProfile();
619
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
620
+ const input = dataStr ? JSON.parse(dataStr) : undefined;
621
+ return await client.function(name, input);
622
+ }
623
+ async triggerWorkflow(opts) {
624
+ const { ref, event, data: dataStr } = opts;
625
+ const profile = util.getCurrentProfile();
626
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
627
+ const input = dataStr ? JSON.parse(dataStr) : undefined;
628
+ const { data } = await client.workflow(event, input);
629
+ return data;
630
+ }
631
+ async createComponent(opts) {
632
+ const { name, tag, label: labelStr, initialVersion, workspaces, scope, publish, data: dataStr, file } = opts;
633
+ const profile = util.getCurrentProfile();
634
+ const httpClient = new Api({ token: profile.token, host: profile.host }).getPlatformClient();
635
+ let payload;
636
+ if (file) {
637
+ payload = JSON.parse(readFileSync(resolve(file), "utf-8"));
638
+ }
639
+ else if (dataStr) {
640
+ payload = JSON.parse(dataStr);
641
+ }
642
+ else {
643
+ payload = {
644
+ name,
645
+ tag,
646
+ label: labelStr ? JSON.parse(labelStr) : { locales: {} },
647
+ initial_version: initialVersion || "0.1.0",
648
+ ...(workspaces && { workspaces }),
649
+ ...(scope && { scope }),
650
+ ...(publish !== undefined && { publish }),
651
+ };
652
+ }
653
+ const { data } = await httpClient.post("/v3/system/component/create", payload);
654
+ return data;
655
+ }
656
+ async updateSettings(opts) {
657
+ const { ref, version, data: dataStr, file } = opts;
658
+ if (!dataStr && !file) {
659
+ console.error("Error: either --data or --file must be provided");
660
+ process.exit(1);
661
+ }
662
+ const profile = util.getCurrentProfile();
663
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
664
+ const settings = file
665
+ ? JSON.parse(readFileSync(resolve(file), "utf-8"))
666
+ : JSON.parse(dataStr);
667
+ const { data } = await client.saveSettings(settings, version);
668
+ return data;
669
+ }
670
+ async forkVersion(opts) {
671
+ const { ref, name, from, data: dataStr, file } = opts;
672
+ const profile = util.getCurrentProfile();
673
+ const httpClient = new Api({ token: profile.token, host: profile.host }).getPlatformClient();
674
+ let payload;
675
+ if (file) {
676
+ payload = { ref, ...JSON.parse(readFileSync(resolve(file), "utf-8")) };
677
+ }
678
+ else if (dataStr) {
679
+ payload = { ref, ...JSON.parse(dataStr) };
680
+ }
681
+ else {
682
+ if (!name || !from) {
683
+ console.error("Error: --name and --from are required when not using --data or --file");
684
+ process.exit(1);
685
+ }
686
+ payload = { ref, name, from };
687
+ }
688
+ const { data } = await httpClient.post("/v3/system/component/version/fork", payload);
689
+ return data;
690
+ }
691
+ async forkSchema(opts) {
692
+ const { ref, version, schema, data: dataStr, file } = opts;
693
+ const profile = util.getCurrentProfile();
694
+ const httpClient = new Api({ token: profile.token, host: profile.host }).getPlatformClient();
695
+ let payload;
696
+ if (file) {
697
+ payload = { ref, ...JSON.parse(readFileSync(resolve(file), "utf-8")) };
698
+ }
699
+ else if (dataStr) {
700
+ payload = { ref, ...JSON.parse(dataStr) };
701
+ }
702
+ else {
703
+ if (!version || !schema) {
704
+ console.error("Error: --version and --schema are required when not using --data or --file");
705
+ process.exit(1);
706
+ }
707
+ payload = { ref, version, schema };
708
+ }
709
+ const { data } = await httpClient.post("/v3/system/component/version/fork/schema", payload);
710
+ return data;
711
+ }
712
+ async modelsBulkCreate(opts) {
713
+ const { ref, data: dataStr, file } = opts;
714
+ if (!dataStr && !file) {
715
+ console.error("Error: either --data or --file must be provided");
716
+ process.exit(1);
717
+ }
718
+ const profile = util.getCurrentProfile();
719
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
720
+ const models = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(dataStr);
721
+ const { data } = await client.createMany(models);
722
+ return data;
723
+ }
724
+ async modelsBulkUpdate(opts) {
725
+ const { ref, data: dataStr, file } = opts;
726
+ if (!dataStr && !file) {
727
+ console.error("Error: either --data or --file must be provided");
728
+ process.exit(1);
729
+ }
730
+ const profile = util.getCurrentProfile();
731
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
732
+ const models = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(dataStr);
733
+ const { data } = await client.updateMany(models);
734
+ return data;
735
+ }
736
+ async modelsModify(opts) {
737
+ const { ref, filters: filtersStr, data: dataStr, file } = opts;
738
+ const profile = util.getCurrentProfile();
739
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
740
+ let filters, updateData, options;
741
+ if (file) {
742
+ const payload = JSON.parse(readFileSync(resolve(file), "utf-8"));
743
+ filters = payload.filters;
744
+ updateData = payload.data;
745
+ options = payload.options;
746
+ }
747
+ else {
748
+ if (!filtersStr || !dataStr) {
749
+ console.error("Error: --filters and --data are required (or use --file)");
750
+ process.exit(1);
751
+ }
752
+ filters = JSON.parse(filtersStr);
753
+ updateData = JSON.parse(dataStr);
754
+ }
755
+ const { data } = await client.modify(filters, updateData, options);
756
+ return data;
757
+ }
758
+ async extensionGet(opts) {
759
+ const { ref, name, version } = opts;
760
+ const profile = util.getCurrentProfile();
761
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
762
+ const { data } = await client.getExtension(name, version);
763
+ return data;
764
+ }
765
+ async extensionInstall(opts) {
766
+ const { ref, version, data: dataStr, file } = opts;
767
+ if (!dataStr && !file) {
768
+ console.error("Error: either --data or --file must be provided");
769
+ process.exit(1);
770
+ }
771
+ const profile = util.getCurrentProfile();
772
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
773
+ const extension = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(dataStr);
774
+ const { data } = await client.installExtension(extension, version);
775
+ return data;
776
+ }
777
+ async extensionUpdate(opts) {
778
+ const { ref, version, name, data: dataStr, file } = opts;
779
+ if (!dataStr && !file) {
780
+ console.error("Error: either --data or --file must be provided");
781
+ process.exit(1);
782
+ }
783
+ const profile = util.getCurrentProfile();
784
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
785
+ const patch = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(dataStr);
786
+ const { data } = await client.updateExtension(name, version, patch);
787
+ return data;
788
+ }
789
+ async extensionDelete(opts) {
790
+ const { ref, version, name } = opts;
791
+ const profile = util.getCurrentProfile();
792
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
793
+ const { data } = await client.deleteExtension(name, version);
794
+ return data;
795
+ }
796
+ async policyGet(opts) {
797
+ const { ref, version, name } = opts;
798
+ const profile = util.getCurrentProfile();
799
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
800
+ const { data } = await client.getPolicy(name, version);
801
+ return data;
802
+ }
803
+ async policyInstall(opts) {
804
+ const { ref, version, data: dataStr, file } = opts;
805
+ if (!dataStr && !file) {
806
+ console.error("Error: either --data or --file must be provided");
807
+ process.exit(1);
808
+ }
809
+ const profile = util.getCurrentProfile();
810
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
811
+ const policy = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(dataStr);
812
+ const { data } = await client.installPolicy(policy, version);
813
+ return data;
814
+ }
815
+ async policyUpdate(opts) {
816
+ const { ref, version, name, data: dataStr, file } = opts;
817
+ if (!dataStr && !file) {
818
+ console.error("Error: either --data or --file must be provided");
819
+ process.exit(1);
820
+ }
821
+ const profile = util.getCurrentProfile();
822
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
823
+ const patch = file ? JSON.parse(readFileSync(resolve(file), "utf-8")) : JSON.parse(dataStr);
824
+ const { data } = await client.updatePolicy(name, version, patch);
825
+ return data;
826
+ }
827
+ async policyDelete(opts) {
828
+ const { ref, version, name } = opts;
829
+ const profile = util.getCurrentProfile();
830
+ const client = new Api({ token: profile.token, host: profile.host }).component(ref);
831
+ const { data } = await client.deletePolicy(name, version);
832
+ return data;
833
+ }
377
834
  }
378
835
  export default new ComponentCommand();
@@ -1,17 +1,26 @@
1
1
  import CLI from "../lib/cli.js";
2
2
  import { writeFileSync } from "fs";
3
+ import { JSONPath } from "jsonpath-plus";
4
+ import get from "lodash/get.js";
5
+ function applyTemplate(template, data) {
6
+ return template.replace(/\{\{\.?([\w.[\]*]+)\}\}/g, (_match, path) => {
7
+ const val = get(data, path);
8
+ return val === undefined ? '' : typeof val === 'object' ? JSON.stringify(val) : String(val);
9
+ });
10
+ }
3
11
  export default class OutputFormatCommand {
4
12
  command;
5
13
  constructor(command) {
6
14
  this.command = command;
7
15
  this.command
8
- .option("-f, --format <format>")
9
- .option("-o, --output <file>");
16
+ .option("-f, --format <format>", "Output format: json | yaml | table | jsonpath | template")
17
+ .option("-o, --output <file>", "Write output to a file")
18
+ .option("--template <template>", "Template string for jsonpath or template formats (use with -f jsonpath or -f template)");
10
19
  }
11
20
  action(fn) {
12
21
  this.command.action(async (...args) => {
13
22
  const results = await fn(...args);
14
- const { format, output } = this.command.opts();
23
+ const { format, output, template } = this.command.opts();
15
24
  if (!output) {
16
25
  switch (format) {
17
26
  case 'json':
@@ -20,11 +29,58 @@ export default class OutputFormatCommand {
20
29
  case 'table':
21
30
  CLI.writeTable(results);
22
31
  break;
32
+ case 'jsonpath': {
33
+ if (!template) {
34
+ console.error('--template is required with --format jsonpath');
35
+ process.exit(1);
36
+ }
37
+ const found = JSONPath({ path: template, json: results });
38
+ const single = Array.isArray(found) && found.length === 1 ? found[0] : found;
39
+ CLI.write(typeof single === 'object' ? JSON.stringify(single, null, 4) : String(single));
40
+ break;
41
+ }
42
+ case 'template': {
43
+ if (!template) {
44
+ console.error('--template is required with --format template');
45
+ process.exit(1);
46
+ }
47
+ if (Array.isArray(results)) {
48
+ results.forEach(item => CLI.write(applyTemplate(template, item)));
49
+ }
50
+ else {
51
+ CLI.write(applyTemplate(template, results));
52
+ }
53
+ break;
54
+ }
23
55
  default: console.log(results);
24
56
  }
25
57
  return;
26
58
  }
27
- writeFileSync(output, results);
59
+ let serialized;
60
+ if (format === 'jsonpath') {
61
+ if (!template) {
62
+ console.error('--template is required with --format jsonpath');
63
+ process.exit(1);
64
+ }
65
+ const found = JSONPath({ path: template, json: results });
66
+ const single = Array.isArray(found) && found.length === 1 ? found[0] : found;
67
+ serialized = typeof single === 'object' ? JSON.stringify(single, null, 4) : String(single);
68
+ }
69
+ else if (format === 'template') {
70
+ if (!template) {
71
+ console.error('--template is required with --format template');
72
+ process.exit(1);
73
+ }
74
+ serialized = Array.isArray(results)
75
+ ? results.map(item => applyTemplate(template, item)).join('\n')
76
+ : applyTemplate(template, results);
77
+ }
78
+ else {
79
+ serialized = format === 'json' || typeof results === 'object'
80
+ ? JSON.stringify(results, null, 4)
81
+ : String(results);
82
+ }
83
+ writeFileSync(output, serialized);
28
84
  });
29
85
  return this.command;
30
86
  }
@@ -14,8 +14,8 @@ export function forgeDevKernelPlugin(appName, platformUrl) {
14
14
  ? `(function(){
15
15
  var _appRef=${JSON.stringify(appRef)};
16
16
  var _platformUrl=${JSON.stringify(platUrl)};
17
- window.forge=window.forge||{};
18
- window.forge.requestPermissions=function(permissions,reason){
17
+ window.$forge=window.forge||{};
18
+ window.$forge.requestPermissions=function(permissions,reason){
19
19
  var appName=_appRef||sessionStorage.getItem('forge_app_name')||'';
20
20
  var params=new URLSearchParams();
21
21
  params.set('app_ref',appName);
@@ -84,8 +84,8 @@ export function forgeDevKernelPlugin(appName, platformUrl) {
84
84
  });
85
85
  });
86
86
  };
87
- console.log('[ptkl forge dev] window.forge ready (platform: '+_platformUrl+')'); window.forge.dynamicImport=function(url){return import(url).then(function(){});}; window.forge.dynamicImportCSS=function(url){return new Promise(function(resolve,reject){var link=document.createElement('link');link.rel='stylesheet';link.href=url;link.onload=function(){resolve();};link.onerror=function(){reject(new Error('Failed to load CSS: '+url));};document.head.appendChild(link);});};
88
- window.forge.requestMarketplaceInstall=function(itemId,itemType,options){
87
+ console.log('[ptkl forge dev] window.forge ready (platform: '+_platformUrl+')'); window.$forge.dynamicImport=function(url){return import(url).then(function(){});}; window.$forge.dynamicImportCSS=function(url){return new Promise(function(resolve,reject){var link=document.createElement('link');link.rel='stylesheet';link.href=url;link.onload=function(){resolve();};link.onerror=function(){reject(new Error('Failed to load CSS: '+url));};document.head.appendChild(link);});};
88
+ window.$forge.requestMarketplaceInstall=function(itemId,itemType,options){
89
89
  var appName=(options&&options.initiator)||sessionStorage.getItem('forge_app_name')||'';
90
90
  var params=new URLSearchParams();
91
91
  params.set('id',itemId);
@@ -147,7 +147,7 @@ export function forgeDevKernelPlugin(appName, platformUrl) {
147
147
  });
148
148
  });
149
149
  };
150
- window.forge.openDeveloperIntegrations=function(){
150
+ window.$forge.openDeveloperIntegrations=function(){
151
151
  var integrationsUrl=_platformUrl+'/admin/developer/integrations';
152
152
  return new Promise(function(resolve){
153
153
  var overlay=document.createElement('div');
@@ -179,23 +179,139 @@ export function forgeDevKernelPlugin(appName, platformUrl) {
179
179
  overlay.addEventListener('click',function(e){if(e.target===overlay)cleanup();});
180
180
  });
181
181
  };
182
+ window.$forge.openOnboarding=function(){
183
+ if(window!==window.top)return Promise.resolve({completed:false});
184
+ var onboardingUrl=_platformUrl+'/onboarding';
185
+ return new Promise(function(resolve){
186
+ var overlay=document.createElement('div');
187
+ overlay.style.cssText='position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.72);display:flex;align-items:center;justify-content:center;';
188
+ var dialog=document.createElement('div');
189
+ dialog.style.cssText='position:relative;width:960px;max-width:calc(100vw - 2rem);height:85vh;max-height:calc(100vh - 4rem);border-radius:16px;overflow:hidden;box-shadow:0 32px 80px rgba(0,0,0,0.8);background:#0f0f10;';
190
+ var closeBtn=document.createElement('button');
191
+ closeBtn.textContent='\u00D7';
192
+ closeBtn.style.cssText='position:absolute;top:10px;right:12px;z-index:3;background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.15);color:#fff;font-size:1.25rem;line-height:1;width:30px;height:30px;border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;';
193
+ var loader=document.createElement('div');
194
+ loader.style.cssText='position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#0f0f10;z-index:2;pointer-events:none;';
195
+ var spinner=document.createElement('div');
196
+ spinner.style.cssText='width:36px;height:36px;border:3px solid rgba(255,255,255,0.12);border-top-color:#fff;border-radius:50%;animation:forge-spin 0.7s linear infinite;';
197
+ var style=document.createElement('style');
198
+ style.textContent='@keyframes forge-spin{to{transform:rotate(360deg)}}';
199
+ loader.appendChild(style);
200
+ loader.appendChild(spinner);
201
+ var iframe=document.createElement('iframe');
202
+ iframe.style.cssText='width:100%;height:100%;border:none;display:block;';
203
+ iframe.addEventListener('load',function(){loader.style.display='none';});
204
+ dialog.appendChild(closeBtn);
205
+ dialog.appendChild(loader);
206
+ dialog.appendChild(iframe);
207
+ overlay.appendChild(dialog);
208
+ document.body.appendChild(overlay);
209
+ setTimeout(function(){iframe.src=onboardingUrl;},0);
210
+ function cleanup(){
211
+ window.removeEventListener('message',onMessage);
212
+ overlay.remove();
213
+ }
214
+ function onMessage(e){
215
+ if(e.origin!==_platformUrl)return;
216
+ if(!e.data)return;
217
+ if(e.data.type==='forge_onboarding_complete'){cleanup();resolve({completed:true});}
218
+ }
219
+ window.addEventListener('message',onMessage);
220
+ closeBtn.addEventListener('click',function(){cleanup();resolve({completed:false});});
221
+ overlay.addEventListener('click',function(e){if(e.target===overlay){cleanup();resolve({completed:false});}});
222
+ });
223
+ };
224
+ var _supportTicketOverlay=null;
225
+ var _supportTicketOnMessage=null;
226
+ window.$forge.closeSupportTicketDialog=function(){
227
+ if(_supportTicketOnMessage){
228
+ window.removeEventListener('message',_supportTicketOnMessage);
229
+ _supportTicketOnMessage=null;
230
+ }
231
+ if(_supportTicketOverlay){
232
+ _supportTicketOverlay.remove();
233
+ _supportTicketOverlay=null;
234
+ }
235
+ };
236
+ window.$forge.createSupportTicket=function(options){
237
+ window.$forge.closeSupportTicketDialog();
238
+ var defaults=(options&&options.defaults)||{};
239
+ var params=new URLSearchParams();
240
+ if(defaults.subject)params.set('subject',defaults.subject);
241
+ if(defaults.description)params.set('description',defaults.description);
242
+ if(defaults.topic)params.set('topic',defaults.topic);
243
+ if(defaults.priority)params.set('priority',defaults.priority);
244
+ var qs=params.toString();
245
+ var ticketUrl=_platformUrl+'/support/create-ticket'+(qs?'?'+qs:'');
246
+ return new Promise(function(resolve){
247
+ var overlay=document.createElement('div');
248
+ overlay.style.cssText='position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.72);display:flex;align-items:center;justify-content:center;';
249
+ var dialog=document.createElement('div');
250
+ dialog.style.cssText='position:relative;width:600px;max-width:calc(100vw - 2rem);height:640px;max-height:calc(100vh - 4rem);border-radius:16px;overflow:hidden;box-shadow:0 32px 80px rgba(0,0,0,0.8);';
251
+ var closeBtn=document.createElement('button');
252
+ closeBtn.textContent='\u00D7';
253
+ closeBtn.style.cssText='position:absolute;top:10px;right:12px;z-index:3;background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.15);color:#fff;font-size:1.25rem;line-height:1;width:30px;height:30px;border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;';
254
+ var loader=document.createElement('div');
255
+ loader.style.cssText='position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:#0f0f10;z-index:2;pointer-events:none;';
256
+ var spinner=document.createElement('div');
257
+ spinner.style.cssText='width:36px;height:36px;border:3px solid rgba(255,255,255,0.12);border-top-color:#fff;border-radius:50%;animation:forge-spin 0.7s linear infinite;';
258
+ var style=document.createElement('style');
259
+ style.textContent='@keyframes forge-spin{to{transform:rotate(360deg)}}';
260
+ loader.appendChild(style);
261
+ loader.appendChild(spinner);
262
+ var iframe=document.createElement('iframe');
263
+ iframe.style.cssText='width:100%;height:100%;border:none;display:block;';
264
+ iframe.addEventListener('load',function(){loader.style.display='none';});
265
+ dialog.appendChild(closeBtn);
266
+ dialog.appendChild(loader);
267
+ dialog.appendChild(iframe);
268
+ overlay.appendChild(dialog);
269
+ document.body.appendChild(overlay);
270
+ _supportTicketOverlay=overlay;
271
+ setTimeout(function(){iframe.src=ticketUrl;},0);
272
+ var settled=false;
273
+ function resolveOnce(result){if(settled)return;settled=true;resolve(result);}
274
+ function onMessage(e){
275
+ if(e.origin!==_platformUrl)return;
276
+ if(!e.data)return;
277
+ if(e.data.type==='support_ticket_close'){window.$forge.closeSupportTicketDialog();resolveOnce({created:false});return;}
278
+ if(e.data.type==='support_ticket_created'){resolveOnce({created:true,ticket:e.data.ticket||null});return;}
279
+ if(e.data.type==='support_ticket_denied'){window.$forge.closeSupportTicketDialog();resolveOnce({created:false});}
280
+ }
281
+ _supportTicketOnMessage=onMessage;
282
+ window.addEventListener('message',onMessage);
283
+ closeBtn.addEventListener('click',function(){window.$forge.closeSupportTicketDialog();resolveOnce({created:false});});
284
+ overlay.addEventListener('click',function(e){if(e.target===overlay){window.$forge.closeSupportTicketDialog();resolveOnce({created:false});}});
285
+ });
286
+ };
182
287
  })();`
183
288
  : `(function(){
184
- window.forge=window.forge||{};
185
- window.forge.requestPermissions=function(){
186
- console.warn('[ptkl forge dev] window.forge.requestPermissions unavailable — pass --platform-url <url> to enable.');
289
+ window.$forge=window.forge||{};
290
+ window.$forge.requestPermissions=function(){
291
+ console.warn('[ptkl forge dev] window.$forge.requestPermissions unavailable — pass --platform-url <url> to enable.');
187
292
  return Promise.reject(new Error('requestPermissions requires --platform-url in ptkl forge dev'));
188
293
  };
189
- window.forge.requestMarketplaceInstall=function(){
190
- console.warn('[ptkl forge dev] window.forge.requestMarketplaceInstall unavailable — pass --platform-url <url> to enable.');
294
+ window.$forge.requestMarketplaceInstall=function(){
295
+ console.warn('[ptkl forge dev] window.$forge.requestMarketplaceInstall unavailable — pass --platform-url <url> to enable.');
191
296
  return Promise.reject(new Error('requestMarketplaceInstall requires --platform-url in ptkl forge dev'));
192
297
  };
193
- window.forge.openDeveloperIntegrations=function(){
194
- console.warn('[ptkl forge dev] window.forge.openDeveloperIntegrations unavailable — pass --platform-url <url> to enable.');
298
+ window.$forge.openDeveloperIntegrations=function(){
299
+ console.warn('[ptkl forge dev] window.$forge.openDeveloperIntegrations unavailable — pass --platform-url <url> to enable.');
195
300
  return Promise.resolve();
196
301
  };
197
- window.forge.dynamicImport=function(url){return import(url).then(function(){});};
198
- window.forge.dynamicImportCSS=function(url){return new Promise(function(resolve,reject){var link=document.createElement('link');link.rel='stylesheet';link.href=url;link.onload=function(){resolve();};link.onerror=function(){reject(new Error('Failed to load CSS: '+url));};document.head.appendChild(link);});};}
302
+ window.$forge.openOnboarding=function(){
303
+ console.warn('[ptkl forge dev] window.$forge.openOnboarding unavailable — pass --platform-url <url> to enable.');
304
+ return Promise.resolve({completed:false});
305
+ };
306
+ window.$forge.createSupportTicket=function(){
307
+ console.warn('[ptkl forge dev] window.$forge.createSupportTicket unavailable — pass --platform-url <url> to enable.');
308
+ return Promise.reject(new Error('createSupportTicket requires --platform-url in ptkl forge dev'));
309
+ };
310
+ window.$forge.closeSupportTicketDialog=function(){
311
+ console.warn('[ptkl forge dev] window.$forge.closeSupportTicketDialog unavailable — pass --platform-url <url> to enable.');
312
+ };
313
+ window.$forge.dynamicImport=function(url){return import(url).then(function(){})};
314
+ window.$forge.dynamicImportCSS=function(url){return new Promise(function(resolve,reject){var link=document.createElement('link');link.rel='stylesheet';link.href=url;link.onload=function(){resolve();};link.onerror=function(){reject(new Error('Failed to load CSS: '+url));};document.head.appendChild(link);});};}
199
315
  })();`;
200
316
  return {
201
317
  name: 'ptkl-forge-dev-kernel',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ptkl/toolkit",
3
- "version": "0.9.3",
3
+ "version": "0.10.0",
4
4
  "description": "A command-line toolkit for managing Protokol platform applications, profiles, functions, and components",
5
5
  "keywords": [
6
6
  "protokol",
@@ -49,6 +49,7 @@
49
49
  "circular-json": "^0.5.9",
50
50
  "commander": "^12.1.0",
51
51
  "js-yaml": "^4.1.0",
52
+ "jsonpath-plus": "^10.4.0",
52
53
  "less": "^4.1.1",
53
54
  "lodash": "^4.17.21",
54
55
  "open": "^10.1.2",